query
stringlengths
7
9.55k
document
stringlengths
10
363k
metadata
dict
negatives
sequencelengths
0
101
negative_scores
sequencelengths
0
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
This is customized because GENCAT
def participatory_processes @participatory_processes ||= filtered_processes.includes(attachments: :file_attachment) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def private; end", "def formation; end", "def probers; end", "def guct\n end", "def suivre; end", "def terpene; end", "def blg; end", "def schubert; end", "def custom; end", "def custom; end", "def verdi; end", "def specie; end", "def specie; end", "def specie; end", "def specie; end", "def cobasysprog\n end", "def villian; end", "def intensifier; end", "def refutal()\n end", "def berlioz; end", "def mitch_hedberg; end", "def weber; end", "def zuruecksetzen()\n end", "def celebration; end", "def extra; end", "def nasa_space_craft; end", "def feruchemist; end", "def begingraphics(*)\n super\n end", "def gounod; end", "def schumann; end", "def sn\n end", "def getc() end", "def getc() end", "def getc() end", "def upc_e; end", "def dh; end", "def mi_carrera\n\n\tend", "def jack_handey; end", "def stderrs; end", "def getgm() end", "def wagner; end", "def g; end", "def g; end", "def invention; end", "def rossini; end", "def implementation; end", "def implementation; end", "def ca; end", "def escaper; end", "def bellini; end", "def gp_flags; end", "def scf\n end", "def strategy; end", "def trd; end", "def who_we_are\r\n end", "def mathtex(*)\n super\n end", "def getc\n end", "def getc\n end", "def legionnairs\n\n end", "def transformations; end", "def myletter\n \n end", "def strain; end", "def initialize\n\t\t\n\tend", "def init; end", "def init; end", "def init; end", "def init; end", "def initialize\r\n\r\n end", "def isolated; end", "def isolated; end", "def surge; end", "def jaeger_quest; end", "def king_richard_iii; end", "def bs; end", "def alt; end", "def nebula; end", "def production_curtailment; end", "def scientist; end", "def operations; end", "def operations; end", "def src; end", "def src; end", "def src; end", "def processor; end", "def cp_e\n end", "def initialize\n \n end", "def fill_from_gemo\r\n end", "def england\n end", "def origin; end", "def origin; end", "def origin; end", "def gPXE; iPXE; end", "def malts; end", "def genCurrentLayer\n end", "def flags; end", "def code_of_conduct; end", "def eplore\n end", "def tld; end", "def tld; end", "def nn\n end", "def romeo_and_juliet; end" ]
[ "0.7225691", "0.66720587", "0.64770335", "0.6476829", "0.64121234", "0.6375613", "0.63514936", "0.634799", "0.62883306", "0.62883306", "0.6268521", "0.6214126", "0.6214126", "0.6214126", "0.6214126", "0.6209637", "0.61696506", "0.6142058", "0.60313547", "0.6003933", "0.59594035", "0.59584606", "0.59467727", "0.59399736", "0.59344834", "0.5919069", "0.5914683", "0.5888876", "0.5881069", "0.5864218", "0.5806302", "0.5752053", "0.5752053", "0.5752053", "0.5740611", "0.5739169", "0.5713195", "0.5706175", "0.57027835", "0.569302", "0.568103", "0.56746155", "0.56746155", "0.56643516", "0.5654479", "0.5651167", "0.5651167", "0.5610862", "0.5601316", "0.5595709", "0.5584813", "0.5556027", "0.555594", "0.5554188", "0.55519575", "0.55516875", "0.55456597", "0.55456597", "0.55320615", "0.5519811", "0.55169433", "0.5512933", "0.5511081", "0.5510939", "0.5510939", "0.5510939", "0.5510939", "0.5509859", "0.5509102", "0.5509102", "0.55088127", "0.55081856", "0.55079156", "0.5504074", "0.5500078", "0.5493217", "0.5492848", "0.549266", "0.5490361", "0.5490361", "0.54897904", "0.54897904", "0.54897904", "0.54844874", "0.54832906", "0.5477126", "0.54727924", "0.5463599", "0.54600513", "0.54600513", "0.54600513", "0.54550344", "0.54499274", "0.5448988", "0.5431918", "0.5430846", "0.5430025", "0.5427566", "0.5427566", "0.5426239", "0.54115623" ]
0.0
-1
This is customized because GENCAT
def participatory_process_groups @participatory_process_groups ||= Decidim::ParticipatoryProcesses::OrganizationParticipatoryProcessGroups.new(current_organization).query .where(id: filtered_processes.grouped.group_ids) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def private; end", "def formation; end", "def probers; end", "def guct\n end", "def suivre; end", "def terpene; end", "def blg; end", "def schubert; end", "def custom; end", "def custom; end", "def verdi; end", "def specie; end", "def specie; end", "def specie; end", "def specie; end", "def cobasysprog\n end", "def villian; end", "def intensifier; end", "def refutal()\n end", "def berlioz; end", "def mitch_hedberg; end", "def weber; end", "def zuruecksetzen()\n end", "def celebration; end", "def extra; end", "def nasa_space_craft; end", "def feruchemist; end", "def begingraphics(*)\n super\n end", "def gounod; end", "def schumann; end", "def sn\n end", "def getc() end", "def getc() end", "def getc() end", "def upc_e; end", "def dh; end", "def mi_carrera\n\n\tend", "def jack_handey; end", "def stderrs; end", "def getgm() end", "def wagner; end", "def g; end", "def g; end", "def invention; end", "def rossini; end", "def implementation; end", "def implementation; end", "def ca; end", "def escaper; end", "def bellini; end", "def gp_flags; end", "def scf\n end", "def strategy; end", "def trd; end", "def who_we_are\r\n end", "def mathtex(*)\n super\n end", "def getc\n end", "def getc\n end", "def legionnairs\n\n end", "def transformations; end", "def myletter\n \n end", "def strain; end", "def initialize\n\t\t\n\tend", "def init; end", "def init; end", "def init; end", "def init; end", "def initialize\r\n\r\n end", "def isolated; end", "def isolated; end", "def surge; end", "def jaeger_quest; end", "def king_richard_iii; end", "def bs; end", "def alt; end", "def nebula; end", "def production_curtailment; end", "def scientist; end", "def operations; end", "def operations; end", "def src; end", "def src; end", "def src; end", "def processor; end", "def cp_e\n end", "def initialize\n \n end", "def fill_from_gemo\r\n end", "def england\n end", "def origin; end", "def origin; end", "def origin; end", "def gPXE; iPXE; end", "def malts; end", "def genCurrentLayer\n end", "def flags; end", "def code_of_conduct; end", "def eplore\n end", "def tld; end", "def tld; end", "def nn\n end", "def romeo_and_juliet; end" ]
[ "0.7225691", "0.66720587", "0.64770335", "0.6476829", "0.64121234", "0.6375613", "0.63514936", "0.634799", "0.62883306", "0.62883306", "0.6268521", "0.6214126", "0.6214126", "0.6214126", "0.6214126", "0.6209637", "0.61696506", "0.6142058", "0.60313547", "0.6003933", "0.59594035", "0.59584606", "0.59467727", "0.59399736", "0.59344834", "0.5919069", "0.5914683", "0.5888876", "0.5881069", "0.5864218", "0.5806302", "0.5752053", "0.5752053", "0.5752053", "0.5740611", "0.5739169", "0.5713195", "0.5706175", "0.57027835", "0.569302", "0.568103", "0.56746155", "0.56746155", "0.56643516", "0.5654479", "0.5651167", "0.5651167", "0.5610862", "0.5601316", "0.5595709", "0.5584813", "0.5556027", "0.555594", "0.5554188", "0.55519575", "0.55516875", "0.55456597", "0.55456597", "0.55320615", "0.5519811", "0.55169433", "0.5512933", "0.5511081", "0.5510939", "0.5510939", "0.5510939", "0.5510939", "0.5509859", "0.5509102", "0.5509102", "0.55088127", "0.55081856", "0.55079156", "0.5504074", "0.5500078", "0.5493217", "0.5492848", "0.549266", "0.5490361", "0.5490361", "0.54897904", "0.54897904", "0.54897904", "0.54844874", "0.54832906", "0.5477126", "0.54727924", "0.5463599", "0.54600513", "0.54600513", "0.54600513", "0.54550344", "0.54499274", "0.5448988", "0.5431918", "0.5430846", "0.5430025", "0.5427566", "0.5427566", "0.5426239", "0.54115623" ]
0.0
-1
as a string. If there is no missing letter, the method should return nil. bonus: returns a string of all missing letters as a string. ex: find_missing_letter("ace") would return "bd", write your own test. split the string into an array each through and check the next char against the current if next char not in order then append to result array
def find_missing_letter(range) # result = [] # prev_char = "" # array = range.split("") # array.each do |char| # if prev_char.next != char # result << prev_char.next # end # prev_char = char # end # result first_letter = range[0] last_letter = range[-1] test_range = (first_letter..last_letter).to_a result = "" test_range.each do |letter| result += letter unless range.include?(letter) end result != "" ? result : nil end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def find_missing_letter(string)\n if string.empty?\n missing_letters = (\"a\"..\"z\").to_a\n else\n alphabet = (\"a\"..\"z\").to_a\n missing_letters = alphabet[alphabet.index(string.split(\"\").first)..alphabet.index(string.split(\"\").last)]- string.split(\"\")\n end\n missing_letters.empty? ? nil : missing_letters.join\nend", "def find_missing_letter(string)\n string = string.split(\"\")\n f_letter = string.first\n l_letter = string.last\n all_letters = f_letter.upto(l_letter).to_a\n missing = all_letters - string \n if missing == []\n return nil\n else\n return missing\n end \nend", "def missing_letters(string)\n missing = []\n ('a'..'z').each do |letter|\n if !string.include?(letter)\n missing << letter\n end\n end\n missing\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 missingChars(str)\n\t\n\t# A boolean array to store characters\n\t# present in string.\t\n\n alfabeto = 'abcdefghijklmnopqrstuvxyz' \n arr = alfabeto.split('');\n\n arrstr = str.split('');\n arrmissing = [] \n \n \n\t# Traverse string and mark characters\n\t# present in string.\n\tfor i in 0..arr.length() - 1 do\n if (arrstr.include?(arr[i].downcase) == false) and (arrstr.include?(arr[i].upcase) == false)\n arrmissing.push(arr[i].downcase) \n end \n end \n \n return arrmissing.join();\n\n \n\n\t# Store missing characters in alphabetic\n\t# order.\n\t\nend", "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 find_missing_letter(range)\n start_index = 0\n reference = \"abcdefghijklmnopqrstuvwxyz\".split(\"\")\n sorted_range = range.split(\"\").sort\n missing_letters = []\n\n reference.each_with_index do |letter, index|\n if sorted_range[0] == letter\n start_index = index\n end\n end\n\n sorted_range.each do |letter|\n unless letter == reference[start_index]\n missing_letters << reference[start_index]\n start_index+=1 #If a letter is missing, need to add twice to skip over to the next one\n end\n start_index+=1\n end\n\n if missing_letters.any?\n return missing_letters.join(\"\")\n else\n return nil\n end\n\nend", "def missing_letters(string)\n output = []\n\n ('a'..'z').each do |el|\n if !string.include?(el) \n output << el\n end\n end\n output\nend", "def missing_letters(string)\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 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 missing_letters(string)\n return ('a'..'z').to_a.select {|e| !string.include?(e)}\nend", "def missing_letters(string)\n ('a'..'z').to_a.reject { |letter| string.include?(letter) }\nend", "def missing_letters(string)\n ('a'..'z').reject {|letter| string.include?(letter)}\nend", "def missing_letters(string)\n string = string.downcase\n (\"a\"..\"z\").to_a.reject {|letter| string.include?(letter) }\nend", "def missing_letters(string)\n a_to_z_array = (\"a\"..\"z\").to_a\n a_to_z_array - string.chars\n\nend", "def missing_letters(string)\n letters = %w[a b c d e f g h i j k l m n o p q r s t u v w x y z]\n letters.select { |c| c unless string.include?(c) }\nend", "def find_missing_letter(range)\n letters = range.split(\"\")\n full_letters = (letters[0]..letters[-1]).to_a\n full_letters.each do |letter|\n if letters.include?(letter) \n\n elsif not letters.include?(letter)\n return letter\n end\n if letters == full_letters\n return nil\n end\n end\n \n \n\nend", "def missing_letters(string)\n ('a'..'z').reject { |letter| string.downcase.include? letter }\nend", "def missing_letters(string)\n alphabet = (\"a\"..\"z\").to_a\n alphabet.reject { |x| string.downcase.include?(x) }\nend", "def missing_letters(string)\n letters = ('a'..'z').to_a\n letters.reject { |char| string.downcase.include?(char) }\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 missing_letters(string)\n alphabet='a'..'z'\n alphabet.reject {|el|string.downcase.include?(el)}\nend", "def missing_letter2(word)\n alphabet = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n for letter in alphabet.split(\"\")\n if letter == word[0]\n start = alphabet.index(letter)\n break\n end\n end\n\n for letter in word\n if letter != alphabet[start]\n return alphabet[start]\n else start +=1\n end\n end\nend", "def find_missing_letter(arr)\n missing_letter = ''\n (arr[0]...arr[-1]).each do |x|\n if !arr.include?(x)\n print x\n end\n end\n\nend", "def find_missing_letter(range)\nsplit_range = []\nsplit_range = range.split(//)\narray = []\n\nrange_two = (split_range[0]..split_range[-1]).to_a\narray << range_two - split_range\n\n if array.length > 0\n p array.join\n else\n p nil\n end\nend", "def find_missing_letter(range)\n numbers = []\n\n range.each_byte do |number|\n numbers << number\n end\n\n starting_point = numbers[0]\n ending_point = numbers.last\n\n new_array = []\n\n range_length = range.length\n\n range_length.times do\n new_array << starting_point.next\n starting_point += 1\n end\n\n missing_letter = \"\"\n counter = 0\n range_length.times do\n if new_array[counter] == numbers[counter + 1]\n counter += 1\n else\n missing_letter = new_array[counter]\n end\n end\n\n if missing_letter < ending_point\n return missing_letter.chr\n else\n return nil\n end\nend", "def missing_letter(word)\n word.each_with_index do |letter, i|\n return letter.next if word[i + 1] != letter.next\n end\nend", "def find_missing_letter(range)\n array_1 = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\"]\n start_index = array_1.index(range[0]) \n\n range.split(//).each do |letter|\n if letter == array_1[start_index]\n start_index += 1\n else\n return array_1[start_index] \n end\n end\n nil\nend", "def find_missing_letter(arr)\n ((arr.first..arr.last).to_a - arr).first\nend", "def missing_letter(word)\n # your code goes here\n alpha = ('a'..'z').to_a\n index = alpha.index word.first.downcase\n word.each do |letter|\n if letter.downcase != alpha[index]\n alpha[index] < letter ? (return alpha[index]) : (return alpha[index].upcase)\n end\n index +=1\n end\n\nend", "def find_missing_letter(arr)\n((arr.first..arr.last).to_a - arr).first\nend", "def missing_letters\n missing = Array.new\n ('a'..'z').each {|l| missing << l if @hist[l] == 0}\n missing\n end", "def find_missing_letter(arr)\n #your code here\n result = 0\n base_arr = arr.join().codepoints\n base_arr.each_with_index do |item,index|\n if base_arr[index+1] != item + 1\n result = item + 1\n break\n end\n end\n result.chr\nend", "def find_missing_letter(range)\n results = []\n range.chars.each_slice(2) do |a, b|\n next if b.nil?\n results << a.next unless a.next == b\n end\n\n return nil if results.empty?\n results\nend", "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 missing_from_letters\n word.chars.uniq.inject(\"\") do |memo, l|\n difference = word.count(l) - letters.count(l)\n if difference > 0\n memo += l * difference\n end\n memo\n end\n end", "def find_missing_letter(arr)\n ((arr.first..arr.last).to_a - arr).first\n\n # or...\n # letters = (arr.first..arr.last).to_a\n # return (letters - arr).first\nend", "def find_missing_letter(arr)\n ([*arr.first..arr.last] - arr).first\nend", "def non_unique_letters(string)\n string.chars.reduce([]) do |array,letter|\n if string.count(letter) > 1 && array.include?(letter) == false && letter != \" \"\n array << letter\n else\n array\n end\n end\nend", "def find_missing_letter(arr)\n arr.each_with_index { |ltr, i| return ltr.next unless ltr.next == arr[i + 1] }\nend", "def find_missing_letter(arr)\n lower_case_alphabet = (\"a\"..\"z\").to_a\n upper_case_alphabet = (\"A\"..\"Z\").to_a\n\n if lower_case_alphabet.include?(arr.first)\n min = lower_case_alphabet.index(arr.first)\n max = lower_case_alphabet.index(arr.last)\n lower_case_alphabet[min..max].select { |letter| !arr.include?(letter) }.first\n else\n min = upper_case_alphabet.index(arr.first)\n max = upper_case_alphabet.index(arr.last)\n upper_case_alphabet[min..max].select { |letter| !arr.include?(letter) }.first\n end\nend", "def get_letters(game)\n game.letters.split(\"\").reject{|letter| game.word.upcase.include?(letter)}.join(\" \")\nend", "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 non_unique_letters(string)\n\n result = [] # empty accumulator\n\n string.split(\"\").uniq.each do |uni| # finding character present in the string\n each_char = 0\n\n string.split(\"\").each do |ltr| # iterating array of string\n each_char += 1 if ltr == uni\n end\n result << uni if each_char > 1\n end\n\n result\nend", "def comes_after(str,letter)\n split = str.split(\"\")\n correct_letters = split.each_with_index.select {|char,index| (split[index - 1] === letter || split[index - 1] === letter.upcase) && char =~ /[[:alpha:]]/}\n final = correct_letters.map {|item| item[0]}.join(\"\")\n if final.first = \"P\"\n \tfinal.delete_at(0)\n end\n return final\nend", "def guess_letter\n @unused_letters.pop\n end", "def first_non_repeating_letter(s) \n chars = []\n s.split(//).each do |character|\n if chars.include?(character) || chars.include?(character.downcase) || chars.include?(character.upcase)\n chars.delete(character)\n else\n chars << character \n end\n end\n # return chars[0] \n chars.empty? ? \"\" : chars[0]\nend", "def solution(string)\n\talphabet = (\"A\"..\"Z\").to_a\n\n\tarr = []\n\tstring.chars.each do |letter|\n\t\tif alphabet.include?(letter)\n\t\t\tarr << \" \"\n\t\t\tarr << letter\n\t\telse\n\t\t\tarr << letter\n\t\tend\n\tend\narr.join\nend", "def non_unique_letters(string)\nend", "def uses_available_letters?(input, letters_in_hand)\n input = input.split('')\n letters_in_hand.reject do |letter|\n if input.include?(letter)\n input.slice!(input.index(letter))\n end\n end\n # the length of the input checks that the user used only available letters\n if input.length == 0\n return true\n else\n return false\n end\nend", "def comes_after(str,letter)\n result = []\n unwanted_chars = \"1234567890.,!;:?_ \"\n str.length.times do |index|\n if str[index] == letter.downcase || str[index] == letter.upcase\n result << str[index + 1]\n end\n end\n result.join.delete(unwanted_chars)\nend", "def first_non_repeating_letter(string)\n letter_group = letters.split('').group_by{ |x| x.downcase }\n uniqs = letter_group.reject{ |letter, arr| arr.count > 1 }.keys\n for x in 0..uniqs.length\n\n end\n\n\n\n # letters = string.split('')\n # letter_group = letters.group_by{ |x| x.downcase }\n # p letter_group\n # uniqs = letter_group.reject{ |letter, arr| arr.count > 1 }.keys\n # p uniqs\n # '' + uniqs[0].to_s\nend", "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 NonrepeatingCharacter(str)\n str.chars.each_with_index do |char,idx|\n after = idx + 1\n return char unless str.chars[after..str.length - 1].include?(char)\n end\nend", "def non_unique_letters(string)\n non_unique_arr = []\n new_str = string.delete(' ')\n new_str.each_char do |ch|\n count = string.count(ch)\n if count > 1\n non_unique_arr << ch\n end\n end\n non_unique_arr.uniq.sort\nend", "def first_non_repeating_letter(s)\n letters = s.downcase.split('')\n\n letters&.each_with_index do |l,i|\n return s[i] if letters.count(l) == 1\n end\n ''\nend", "def non_unique_letters(string)\n answer = string.chars.select {|char| string.count(char) > 1}\n answer.delete(' ')\n answer.sort.uniq\nend", "def letter_check(letter)\n @word.chars.each_with_index do |letter_in_word, index|\n if letter == letter_in_word\n @result_str[index] = letter\n end\n end\n if [email protected]?(letter)\n puts \"Sorry try again\"\n end\n @result_str\n end", "def first_non_repeating_letter(str)\n non_repeats = str.chars.reject do |chr|\n str.downcase.count(chr.downcase) > 1\n end\n non_repeats.empty? ? \"\" : non_repeats.first\nend", "def crunch(string)\n no_duplicates = ''\n string.chars.each do |letter|\n no_duplicates << letter unless no_duplicates[-1] == letter\n end\n no_duplicates\nend", "def non_unique_letters(string)\n new_arr = string.chars.select {|c| string.chars.count(c) > 1 }\n new_arr.delete(' ')\n new_arr.uniq!\n new_arr.sort!\n return new_arr\nend", "def first_non_repeating_letter(string)\n result = ''\n letter_count = Hash.new(0)\n string.chars.each do |letter|\n letter_count[letter.to_sym] += 1\n end\n letter_count.select do |letter, count|\n result = letter if count == 1\n break if result.size == 1\n end\n result.to_s\nend", "def non_unique_letters(string)\n alpha = ('a'..'z').to_a\n our_new_letters = []\n counters = Hash.new(0)\n arr = string.downcase.split(\"\").select {|letter| string.count(letter) > 1}\n arr.each do |c|\n counters[c] += 1\n our_new_letters << c if counters[c] <= 1\n end\n our_new_letters.select {|x| alpha.include?(x)}\nend", "def non_unique_letters(string)\n arr = string.split.join.split('')\n arr.select { |c| c if arr.count(c) > 1 }.uniq.sort\nend", "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 non_unique_letters(string)\n character=string.chars.uniq\n character.delete(\" \")\n character.select {|char| string.count(char)>1}\nend", "def only_alpha(string)\r\n\ts = string.split(\"\")\r\n\tstring1=\"\"\r\n\ts.each do |letter|\r\n\t\tif (letter >= \"a\" && letter <= \"z\") || (letter >= \"A\" && letter <= \"Z\")\r\n\t\t\tstring1 += letter\r\n\t\tend\r\n\tend\r\n\tputs string1\r\nend", "def solve(s)\n new_str = ''\n s.each_char do |char|\n if new_str[-1] != char\n new_str += char\n end\n end\n return new_str\nend", "def next_unused_letter sol\n\n\tx = 'a'.ord\n\n\tfor i in 0...sol.size\n\t\tfor j in 0...sol[0].size\n\t\t\tif sol[i][j].ord > x\n\t\t\t\tx = sol[i][j].ord\n\t\t\tend\n\t\tend\n\tend\n\n\treturn (x + 1).chr\nend", "def guessed_wrong_letter()\n if $hidden_word_arr.exclude?($input)\n $guessed.append($input)\n end\n end", "def hackerrankInString(str)\n expected_chars = %w[h a c k e r r a n k]\n input_chars = str.chars\n\n str.chars.each do |char|\n # Thought so, apparently not: Edge case: there should be no more chars after the last 'k' in hackerrank.\n # break if expected_chars.empty?\n\n input_chars.shift\n expected_chars.shift if char == expected_chars[0]\n end\n\n expected_chars.empty? && input_chars.empty? ? 'YES' : 'NO'\nend", "def first_non_repeating_letter(s)\n first_char = ''\n previous_chars = []\n\n s.each_char.with_index do |char, i|\n if s[i + 1..-1].downcase.include?(char.downcase)\n previous_chars << char\n else\n unless previous_chars.join('').downcase.include?(char.downcase)\n first_char += char\n end\n\n end\n end\n\n if first_char.empty?\n return first_char\n else\n return first_char[0]\n end\nend", "def next_letter(full_name)\r\n\tidx = 0\r\n\twhile idx < full_name.length\r\n\t\tname = full_name.split('')\r\n\t\tname.map! { |letter| letter.next unless (letter.next == \"!\") }\r\n\t\tidx += 1\r\n\tend\r\n\tname\r\nend", "def find_first_non_repeated_letter(str)\n flag = 0 #flag used to test for same character\n i = 0 #counter\n a = str.length #length of string for loop\n while i < a do \n\n if str[i] == str[i + 1] #compares character and next character\n flag = 1 #if match set flag\n elsif flag == 0 #check to see if flag has been set \n return str[i] #if flag not set return character\n else\n if i == str.length - 1 #check to see if reached end of string\n return nil #return nil\n end\n flag = 0 #no match at this point set flag to 0\n end\n i += 1 #advance counter\n end\nend", "def non_unique_letters(string)\n string.delete!(' ').chars.select { |e| string.count(e) > 1 }.uniq.sort\nend", "def non_unique_letters(string)\n letters = string.chars.uniq\n letters.select {|letter| string.count(letter) > 1 }\nend", "def char_checker(char_input)\n\t\t#The letter is checked to be included in the word. \n\t\n\t\tif @input_string_array.include? char_input\n\n\t\t\t#If the char is a match we want to iterate through each letter and replace the blank with the letter. \n\t\t\ti = 0\n\t\t\t@input_string_array.each do |char|\n\t\t\t\tif char_input == @input_string_array[i]\n\t\t\t\t\t\n\t\t\t\t\t#Replace the blank with the character\n\t\t\t\t\t@blanks[i] = char_input\n\t\t\t\tend\n\n\t\t\ti += 1\n\t\t\tend\n\t\t\t\n\t\telse\n\t\t\tputs \"That letter does not exist in the word.\"\n\t\tend\n\t\t\t\t\t\t\n\t\n\t\t@blanks\n\tend", "def split_char(string, character)\n i = 0\n temp = \"\"\n output = []\n while i < string.length\n if string[i] != character\n temp << string[i]\n else\n output << temp\n temp = \"\"\n end\n i += 1\n end\n output << temp\n return output\nend", "def nonrptchar(string)\n strcpy = string.reverse.chars\n while strcpy != nil do \n y = strcpy.pop\n if strcpy.include? y\n strcpy.delete(y)\n else\n return y\n end\n end\nend", "def first_non_repeating_letter(str)\n str.chars.each { |char| return char if str.downcase.count(char.downcase) == 1 }\n ''\nend", "def dealphabetize(\n alphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n )\n str = to_s\n alphabet = alphabet.to_s\n len = alphabet.length\n str.chars.inject(0) do |num, char|\n i = alphabet.index(char)\n raise(\"Character not in alphabet: '#{char}'\") if i.nil?\n\n num * len + i\n end\n end", "def find_letters str\n arr = str.split('')\n count = 0\n arr2 = []\n for i in arr\n if (arr.count(i) <= 1)\n arr2.push(i)\n end\n end\n arr2\nend", "def non_repeating_character(str)\n str.each_char do |char|\n return char if str.count(char) == 1\n end\nend", "def non_unique_letters(string)\n words = string.split(\"\")\n new_arr = []\n words.each do |char| \n if words.count(char) > 1 && char != \" \"\n new_arr << char\n end\n end \n new_arr.uniq.sort\nend", "def non_unique_letters(string)\n uniq_letters = string.chars.uniq\n uniq_letters.select { |ch| string.count(ch) > 1 }\nend", "def crunch(string)\n clean_string = ''\n string.each_char do |letter|\n clean_string << letter unless letter == clean_string[-1]\n end\n clean_string\nend", "def unique_chars(str) \n # split the string into an array\n # order the array\n # iterate through the array\n # if next iteration is same as previous point, then there are duplicates\n\n array_str = str.downcase.split(\"\").sort()\n last_char = nil\n\n array_str.each do |let|\n if (let == last_char)\n raise ArgumentError, \"string is not unique!\"\n else\n last_char = let\n end\n end\n\n puts \"String has all unique characters!\"\nend", "def decrypt(my_string)\n i = 0\n new_string = \"\"\n # chose to create a new string to return rather than modify the input\n # string by side effect\n \n until i == my_string.length\n if $alphabet.index(my_string[i]) == nil\n new_string += my_string[i]\n else\n new_string += $alphabet[$alphabet.index(my_string[i])-1]\n #wraps automatically from 0 to -1; don't need 3rd condition\n end\n i = i + 1\n end\n \n return new_string\nend", "def depunctuate(a_string)\n alphabet = [*\"A\"..\"Z\"] + [*\"a\"..\"z\"]\n result = \"\"\n a_string.length.times do |i|\n if alphabet.include?(a_string[i])\n result << a_string[i]\n end\n end\n result\nend", "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 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 repeating_letters?(str)\n dStr = str.downcase.chars\n checkStr = \"\"\n\n dStr.each do |char|\n if checkStr.index(char) != nil\n return true\n else\n checkStr += char\n end\n end\n false\nend", "def remove_repeated(string)\n last_letter = \"\"\n fixed_string_array = []\n string.split(\"\").each do |letter|\n if letter == last_letter\n fixed_string_array.pop\n else\n fixed_string_array.push(letter)\n end\n last_letter = letter\n end\n fixed_string_array.join(\"\")\nend", "def solution(string)\n result = \"\"\n string.each_char do |char|\n if char =~ /[A-Z]/\n result += \" #{char}\" \n else\n result += char\n end\n end\n result\nend", "def first_non_repeating_letter(str)\n return '' if str.empty? || str.chars.uniq.size <= str.size/2\n str.chars.each { |e| return e if str.downcase.count(e.downcase) == 1 }\nend", "def bad_decode(letter1, letter2, letter3)\n new1 = \"abcdefghijklmnopqrstuvwxyz\".index(letter1) - 1\n puts \"abcdefghijklmnopqrstuvwxyz\"[new1.to_i]\n new2 = \"abcdefghijklmnopqrstuvwxyz\".index(letter2) - 1\n puts \"abcdefghijklmnopqrstuvwxyz\"[new2.to_i]\n new3 = \"abcdefghijklmnopqrstuvwxyz\".index(letter3) - 1\n puts \"abcdefghijklmnopqrstuvwxyz\"[new3.to_i]\nend", "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 non_unique_letters(string)\n count_hash = Hash.new(0)\n string.chars.each do |letter|\n count_hash[letter] += 1 unless letter == \" \"\n end\n count_hash.select { |_letter, counts| counts > 1 }.keys.sort\nend", "def crunch(string)\n str_result = ''\n string.chars.each do |char|\n str_result << char unless char == str_result[-1]\n end\n str_result\nend" ]
[ "0.8343222", "0.819091", "0.77769184", "0.7709831", "0.76052773", "0.7605015", "0.7584002", "0.75720584", "0.7566565", "0.75613004", "0.74952155", "0.7481679", "0.746577", "0.7425209", "0.738644", "0.7382518", "0.73818976", "0.7340042", "0.7254415", "0.7247441", "0.7239824", "0.71941435", "0.7151782", "0.7136968", "0.70946056", "0.70408976", "0.7036644", "0.6982443", "0.6948157", "0.6821812", "0.6809454", "0.6803314", "0.68004906", "0.6719324", "0.67162085", "0.6715475", "0.6688656", "0.66513985", "0.6637127", "0.65405583", "0.6482394", "0.64633036", "0.6309993", "0.62772614", "0.624769", "0.622201", "0.61856717", "0.6173627", "0.6166464", "0.60956454", "0.6050903", "0.6036626", "0.6036481", "0.6029993", "0.60249066", "0.60036343", "0.5998945", "0.5989137", "0.5988776", "0.59278166", "0.59245855", "0.59242314", "0.589144", "0.58831596", "0.58568776", "0.58501315", "0.5834693", "0.58076096", "0.58019114", "0.58008003", "0.579922", "0.5793278", "0.5787586", "0.5780317", "0.5772843", "0.5757044", "0.57407475", "0.57387143", "0.57375246", "0.57338387", "0.57251704", "0.5714772", "0.57132804", "0.5700964", "0.5683854", "0.56749904", "0.5667722", "0.56519115", "0.56374335", "0.56285435", "0.5626694", "0.5626433", "0.56128263", "0.5597301", "0.55966055", "0.5590285", "0.5573827", "0.5570038", "0.5567536", "0.5567013" ]
0.75941455
6
GET /advertisements GET /advertisements.json
def index @advertisements = Advertisement.all respond_to do |format| format.html # index.html.erb format.json { render json: @advertisements } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def show\n respond_to do |format|\n format.html\n format.json { render json: { advertisements: @advertisements } }\n end\n end", "def index\n @advertisements = Advertisement.where(merchant_id: params[:merchant_id])\n\n render json: @advertisements\n end", "def index\n @advertisements = Advertisement.all\n end", "def index\n @advertisements = Advertisement.all\n end", "def index\n if (current_user && !current_user.advertiser?)\n @advertisements = Advertisement.find_recommendations_for(current_user)\n \n @advertisements += Advertisement.for_homepage(current_user).excluding_ids(@advertisements.collect(&:id))\n else\n @advertisements = Advertisement.for_homepage(current_user)\n end\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @advertisements }\n end\n end", "def index\n @advertisements = Advertisement.page(params[:page])\n end", "def index\n @advertises = Advertise.all\n render 'index', formats: 'json', handlers: 'jbuilder'\n end", "def index\n @advertisements = Advertisement.where(user: current_user).order(updated_at: :desc).with_attached_images\n\n respond_to do |format|\n format.html\n format.json { render json: { advertisements: @advertisements } }\n end\n end", "def index\n @manage_advertisements = ManageAdvertisement.all\n end", "def index\n @advertisements = Advertisement.all\n @advertisements = Advertisement.where(\"user_id = ?\", current_user.id)\n end", "def index\n @advertises = current_user.advertises.page(params[:page])\n respond_to do |format|\n format.html\n format.json\n end\n end", "def index\n @advertisers = Advertiser.all\n end", "def show\n render json: @advert\n end", "def index\n @ads = Ad.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @ads }\n end\n end", "def index\n @ads = Ad.all\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @ads }\n end\n end", "def index\n if current_user.try(:admin?)\n @advertisements = Advertisement.page(params[:page]).per(10).order(\"updated_at DESC\")\n else\n @advertisements = Advertisement.where(state: \"published\").page(params[:page]).per(10).order(\"updated_at DESC\")\n end\n end", "def index\n @announcements = Announcement.order(created_at: :desc).all\n render json: @announcements, each_serializer: AnnouncementsSerializer\n end", "def index\n @advertises = Advertise.all\n end", "def index\n @advertises = Advertise.all\n end", "def show\n @advertisement = Advertisement.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @advertisement }\n end\n end", "def index\n @leases = Lease.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @leases }\n end\n end", "def index\n @leads = Lead.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @leads }\n end\n end", "def index\n @appeals = @conference.appeals\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @appeals }\n end\n end", "def show\n @advertisment = Advertisment.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @advertisment }\n end\n end", "def index\n \n @advertises = Advertise.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @advertises }\n end\n end", "def index\n @leads = Lead.upcoming\n .includes(:updates, :agents, :agent)\n .order(created_at: :desc)\n .page(params[:page])\n .per(50)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @leads }\n end\n end", "def show\n @advocacy = Advocacy.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @advocacy }\n end\n end", "def index\n @adopters = Adopter.where(filtering_params)\n\n render json: @adopters\n end", "def index\n @admittings = Admitting.all\n render json: @admittings\n end", "def index\n @adversaires = Adversaire.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @adversaires }\n end\n end", "def index\n @announcements = Announcement.all\n\n respond_to do |format|\n format.html { render html: '200' }\n format.json { render 'announcements/index', announcements: @announcements, status: :ok }\n end\n end", "def new\n @advertise = Advertise.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @advertise }\n end\n end", "def index\n @banners = Banner.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @banners }\n end\n end", "def show\n render json: @adopter\n end", "def index\n @allocations = Allocation.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @allocations }\n end\n end", "def index\n if (params[:client_id])\n @engagements = Engagement.find_all_by_client_id(params[:client_id])\n else\n @engagements = Engagement.all\n end\n\n respond_with(@engagements)\n end", "def index\n @recommended_links = RecommendedLink.all\n\n render json: @recommended_links\n end", "def show\n @advert = Advert.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @advert }\n end\n end", "def index\n @advert = Advert.find(params[:advert_id])\n @bids = @advert.bids\n end", "def index\n @apartments = @building.apartments\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @apartments }\n end\n end", "def dresses\n render json: { collections: Collection.published_dresses }\n end", "def index\n @meals = Meal.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @meals }\n end\n end", "def index\n \n if params[:comapny_id].present?\n @advertisements = @user.advertisements.paginate(:page => params[:page], :per_page => 10)\n else\n @advertisements = current_user.advertisements.paginate(:page => params[:page], :per_page => 10)\n end\n \n end", "def index\n render json: Apartment.all\n end", "def show\n render json: @admitting\n end", "def index\n @adverts = Advert.all\n end", "def index\n @admin_agencies = Admin::Agency.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @admin_agencies }\n end\n end", "def index\n @deseases = Desease.order(:id)\n\n render json: @deseases\n end", "def index\n @arrangements = Arrangement.query_list(params[:auction_id], params[:accept_status])\n render json: @arrangements, status: 200\n end", "def meals\n get(\"/user/#{@user_id}/meals.json\")\n end", "def index\n @audiences = Audience.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @audiences }\n end\n end", "def show\n @announcement = Announcement.find(params[:id])\n render json:@announcement\n end", "def index\n @awards = Award.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @awards }\n end\n end", "def index\n @applicants = Applicant.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @applicants }\n end\n end", "def index\n respond_with Ad.all \n end", "def show\n advertisement = nil\n consumer_page_view = @consumer.crumbs.map{ |crumb| crumb.beacon_id }.uniq.sample\n if consumer_page_view\n @sem3.products_field( \"upc\", Beacon.find(consumer_page_view).first_party_data.sample )\n advertisement = @sem3.get_products\n end\n\n logger.debug \"Advertisement : #{advertisement}\"\n\n respond_to do |format|\n if advertisement\n format.html # show.html.erb\n format.json { render json: advertisement['results'].first }\n else\n format.html # show.html.erb\n format.json { render json: {\"status\" => \"error\"}, status: :not_found }\n end\n end\n end", "def index\n @announcements = Announcement.all\n render json: @announcements, include: [:member => {only: [:first_name, :last_name, :id]}]\n end", "def index\n respond_with(deals)\n end", "def index\n @ads = Ad.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @ads }\n format.json { render :json => @ads }\n end\n end", "def apayments\n\t\t@request = Request.find(params[:id])\n\t\trespond_to do |format|\n\t\t\tformat.html # show.html.erb\n\t\t\tformat.json {} # aPayments.json.jbuilder\n\t\tend\n\tend", "def adcreatives(options = {})\n\t\t\tself.id = self.id + \"/adcreatives\"\n\t\t\tread options\n\t\tend", "def index\n @advetisers = Advetiser.all\n end", "def index\n @sayings = Saying.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @sayings }\n end\n end", "def index\n announcements = Announcement.all\n if params[:category]\n announcements = announcements.where([\"game_category = ?\", params[:category]])\n end\n if params['sort']\n f = params['sort'].split(',').first\n field = f[0] == '-' ? f[1..-1] : f\n order = f[0] == '-' ? 'DESC' : 'ASC'\n if Announcement.new.has_attribute?(field)\n announcements = announcements.order(\"#{field} #{order}\")\n end\n end\n announcements = Announcement.page(params[:page] ? params[:page][:number] : 1)\n render json: announcements, meta: pagination_meta(announcements), include: ['user', 'pictures']\n end", "def show\n @advert = Advert.find(params[:id])\n @vcounter = ViewsCounter.counter('Advert', params[:id])\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @advert }\n end\n end", "def index\n client = find_client(request.headers[\"X-CLIENT-TOKEN\"], request.headers[\"X-CLIENT-EMAIL\"])\n @appointments = client.appointments.includes(:stylist).includes(:offerings).order(\"created_at DESC\")\n respond_to do |f|\n f.json {\n render :json => @appointments\n }\n end\n end", "def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @appeal }\n end\n end", "def index\n @adverts = Advert.paginate(:page => params[:page], :per_page => 10).order('id DESC').accessible_by(current_ability)\n end", "def index\n @items = Admin::Item.by_agency(@current_agency.id)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @admin_items }\n end\n end", "def index\n @advartisments = Advartisment.all\n end", "def index\n @alleys = Alley.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @alleys }\n end\n end", "def index\n @departments = Department.all\n respond_to do |format|\n format.json{ render json: @departments}\n end\n end", "def index\n @affiliates = Affiliate.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @affiliate }\n end\n end", "def index\n @allies = Ally.all\n end", "def index\n base_url = 'https://www.googleapis.com/books/v1/volumes?q=fiction&maxResults=20'\n and_key = '&key='\n key = ENV['GOOGLE_BOOKS_API_KEY'] \n googleurl = base_url + and_key + key\n\n response = RestClient.get(googleurl)\n @books = JSON.parse(response)\n\n respond_to do |format|\n format.html\n format.json { render json: @books }\n end\n\nend", "def index\n @announcements = Announcement.all\n end", "def index\n @announcements = Announcement.all\n end", "def show\n @advertise = Advertise.find(params[:id])\n authorize! :show, @advertise, :message => 'Acceso denegado.'\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @advertise }\n end\n end", "def index\n @space = Space.find(params[:space_id])\n @leases = Lease.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @leases }\n end\n end", "def ambassadors(params = {})\n self.class.get('/ambassador/all', params)\n end", "def index\n @offers = Offer.all\n\n render json: @offers\n end", "def index\n @diaries = current_user.diaries.all\n respond_to do |format|\n format.html {render :index}\n format.json { render json: @diaries }\n end\n end", "def bannerAll\n @links = Link.order(\"link asc\")\n respond_to do |format|\n format.html # bannerAll.html.erb\n format.json { render json: @link }\n end\n end", "def index\n @announcements = current_group.announcements.paginate(:page => params[:page],\n :per_page => params[:per_page],\n :order => \"updated_at desc\")\n\n @announcement = Announcement.new\n\n respond_to do |format|\n format.html # index.html.haml\n format.json { render :json => @announcements }\n end\n end", "def show\n @home_indices_ad = Home::Indices::Ad.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @home_indices_ad }\n end\n end", "def show\n @adv = Advantage.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @adv }\n end\n end", "def index\n @announcements = Announcement.all\n end", "def index\n @pending_recommended_links = PendingRecommendedLink.all\n\n render json: @pending_recommended_links\n end", "def index\n @banners = Banner.where('active =?', true).order(:display_order)\n\n render json: @banners\n end", "def index\n #product_categories\n @leads = Lead.all\n respond_to do |format|\n format.html { render :layout => 'layouts/admin' }# index.html.erb\n format.json { render json: @leads }\n end\n end", "def show\n render json: @banner\n end", "def index\n # Fetch all the categories the current user has preferred.\n @agencies = UsersAgency.preferrence_of current_user\n render template: 'api/v1/agencies/index', locals: { current_user: current_user }, status: :ok\n\n end", "def index\n @articles = Article.all\n\n respond_to do |format|\n format.json { render json: @articles }\n end\n end", "def index\n if @author_id\n @publications = @author.publications\n else\n @publications = Publication.all\n end\n render json: @publications\n end", "def index\n\n get_collections\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @deities }\n format.js {}\n end\n end", "def index\n @attendees = Attendees.all\n render json: @attendees\n end", "def index\n @adverts = @advert_class.all\n end", "def get_ads(params, headers={})\n url = \"#{@fqdn}#{SERVICE_URL}\"\n\n if params\n args = \"?\"\n params.each do |key, value|\n if value && !value.empty?\n args << \"&\" unless args.end_with? \"?\"\n args << \"#{CGI.escape(key.to_s)}=#{CGI.escape(value.to_s)}\"\n end\n end\n url << args\n end\n\n self.get(url, headers)\n end", "def index\n @adjs = Adj.all\n end" ]
[ "0.7671461", "0.7202624", "0.7116933", "0.7116933", "0.682151", "0.68149704", "0.67937994", "0.6704052", "0.6591452", "0.64982456", "0.6447812", "0.63391554", "0.6260698", "0.6211911", "0.61962545", "0.61804163", "0.6179664", "0.61773366", "0.61773366", "0.61765516", "0.614759", "0.61196196", "0.61189497", "0.60823125", "0.60777736", "0.6037879", "0.60307264", "0.5976852", "0.59647036", "0.5943156", "0.59256285", "0.59196985", "0.5916505", "0.59136504", "0.59101546", "0.5906301", "0.59003377", "0.58931303", "0.58920217", "0.58899385", "0.5840449", "0.58382034", "0.58246684", "0.5824375", "0.57877105", "0.5774203", "0.57674706", "0.5757085", "0.5755573", "0.5754063", "0.57438225", "0.5738219", "0.5732554", "0.5716424", "0.5714903", "0.57115805", "0.57081866", "0.5704556", "0.5703795", "0.5695585", "0.5693231", "0.56885576", "0.568493", "0.5672205", "0.56576157", "0.56542265", "0.5649767", "0.56478125", "0.56372076", "0.56341225", "0.5631571", "0.5617369", "0.56173337", "0.5612609", "0.56087893", "0.56075114", "0.56075114", "0.5606229", "0.560403", "0.5600687", "0.5598143", "0.55956274", "0.55698276", "0.5565884", "0.55635375", "0.55585265", "0.555459", "0.555419", "0.5551652", "0.5550429", "0.5546835", "0.5546493", "0.5541342", "0.55304617", "0.55296266", "0.5527686", "0.5522607", "0.5513203", "0.5512268" ]
0.7539251
2
GET /advertisements/1 GET /advertisements/1.json
def show advertisement = nil consumer_page_view = @consumer.crumbs.map{ |crumb| crumb.beacon_id }.uniq.sample if consumer_page_view @sem3.products_field( "upc", Beacon.find(consumer_page_view).first_party_data.sample ) advertisement = @sem3.get_products end logger.debug "Advertisement : #{advertisement}" respond_to do |format| if advertisement format.html # show.html.erb format.json { render json: advertisement['results'].first } else format.html # show.html.erb format.json { render json: {"status" => "error"}, status: :not_found } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def show\n respond_to do |format|\n format.html\n format.json { render json: { advertisements: @advertisements } }\n end\n end", "def index\n @advertisements = Advertisement.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @advertisements }\n end\n end", "def index\n @advertisements = Advertisement.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @advertisements }\n end\n end", "def index\n @advertisements = Advertisement.where(merchant_id: params[:merchant_id])\n\n render json: @advertisements\n end", "def index\n @advertisements = Advertisement.all\n end", "def index\n @advertisements = Advertisement.all\n end", "def index\n @advertises = Advertise.all\n render 'index', formats: 'json', handlers: 'jbuilder'\n end", "def index\n @advertisements = Advertisement.page(params[:page])\n end", "def index\n @advertisements = Advertisement.where(user: current_user).order(updated_at: :desc).with_attached_images\n\n respond_to do |format|\n format.html\n format.json { render json: { advertisements: @advertisements } }\n end\n end", "def show\n @advertisement = Advertisement.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @advertisement }\n end\n end", "def index\n if (current_user && !current_user.advertiser?)\n @advertisements = Advertisement.find_recommendations_for(current_user)\n \n @advertisements += Advertisement.for_homepage(current_user).excluding_ids(@advertisements.collect(&:id))\n else\n @advertisements = Advertisement.for_homepage(current_user)\n end\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @advertisements }\n end\n end", "def show\n render json: @advert\n end", "def index\n @advertises = current_user.advertises.page(params[:page])\n respond_to do |format|\n format.html\n format.json\n end\n end", "def new\n @advertise = Advertise.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @advertise }\n end\n end", "def show\n @advertisment = Advertisment.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @advertisment }\n end\n end", "def show\n @advert = Advert.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @advert }\n end\n end", "def show\n @advocacy = Advocacy.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @advocacy }\n end\n end", "def index\n @manage_advertisements = ManageAdvertisement.all\n end", "def index\n @advertisements = Advertisement.all\n @advertisements = Advertisement.where(\"user_id = ?\", current_user.id)\n end", "def show\n @advert = Advert.find(params[:id])\n @vcounter = ViewsCounter.counter('Advert', params[:id])\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @advert }\n end\n end", "def index\n @advertisers = Advertiser.all\n end", "def index\n @advertises = Advertise.all\n end", "def index\n @advertises = Advertise.all\n end", "def index\n @appeals = @conference.appeals\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @appeals }\n end\n end", "def index\n @ads = Ad.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @ads }\n end\n end", "def show\n render json: @adopter\n end", "def set_advertise\n @advertise = Advertise.find(params[:id])\n end", "def set_advertise\n @advertise = Advertise.find(params[:id])\n end", "def set_advertise\n @advertise = Advertise.find(params[:id])\n end", "def index\n @ads = Ad.all\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @ads }\n end\n end", "def index\n \n @advertises = Advertise.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @advertises }\n end\n end", "def show\n @advertise = Advertise.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @advertise }\n end\n end", "def index\n @leases = Lease.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @leases }\n end\n end", "def show\n @announcement = Announcement.find(params[:id])\n render json:@announcement\n end", "def index\n @advert1s = Advert1.all\n end", "def show\n @home_indices_ad = Home::Indices::Ad.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @home_indices_ad }\n end\n end", "def show\n @adv = Advantage.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @adv }\n end\n end", "def show\n @advertise = Advertise.find(params[:id])\n authorize! :show, @advertise, :message => 'Acceso denegado.'\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @advertise }\n end\n end", "def index\n if current_user.try(:admin?)\n @advertisements = Advertisement.page(params[:page]).per(10).order(\"updated_at DESC\")\n else\n @advertisements = Advertisement.where(state: \"published\").page(params[:page]).per(10).order(\"updated_at DESC\")\n end\n end", "def index\n @advert = Advert.find(params[:advert_id])\n @bids = @advert.bids\n end", "def new\n @advert = Advert.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @advert }\n end\n end", "def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @appeal }\n end\n end", "def new\n @advertisement = Advertisement.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @advertisement }\n end\n end", "def new\n @advertisement = Advertisement.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @advertisement }\n end\n end", "def new\n @advertisement = Advertisement.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @advertisement }\n end\n end", "def index\n @banners = Banner.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @banners }\n end\n end", "def show\n render json: @banner\n end", "def create\n @advertise = Advertise.new(advertise_params)\n\n respond_to do |format|\n if @advertise.save\n format.html { redirect_to @advertise, notice: 'Advertise was successfully created.' }\n format.json { render :show, status: :created, location: @advertise }\n else\n format.html { render :new }\n format.json { render json: @advertise.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n \n if params[:comapny_id].present?\n @advertisements = @user.advertisements.paginate(:page => params[:page], :per_page => 10)\n else\n @advertisements = current_user.advertisements.paginate(:page => params[:page], :per_page => 10)\n end\n \n end", "def show\n @lease = Lease.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @lease }\n end\n end", "def index\n @leads = Lead.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @leads }\n end\n end", "def create\n @advertise = Advertise.new(advertise_params)\n\n respond_to do |format|\n if @advertise.save\n format.html { redirect_to @advertise, notice: \"Advertise was successfully created.\" }\n format.json { render :show, status: :created, location: @advertise }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @advertise.errors, status: :unprocessable_entity }\n end\n end\n end", "def show\n @ad = Ad.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @ad }\n end\n end", "def show\n @ad = Ad.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @ad }\n end\n end", "def show\n @ad = Ad.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @ad }\n end\n end", "def index\n @applicants = Applicant.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @applicants }\n end\n end", "def new\n @advertisment = Advertisment.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @advertisment }\n end\n end", "def new\n\n \n @advert = Advert.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @advert }\n \n end\n end", "def index\n @adopters = Adopter.where(filtering_params)\n\n render json: @adopters\n end", "def index\n @adversaires = Adversaire.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @adversaires }\n end\n end", "def index\n @meals = Meal.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @meals }\n end\n end", "def index\n @adverts = Advert.all\n end", "def show\n @purchasing_ad = PurchasingAd.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @purchasing_ad }\n end\n end", "def show\n @advertisement = Advertisement.where(id: params[:id]).last\n end", "def index\n @announcements = Announcement.order(created_at: :desc).all\n render json: @announcements, each_serializer: AnnouncementsSerializer\n end", "def show\n render json: @admitting\n end", "def index\n @announcements = Announcement.all\n\n respond_to do |format|\n format.html { render html: '200' }\n format.json { render 'announcements/index', announcements: @announcements, status: :ok }\n end\n end", "def index\n render json: Apartment.all\n end", "def index\n @affiliates = Affiliate.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @affiliate }\n end\n end", "def show\n @announce = Announce.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @announce }\n end\n end", "def show\n @announce = Announce.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @announce }\n end\n end", "def new\n # @advertisement = Advertisement.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @advertisement }\n end\n end", "def advertise\n begin\n render params[:id]\n rescue ActionView::MissingTemplate\n render :file => \"#{Rails.root}/public/advertise\", :layout => false, :status => :not_found\n end\n end", "def index\n @allocations = Allocation.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @allocations }\n end\n end", "def show\n @audience = Audience.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @audience }\n end\n end", "def index\n @items = Admin::Item.by_agency(@current_agency.id)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @admin_items }\n end\n end", "def index\n @audiences = Audience.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @audiences }\n end\n end", "def index\n @apartments = @building.apartments\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @apartments }\n end\n end", "def index\n id = params[:id].to_i\n\n if id != 0\n \t @agencies = @agencies.paginate(page: params[:page], per_page: 10).order(:name).find_all_by_id(id)\n if @agencies.any?\n @agency_name = @agencies.first.name\n end\n else\n \t @agencies = @agencies.paginate(page: params[:page], per_page: 10).order(:name).find(:all)\n end\n\n\t\t@records_returned = @agencies.count\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @agencies }\n end\n end", "def index\n @recommended_links = RecommendedLink.all\n\n render json: @recommended_links\n end", "def show\n @agencies = Agency.find(params[:id])\n\n if @agencies \n respond_to do |format|\n format.json { render :json => @agencies }\n format.xml { render :xml => @agencies }\n end \n else\n head :not_found\n end\n end", "def index\n @admittings = Admitting.all\n render json: @admittings\n end", "def index\n @deseases = Desease.order(:id)\n\n render json: @deseases\n end", "def index\n @leads = Lead.upcoming\n .includes(:updates, :agents, :agent)\n .order(created_at: :desc)\n .page(params[:page])\n .per(50)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @leads }\n end\n end", "def index\n @ads = Ad.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @ads }\n format.json { render :json => @ads }\n end\n end", "def index\n @admin_agencies = Admin::Agency.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @admin_agencies }\n end\n end", "def index\n if (params[:client_id])\n @engagements = Engagement.find_all_by_client_id(params[:client_id])\n else\n @engagements = Engagement.all\n end\n\n respond_with(@engagements)\n end", "def index\n base_url = 'https://www.googleapis.com/books/v1/volumes?q=fiction&maxResults=20'\n and_key = '&key='\n key = ENV['GOOGLE_BOOKS_API_KEY'] \n googleurl = base_url + and_key + key\n\n response = RestClient.get(googleurl)\n @books = JSON.parse(response)\n\n respond_to do |format|\n format.html\n format.json { render json: @books }\n end\n\nend", "def show\n @avert = Avert.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @avert }\n end\n end", "def meals\n get(\"/user/#{@user_id}/meals.json\")\n end", "def show\n @advertisement = Advertisement.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @advertisement }\n end\n end", "def index\n @adverts = Advert.paginate(:page => params[:page], :per_page => 10).order('id DESC').accessible_by(current_ability)\n end", "def show\n @admin_agency = Admin::Agency.where(:id => params[:id]).includes(:pages)[0]\n \n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @admin_agency }\n end\n end", "def show\n @adversaire = Adversaire.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @adversaire }\n end\n end", "def show\n render json: @diet, status: 200, root: true\n end", "def index\n respond_with(deals)\n end", "def show\n render json: Alien.find(params[\"id\"])\n end", "def show\n @drip = Drip.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @drip }\n end\n end", "def show\n @agencies = Agency.find(params[:id])\n\n if @agencies \n respond_to do |format|\n format.json { render :json => @agencies }\n format.xml { render :xml => @agencies }\n end \n else\n head :not_found\n end\n end", "def index\n @announcements = Announcement.visible.where(locale: I18n.locale || 'en').paginate(:page => params[:page], :per_page => 10)\n \n @announcements.first.increase_views unless @announcements.empty?\n\n @title = \"News\"\n\n logger.debug @announcement.inspect\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @announcements }\n end\n end" ]
[ "0.7674561", "0.73763406", "0.73763406", "0.70393205", "0.6935458", "0.6935458", "0.6715051", "0.66931844", "0.661896", "0.65987253", "0.6579459", "0.6576351", "0.6520924", "0.64730126", "0.6456537", "0.6437107", "0.6414039", "0.63672954", "0.6350185", "0.6329816", "0.62910706", "0.6195661", "0.6195661", "0.6146519", "0.6130526", "0.6123469", "0.61093086", "0.61093086", "0.61093086", "0.61040705", "0.60902965", "0.60875684", "0.60871315", "0.60646176", "0.6040619", "0.60162556", "0.60087746", "0.59909", "0.5988957", "0.5966967", "0.5954628", "0.5948181", "0.59264445", "0.59264445", "0.59264445", "0.5918679", "0.59114337", "0.5894861", "0.5894716", "0.5887158", "0.5852197", "0.5852025", "0.58360463", "0.58360463", "0.58360463", "0.5833711", "0.58213615", "0.58181715", "0.5804684", "0.5803391", "0.5798714", "0.57976747", "0.57923895", "0.5790824", "0.5777168", "0.57744294", "0.57614803", "0.57579875", "0.57424104", "0.57330245", "0.57330245", "0.5732714", "0.572536", "0.5724776", "0.5716566", "0.5704923", "0.5700367", "0.5698311", "0.5685604", "0.56829685", "0.5678777", "0.5674756", "0.5664418", "0.5663894", "0.5643093", "0.56378293", "0.5629681", "0.5629472", "0.56292945", "0.5626632", "0.56242424", "0.56185484", "0.5613441", "0.5608964", "0.5608297", "0.55847925", "0.5582871", "0.5580945", "0.55790067", "0.5577697" ]
0.60796714
33
GET /advertisements/new GET /advertisements/new.json
def new @advertisement = Advertisement.new respond_to do |format| format.html # new.html.erb format.json { render json: @advertisement } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def new\n @advertise = Advertise.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @advertise }\n end\n end", "def new\n @advert = Advert.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @advert }\n end\n end", "def new\n @advertisment = Advertisment.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @advertisment }\n end\n end", "def new\n # @advertisement = Advertisement.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @advertisement }\n end\n end", "def new\n @lease = Lease.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @lease }\n end\n end", "def new\n\n \n @advert = Advert.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @advert }\n \n end\n end", "def new\n @advocacy = Advocacy.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @advocacy }\n end\n end", "def apnew\n @advicepost = Advicepost.find(params[:id])\n\n respond_to do |format|\n format.html # apnew.html.erb\n format.json { render json: @advicepost }\n end\n end", "def new\n @ad = Ad.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @ad }\n end\n end", "def new\n @ad = Ad.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @ad }\n end\n end", "def create\n @advertise = Advertise.new(advertise_params)\n\n respond_to do |format|\n if @advertise.save\n format.html { redirect_to @advertise, notice: 'Advertise was successfully created.' }\n format.json { render :show, status: :created, location: @advertise }\n else\n format.html { render :new }\n format.json { render json: @advertise.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @announcement = Announcement.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @announcement }\n end\n end", "def create\n @advertise = Advertise.new(advertise_params)\n\n respond_to do |format|\n if @advertise.save\n format.html { redirect_to @advertise, notice: \"Advertise was successfully created.\" }\n format.json { render :show, status: :created, location: @advertise }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @advertise.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @adv = Advantage.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @adv }\n end\n end", "def new\n @announce = Announce.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @announce }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @agency }\n end\n end", "def new\n @new_policy = NewPolicy.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @new_policy }\n end\n end", "def new\n @award = Award.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @award }\n end\n end", "def new\n @award = Award.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @award }\n end\n end", "def new\n @advertise = Advertise.new\n @result = nil\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @advertise }\n end\n end", "def new\n @appeal = Appeal.new\n @appeal.build_topic\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @appeal }\n end\n end", "def new\n @arrival = Arrival.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @arrival }\n end\n end", "def new\n @arrival = Arrival.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @arrival }\n end\n end", "def new\n @news_agency = NewsAgency.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @news_agency }\n end\n end", "def new\n @publication = Publication.new\n @publication.url ||= 'http://www.'\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @publication }\n end\n end", "def new\n @meal = Meal.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @meal }\n end\n end", "def new\n @meal = Meal.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @meal }\n end\n end", "def new\n @party = Party.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @party }\n end\n end", "def new\n @publication = Publication.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @publication }\n end\n end", "def new\n @wadl = Wadl.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @wadl }\n end\n end", "def new\n @addre = Addre.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @addre }\n end\n end", "def new\n @publisher = Publisher.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @publisher }\n end\n end", "def new\n @create_classified_ad = CreateClassifiedAd.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @create_classified_ad }\n end\n end", "def new\n @audience = Audience.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @audience }\n end\n end", "def new\n @representante_athlete = Representante::Athlete.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @representante_athlete }\n end\n end", "def new\n @meal = Meal.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @meal }\n end\n end", "def new\n @getadvice = Getadvice.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @getadvice }\n end\n end", "def new\n @ad_type = AdType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @ad_type }\n end\n end", "def new_lead\n @lead = Lead.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @lead }\n end\n end", "def new\n @drip = Drip.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @drip }\n end\n end", "def new\n @publisher = Publisher.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @publisher }\n end\n end", "def new\n @creative = Creative.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @creative }\n end\n end", "def create\n @advertisement = Advertisement.new(params[:advertisement])\n\n respond_to do |format|\n if @advertisement.save\n format.html { redirect_to @advertisement, notice: 'Advertisement was successfully created.' }\n format.json { render json: @advertisement, status: :created, location: @advertisement }\n else\n format.html { render action: \"new\" }\n format.json { render json: @advertisement.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @engagement = Engagement.new\n @clients = Client.all\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @engagement }\n end\n end", "def new\n @applicant = Applicant.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @applicant }\n end\n end", "def new\n @lease = Lease.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @lease }\n end\n end", "def new\n @avert = Avert.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @avert }\n end\n end", "def new\n @applicant = Applicant.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @applicant }\n end\n end", "def new\n @applicant = Applicant.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @applicant }\n end\n end", "def new\n @lead = Lead.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @lead }\n end\n end", "def new\n @auction = Auction.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @auction }\n end\n end", "def new\n @holding = Holding.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @holding }\n end\n end", "def new\n @holding = Holding.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @holding }\n end\n end", "def new\n @ad_tag = AdTag.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @ad_tag }\n end\n end", "def new\n @banner = Banner.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @banner }\n end\n end", "def new\n @banner = Banner.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @banner }\n end\n end", "def new\n @atr = Atr.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @atr }\n end\n end", "def create\n @advertisment = Advertisment.new(params[:advertisment])\n\n respond_to do |format|\n if @advertisment.save\n format.html { redirect_to @advertisment, notice: 'Advertisment was successfully created.' }\n format.json { render json: @advertisment, status: :created, location: @advertisment }\n else\n format.html { render action: \"new\" }\n format.json { render json: @advertisment.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @anchoring = Anchoring.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @anchoring }\n end\n end", "def new\n @nlp = Nlp.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @nlp }\n end\n end", "def create\n @advert = Advert.new(params[:advert])\n\n respond_to do |format|\n if @advert.save\n format.html { redirect_to @advert, notice: 'Advert was successfully created.' }\n format.json { render json: @advert, status: :created, location: @advert }\n else\n format.html { render action: \"new\" }\n format.json { render json: @advert.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @applicant = Applicant.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @applicant }\n end\n end", "def new\n @allocation = Allocation.new params[:allocation]\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @allocation }\n end\n end", "def new\n @law = Law.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @law }\n end\n end", "def new\n @assay = Assay.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @assay }\n end\n end", "def new\n @anniversary = Anniversary.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @anniversary }\n end\n end", "def new\n @advert = Advert.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @advert }\n end\n end", "def new\n @advert = Advert.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @advert }\n end\n end", "def new\n @pagenate = Pagenate.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @pagenate }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @alley }\n end\n end", "def create\n @advertisement = Advertisement.new(advertisement_params)\n if @advertisement.save\n redirect_to advertisements_path\n else\n render :new\n end\n end", "def new\n @fiction = Fiction.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @fiction }\n end\n end", "def new\n @ped = Ped.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @ped }\n end\n end", "def new\n @adotando_animal = AdotandoAnimal.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @adotando_animal }\n end\n end", "def new\n @anrede = Anrede.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @anrede }\n end\n end", "def new\n @articleurl = Articleurl.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @articleurl }\n end\n end", "def new\n @saying = Saying.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @saying }\n end\n end", "def new\n @papel = Papel.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @papel }\n end\n end", "def new\n @affiliate_link = AffiliateLink.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @affiliate_link }\n end\n end", "def new\n @purchasing_ad = PurchasingAd.new\n @categories = Category.all\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @purchasing_ad }\n end\n end", "def new\n @home_indices_ad = Home::Indices::Ad.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @home_indices_ad }\n end\n end", "def new\n @announce_c = AnnounceC.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @announce_c }\n end\n end", "def new\n @apprentice = Apprentice.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @apprentice }\n end\n end", "def new\n @borrower = Borrower.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @borrower }\n end\n end", "def new\n @borrower = Borrower.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @borrower }\n end\n end", "def new\n @aadt = Aadt.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @aadt }\n end\n end", "def new\n @passage = Passage.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @passage }\n end\n end", "def create\n # @advertisement = Advertisement.new(params[:advertisement])\n respond_to do |format|\n if @advertisement.save\n format.html { redirect_to @advertisement, notice: 'Advertisement was successfully created.' }\n format.json { render json: @advertisement, status: :created, location: @advertisement }\n else\n format.html { render action: \"new\", notice: 'Advertisement was NOT successfully created.' }\n format.json { render json: @advertisement.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @badge = Badge.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @badge }\n end\n end", "def new\n @agency_type = AgencyType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @agency_type }\n end\n end", "def new\n @aspirant = Aspirant.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @aspirant }\n end\n end", "def new\n @amendment = Amendment.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @amendment }\n end\n end", "def new\n \n @title = \"availabilities/new\"\n @availability = Availability.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @availability }\n end\n end", "def new\n @supplies_loan = SuppliesLoan.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @supplies_loan }\n end\n end", "def new\n authenticate_user!\n @auction = Auction.new\n\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @auction }\n end\n end", "def new\n @offer = Offer.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @offer }\n end\n end", "def new\n @offer = Offer.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @offer }\n end\n end", "def new\n @offer = Offer.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @offer }\n end\n end" ]
[ "0.76206595", "0.7297989", "0.72325534", "0.71533144", "0.7111669", "0.7000442", "0.69535595", "0.6822083", "0.6812474", "0.6812474", "0.6793023", "0.6746201", "0.6719198", "0.67072266", "0.6700006", "0.6695936", "0.66890997", "0.6650996", "0.6650996", "0.66219807", "0.66046166", "0.659885", "0.659885", "0.6594782", "0.6590307", "0.6586876", "0.6586876", "0.65705293", "0.65636873", "0.655934", "0.65545106", "0.6547377", "0.6547114", "0.6536746", "0.65287054", "0.6528547", "0.6527352", "0.65107703", "0.65000415", "0.6497114", "0.6494654", "0.649359", "0.6490748", "0.6486711", "0.64834404", "0.64833903", "0.64828676", "0.64821136", "0.64821136", "0.64801365", "0.6466945", "0.6459918", "0.6459918", "0.6453998", "0.6450306", "0.6450306", "0.64476454", "0.6429155", "0.64174575", "0.64139163", "0.6413405", "0.64102674", "0.6406738", "0.6405128", "0.6402743", "0.639167", "0.6389637", "0.6389637", "0.6384708", "0.63835424", "0.63832283", "0.63811964", "0.63810337", "0.63802224", "0.6373983", "0.63719624", "0.6371614", "0.63712126", "0.6369321", "0.6368829", "0.6367749", "0.6366185", "0.63648975", "0.6354887", "0.6354887", "0.6352868", "0.6352079", "0.63502395", "0.63482416", "0.63476306", "0.63420075", "0.63409865", "0.63399416", "0.6339752", "0.63385326", "0.6337561", "0.6337561", "0.6337561" ]
0.72619087
4
POST /advertisements POST /advertisements.json
def create @advertisement = Advertisement.new(params[:advertisement]) respond_to do |format| if @advertisement.save format.html { redirect_to @advertisement, notice: 'Advertisement was successfully created.' } format.json { render json: @advertisement, status: :created, location: @advertisement } else format.html { render action: "new" } format.json { render json: @advertisement.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create\n @advertise = Advertise.new(advertise_params)\n\n respond_to do |format|\n if @advertise.save\n format.html { redirect_to @advertise, notice: 'Advertise was successfully created.' }\n format.json { render :show, status: :created, location: @advertise }\n else\n format.html { render :new }\n format.json { render json: @advertise.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @advertise = Advertise.new(advertise_params)\n\n respond_to do |format|\n if @advertise.save\n format.html { redirect_to @advertise, notice: \"Advertise was successfully created.\" }\n format.json { render :show, status: :created, location: @advertise }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @advertise.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @advertisement = current_user.advertisements.build(advertisement_params)\n @advertisement.state = \"waiting\"\n\n respond_to do |format|\n if @advertisement.save\n format.html { redirect_to @advertisement, notice: 'Advertisement was successfully created.' }\n format.json { render :show, status: :created, location: @advertisement }\n else\n format.html { render :new }\n format.json { render json: @advertisement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @advertisement = current_user.ads.new(advertisement_params)\n\n respond_to do |format|\n if @advertisement.save\n format.html { redirect_to app_advertisements_url, notice: 'Advertisement was successfully created.' }\n format.json { render :show, status: :created, location: @advertisement }\n else\n format.html { render :new }\n format.json { render json: @advertisement.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @advertisements = Advertisement.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @advertisements }\n end\n end", "def index\n @advertisements = Advertisement.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @advertisements }\n end\n end", "def create\n # @advertisement = Advertisement.new(params[:advertisement])\n respond_to do |format|\n if @advertisement.save\n format.html { redirect_to @advertisement, notice: 'Advertisement was successfully created.' }\n format.json { render json: @advertisement, status: :created, location: @advertisement }\n else\n format.html { render action: \"new\", notice: 'Advertisement was NOT successfully created.' }\n format.json { render json: @advertisement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @advertisement = current_user.advertisements.new(advertisement_params)\n @advertisement.status = INACTIVE\n respond_to do |format|\n if @advertisement.save\n \n format.html { redirect_to @advertisement, notice: 'Advertisement was successfully created.' }\n format.json { render :show, status: :created, location: @advertisement }\n message = \"Heyy new advertisement: #{@advertisement.title} is added by #{current_user.user_profile.name}\"\n User.get_customer_dealer(message)\n else\n format.html { render :new }\n format.json { render json: @advertisement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @advertisment = Advertisment.new(params[:advertisment])\n\n respond_to do |format|\n if @advertisment.save\n format.html { redirect_to @advertisment, notice: 'Advertisment was successfully created.' }\n format.json { render json: @advertisment, status: :created, location: @advertisment }\n else\n format.html { render action: \"new\" }\n format.json { render json: @advertisment.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @advert = Advert.new(params[:advert])\n\n respond_to do |format|\n if @advert.save\n format.html { redirect_to @advert, notice: 'Advert was successfully created.' }\n format.json { render json: @advert, status: :created, location: @advert }\n else\n format.html { render action: \"new\" }\n format.json { render json: @advert.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @advert = Advert.new(advert_params)\n\n respond_to do |format|\n if @advert.save\n format.html { redirect_to @advert, notice: 'Advert was successfully created.' }\n format.json { render :show, status: :created, location: @advert }\n else\n format.html { render :new }\n format.json { render json: @advert.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @advertise = Advertise.new(params[:advertise])\n authorize! :create, @advertise, :message => 'Acceso denegado.'\n respond_to do |format|\n if @advertise.save\n format.html { redirect_to @advertise, notice: t(\"activerecord.alerts.advertise.created\") }\n format.json { render json: @advertise, status: :created, location: @advertise }\n else\n format.html { render action: \"new\" }\n format.json { render json: @advertise.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @advertisements = Advertisement.all\n end", "def index\n @advertisements = Advertisement.all\n end", "def create\n @advertisement = Advertisement.new(advertisement_params)\n if @advertisement.save\n redirect_to advertisements_path\n else\n render :new\n end\n end", "def show\n respond_to do |format|\n format.html\n format.json { render json: { advertisements: @advertisements } }\n end\n end", "def create\n @adopter = Adopter.new(adopter_params)\n\n if @adopter.save\n render json: @adopter, status: :created, location: @adopter\n else\n render json: @adopter.errors, status: :unprocessable_entity\n end\n end", "def create\n @article = Article.new(article_params)\n\n json_parse = JSON.parse(@article.advertisement)\n ad_hash = json_parse.map { |data|\n ApplicationController.helpers.a8_parse(data)\n }\n ad_hash_json = ActiveSupport::JSON.encode(ad_hash)\n @article[:advertisement] = ad_hash_json\n\n respond_to do |format|\n if @article.save\n format.html { redirect_to @article, notice: 'Article was successfully created.' }\n format.json { render :show, status: :created, location: @article }\n else\n format.html { render :new }\n format.json { render json: @article.errors, status: :unprocessable_entity }\n end\n end\n end", "def advertise_params\n params.require(:advertise).permit(:title, :description,\n :show_for_days, :cost,\n :size, :category_id, :tag_list)\n end", "def create\n @advertisement = Advertisement.new(advertisement_params)\n\n respond_to do |format|\n if @advertisement.save\n format.html { redirect_to events_pictures_step_1_path(:advertisement_id => @advertisement.id), notice: 'Advertisement was successfully created.' }\n format.json { render :show, status: :created, location: @advertisement }\n else\n format.html { render :new }\n format.json { render json: @advertisement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @advert = Advert.new(advert_params)\n\n respond_to do |format|\n if @advert.save\n format.html { redirect_to [:admin, @advert], notice: 'Advert was successfully created.' }\n format.json { render action: 'show', status: :created, location: @advert }\n else\n format.html { render action: 'new' }\n format.json { render json: @advert.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @manage_advertisement = ManageAdvertisement.new(manage_advertisement_params)\n\n respond_to do |format|\n if @manage_advertisement.save\n format.html { redirect_to @manage_advertisement, notice: 'Manage advertisement was successfully created.' }\n format.json { render action: 'show', status: :created, location: @manage_advertisement }\n else\n format.html { render action: 'new' }\n format.json { render json: @manage_advertisement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @advert = @advert_class.new(params[:advert])\n\n respond_to do |format|\n if @advert.save\n format.html { redirect_to @advert, notice: 'Advert was successfully created.' }\n format.json { render json: @advert, status: :created, location: @advert }\n else\n format.html { render action: \"new\" }\n format.json { render json: @advert.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @admin_advertisement = Advertisement.new(admin_advertisement_params)\n @admin_advertisement.admin_id = current_admin.id\n respond_to do |format|\n if @admin_advertisement.save\n format.html { redirect_to admin_advertisements_path, notice: 'Advertisement was successfully created.' }\n format.json { render :show, status: :created, location: @admin_advertisement }\n else\n format.html { render :new }\n format.json { render json: @admin_advertisement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @advertisement = Advertisement.new(advertisement_params)\n @advertisement.user = current_user\n respond_to do |format|\n if @advertisement.save\n format.html { redirect_to @advertisement, notice: 'Advertisement was successfully created.' }\n format.json { render :show, status: :created, location: @advertisement }\n else\n format.html { render :new }\n format.json { render json: @advertisement.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @advertise = Advertise.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @advertise }\n end\n end", "def create\n @advocacy = Advocacy.new(params[:advocacy])\n\n respond_to do |format|\n if @advocacy.save\n format.html { redirect_to @advocacy, notice: 'Advocacy was successfully created.' }\n format.json { render json: @advocacy, status: :created, location: @advocacy }\n else\n format.html { render action: \"new\" }\n format.json { render json: @advocacy.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @advertisements = Advertisement.where(merchant_id: params[:merchant_id])\n\n render json: @advertisements\n end", "def create\n advertisement = params[:advertisement]\n advertisement[\"ad_type\"] = \"video\"\n advertisement[\"user_id\"] = current_user.id\n\n if advertisement[\"content_link\"].start_with? \"http\", \"www\"\n advertisement[\"content_link\"].match /[?|&]v=([^&]*)/\n advertisement[\"content_link\"] = $1\n end\n\n @advertisement = Advertisement.new(advertisement)\n\n respond_to do |format|\n if @advertisement.save\n format.html { redirect_to my_advertisements_path, notice: 'Advertisement was successfully created.' }\n format.json { render json: @advertisement, status: :created, location: @advertisement }\n else\n format.html { render action: \"new\" }\n format.json { render json: @advertisement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @adj = Adj.new(adj_params)\n\n respond_to do |format|\n if @adj.save\n format.html { redirect_to @adj, notice: 'Adj was successfully created.' }\n format.json { render :show, status: :created, location: @adj }\n else\n format.html { render :new }\n format.json { render json: @adj.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @award = Award.new(award_params)\n respond_to do |format|\n if @award.save\n a_data = JSON.parse params[:json_string]\n a_data.each do |a|\n @item = get_new_award_item(@award, a) unless a.nil?\n end\n AwardMailer.approval_request(@award)\n if current_user.admin\n format.html { redirect_to patient_path(@award.patient), notice: 'Award was successfully created.' }\n else\n format.html { redirect_to new_patient_path, notice: 'Award was successfully created.' }\n end\n format.json { render :show, status: :created, location: @award }\n else\n format.html { render :new }\n format.json { render json: @award.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @advetiser = Advetiser.new(advetiser_params)\n\n respond_to do |format|\n if @advetiser.save\n format.html { redirect_to @advetiser, notice: 'Advetiser was successfully created.' }\n format.json { render :show, status: :created, location: @advetiser }\n else\n format.html { render :new }\n format.json { render json: @advetiser.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @advert1 = Advert1.new(advert1_params)\n\n respond_to do |format|\n if @advert1.save\n format.html { redirect_to @advert1, notice: 'Advert1 was successfully created.' }\n format.json { render :show, status: :created, location: @advert1 }\n else\n format.html { render :new }\n format.json { render json: @advert1.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @advert = Advert.new(params[:advert])\n\n respond_to do |format|\n if @advert.save\n format.html { redirect_to(admin_adverts_path, :notice => 'Advert was successfully created.') }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @advert.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @advertiser = Advertiser.new(params[:advertiser])\n\n respond_to do |format|\n if @advertiser.save\n flash[:notice] = 'Advertiser was successfully created.'\n format.html { redirect_to advertiser_url(@advertiser) }\n format.xml { head :created, :location => advertiser_url(@advertiser) }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @advertiser.errors.to_xml }\n end\n end\n end", "def create\n @advert = Advert.new(advert_params)\n @advert.user_id = current_user.id\n\n respond_to do |format|\n if @advert.save\n format.html { redirect_to @advert, notice: 'Advert was successfully created.' }\n format.json { render :show, status: :created, location: @advert }\n else\n format.html { render :new }\n format.json { render json: @advert.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @advertisements = Advertisement.page(params[:page])\n end", "def advertisement_params\n params.require(:advertisement).permit(:title, :description, :web_url, :start_date, :end_date, {images: []})\n end", "def create\n @agency = Agency.new(agency_params)\n\n if @agency.save\n render json: @agency, status: :created, location: @agency\n else\n render json: @agency.errors, status: :unprocessable_entity\n end\n end", "def create\n @advertisement = Advertisement.new(advertisement_params)\n # @advertisement.images.attach(params[:advertisement][:images])\n respond_to do |format|\n if @advertisement.save\n format.html { redirect_to @advertisement, notice: 'Ad was successfully created.' }\n format.json { render :show, status: :created, location: @advertisement }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @advertisement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @advertise = Advertise.new(advertise_params)\n @advertise.user = current_user\n\n respond_to do |format|\n if @advertise.save\n\n Log.create(:logable => @advertise, :user => current_user,\n :msg => _(\"new advertise \\#%{id} created\") % {:id => @advertise.id, asdasD: \"Asd\"})\n\n format.html { redirect_to target_url || @advertise, notice: 'Advertise was successfully created.' }\n format.json { render action: 'show', status: :created, location: @advertise }\n else\n @categories = Category.all\n format.html { render action: 'new' }\n format.json { render json: @advertise.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @advertise = Advertise.new(params[:advertise])\n @advertise.business_name = params[:advertise][:business_name].join(\",\") unless params[:advertise][:business_name].blank?\n respond_to do |format|\n if @advertise.save\n format.html { redirect_to(@advertise, :notice => 'Advertise was successfully created.') }\n format.xml { render :xml => @advertise, :status => :created, :location => @advertise }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @advertise.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n ActiveRecord::Base.transaction do\n @advertisement = Advertisement.new(advertisement_params)\n status = @advertisement.save\n @advertisement.main_image = params[:advertisement][:main_image] if params[:advertisement][:main_image].present?\n @advertisement.alternate_images = params[:advertisement][:alternative_images] if params[:advertisement][:alternative_images].present?\n end\n respond_to do |format|\n if status\n format.html { redirect_to \"/\", notice: 'Advertisement was successfully created.' }\n format.json { render :show, status: :created, location: @advertisement }\n else\n format.html { render :new }\n format.json { render json: @advertisement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @advert = Advert.new(advert_params)\n @advert.user = current_user\n @advert.views = 0\n respond_to do |format|\n if @advert.save\n format.html { redirect_to @advert, notice: 'Advert was successfully created.' }\n format.json { render :show, status: :created, location: @advert }\n else\n format.html { render :new }\n format.json { render json: @advert.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @manage_advertisements = ManageAdvertisement.all\n end", "def index\n if (current_user && !current_user.advertiser?)\n @advertisements = Advertisement.find_recommendations_for(current_user)\n \n @advertisements += Advertisement.for_homepage(current_user).excluding_ids(@advertisements.collect(&:id))\n else\n @advertisements = Advertisement.for_homepage(current_user)\n end\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @advertisements }\n end\n end", "def create\n @home_indices_ad = Home::Indices::Ad.new(params[:home_indices_ad])\n\n respond_to do |format|\n if @home_indices_ad.save\n format.html { redirect_to @home_indices_ad, notice: 'Ad was successfully created.' }\n format.json { render json: @home_indices_ad, status: :created, location: @home_indices_ad }\n else\n format.html { render action: \"new\" }\n format.json { render json: @home_indices_ad.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @announcement = Announcement.new(permitted_params)\n\n respond_to do |format|\n if @announcement.save\n format.html { redirect_to announcements_path, notice: 'Announcement was successfully created.' }\n format.json { render action: 'show', status: :created, location: @announcement }\n else\n format.html { render action: 'new' }\n format.json { render json: @announcement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @ad = Ad.new(ad_params)\n\n if @ad.save\n render :show, status: :created, location: @ad\n else\n render json: @ad.errors, status: :unprocessable_entity\n end\n end", "def create\n @ad = current_advertiser.ads.new(params[:ad])\n respond_to do |format|\n if @ad.save\n format.html { redirect_to(@ad, :notice => 'Ad was successfully created.') }\n format.xml { render :xml => @ad, :status => :created, :location => @ad }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @ad.errors, :status => :unprocessable_entity }\n end\n end\n end", "def advert_params\n params.require(:advert).permit(:title, :description, :image, :tag_list)\n end", "def advertisement_params\n params.require(:advertisement).permit(:title, :content, :price, :category_id)\n end", "def create\n @ad = Ad.new(ad_params)\n\n respond_to do |format|\n if @ad.save\n format.html { redirect_to @ad, notice: 'Ad was successfully created.' }\n format.json { render :show, status: :created, location: @ad }\n else\n format.html { render :new }\n format.json { render json: @ad.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @advertises = Advertise.all\n render 'index', formats: 'json', handlers: 'jbuilder'\n end", "def create\n @advert = Advert.new(advert_params)\n @advert.user_id = session[:user_id]\n @advert.status = 1\n\n respond_to do |format|\n if @advert.save\n format.html { redirect_to @advert, notice: 'Объявление успешно обновлено.' }\n format.json { render action: 'show', status: :created, location: @advert }\n else\n format.html { render action: 'new' }\n format.json { render json: @advert.errors, status: :unprocessable_entity }\n end\n end\n end", "def postEntityAdvertiserCreate( entity_id, tags, locations, max_tags, max_locations, expiry_date, is_national, language, reseller_ref, reseller_agent_id, publisher_id)\n params = Hash.new\n params['entity_id'] = entity_id\n params['tags'] = tags\n params['locations'] = locations\n params['max_tags'] = max_tags\n params['max_locations'] = max_locations\n params['expiry_date'] = expiry_date\n params['is_national'] = is_national\n params['language'] = language\n params['reseller_ref'] = reseller_ref\n params['reseller_agent_id'] = reseller_agent_id\n params['publisher_id'] = publisher_id\n return doCurl(\"post\",\"/entity/advertiser/create\",params)\n end", "def create\n @announcement = Announcement.new(announcement_params)\n\n respond_to do |format|\n if @announcement.save\n format.html { render html: '200' }\n format.json { render 'announcements/announcement', status: :created, announcement: @announcement }\n else\n format.html { render html: '500', status: :unprocessable_entity }\n format.json { render json: @announcement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @ad = Ad.new(params[:ad])\n\n respond_to do |format|\n if @ad.save\n format.html { redirect_to @ad, notice: 'Ad was successfully created.' }\n format.json { render json: @ad, status: :created, location: @ad }\n else\n format.html { render action: \"new\" }\n format.json { render json: @ad.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @adv = Advantage.new(params[:advantage])\n\n respond_to do |format|\n if @adv.save\n format.html { redirect_to administration_advantages_path, notice: 'Advantage was successfully created.' }\n format.json { render json: @adv, status: :created, location: @adv }\n else\n format.html { render action: \"new\" }\n format.json { render json: @adv.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @ad_holder = AdHolder.new(ad_holder_params)\n\n respond_to do |format|\n if @ad_holder.save\n format.html { redirect_to @ad_holder, notice: 'Ad holder was successfully created.' }\n format.json { render :show, status: :created, location: @ad_holder }\n else\n format.html { render :new }\n format.json { render json: @ad_holder.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @advertisement = Advertisement.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @advertisement }\n end\n end", "def new\n @advertisement = Advertisement.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @advertisement }\n end\n end", "def new\n @advertisement = Advertisement.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @advertisement }\n end\n end", "def advertisement_params\n params.require(:advertisement).permit(:advertisement_id, :title, :body, :image1, :delivery_date)\n end", "def advert_params\n params.require(:advert).permit(:price, :adress, :agent_id, :toilet_count, :salon_count)\n end", "def advertisement_params\n params.require(:advertisement).permit(:title, :category, :dollar_value, :expiry_date, :merchant_id)\n end", "def create\n @agency = Agency.new(agency_params)\n\n if @agency.save\n render json: @agency, status: :created, location: @agency\n else\n render json: @agency.errors, status: :unprocessable_entity\n end\n end", "def create\n @ad_banner = AdBanner.new(ad_banner_params)\n\n respond_to do |format|\n if @ad_banner.save\n format.html { redirect_to @ad_banner, notice: 'Ad banner was successfully created.' }\n format.json { render action: 'show', status: :created, location: @ad_banner }\n else\n format.html { render action: 'new' }\n format.json { render json: @ad_banner.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\n @advertiser = Advertiser.new(advertiser_params)\n @advertiser.create_address(address_params)\n @advertiser.user = current_user\n\n respond_to do |format|\n if @advertiser.save\n format.html { redirect_to @advertiser, notice: 'Advertiser was successfully created.' }\n format.json { render json: @advertiser.to_json }\n else\n format.html { render :new }\n format.json { render json: @advertiser.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @advert3 = Advert3.new(advert3_params)\n\n respond_to do |format|\n if @advert3.save\n format.html { redirect_to @advert3, notice: 'Advert3 was successfully created.' }\n format.json { render :show, status: :created, location: @advert3 }\n else\n format.html { render :new }\n format.json { render json: @advert3.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @ad = current_user.ads.new(ad_params)\n\n respond_to do |format|\n if @ad.save\n format.html { redirect_to @ad, notice: 'Ad was successfully created.' }\n format.json { render :show, status: :created, location: @ad }\n else\n format.html { render :new }\n format.json { render json: @ad.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_advertise\n @advertise = Advertise.find(params[:id])\n end", "def set_advertise\n @advertise = Advertise.find(params[:id])\n end", "def set_advertise\n @advertise = Advertise.find(params[:id])\n end", "def create\n @announcement = Announcement.new(params[:announcement])\n\n respond_to do |format|\n if @announcement.save\n format.html { redirect_to @announcement, notice: 'Announcement was successfully created.' }\n format.json { render json: @announcement, status: :created, location: @announcement }\n else\n format.html { render action: \"new\" }\n format.json { render json: @announcement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @admin_advertise = Admin::Advertise.new(admin_advertise_params)\n\n respond_to do |format|\n @admin_advertise.on_status_true = true if params[:admin_advertise][:status] == \"true\"\n if @admin_advertise.save\n unless params[:admin_advertise][:image].blank?\n preloaded = Cloudinary::Uploader.upload(params[:admin_advertise][:image], :use_filename => true, :public_id => \"advertises/#{@admin_advertise.id}\")\n end\n format.html { redirect_to admin_advertises_path, notice: 'Advertise was successfully created.' }\n format.json { render action: 'show', status: :created, location: @admin_advertise }\n else\n format.html { render action: 'new' }\n format.json { render json: @admin_advertise.errors, status: :unprocessable_entity }\n end\n end\n end", "def advert_params\n params.require(:advert).permit(:title, :description, :status, :user_id, images: [])\n end", "def create\n @adviser = Adviser.new(adviser_params)\n\n respond_to do |format|\n if @adviser.save\n format.html { redirect_to @adviser, notice: 'Adviser was successfully created.' }\n format.json { render :show, status: :created, location: @adviser }\n else\n format.html { render :new }\n format.json { render json: @adviser.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n render json: Beverage.create!(beverage_post_params), status: :created\n end", "def create\n @admitting = Admitting.new(admitting_params)\n\n if @admitting.save\n render json: @admitting, status: :created, location: @admitting\n else\n render json: @admitting.errors, status: :unprocessable_entity\n end\n end", "def index\n @advertisements = Advertisement.where(user: current_user).order(updated_at: :desc).with_attached_images\n\n respond_to do |format|\n format.html\n format.json { render json: { advertisements: @advertisements } }\n end\n end", "def create\n @arrondissement = Arrondissement.new(arrondissement_params)\n\n respond_to do |format|\n if @arrondissement.save\n format.html { redirect_to arrondissements_path, notice: 'Arrondissement was successfully created.' }\n format.json { render :show, status: :created, location: @arrondissement }\n else\n format.html { render :new }\n format.json { render json: @arrondissement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n fix_tokenized_input_params\n @ad = @org.ads.build(ad_params)\n\n respond_to do |format|\n if @ad.save\n format.html { redirect_to [@ad.org, @ad], notice: 'Ad was successfully created.' }\n format.json { render :show, status: :created, location: [@ad.org, @ad] }\n else\n format.html { render :new }\n format.json { render json: @ad.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @advertisement_campaign = AdvertisementCampaign.new(advertisement_campaign_params)\n\n respond_to do |format|\n if @advertisement_campaign.save\n format.html { redirect_to @advertisement_campaign, notice: 'Advertisement campaign was successfully created.' }\n format.json { render action: 'show', status: :created, location: @advertisement_campaign }\n else\n format.html { render action: 'new' }\n format.json { render json: @advertisement_campaign.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @advertise.update(advertise_params)\n format.html { redirect_to @advertise, notice: \"Advertise was successfully updated.\" }\n format.json { render :show, status: :ok, location: @advertise }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @advertise.errors, status: :unprocessable_entity }\n end\n end\n end", "def advertisement_params\n params.require(:advertisement).permit(:category_id,:active,:title, :price, :make, :description, :kilometers, :year, :condition, :phone_number, :body_type, :color, :transition_type, :regional_specs, :no_of_cylinders, :doors, :horse_power, :warrenty, :fuel_type, :extras, :technical_features, :locate_your_item, :gps_coordinate)\n end", "def new\n @advertisment = Advertisment.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @advertisment }\n end\n end", "def advertisement_params\n params.require(:advertisement).permit(:titulo, :descricao, :preco, :visualizacao, {imagens: []}, :remove_imagens, :category_id)\n end", "def new\n @advert = Advert.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @advert }\n end\n end", "def advertise_params\n params.require(:advertises).permit(:title, :picture,:description,:package,:state,:time,:type)\n end", "def create\n @advise = Advise.new(advise_params)\n\n respond_to do |format|\n if @advise.save\n format.html { redirect_to @advise, notice: 'Advise was successfully created.' }\n format.json { render :show, status: :created, location: @advise }\n else\n format.html { render :new }\n format.json { render json: @advise.errors, status: :unprocessable_entity }\n end\n end\n end", "def advertisement_params\n params.require(:advertisement).permit(:event_id, :advertisement_name, :advertisement_date, :advertisement_time, :contact_email, :location, :contact_person, :description, :remove_advertisement_date, :display_main_page, :advertisement_start_time, :use_form_button, :which_form, :download_link, :share_download, :use_contact, :recurring_day, :recurring_on, :advertisement, :internal_link_url, :internal_link, :no_expiry, :template_selected, :full_advertisement, :advertisement_type, :force_on_main_page, :enable_disable_ad, :scheduled_when, :schedule, :next_occurence, :options, :slug, :create_own_page)\n end", "def create\n @advertisement = Advertisement.new(params[:advertisement])\n \n @advertisement.uploaded_file = params[:advertisement][:image]\n @advertisement.event_id_id = params[:advertisement][:event_id_id]\n @advertisement.link = params[:advertisement][:link]\n\n respond_to do |format|\n if @advertisement.save\n format.html { redirect_to @advertisement, notice: 'Advertisement was successfully created.' }\n format.json { render json: @advertisement, status: :created, location: @advertisement }\n else\n format.html { render action: \"new\" }\n format.json { render json: @advertisement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @advertisment = Advertisment.new(advertisment_params)\n @advertisment.user_id = current_user.id\n @advertisment.brand_id = params[:brand_id]\n @advertisment.variant_id = params[:varientid]\n respond_to do |format|\n if @advertisment.save\n format.html { redirect_to @advertisment, notice: 'Advertisment was successfully created.' }\n format.json { render :show, status: :created, location: @advertisment }\n else\n format.html { render :new }\n format.json { render json: @advertisment.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @adscripcion = Adscripcion.new(adscripcion_params)\n\n respond_to do |format|\n if @adscripcion.save\n format.html { redirect_to @adscripcion, notice: 'Adscripcion was successfully created.' }\n format.json { render :show, status: :created, location: @adscripcion }\n else\n format.html { render :new }\n format.json { render json: @adscripcion.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n # @advertisement = Advertisement.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @advertisement }\n end\n end", "def create\n passenger = Passenger.new(:name => params[:name], :contact_number => params[:contact_number], :nationality => params[:nationality], :meal_pref => params[:meal_pref])\n passenger.save\n render :json => passenger\n end", "def create\n @appeal = Appeal.new(params[:appeal])\n @appeal.conference = @conference\n\n respond_to do |format|\n if @appeal.save\n format.html { redirect_to [@conference, @appeal], notice: 'Appeal was successfully created.' }\n format.json { render json: @appeal, status: :created, location: @appeal }\n else\n format.html { render layout: \"application_no_nav\",action: \"new\" }\n format.json { render json: @appeal.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @advert_category = AdvertCategory.new(advert_category_params)\n @advert_category.advert_id = params[:advert_id]\n\n respond_to do |format|\n if @advert_category.save\n AddAdvertCategory.new(@advert_category.id).update_params\n format.html { redirect_to :back, notice: 'success' }\n else\n format.html { redirect_to :back, notice: 'error' }\n end\n end\n end", "def index\n @advertisements = Advertisement.all\n @advertisements = Advertisement.where(\"user_id = ?\", current_user.id)\n end" ]
[ "0.68848366", "0.6881313", "0.64537203", "0.6451686", "0.64215386", "0.64215386", "0.63332886", "0.6313317", "0.62875354", "0.6259814", "0.6251439", "0.62460595", "0.62224966", "0.62224966", "0.6218263", "0.6211225", "0.6134877", "0.60934216", "0.6089346", "0.60785955", "0.6075532", "0.6012748", "0.59928167", "0.59633535", "0.5953705", "0.5933243", "0.5911825", "0.5886737", "0.58722717", "0.5843873", "0.5812581", "0.5809207", "0.5808177", "0.5789761", "0.57790434", "0.5751177", "0.57446706", "0.5697896", "0.56820786", "0.5681685", "0.5669214", "0.5668795", "0.5650659", "0.56503546", "0.564343", "0.56299984", "0.561961", "0.56089425", "0.55783904", "0.5577467", "0.55702126", "0.556812", "0.5563943", "0.55629367", "0.5537066", "0.5533336", "0.55307025", "0.5527469", "0.5522128", "0.55199647", "0.54960614", "0.54960614", "0.54960614", "0.5489094", "0.5487664", "0.54875714", "0.548246", "0.547703", "0.5471832", "0.5463322", "0.5461333", "0.54613", "0.54613", "0.54613", "0.5455542", "0.5450128", "0.5439825", "0.5438716", "0.542676", "0.5423035", "0.54206514", "0.54185885", "0.54023874", "0.54014957", "0.5394774", "0.53945476", "0.53939635", "0.5392763", "0.5391888", "0.5391229", "0.536393", "0.5363654", "0.536298", "0.5360926", "0.535644", "0.53550506", "0.53519094", "0.535031", "0.534524", "0.5342709" ]
0.6430163
4
PUT /advertisements/1 PUT /advertisements/1.json
def update @advertisement = Advertisement.find(params[:id]) respond_to do |format| if @advertisement.update_attributes(params[:advertisement]) format.html { redirect_to @advertisement, notice: 'Advertisement was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @advertisement.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update\n respond_to do |format|\n if @advertise.update(advertise_params)\n format.html { redirect_to @advertise, notice: \"Advertise was successfully updated.\" }\n format.json { render :show, status: :ok, location: @advertise }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @advertise.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @advertise.update(advertise_params)\n format.html { redirect_to @advertise, notice: 'Advertise was successfully updated.' }\n format.json { render :show, status: :ok, location: @advertise }\n else\n format.html { render :edit }\n format.json { render json: @advertise.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @admin_advertise.update(admin_advertise_params)\n format.html { redirect_to @admin_advertise, notice: 'Advertise was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @admin_advertise.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @advertise = Advertise.find(params[:id])\n authorize! :update, @advertise, :message => 'Acceso denegado.'\n campusAdvertise = Advertise.find(params[:advertise_id][:campus_ids]) rescue []\n @advertise.campuses=campusAdvertise\n respond_to do |format|\n if @advertise.update_attributes(params[:advertise])\n format.html { redirect_to @advertise, notice: t(\"activerecord.alerts.advertise.updated\") }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @advertise.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @advertise = Advertise.find(params[:id]) \n respond_to do |format|\n if @advertise.update_attributes(params[:advertise])\n format.html { redirect_to(@advertise, :notice => 'Advertise was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @advertise.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n authorize! :update, @advertisement\n respond_to do |format|\n if @advertisement.update(advertisement_params)\n format.html { redirect_to app_advertisements_url, notice: 'Advertisement was successfully updated.' }\n format.json { render :show, status: :ok, location: @advertisement }\n else\n format.html { render :edit }\n format.json { render json: @advertisement.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @advertisement.update_attributes(params[:advertisement])\n format.html { redirect_to my_advertisements_path, notice: 'Advertisement was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @advertisement.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_advertise\n @advertise = Advertise.find(params[:id])\n end", "def set_advertise\n @advertise = Advertise.find(params[:id])\n end", "def set_advertise\n @advertise = Advertise.find(params[:id])\n end", "def update\n respond_to do |format|\n if @advert1.update(advert1_params)\n format.html { redirect_to @advert1, notice: 'Advert1 was successfully updated.' }\n format.json { render :show, status: :ok, location: @advert1 }\n else\n format.html { render :edit }\n format.json { render json: @advert1.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @agency = Agency.find(params[:id])\n\n if @agency.update(agency_params)\n #head :no_content\n render json: @agency, status: :accepted, location: @agency #sera? status accepted? \n else\n render json: @agency.errors, status: :unprocessable_entity\n end\n end", "def create\n @advertise = Advertise.new(advertise_params)\n\n respond_to do |format|\n if @advertise.save\n format.html { redirect_to @advertise, notice: \"Advertise was successfully created.\" }\n format.json { render :show, status: :created, location: @advertise }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @advertise.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @advert.update(advert_params)\n format.html { redirect_to @advert, notice: 'Advert was successfully updated.' }\n format.json { render :show, status: :ok, location: @advert }\n else\n format.html { render :edit }\n format.json { render json: @advert.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @advert.update(advert_params)\n format.html { redirect_to @advert, notice: 'Advert was successfully updated.' }\n format.json { render :show, status: :ok, location: @advert }\n else\n format.html { render :edit }\n format.json { render json: @advert.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @advert.update(advert_params)\n format.html { redirect_to @advert, notice: 'Advert was successfully updated.' }\n format.json { render :show, status: :ok, location: @advert }\n else\n format.html { render :edit }\n format.json { render json: @advert.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @advertise = Advertise.new(advertise_params)\n\n respond_to do |format|\n if @advertise.save\n format.html { redirect_to @advertise, notice: 'Advertise was successfully created.' }\n format.json { render :show, status: :created, location: @advertise }\n else\n format.html { render :new }\n format.json { render json: @advertise.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n render json: Alien.update(params[\"id\"], params[\"alien\"])\n end", "def update\n @advert = Advert.find(params[:id])\n\n respond_to do |format|\n if @advert.update_attributes(params[:advert])\n format.html { redirect_to @advert, notice: 'Advert was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @advert.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @agency = Agency.find(params[:id])\n\n if @agency.update(agency_params)\n #head :no_content\n render json: @agency, status: :accepted, location: @agency #sera? status accepted? \n else\n render json: @agency.errors, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @advertisement.update(advertisement_params)\n format.html { redirect_to advertisements_path, notice: 'Advertisement was successfully updated.' }\n format.json { render :show, status: :ok, location: @advertisement }\n else\n format.html { render :edit }\n format.json { render json: @advertisement.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n # @advertisement = Advertisement.find(params[:id])\n respond_to do |format|\n if @advertisement.update_attributes(params[:advertisement])\n format.html { redirect_to @advertisement, notice: 'Advertisement was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @advertisement.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @advertisement.state = \"published\"\n respond_to do |format|\n if @advertisement.save\n format.html { redirect_to @advertisement, notice: 'Advertisement was successfully updated.' }\n format.json { render :show, status: :ok, location: @advertisement }\n else\n format.html { render :edit }\n format.json { render json: @advertisement.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @advert.update(advert_params)\n format.html { redirect_to [:admin, @advert], notice: 'Advert was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @advert.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @admin_advertisement.update(admin_advertisement_params)\n format.html { redirect_to admin_advertisements_path, notice: 'Advertisement was successfully updated.' }\n format.json { render :show, status: :ok, location: @admin_advertisement }\n else\n format.html { render :edit }\n format.json { render json: @admin_advertisement.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @advertiser = Advertiser.find(params[:id])\n\n respond_to do |format|\n if @advertiser.update_attributes(params[:advertiser])\n flash[:success] = 'Create successfully'\n format.html { redirect_to @advertiser }\n else\n format.html { render :action => \"edit\" }\n end\n end\n end", "def update\n respond_to do |format|\n if @advertise.user == current_user\n\n if @advertise.update(advertise_params)\n Log.create(:logable => @advertise, :user => current_user,\n :msg => _(\"\\#%{id} advertise updated\") % {:id => @advertise.id})\n #:changes => @advertise.changes))\n\n format.html { redirect_to target_url || @advertise, notice: 'Advertise was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @advertise.errors, status: :unprocessable_entity }\n end\n else\n return forbidden\n end\n end\n end", "def update\n respond_to do |format|\n if @advert.update(advert_params)\n format.html { redirect_to @advert, notice: 'Объявление успешно обновлено.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @advert.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @adopter = Adopter.find(params[:id])\n\n if @adopter.update(adopter_params)\n head :no_content\n else\n render json: @adopter.errors, status: :unprocessable_entity\n end\n end", "def update\n @announcement = Announcement.find(params[:id])\n @announcement.title = params[:title]\n @announcement.description = params[:description]\n @announcement.price = params[:price]\n @announcement.photo = params[:photo]\n @announcement.latitude = params[:latitude]\n @announcement.longitude = params[:longitude]\n @announcement.subcategory_id = params[:subcategory_id]\n @announcement.place = params[:place]\n @announcement.save\n render json:@announcement\n end", "def update\n @advert = @advert_class.find(params[:id])\n\n respond_to do |format|\n if @advert.update_attributes(params[:advert])\n format.html { redirect_to @advert, notice: 'Advert was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @advert.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @advertisement.update(advertisement_params)\n format.html { redirect_to @advertisement, notice: 'Ad was successfully updated.' }\n format.json { render :show, status: :ok, location: @advertisement }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @advertisement.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @advertisement.update(advertisement_params)\n format.html { redirect_to @advertisement, notice: 'Advertisement was successfully updated.' }\n format.json { render :show, status: :ok, location: @advertisement }\n else\n format.html { render :edit }\n format.json { render json: @advertisement.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @advertisement.update(advertisement_params)\n format.html { redirect_to @advertisement, notice: 'Advertisement was successfully updated.' }\n format.json { render :show, status: :ok, location: @advertisement }\n else\n format.html { render :edit }\n format.json { render json: @advertisement.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n json_parse = JSON.parse(@article.advertisement)\n ad_hash = json_parse.map { |data|\n ApplicationController.helpers.a8_parse(data)\n }\n ad_hash_json = ActiveSupport::JSON.encode(ad_hash)\n\n regist_article_params = article_params\n regist_article_params[:advertisement] = ad_hash_json\n\n respond_to do |format|\n if @article.update(regist_article_params)\n format.html { redirect_to @article, notice: 'Article was successfully updated.' }\n format.json { render :show, status: :ok, location: @article }\n else\n format.html { render :edit }\n format.json { render json: @article.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @advertisment = Advertisment.find(params[:id])\n\n respond_to do |format|\n if @advertisment.update_attributes(params[:advertisment])\n format.html { redirect_to @advertisment, notice: 'Advertisment was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @advertisment.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_advertisement\n @advertisement = current_user.company.advertisements.find(params[:id])\n end", "def update\n @advocacy = Advocacy.find(params[:id])\n\n respond_to do |format|\n if @advocacy.update_attributes(params[:advocacy])\n format.html { redirect_to @advocacy, notice: 'Advocacy was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @advocacy.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @advertisment.update(advertisment_params)\n format.html { redirect_to @advertisment, notice: 'Advertisment was successfully updated.' }\n format.json { render :show, status: :ok, location: @advertisment }\n else\n format.html { render :edit }\n format.json { render json: @advertisment.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_advertisement\n @advertisement = Advertisement.find(params[:id])\n end", "def set_advertisement\n @advertisement = Advertisement.find(params[:id])\n end", "def set_advertisement\n @advertisement = Advertisement.find(params[:id])\n end", "def set_advertisement\n @advertisement = Advertisement.find(params[:id])\n end", "def set_advertisement\n @advertisement = Advertisement.find(params[:id])\n end", "def set_advertisement\n @advertisement = Advertisement.find(params[:id])\n end", "def set_advertisement\n @advertisement = Advertisement.find(params[:id])\n end", "def set_advertisement\n @advertisement = Advertisement.find(params[:id])\n end", "def create\n @advert = Advert.new(advert_params)\n @advert.user = current_user\n @advert.views = 0\n respond_to do |format|\n if @advert.save\n format.html { redirect_to @advert, notice: 'Advert was successfully created.' }\n format.json { render :show, status: :created, location: @advert }\n else\n format.html { render :new }\n format.json { render json: @advert.errors, status: :unprocessable_entity }\n end\n end\n end", "def offer\n @offer = @host.offers.find(params[:id])\n @offer.update(offer_params) if request.put?\n redirect_to offers_host_path if request.put?\n end", "def update\n @advert = Advert.find(params[:id])\n\n respond_to do |format|\n if @advert.update_attributes(params[:advert])\n flash[:notice] = 'Advert was successfully updated.'\n format.html { redirect_to('/adverts') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @advert.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @advert = Advert.find(params[:id])\n\n respond_to do |format|\n if @advert.update_attributes(params[:advert])\n format.html { redirect_to(admin_adverts_path, :notice => 'Advert was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @advert.errors, :status => :unprocessable_entity }\n end\n end\n end", "def show\n respond_to do |format|\n format.html\n format.json { render json: { advertisements: @advertisements } }\n end\n end", "def update\n apartment = Apartment.find(params[:id])\n apartment.update_attributes(apartment_params)\n render json: apartment\n end", "def update\n @announcement = Announcement.find(params[:id])\n\n if @announcement.update(announcement_params)\n head :no_content\n else\n render json: @announcement.errors, status: :unprocessable_entity\n end\n end", "def set_advert\n @advert = Advert.find(params[:id])\n end", "def set_advert\n @advert = Advert.find(params[:id])\n end", "def set_advert1\n @advert1 = Advert1.find(params[:id])\n end", "def add_aos_version(args = {}) \n post(\"/aosversions.json/\", args)\nend", "def update\n respond_to do |format|\n if @advert3.update(advert3_params)\n format.html { redirect_to @advert3, notice: 'Advert3 was successfully updated.' }\n format.json { render :show, status: :ok, location: @advert3 }\n else\n format.html { render :edit }\n format.json { render json: @advert3.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @advertiser = Advertiser.find(params[:id])\n\n respond_to do |format|\n if @advertiser.update_attributes(params[:advertiser])\n flash[:notice] = 'Advertiser was successfully updated.'\n format.html { redirect_to advertiser_url(@advertiser) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @advertiser.errors.to_xml }\n end\n end\n end", "def update\n @home_indices_ad = Home::Indices::Ad.find(params[:id])\n\n respond_to do |format|\n if @home_indices_ad.update_attributes(params[:home_indices_ad])\n format.html { redirect_to @home_indices_ad, notice: 'Ad was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @home_indices_ad.errors, status: :unprocessable_entity }\n end\n end\n end", "def advertise_params\n params.require(:advertise).permit(:title, :description,\n :show_for_days, :cost,\n :size, :category_id, :tag_list)\n end", "def update\n respond_to do |format|\n if @manage_advertisement.update(manage_advertisement_params)\n format.html { redirect_to @manage_advertisement, notice: 'Manage advertisement was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @manage_advertisement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @advert = Advert.new(advert_params)\n @advert.user_id = session[:user_id]\n @advert.status = 1\n\n respond_to do |format|\n if @advert.save\n format.html { redirect_to @advert, notice: 'Объявление успешно обновлено.' }\n format.json { render action: 'show', status: :created, location: @advert }\n else\n format.html { render action: 'new' }\n format.json { render json: @advert.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @advertisement = Advertisement.find(params[:id])\n\n respond_to do |format|\n if @advertisement.update_attributes(params[:advertisement])\n flash[:notice] = 'Advertisement was successfully updated.'\n format.html { redirect_to(@advertisement) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @advertisement.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @advert1 = Advert1.new(advert1_params)\n\n respond_to do |format|\n if @advert1.save\n format.html { redirect_to @advert1, notice: 'Advert1 was successfully created.' }\n format.json { render :show, status: :created, location: @advert1 }\n else\n format.html { render :new }\n format.json { render json: @advert1.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @adv = Advantage.find(params[:id])\n\n respond_to do |format|\n if @adv.update_attributes(params[:advantage])\n format.html { redirect_to @adv, notice: 'Advantage was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @adv.errors, status: :unprocessable_entity }\n end\n end\n end", "def update!(params)\n res = @client.put(path, nil, params, \"Content-Type\" => \"application/json\")\n @attributes = res.json if res.status == 201\n res\n end", "def create\n @advert = Advert.new(params[:advert])\n\n respond_to do |format|\n if @advert.save\n format.html { redirect_to @advert, notice: 'Advert was successfully created.' }\n format.json { render json: @advert, status: :created, location: @advert }\n else\n format.html { render action: \"new\" }\n format.json { render json: @advert.errors, status: :unprocessable_entity }\n end\n end\n end", "def update options={}\n client.put(\"/#{id}\", options)\n end", "def update_aos_version(args = {}) \n id = args['id']\n temp_path = \"/aosversions.json/{aosVersionId}\"\n path = temp_path\nargs.keys.each do |key|\n if (key == \"aosversionId\")\n args.delete(key)\n path = temp_path.gsub(\"{#{key}}\", id)\n end\nend\n puts \" PATH : #{path}\"\n put(path, args)\nend", "def set_admin_advertise\n @admin_advertise = Admin::Advertise.find(params[:id])\n end", "def create\n @advertisement = current_user.advertisements.build(advertisement_params)\n @advertisement.state = \"waiting\"\n\n respond_to do |format|\n if @advertisement.save\n format.html { redirect_to @advertisement, notice: 'Advertisement was successfully created.' }\n format.json { render :show, status: :created, location: @advertisement }\n else\n format.html { render :new }\n format.json { render json: @advertisement.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_advert\n @advert = Advert.find(params[:id])\n end", "def set_advert\n @advert = Advert.find(params[:id])\n end", "def set_advert\n @advert = Advert.find(params[:id])\n end", "def set_advert\n @advert = Advert.find(params[:id])\n end", "def set_advert\n @advert = Advert.find(params[:id])\n end", "def set_advert\n @advert = Advert.find(params[:id])\n end", "def set_advert\n @advert = Advert.find(params[:id])\n end", "def update\n if @diet.update(diet_params)\n head :no_content, status: 204\n else\n render json: @diet.errors, status: 422\n end\n end", "def index\n @advertisements = Advertisement.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @advertisements }\n end\n end", "def index\n @advertisements = Advertisement.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @advertisements }\n end\n end", "def update\n @ad = Ad.friendly.find(params[:id])\n\n respond_to do |format|\n if @ad.update(ad_params)\n format.html { redirect_to @ad, notice: \"Ad was successfully updated.\" }\n format.json { render :show, status: :ok, location: @ad }\n else\n format.html { render :edit }\n format.json { render json: @ad.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_advocate\n @advocate = Advocate.find(params[:id])\n end", "def set_advertisment\n @advertisment = Advertisment.find(params[:id])\n end", "def update\n if @ad.update(ad_params)\n render :show, status: :ok, location: @ad\n else\n render json: @ad.errors, status: :unprocessable_entity\n end\n end", "def update\n ingredient.update(ingredient_params)\n render json: ingredient\n end", "def update\n respond_to do |format|\n if @advertiser.update(advertiser_params)\n @advertiser.address.update(address_params)\n format.html { redirect_to @advertiser, notice: 'Advertiser was successfully updated.' }\n format.json { render :show, status: :ok, location: @advertiser }\n else\n format.html { render :edit }\n format.json { render json: @advertiser.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @api_v1_initiative.update(api_v1_initiative_params)\n format.html { redirect_to @api_v1_initiative, notice: 'Initiative was successfully updated.' }\n format.json { render :show, status: :ok, location: @api_v1_initiative }\n else\n format.html { render :edit }\n format.json { render json: @api_v1_initiative.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @advert = Advert.new(advert_params)\n\n respond_to do |format|\n if @advert.save\n format.html { redirect_to @advert, notice: 'Advert was successfully created.' }\n format.json { render :show, status: :created, location: @advert }\n else\n format.html { render :new }\n format.json { render json: @advert.errors, status: :unprocessable_entity }\n end\n end\n end", "def update(url, data)\n RestClient.put url, data, :content_type => :json\nend", "def create\n @advert = Advert.new(advert_params)\n\n respond_to do |format|\n if @advert.save\n format.html { redirect_to [:admin, @advert], notice: 'Advert was successfully created.' }\n format.json { render action: 'show', status: :created, location: @advert }\n else\n format.html { render action: 'new' }\n format.json { render json: @advert.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @animal.update(animal_params)\n respond_with(@shelter)\n end", "def update\n respond_to do |format|\n if @ad_banner.update(ad_banner_params)\n format.html { redirect_to @ad_banner, notice: 'Ad banner was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @ad_banner.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_deal(id, params)\n put(\"deals/#{id}\", deal: params)\n end", "def update\n respond_to do |format|\n if @offering.update(offering_params)\n format.html { redirect_to @offering, notice: 'La oferta de servicio ha sido actualizada correctamente.' }\n format.json { render :show, status: :ok, location: @offering }\n else\n format.html { render :edit }\n format.json { render json: @offering.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @agency.update(agency_params)\n format.html { redirect_to @agency, notice: \"Agency was successfully updated.\" }\n format.json { render :show, status: :ok, location: @agency }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @agency.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @client = Client.find(params[:id])\n @uuid = params[:uuid]\n respond_to do |format|\n if @client.update_attributes(params[:client])\n format.html { redirect_to :controller => 'ads', :action => 'admin_dash', :id => 1, :uuid => @uuid, notice: 'Client was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @client.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_advertiser\n @advertiser = Advertiser.find(params[:id])\n end" ]
[ "0.6978973", "0.692015", "0.6558807", "0.64093983", "0.6406906", "0.618249", "0.61492044", "0.6126311", "0.6126311", "0.6126311", "0.6111755", "0.6104872", "0.6038145", "0.6035168", "0.6035168", "0.6035168", "0.60293984", "0.5999683", "0.59949195", "0.599381", "0.5955715", "0.5920339", "0.5918264", "0.5913248", "0.58957", "0.58926105", "0.58923644", "0.58548236", "0.58506954", "0.5844034", "0.583406", "0.5820757", "0.58168626", "0.58168626", "0.5745543", "0.57353354", "0.5703132", "0.570182", "0.5650335", "0.5644927", "0.5644927", "0.5644927", "0.5644927", "0.5644927", "0.5644927", "0.5644927", "0.5644927", "0.56373924", "0.56324476", "0.5629777", "0.5623749", "0.56054634", "0.55997217", "0.5596741", "0.5587032", "0.5587032", "0.55809027", "0.55751896", "0.5574928", "0.5572236", "0.5571463", "0.5568504", "0.5561857", "0.55614024", "0.55536216", "0.5550801", "0.55471224", "0.5538349", "0.5515271", "0.55114824", "0.55089384", "0.5500688", "0.54865086", "0.54860306", "0.54860306", "0.54860306", "0.54860306", "0.54860306", "0.54860306", "0.54860306", "0.5485567", "0.5480556", "0.5480556", "0.5475899", "0.54728425", "0.5459475", "0.5455599", "0.54550916", "0.54524827", "0.5445176", "0.544085", "0.54259115", "0.54242057", "0.5423698", "0.5420698", "0.5405171", "0.5404908", "0.5403669", "0.5403097", "0.54029995" ]
0.59350944
21
DELETE /advertisements/1 DELETE /advertisements/1.json
def destroy @advertisement = Advertisement.find(params[:id]) @advertisement.destroy respond_to do |format| format.html { redirect_to advertisements_url } format.json { head :no_content } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n @advertise.destroy\n respond_to do |format|\n format.html { redirect_to advertises_url, notice: 'Advertise was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @advertise.destroy\n respond_to do |format|\n format.html { redirect_to advertises_url, notice: \"Advertise was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n # @advertisement = Advertisement.find(params[:id])\n @advertisement.destroy\n respond_to do |format|\n format.html { redirect_to advertisements_url }\n format.json { head :ok }\n end\n end", "def destroy\n @manage_advertisement.destroy\n respond_to do |format|\n format.html { redirect_to manage_advertisements_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @advertise = Advertise.find(params[:id])\n @advertise.destroy\n\n respond_to do |format|\n format.html { redirect_to(advertises_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @advertise = Advertise.find(params[:id])\n authorize! :destroy, @advertise, :message => 'Acceso denegado.'\n @advertise.destroy\n\n respond_to do |format|\n format.html { redirect_to advertises_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @advert.destroy\n respond_to do |format|\n format.html { redirect_to adverts_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @advert1.destroy\n respond_to do |format|\n format.html { redirect_to advert1s_url, notice: 'Advert1 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n loaded = Cloudinary::Uploader.destroy(\"advertises/#{@admin_advertise.id}\", :public_id => \"advertises/#{@admin_advertise.id}\", :invalidate => true)\n @admin_advertise.destroy\n respond_to do |format|\n format.html { redirect_to admin_advertises_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @admin_advertisement.destroy\n respond_to do |format|\n format.html { redirect_to admin_advertisements_url, notice: 'Advertisement was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n authorize! :destroy, @advertisement\n @advertisement.destroy\n respond_to do |format|\n format.html { redirect_to app_advertisements_url, notice: 'Advertisement was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @advert = Advert.find(params[:id])\n @advert.destroy\n\n respond_to do |format|\n format.html { redirect_to adverts_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @advert = Advert.find(params[:id])\n @advert.destroy\n\n respond_to do |format|\n format.html { redirect_to adverts_url }\n format.json { head :no_content }\n end\n end", "def destroy \n @advertisement.destroy\n respond_to do |format|\n format.html { redirect_to advertisements_url, notice: 'Advertisement was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @advertisement.destroy\n respond_to do |format|\n format.html { redirect_to advertisements_url, notice: 'Ad was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @advertisement.destroy\n respond_to do |format|\n format.html { redirect_to advertisements_url, notice: 'Advertisement was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @advertisement.destroy\n respond_to do |format|\n format.html { redirect_to advertisements_url, notice: 'Advertisement was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @advertisement.destroy\n respond_to do |format|\n format.html { redirect_to advertisements_url, notice: 'Advertisement was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @advertisment = Advertisment.find(params[:id])\n @advertisment.destroy\n\n respond_to do |format|\n format.html { redirect_to advertisments_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @advert.destroy\n respond_to do |format|\n format.html { redirect_to admin_adverts_url, notice: 'Advert was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @advert.destroy\n respond_to do |format|\n format.html { redirect_to adverts_url, notice: 'Advert was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @advert.destroy\n respond_to do |format|\n format.html { redirect_to adverts_url, notice: 'Advert was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @advert.destroy\n respond_to do |format|\n format.html { redirect_to adverts_url, notice: 'Advert was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @advertisement = Advertisement.find(params[:id])\n #if File.exists?(\"#{Rails.root}/#{@advertisement.filename}\")\n #File.delete(\"#{@advertisement.filename}\")\n #end\n @advertisement.destroy\n\n respond_to do |format|\n format.html { redirect_to advertisements_url }\n format.json { head :no_content }\n end\n end", "def delete\n client.delete(\"/#{id}\")\n end", "def destroy\n @client = Client.find(params[:id])\n @client.destroy\n @uuid = params[:uuid]\n respond_to do |format|\n format.html { redirect_to :controller => 'ads', :action => 'admin_dash', :id => 1, :uuid => @uuid }\n format.json { head :no_content }\n end\n end", "def delete_aos_version(args = {}) \n delete(\"/aosversions.json/#{args[:aosVersionId]}\", args)\nend", "def destroy\n @advert = @advert_class.find(params[:id])\n @advert.destroy\n\n respond_to do |format|\n format.html { redirect_to adverts_url }\n format.json { head :no_content }\n end\n end", "def destroy\n id = params[:id]\n src = Tagaly3::SRC\n # Code to connect with API\n @uri = URI.parse(src)\n http = Net::HTTP.start(@uri.host,@uri.port)\n request = Net::HTTP::Delete.new(\"/adexchange/advertiser/advertisement/#{id}\")\n response = http.request(request)\n http.finish\n redirect_to '/ads/'\n end", "def destroy\n @advocacy = Advocacy.find(params[:id])\n @advocacy.destroy\n\n respond_to do |format|\n format.html { redirect_to advocacies_url }\n format.json { head :ok }\n end\n end", "def delete\n render json: Alien.delete(params[\"id\"])\n end", "def destroy\n @home_indices_ad = Home::Indices::Ad.find(params[:id])\n @home_indices_ad.destroy\n\n respond_to do |format|\n format.html { redirect_to home_indices_ads_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @advertisment.destroy\n respond_to do |format|\n format.html { redirect_to advertisments_url, notice: 'Advertisment was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n begin\n @advert.destroy\n\n rescue Exception => e\n notice = e.message\n else\n notice = 'Advert was successfully destroyed.'\n end\n\n respond_to do |format|\n format.html { redirect_to adverts_url, notice: notice }\n format.json { head :no_content }\n end\n end", "def destroy\n @ad = Ad.find(params[:id])\n @ad.destroy\nrender json: 1\n end", "def destroy\n @advertiser.destroy\n respond_to do |format|\n format.html { redirect_to advertisers_url, notice: 'Advertiser was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @ad_banner.destroy\n respond_to do |format|\n format.html { redirect_to ad_banners_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @advert3.destroy\n respond_to do |format|\n format.html { redirect_to advert3s_url, notice: 'Advert3 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @advert = Advert.find(params[:id])\n @advert.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_adverts_url, :notice => 'Advert was deleted') }\n format.xml { head :ok }\n end\n end", "def destroy\n @advert = Advert.find(params[:id])\n @advert.destroy\n\n respond_to do |format|\n format.html { redirect_to(adverts_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @banner = Banner.find(params[:id])\n @banner.destroy\n\n respond_to do |format|\n format.html { redirect_to admins_banners_url }\n format.json { head :no_content }\n end\n end", "def destroy\n if @advertise.user == current_user\n # BUG: Log entry should contains the removed advertise\n # id even after its removal.\n Log.create(:user => current_user,\n :msg => _(\"advertise deleted\", :id => @advertise.id))\n\n @advertise.destroy\n else\n return forbidden\n end\n\n respond_to do |format|\n format.html { redirect_to target_url || advertises_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @ad = Ad.find(params[:id])\n @ad.destroy\n\n respond_to do |format|\n format.html { redirect_to ads_url }\n format.json { head :no_content }\n end\n end", "def delete\n client.delete(url)\n @deleted = true\nend", "def destroy\n @banner = Banner.find(params[:id])\n @banner.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_banners_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @lease = Lease.find(params[:id])\n @lease.destroy\n\n respond_to do |format|\n format.html { redirect_to leases_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @advertiser = Advertiser.find(params[:id])\n @advertiser.destroy\n\n respond_to do |format|\n format.html { redirect_to advertisers_url }\n format.xml { head :ok }\n end\n end", "def destroy\n @advertisement_campaign.destroy\n respond_to do |format|\n format.html { redirect_to advertisement_campaigns_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @adj.destroy\n respond_to do |format|\n format.html { redirect_to adjs_url, notice: 'Adj was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @adhub = Adhub.find(params[:id])\n @adhub.destroy\n respond_to do |format|\n format.html { redirect_to adhubs_url, notice: \"Advertisement was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @adv = Advantage.find(params[:id])\n @adv.destroy\n\n respond_to do |format|\n format.html { redirect_to administration_advantages_url }\n format.json { head :no_content }\n end\n end", "def destroy\n client=Client.find_by_id(params[:id])\n if client != nil\n if client.destroy\n head 204\n end\n else\n head 404\n end\n end", "def destroy\n @admin_agency = Admin::Agency.find(params[:id])\n @admin_agency.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_agencies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @ad.destroy\n respond_to do |format|\n format.html { redirect_to ads_path, notice: 'Quảng cáo đã được xóa.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @ad.destroy\n respond_to do |format|\n format.html { redirect_to ads_url, notice: 'Ad was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @ad.destroy\n respond_to do |format|\n format.html { redirect_to ads_url, notice: 'Ad was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @ad.destroy\n respond_to do |format|\n format.html { redirect_to ads_url, notice: 'Ad was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @ad.destroy\n respond_to do |format|\n format.html { redirect_to ads_url, notice: \"Ad was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @bottom_ad.destroy\n respond_to do |format|\n format.html { redirect_to admin_bottom_ads_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @avert = Avert.find(params[:id])\n @avert.destroy\n\n respond_to do |format|\n format.html { redirect_to averts_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @ad = Ad.find(params[:id])\n @ad.destroy\n\n respond_to do |format|\n format.html { render :action => :admin_dash, :id => 1, :uuid => @uuid }\n format.json { head :no_content }\n end\n end", "def delete endpoint\n do_request :delete, endpoint\n end", "def destroy\n @announcement = Announcement.find(params[:id])\n @announcement.destroy\n render json:@announcement\n\n end", "def destroy\n @appeal.destroy\n\n respond_to do |format|\n format.html { redirect_to conference_appeals_path(@conference) }\n format.json { head :no_content }\n end\n end", "def destroy\n @adss.destroy\n respond_to do |format|\n format.html { redirect_to adsses_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @aadt = Aadt.find(params[:id])\n @aadt.destroy\n\n respond_to do |format|\n format.html { redirect_to aadts_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @purchasing_ad = PurchasingAd.find(params[:id])\n @purchasing_ad.destroy\n\n respond_to do |format|\n format.html { redirect_to purchasing_ads_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @lease.destroy\n respond_to do |format|\n format.html { redirect_to leases_url, notice: 'Lease was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @agency = Agency.find(params[:id])\n @agency.destroy\n\n #head :no_content\n head :accepted # o deberia dejarlo en not_content\n end", "def delete\n api_client.delete(url)\n end", "def destroy\n@magazine = Magazine.find_by_id(params[:magazine_id])\[email protected]\nrespond_to do |format|\nformat.html { redirect_to magazine_ads_path(@magazine), notice: 'Ad was successfully destroyed.' }\nformat.json { head :no_content }\nend\nend", "def destroy\n animal = Animal.find(params[:id])\n animal.destroy\n head 204\n end", "def destroy\n @adviser.destroy\n respond_to do |format|\n format.html { redirect_to advisers_url, notice: 'Adviser was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @audience = Audience.find(params[:id])\n @audience.destroy\n\n respond_to do |format|\n format.html { redirect_to audiences_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @ad.destroy\n respond_to do |format|\n format.html { redirect_to ads_url, notice: 'Post was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n\n if @role != ADMIN\n @advertisement.destroy\n respond_to do |format|\n format.html { redirect_to advertisements_url, notice: 'Advertisement was successfully destroyed.' }\n format.json { head :no_content }\n end\n else\n flash[:error] = \"Sorry invalid request. \"\n redirect_to :back\n end\n end", "def destroy\n @news_agency = NewsAgency.find(params[:id])\n @news_agency.destroy\n\n respond_to do |format|\n format.html { redirect_to news_agencies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @agency.destroy\n respond_to do |format|\n format.html { redirect_to agencies_url, notice: \"Agency was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @ad.destroy\n\n respond_to do |format|\n format.html { redirect_to(ads_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @adocao_animal = AdocaoAnimal.find(params[:id])\n @adocao_animal.destroy\n\n respond_to do |format|\n format.html { redirect_to adocao_animals_url }\n format.json { head :no_content }\n end\n end", "def delete\n request(:delete)\n end", "def delete!( opts = {} )\n http_action :delete, nil, opts\n end", "def destroy\n @advetiser.destroy\n respond_to do |format|\n format.html { redirect_to advetisers_url, notice: 'Advetiser was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n if @diet.destroy\n head :no_content, status: 200\n else\n render json: @diet.errors, status: 405\n end\n end", "def destroy\n\[email protected]\n\trespond_to do |format|\n\t format.html { redirect_to ads_url, notice: 'Ad was successfully destroyed.' }\n\t format.json { head :no_content }\n\tend\n end", "def deleteEntityAdvertiser( entity_id, gen_id)\n params = Hash.new\n params['entity_id'] = entity_id\n params['gen_id'] = gen_id\n return doCurl(\"delete\",\"/entity/advertiser\",params)\n end", "def destroy\n @campaign_banner.destroy\n respond_to do |format|\n format.html { redirect_to campaign_banners_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @api_v1_initiative.destroy\n respond_to do |format|\n format.html { redirect_to api_v1_initiatives_url, notice: 'Initiative was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @ad.destroy\n respond_to do |format|\n format.html { redirect_to org_ads_url(@ad.org), notice: 'Ad was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @announcement = Announcement.find(params[:id])\n @announcement.destroy\n\n respond_to do |format|\n format.html { redirect_to announcements_url }\n format.json { head :ok }\n end\n end", "def destroy\n @adopter.destroy\n\n head :no_content\n end", "def destroy\n authorize @lease\n @lease.destroy\n respond_to do |format|\n format.html { redirect_to leases_url, notice: 'Lease was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @announcement.destroy\n respond_to do |format|\n format.html { redirect_to announcements_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @announcement.destroy\n respond_to do |format|\n format.html { redirect_to announcements_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @announcement.destroy\n respond_to do |format|\n format.html { redirect_to announcements_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @drip = Drip.find(params[:id])\n @drip.destroy\n\n respond_to do |format|\n format.html { redirect_to drips_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @adherent.destroy\n respond_to do |format|\n format.html { redirect_to adherents_url, notice: 'Adherent was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @agency = Agency.find(params[:id])\n @agency.destroy\n\n #head :no_content\n head :accepted # o deberia dejarlo en not_content\n end", "def destroy\n @signed_lease.destroy\n respond_to do |format|\n format.html { redirect_to signed_leases_url, notice: 'Signed lease was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @loadbalancer = Loadbalancer.find(params[:id])\n checkaccountobject(\"loadbalancers\",@loadbalancer)\n @loadbalancer.send_delete\n\n respond_to do |format|\n format.html { redirect_to loadbalancers_url }\n format.json { head :ok }\n end\n end" ]
[ "0.7651922", "0.7646948", "0.741282", "0.73541045", "0.73157495", "0.7311145", "0.71902347", "0.71623296", "0.7154859", "0.71490514", "0.7144615", "0.71437955", "0.71437955", "0.71137816", "0.7093831", "0.7093461", "0.7093461", "0.7093461", "0.7075143", "0.7047947", "0.7031743", "0.7031743", "0.7031743", "0.7025016", "0.69831467", "0.6939873", "0.69396037", "0.6929521", "0.6915953", "0.69059426", "0.6898411", "0.68890923", "0.68571633", "0.6836456", "0.68281764", "0.682194", "0.67863303", "0.6770991", "0.67520607", "0.6738175", "0.6720501", "0.67171746", "0.6713108", "0.6707547", "0.6704846", "0.667532", "0.66719145", "0.66607666", "0.66571945", "0.6650025", "0.6646834", "0.6638574", "0.6623827", "0.6603203", "0.65987384", "0.65987384", "0.65987384", "0.659382", "0.65907276", "0.6574995", "0.6574933", "0.6569422", "0.6567742", "0.65559846", "0.6553712", "0.65459687", "0.65446544", "0.6541782", "0.6534906", "0.65332514", "0.6533164", "0.6519875", "0.6512514", "0.6508154", "0.6505134", "0.6491864", "0.6489216", "0.648787", "0.6481562", "0.64801264", "0.64763474", "0.64762974", "0.6475964", "0.64743996", "0.6471632", "0.6471318", "0.6467482", "0.64605445", "0.6460402", "0.64602107", "0.6459913", "0.6451709", "0.6450884", "0.6450884", "0.6450884", "0.6449964", "0.64495784", "0.64445484", "0.644142", "0.6434046" ]
0.736775
3
Run distances against datasets listed in metadata's +:dist_req+
def distances_by_request(metric) return unless dataset.metadata[:dist_req] $stderr.puts 'Running distances by request' dataset.metadata[:dist_req].each do |target| ds = ref_project.dataset(target) and send(metric, ds) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def check_dist(cli)\n p = cli.load_project\n %i[ani aai].each do |dist|\n res = p.result(\"#{dist}_distances\")\n next if res.nil?\n\n cli.say \"Checking #{dist} table for consistent datasets\"\n notok, fix = check_dist_eval(cli, p, res)\n check_dist_fix(cli, p, fix)\n check_dist_recompute(cli, res, notok)\n end\n end", "def cleanup_distances!\n return if get_result(:distances).nil?\n\n require 'miga/sqlite'\n ref = project.datasets.select(&:ref?).select(&:active?).map(&:name)\n %i[haai aai ani].each do |metric|\n cleanup_distances_by_metric!(ref, metric)\n end\n end", "def add_result_distances(base, _opts)\n if nonmulti?\n if ref?\n add_result_distances_ref(base)\n else\n add_result_distances_nonref(base)\n end\n else\n add_result_distances_multi(base)\n end\n end", "def add_result_distances(base, _opts)\n if nonmulti?\n if ref?\n add_result_distances_ref(base)\n else\n add_result_distances_nonref(base)\n end\n else\n add_result_distances_multi(base)\n end\n end", "def add_result_distances(base, _opts)\n if is_nonmulti?\n if is_ref?\n add_result_distances_ref(base)\n else\n add_result_distances_nonref(base)\n end\n else\n add_result_distances_multi(base)\n end\n end", "def dist(*args)\n case args.length\n when 4\n dist2d(*args)\n when 6\n dist3d(*args)\n else\n raise ArgumentError, 'takes 4 or 6 parameters'\n end\n end", "def norm_s_dist()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::Norm_S_Dist::NormSDistRequestBuilder.new(@path_parameters, @request_adapter)\n end", "def f_dist()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::F_Dist::FDistRequestBuilder.new(@path_parameters, @request_adapter)\n end", "def cleanup_distances!\n r = get_result(:distances)\n ref = project.datasets.select(&:ref?).select(&:active?).map(&:name)\n return if r.nil?\n\n %i[haai_db aai_db ani_db].each do |db_type|\n db = r.file_path(db_type)\n next if db.nil? || !File.size?(db)\n\n sqlite_db = SQLite3::Database.new db\n table = db_type[-6..-4]\n val = sqlite_db.execute \"select seq2 from #{table}\"\n next if val.empty?\n\n (val.map(&:first) - ref).each do |extra|\n sqlite_db.execute \"delete from #{table} where seq2=?\", extra\n end\n end\n end", "def dist(start,target)\n return @matriks_data[start,target]\n end", "def calculate_distance_with_math\n distance = []\n @params.each do |args|\n args.each_with_index do |arg, _index|\n validate(arg)\n lat1 = arg[0][0].to_f * Math::PI / 180\n lat2 = arg[1][0].to_f * Math::PI / 180\n lon1 = arg[0][1].to_f * Math::PI / 180\n lon2 = arg[1][1].to_f * Math::PI / 180\n dlat = lat2 - lat1\n dlon = lon2 - lon1\n\n a = (Math.sin(dlat / 2)**2) + (Math.cos(lat1) * Math.cos(lat2) * Math.sin(dlon / 2)**2)\n c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))\n\n distance << radius * c\n end\n end\n distance\n end", "def add_result_distances(base, _opts)\n return nil unless result_files_exist?(base, %w[.rds .txt])\n\n r = MiGA::Result.new(\"#{base}.json\")\n r.add_file(:rds, 'miga-project.rds')\n r.add_file(:rdata, 'miga-project.Rdata') # Legacy file\n r.add_file(:matrix, 'miga-project.txt')\n r.add_file(:log, 'miga-project.log') # Legacy file\n r.add_file(:hist, 'miga-project.hist')\n r\n end", "def norm_dist()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::Norm_Dist::NormDistRequestBuilder.new(@path_parameters, @request_adapter)\n end", "def t_dist()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::T_Dist::TDistRequestBuilder.new(@path_parameters, @request_adapter)\n end", "def fX_(n1, n2, x); fdist(n1, n2, x); end", "def distance_sum(runs)\n runs.inject(0.0) { |sum, run| sum + run[:metadata][:distance].to_f }\n end", "def cleanup_distances!\n r = get_result(:distances)\n ref = project.datasets.select(&:is_ref?).select(&:is_active?).map(&:name)\n return if r.nil?\n [:haai_db, :aai_db, :ani_db].each do |db_type|\n db = r.file_path(db_type)\n next if db.nil? or not File.size? db\n sqlite_db = SQLite3::Database.new db\n table = db_type[-6..-4]\n val = sqlite_db.execute \"select seq2 from #{table}\"\n next if val.empty?\n (val.map(&:first) - ref).each do |extra|\n sqlite_db.execute \"delete from #{table} where seq2=?\", extra\n end\n end\n end", "def brute_algorithm(args)\n data_set.keys.each do |key|\n data_set[key].each do |value|\n raise LearnFailure, \"Different points size, error key - #{key}, error value - #{value}\" if args[:point].size != value.size\n points << { distance: calc_distance(args[:point], value), label: key }\n end\n end\n end", "def distances= distances\n\t\t\t@distances = distances\n\t\t\t@farthest, @maximum = distances.farthest\n\t\tend", "def get_distance_duration(start_locations, end_locations)\n origins = start_locations.map{ |l| l.map(&:to_s).join(\",\") }.join(\"|\")\n destinations = end_locations.map{ |l| l.map(&:to_s).join(\",\") }.join(\"|\")\n\n request_url = \"https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=\"+\n \"#{origins}&destinations=#{destinations}&mode=bicycling&key=#{ENV['GOOGLE_MAPS_API_KEY_TEST']}\"\n\n response = HTTP.get(request_url).parse\nend", "def add_result_distances_multi(base)\n MiGA::Result.new(\"#{base}.json\")\n end", "def add_result_distances_multi(base)\n MiGA::Result.new(\"#{base}.json\")\n end", "def compute_datasets(pr, distribution_array)\n\tdata_set = Hash.new\n\tinitialize_data_set = parse_response_list(pr.first.response_list, pr.first)\n\n\tinitialize_data_set.each_key do |key|\n\t\tdata_set[key] = Hash.new\n\tend\n\n\tweights_map_array = Array.new\n\tdistribution_array.each do |distribution|\n\t\tweights_map_array << distribution.get_weights_submission_map(pr)\n\tend\n\n\t#for each submission\n\tpr.each_with_index do |submission, index|\n\t\tsubmission_hash = parse_response_list(submission.response_list, submission)\n\t\t#for each of the responses to the question\n\t\tsubmission_hash.each_pair do |key, value|\n\t\t\tif (!key.nil? && !value.nil?)\n\t\t\t\tweight_value = 0\n\t\t\t\tweights_map_array.each do |weights_map|\n\t\t\t\t\t#weights_map[1][index] represents the index into the weights array, which is\n\t\t\t\t\t#weights_map[0]\n\t\t\t\t\tweight_value += weights_map[0][weights_map[1][index]]\n\t\t\t\tend\n\n\t\t\t\t#we average out by the number of distributions\n\t\t\t\tweight_value = weight_value / weights_map_array.length\n\n\t\t\t\tdata_set[key][value] = data_set[key].fetch(value, 0) + weight_value\n\t\t\tend\t\n\t\tend\n\tend\n\n\treturn data_set\nend", "def add_result_distances_multi(base)\n MiGA::Result.new(\"#{base}.json\")\n end", "def generate_dists(pkg_hash)\n pkg_hash.each do |origin_name, dists|\n dists.each do |dist_name, dist_args|\n dist_args[:components].each do |component_name, arches|\n packages = arches.values.flatten.compact.map(&:values).flatten.compact.map(&:values).flatten.compact\n p_file = primary_file(origin_name, dist_name, component_name, packages)\n f_file = filelist_file(origin_name, dist_name, component_name, packages)\n sign_file_if_setup do\n repomd_file(origin_name, dist_name, component_name,\n :primary => p_file,\n :filelists => f_file)\n end\n end\n end\n end\n true\n end", "def calculate_group_distance\n sum = 0.0\n @patterns.each { |pattern|\n sum += calculate_distance(pattern.features, @center.features)\n }\n sum\n end", "def dist(a1, a2)\n Math.sqrt(a1.zip(a2).map { |x| (x[1] - x[0])**2 }.reduce(:+))\n end", "def distance _obj, _args\n \"_obj distance _args;\" \n end", "def add_result_distances_nonref(base)\n return nil unless\n result_files_exist?(base, %w[.aai-medoids.tsv .aai.db]) ||\n result_files_exist?(base, %w[.ani-medoids.tsv .ani.db])\n\n add_files_to_ds_result(\n MiGA::Result.new(\"#{base}.json\"), name,\n aai_medoids: '.aai-medoids.tsv',\n haai_db: '.haai.db',\n aai_db: '.aai.db',\n ani_medoids: '.ani-medoids.tsv',\n ani_db: '.ani.db',\n ref_tree: '.nwk',\n ref_tree_pdf: '.nwk.pdf',\n intax_test: '.intax.txt'\n )\n end", "def add_result_distances_nonref(base)\n return nil unless\n result_files_exist?(base, %w[.aai-medoids.tsv .aai.db]) ||\n result_files_exist?(base, %w[.ani-medoids.tsv .ani.db])\n\n add_files_to_ds_result(\n MiGA::Result.new(\"#{base}.json\"), name,\n aai_medoids: '.aai-medoids.tsv',\n haai_db: '.haai.db',\n aai_db: '.aai.db',\n ani_medoids: '.ani-medoids.tsv',\n ani_db: '.ani.db',\n ref_tree: '.nwk',\n ref_tree_pdf: '.nwk.pdf',\n intax_test: '.intax.txt'\n )\n end", "def add_result_distances_nonref(base)\n return nil unless\n result_files_exist?(base, %w[.aai-medoids.tsv .aai.db]) or\n result_files_exist?(base, %w[.ani-medoids.tsv .ani.db])\n r = MiGA::Result.new(\"#{base}.json\")\n add_files_to_ds_result(r, name, aai_medoids: \".aai-medoids.tsv\",\n haai_db: \".haai.db\", aai_db: \".aai.db\", ani_medoids: \".ani-medoids.tsv\",\n ani_db: \".ani.db\", ref_tree: \".nwk\", ref_tree_pdf: \".nwk.pdf\",\n intax_test: \".intax.txt\")\n end", "def next_distances(save = true) ; next_task(@@DISTANCE_TASKS, save) ; end", "def distribute\n raise NotImplementedError, 'You must be implement\"dist\" method.'\n end", "def add_result_distances(base)\n return nil unless result_files_exist?(base, %w[.Rdata .log .txt])\n r = MiGA::Result.new(\"#{base}.json\")\n r.add_file(:rdata, \"miga-project.Rdata\")\n r.add_file(:matrix, \"miga-project.txt\")\n r.add_file(:log, \"miga-project.log\")\n r.add_file(:hist, \"miga-project.hist\")\n r\n end", "def mk_dist\n xpanded = expand_dist(options[:'<val>'])\n wf.mk_distribution(xpanded.map(&:to_f))\n end", "def add_result_distances(base)\n return nil unless result_files_exist?(base, %w[.Rdata .log .txt])\n r = MiGA::Result.new(\"#{base}.json\")\n r.add_file(:rdata, 'miga-project.Rdata')\n r.add_file(:matrix, 'miga-project.txt')\n r.add_file(:log, 'miga-project.log')\n r.add_file(:hist, 'miga-project.hist')\n r\n end", "def calculate(route)\n dist = 0\n route.each_cons(2) { |points| dist = dist + points[0].distance(points[1])}\n dist\nend", "def distance_measurement; end", "def add_result_distances_ref(base)\n pref = File.dirname(base)\n return nil unless\n File.exist?(\"#{pref}/01.haai/#{name}.db\")\n r = MiGA::Result.new(\"#{base}.json\")\n r.add_files(haai_db: \"01.haai/#{name}.db\", aai_db: \"02.aai/#{name}.db\",\n ani_db: \"03.ani/#{name}.db\")\n r\n end", "def compute_accumulated_distances(distances)\n acc_distances = []\n distances.reduce do |acc, distance|\n acc += distance\n acc_distances << acc\n acc\n end\n acc_distances\n end", "def grab_nearest_by_location(distance, loc)\n\n end", "def calculate_distance(vals1, vals2)\n vals1_sum = vals1.inject(:+)\n vals2_sum = vals2.inject(:+)\n\n (0..11).map { |i| ((vals1[i].to_f/vals1_sum)-(vals2[i].to_f/vals2_sum))**2 }.inject(:+)\nend", "def geodist(key, from, to, unit = \"m\")\n\t\t\t\t\tcall(\"GEODIST\", key, from, to, unit)\n\t\t\t\tend", "def f_dist_r_t()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::F_Dist_RT::FDistRTRequestBuilder.new(@path_parameters, @request_adapter)\n end", "def next_distances(save = true)\n next_task(@@DISTANCE_TASKS, save)\n end", "def documentDistance doc1,doc2\n\tputs \"Implmementing doc\"\nend", "def euclidean_distance(s1, s2)\n d2 = 0.0\n get_features.each do |f|\n if s1.has_key? f and s2.has_key? f\n d2 += (s1[f]-s2[f])**2\n end\n end\n \n Math.sqrt(d2)\n end", "def distance_calculator\n @trips.each do |trip|\n @total_distance += trip.distance.to_f\n end\n end", "def distance(capabilities)\n distance_value = 0\n center_value = 0\n \n self.each do |c|\n center_value += 1\n distance_value += 1 if capabilities.include?(c.name)\n end\n \n (center_value - (2 * distance_value))\n end", "def distance_between(src, tar)\n @edges.each do |edge|\n return edge.distance if edge.src == src and edge.tar == tar\n end\n nil\n end", "def extract_distance dist\n is_numeric?(dist) ? dist.send(unit) : dist \n end", "def add_distances(points)\n points_dist = points.select { |p| p.key? :distance }\n\n return DistResultAlreadyValid.new(points) \\\n if points_dist.length == points.length\n\n return DistResultInvalid.new('Only some points with distance') \\\n unless points_dist.empty?\n\n points.each_index do |idx|\n if idx.zero?\n points[0][:distance] = 0.0\n else\n src = points[idx - 1]\n dst = points[idx]\n points[idx][:distance] = \\\n src[:distance] + \\\n Haversine.distance(src[:latitude],\n src[:longitude],\n dst[:latitude],\n dst[:longitude]).to_meters\n end\n end\n\n DistResultValid.new(points)\nend", "def add_result_distances_ref(base)\n pref = File.dirname(base)\n return nil unless File.exist?(\"#{pref}/01.haai/#{name}.db\")\n\n MiGA::Result.new(\"#{base}.json\").tap do |r|\n r.add_files(\n haai_db: \"01.haai/#{name}.db\",\n aai_db: \"02.aai/#{name}.db\",\n ani_db: \"03.ani/#{name}.db\"\n )\n end\n end", "def add_result_distances_ref(base)\n pref = File.dirname(base)\n return nil unless File.exist?(\"#{pref}/01.haai/#{name}.db\")\n\n MiGA::Result.new(\"#{base}.json\").tap do |r|\n r.add_files(\n haai_db: \"01.haai/#{name}.db\",\n aai_db: \"02.aai/#{name}.db\",\n ani_db: \"03.ani/#{name}.db\"\n )\n end\n end", "def compute_total_distance(distances)\n if distances.size != 0\n distances.reduce(:+)\n else\n 0\n end\n end", "def distributions_for flowcell_id\n lims_data = data_for flowcell_id\n distributions = []\n lims_data[\"samples\"].each do |lims_sample_data|\n unless distributions.collect {|d| d[:lane]}.include? lims_sample_data[\"laneID\"]\n if lims_sample_data[\"resultsPath\"]\n distribution = { :lane => lims_sample_data[\"laneID\"], :path => lims_sample_data[\"resultsPath\"] }\n distributions << distribution\n end\n end\n end\n distributions\n end", "def run\n super\n\n domain_name = _get_entity_name\n\n # first check... if this is a wildcard domain, we cannot continue,\n # results will be generally untrustworthy.\n # todo... in the future, make a list and we can check against it\n wildcards = gather_wildcard_ips(domain_name)\n unless wildcards.empty?\n _log_error \"Cowardly refusing to pull data on a wildcard domains\"\n _log_error \"wildcards: #{wildcards}\"\n return\n end\n\n # Make sure the key is set\n api_key = _get_task_config(\"zetalytics_api_key\")\n\n # search it\n result = search_zetalytics_by_domain(api_key, domain_name)\n\n # create our entities\n create_entities(result) if result\n\n end", "def distance_calculator(start, destination)\n #http://forrst.com/posts/Read_JSON_data_using_Ruby-13V\n url = \"http://maps.googleapis.com/maps/api/distancematrix/json?origins=#{start}&destinations=#{destination}&mode=driving&sensor=false\"\n \n buffer = open(url).read\n result = JSON.parse(buffer)\n \n duration = result[\"rows\"].first[\"elements\"].first[\"duration\"][\"value\"]\n distance = result[\"rows\"].first[\"elements\"].first[\"distance\"][\"value\"]\n return duration.to_f/60, distance.to_f/1000\nend", "def collect_metrics\n\n # Build a set of matchers to match the paths we need to find metrics\n # for.\n path_matchers = []\n @paths.each do |path|\n path_matchers << { :path => matcher_for_path(path) }\n end\n\n # Figure out what metric model to use (Metric or one of the average\n # models).\n metric_model = metric_model_for_timespan\n\n # Build a query to locate the metrics.\n query = metric_model.where(:$or => path_matchers)\n query = query.where(:node_id => @node_id)\n query = query.where(:timestamp.gte => @from)\n query = query.where(:timestamp.lte => @to)\n query = query.sort(:timestamp.asc)\n metrics = query.all\n\n # Return a data set based on the collection of metrics.\n data_set_for_metrics(metrics)\n\n end", "def fdist(n1, n2, f); 1.0 - q_f(n1, n2, f); end", "def create_distance_metric(dist_measurer)\n lambda do |button_sequence|\n dist = 0\n button_sequence.each_adjacent_pair do |button_pair|\n dist += dist_measurer[button_pair.first, button_pair.last]\n end\n dist\n end\nend", "def text_distance_graph\n @data_location = '/text_distance_graph_data'\nend", "def initialize(data, options = {})\n @separation = options.delete(:separation)\n @resolution = options.delete(:resolution)\n @nils = options.delete(:nils)\n @data = precluster(data)\n @distances = Distances.new(@data, @nils)\n end", "def chi_sq_dist()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::ChiSq_Dist::ChiSqDistRequestBuilder.new(@path_parameters, @request_adapter)\n end", "def dist_L2 other\n raise ArgumentError if other.size != size or other.data.keys != data.keys\n\n sum=0.0\n data.each { |key,value|\n sum+=(value-other[key])**2\n }\n Math::sqrt(sum)\n end", "def total_distance_driven\n distances = rides.map{ |ride| ride.distance }\n distances.reduce(:+)\n end", "def fit(x, _y = nil)\n x = ::Rumale::Validation.check_convert_sample_array(x)\n raise ArgumentError, 'the input distance matrix should be square' if check_invalid_array_shape(x)\n\n # initialize some varibales.\n distance_mat = @params[:metric] == 'precomputed' ? x : ::Rumale::PairwiseMetric.euclidean_distance(x)\n init_cluster_centers(distance_mat)\n error = distance_mat[true, @medoid_ids].mean\n @params[:max_iter].times do |_t|\n cluster_labels = assign_cluster(distance_mat[true, @medoid_ids])\n @params[:n_clusters].times do |n|\n assigned_ids = cluster_labels.eq(n).where\n @medoid_ids[n] = assigned_ids[distance_mat[assigned_ids, assigned_ids].sum(axis: 1).min_index]\n end\n new_error = distance_mat[true, @medoid_ids].mean\n break if (error - new_error).abs <= @params[:tol]\n\n error = new_error\n end\n @cluster_centers = x[@medoid_ids, true].dup if @params[:metric] == 'euclidean'\n self\n end", "def run\n self.prominence!\n return self.send_results if @query.any?\n\n self.fuzzy_match\n self.apply_narrowing_filters\n self.apply_limit\n self.load_and_sort_by_matches\n self.send_results\n end", "def update!(**args)\n @annotation_resource_name = args[:annotation_resource_name] if args.key?(:annotation_resource_name)\n @distance = args[:distance] if args.key?(:distance)\n end", "def dist(cities)\n @possible_distances = []\n shuffle_cities(cities).each do |array_of_array| \n @possible_distances.push(move_count(array_of_array))\n end\n @possible_distances.min\n end", "def distributions\n distributions = []\n uris = metadata[dataset_uri][dcat.distribution.to_s]\n uris.each do |uri|\n d = metadata[uri]\n distribution = {\n :title => d[dct.title.to_s][0],\n :accessURL => d[dcat.accessURL.to_s][0],\n :issued => d[dct.issued.to_s][0]\n }\n distributions << Distribution.new(self, dcat_resource: distribution)\n end\n return distributions\n rescue\n nil\n end", "def distance_metric(product1, product2) (get_value(product1) - get_value(product2)).abs end", "def each_dist\n count.times do |i|\n yield( self[i])\n end\n end", "def compute_distance\n if exercise_rows\n exercise_rows.sort_by_part_order.inject(0) do |sum, row|\n actual_row_distance = row.compute_displayable_distance(distance).to_i\n actual_row_distance = distance if actual_row_distance == 0\n sum + actual_row_distance\n end\n else\n distance\n end\n end", "def dist(line_start, stop_start, stop_finish)\n x = $mta[line_start].index(stop_start)\n y = $mta[line_start].index(stop_finish)\n return (x - y).abs \nend", "def expon_dist()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::Expon_Dist::ExponDistRequestBuilder.new(@path_parameters, @request_adapter)\n end", "def calculate_distance(line_stops, origin_station, destination_station)\n orig_stop = line_stops.index(origin_station)\n dest_stop = line_stops.index(destination_station)\n dist = (orig_stop - dest_stop).abs\nend", "def cleanup_distances_by_metric!(ref, metric)\n db_type = :\"#{metric}_db\"\n db = get_result(:distances).file_path(db_type)\n return if db.nil? || !File.size?(db)\n\n sqlite_db = MiGA::SQLite.new(db)\n table = db_type[-6..-4]\n val = sqlite_db.run(\"select seq2 from #{table}\")\n return if val.empty?\n\n (val.map(&:first) - ref).each do |extra|\n sqlite_db.run(\"delete from #{table} where seq2=?\", extra)\n end\n end", "def dist(r1, c1, r2, c2)\r\n return Math.sqrt((c1-c2)**2 + (r1-r2)**2)\r\nend", "def distance(a, b)\n return @distance_function.call(a, b) if @distance_function\n return euclidean_distance(a, b)\n end", "def nearby_stops(lng, lat, dist, sources = nil)\n stops = []\n sources ||= Stop.all\n sources.each do |stop|\n stops << stop if check_stop(stop, lng, lat, dist)\n end\n stops.sort! { |a, b| a.dist <=> b.dist }\n end", "def expand_dist(dist)\n dist.map do |v|\n if v.is_a?(String) && v.include?('x')\n x, val = v.split('x', 2)\n Array.new(x.to_i, val.to_f)\n else\n v.to_f\n end\n end.flatten\n end", "def calculate_distance_from_destination_for_all\n if @destination.nil?\n raise ArgumentError, 'Destination coordinates must be provided'\n end\n\n @customers.each do |customer|\n if valid_record?(customer)\n customer_lat_long = customer['latitude'], customer['longitude']\n end\n destination_lat_long = @destination[0], @destination[1]\n distance_between = DistanceBetween.new(customer_lat_long, destination_lat_long).calculate\n add_distance_to_customer_records(customer, distance_between)\n end\n end", "def nearestLocations _args\n \"nearestLocations _args;\" \n end", "def clusterTaxonDist(db, kingdom)\n dist = Hash.new\n ranks = Hash.new\n counts = Hash.new\n STDERR << \"Computing taxononomy distro for \" << kingdom << \"...\\n\"\n db.execute(\"SELECT phylum, class, ord, family, genus, cluster_num FROM classification \" +\n \"JOIN cluster ON cluster.seq_name = classification.seq_name WHERE kingdom = '#{kingdom}'\").each do |row|\n phylum, cl, ord, family, genus, cluster_num = row\n group = phylum\n counts[cluster_num] = 0 if (!counts[cluster_num])\n counts[cluster_num] += 1\n if (kingdom == \"Bacteria\")\n if (genus =~/Pelagibacter/)\n group = \"Pelagibacter\"\n elsif (genus =~/Prochlorococcus/)\n group = \"Prochlorococcus\"\n elsif (genus =~/Synechococcus/)\n group = \"Synechococcus\"\n elsif (cl == \"Alphaproteobacteria\")\n group = \"Other alphaproteobacteria\"\n elsif (group == \"Cyanobacteria\")\n group = \"Other cyanobacteria\"\n elsif (group =~/Bacteroidetes|Chlorobi/)\n group = \"Bacteroidetes/Chlorobi\"\n elsif (cl =~/Betaproteobacteria/)\n group = \"Betaproteobacteria\"\n elsif (cl =~/Gammaproteobacteria/)\n group = \"Gammaproteobacteria\"\n elsif (cl =~/Deltaproteobacteria/)\n group = \"Deltaproteobacteria\"\n elsif (cl =~/Epsilonproteobacteria/)\n group = \"Epsilonproteobacteria\"\n elsif (group =~/Proteobacteria/)\n group = \"Other proteobacteria\"\n elsif (group =~/Rhodobacterales/)\n group = \"Rhodobacterales\"\n elsif (group =~/Actinobacteria/)\n group = \"Actinobacteria\" \n elsif (group =~/Firmicutes/)\n group = \"Firmicutes\" \n elsif (group =~/Chlamydiae|Verrucomicrobia/)\n group = \"Chlamydiae/Verrucomicrobia\"\n elsif (group =~/Spirochaetes/)\n group = \"Spirochaetes\"\n elsif (group =~/Thermotogae/)\n group = \"Thermotogae\"\n elsif (group =~/Planctomycetes/)\n group = \"Planctomycetes\" \n elsif (group =~/Unknown/)\n group = \"Unknown\" \n else\n group = \"Other bacteria\"\n end\n elsif (kingdom == \"Eukaryota\")\n group = phylum\n elsif (kingdom == \"Viruses\")\n group = phylum\n group = \"Other viruses\" if (group =~/\\(phylum\\)/)\n end\n next if group == \"Mixed\"\n group = kingdom + \": \" + group\n dist[cluster_num] = Hash.new if (!dist[cluster_num])\n dist[cluster_num][group] = 0 if (!dist[cluster_num][group])\n dist[cluster_num][group] += 1\n ranks[group] = 0 if (!ranks[group])\n ranks[group] += 1\n end\n dist.keys.each do |cluster|\n sum = dist[cluster].values.reduce(:+)\n dist[cluster].keys.each do |key|\n dist[cluster][key] = ((dist[cluster][key]*1000) / sum) / 10.0\n end\n end\n return dist, ranks.keys.sort {|x, y| ranks[y] <=> ranks[x]}, counts\nend", "def perform(druid)\n druid_obj = Dor.find(druid)\n collection_id = Dor::WASCrawl::Dissemination::Utilities.get_collection_id(druid_obj)\n collection_path = Dor::Config.was_crawl_dissemination.stacks_collections_path + collection_id\n contentMetadata = druid_obj.datastreams['contentMetadata']\n path_working_directory = Dor::Config.was_crawl_dissemination.path_working_directory\n\n path_indexer_service = Dor::WASCrawl::PathIndexerService.new(druid, collection_path, path_working_directory, contentMetadata.content)\n path_indexer_service.merge\n path_indexer_service.sort\n path_indexer_service.publish\n path_indexer_service.clean\n end", "def update!(**args)\n @datapoint = args[:datapoint] if args.key?(:datapoint)\n @distance = args[:distance] if args.key?(:distance)\n end", "def distance(m1, m2)\n n = m1.size\n sum = 0.0\n n.times do |i|\n n.times do |j|\n dif = m2[i][j] - m1[i][j]\n sum += dif * dif\n end\n end\n sum\nend", "def distance\n return nil unless @locations.size > 1\n locations.each_cons(2).reduce(0) do |acc, (loc1, loc2)|\n acc + loc1.distance_to(loc2)\n end\n end", "def t_dist_2_t()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::T_Dist_2T::TDist2TRequestBuilder.new(@path_parameters, @request_adapter)\n end", "def get_distribution_list(options = {})\n request({\n :expects => 200,\n :idempotent => true,\n :method => 'GET',\n :parser => Fog::Parsers::AWS::CDN::GetDistributionList.new,\n :path => \"/distribution\",\n :query => options\n })\n end", "def statistic_distance(statistics)\n if previous\n distance_from_previous = distance_from [previous.latitude, previous.longitude]\n if distance_from_previous\n statistics.tdistance += distance_from_previous\n statistics.tdistance = statistics.tdistance.round(2)\n end\n end \n end", "def chi_sq_dist_r_t()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::ChiSq_Dist_RT::ChiSqDistRTRequestBuilder.new(@path_parameters, @request_adapter)\n end", "def [] i=0\n dist[i]\n end", "def initialize_routes(data, single)\n data.each do |line|\n @metros[line['ports'][0]].add_distination(line['ports'][1], line['distance'])\n if single == 0\n @metros[line['ports'][1]].add_distination(line['ports'][0], line['distance'])\n end\n end\n end", "def get_distance(atomid1, atomid2)\n # calculate distance matrix on request\n if not @distance_matrix\n calculate_distancematrix\n end\n\n return @distance_matrix.get_value(atomid1, atomid2)\n end", "def euclideanDistance(obj1, obj2)\r\n\teuc = 0\r\n\tfor d in 0...obj1.length\r\n\t\teuc += (obj1[d] - obj2[d])**2\r\n\tend\r\n\tMath.sqrt(euc)\r\nend", "def distance\n @data['distance']['value']\n end", "def fetch(*args)\n #FIXME: Refactor this\n start_time_ptr = empty_pointer\n end_time_ptr = empty_pointer\n step_ptr = empty_pointer\n ds_count_ptr = empty_pointer\n ds_names_ptr = empty_pointer\n values_ptr = empty_pointer\n\n argv = to_pointer([\"fetch\"] + args)\n if respond_to?(:rrd_fetch_r)\n file = args[0]\n cf = args[1]\n options = {}\n args[2..-1].each_slice(2) {|v| options[v.first] = v.last}\n start_time = options[\"--start\"]\n end_time = options[\"--end\"]\n step = options[\"--resolution\"]\n start_time_ptr.put_int(0, start_time.to_i)\n end_time_ptr.put_int(0, end_time.to_i)\n step_ptr.put_int(0, step.to_i)\n return false unless rrd_fetch_r(file, cf, start_time_ptr, end_time_ptr, step_ptr, ds_count_ptr, ds_names_ptr, values_ptr) == 0\n else\n return false unless rrd_fetch(args.size+1, argv, start_time_ptr, end_time_ptr, step_ptr, ds_count_ptr, ds_names_ptr, values_ptr) == 0\n end\n\n ds_count = ds_count_ptr.get_int(0)\n start_time = start_time_ptr.get_int(0)\n end_time = end_time_ptr.get_int(0)\n step = step_ptr.get_int(0)\n\n result_lines = (end_time-start_time)/step\n\n ds_names = ds_names_ptr.get_pointer(0).get_array_of_string(0, ds_count)\n values = values_ptr.get_pointer(0).get_array_of_double(0, result_lines * ds_count)\n\n result = [[\"time\"] + ds_names]\n (0..result_lines-1).each do |line|\n date = start_time + line*step\n first = ds_count*line\n last = ds_count*line + ds_count - 1\n result << [date] + values[first..last]\n end\n\n free_in_rrd(*ds_names_ptr.read_pointer.read_array_of_pointer(ds_count))\n free_in_rrd(values_ptr.read_pointer, ds_names_ptr.read_pointer)\n\n result\n ensure\n free_pointers\n end", "def index\n\t @somewhere = [52.477995,13.566360]\n\t @sites = Site.joins(:sizes).includes([:sizes, :reviews])\n\t @sites.sort_by{|s| s.distance_to(@somewhere)}\n\t \n\t #@sites = Site.by_distance(:origin => @somewhere).order('distance ASC')\n\t \n end" ]
[ "0.6014446", "0.59729105", "0.579879", "0.579879", "0.57411486", "0.5702526", "0.5352509", "0.53382516", "0.5336454", "0.5332691", "0.53043216", "0.52376676", "0.52144223", "0.5210712", "0.5202379", "0.5180323", "0.51697487", "0.51528037", "0.51419413", "0.5140173", "0.5138416", "0.5138416", "0.5110601", "0.50951475", "0.50352335", "0.5015083", "0.4999114", "0.4998511", "0.49820873", "0.49804196", "0.49731", "0.4971771", "0.4961471", "0.49590823", "0.49505988", "0.49486065", "0.4928808", "0.48897693", "0.48883334", "0.48634583", "0.48570243", "0.48553923", "0.48475552", "0.48071653", "0.48023993", "0.47985688", "0.47968155", "0.47937417", "0.47438842", "0.47377038", "0.47341666", "0.47315758", "0.4715722", "0.4715722", "0.47099128", "0.47025868", "0.46941468", "0.46940172", "0.46878245", "0.4683652", "0.4681861", "0.46659938", "0.4663469", "0.46510845", "0.464256", "0.46352524", "0.46334916", "0.46182412", "0.46126458", "0.46084303", "0.45853698", "0.45846868", "0.45836157", "0.45812377", "0.45709303", "0.45507333", "0.45495054", "0.45471212", "0.45447075", "0.45370808", "0.4532769", "0.45315504", "0.4530332", "0.4528924", "0.45240813", "0.45210302", "0.4511983", "0.44984877", "0.44979593", "0.44976562", "0.4497547", "0.4490984", "0.44857025", "0.44780052", "0.4470109", "0.4469896", "0.44642675", "0.44572031", "0.4456556", "0.4455162" ]
0.8088296
0
Builds a tree with all visited medoids from any classification level
def build_medoids_tree(metric) $stderr.puts "Building medoids tree (metric = #{metric})" db = query_db(metric) return unless File.size? db out_base = File.expand_path(dataset.name, home) ds_matrix = "#{out_base}.txt" ds_matrix_fh = File.open(ds_matrix, 'w') ds_matrix_fh.puts %w[a b value].join("\t") # Find all values in the database seq2 = [] foreach_in_db(db, metric) do |r| seq2 << r[0] ds_matrix_fh.puts r[0, 3].join("\t") end # Find all values among visited datasets in ref_project ref_r = ref_project.result("#{metric}_distances") or return Zlib::GzipReader.open(ref_r.file_path(:matrix)) do |fh| fh.each_line do |ln| r = ln.chomp.split("\t") next unless seq2.include?(r[1]) or seq2.include?(r[2]) ds_matrix_fh.puts r[1, 3].join("\t") end end ds_matrix_fh.close ref_tree = File.expand_path('utils/ref-tree.R', MiGA::MiGA.root_path) `"#{ref_tree}" "#{ds_matrix}" "#{out_base}" "#{dataset.name}"` File.unlink ds_matrix end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def build_tree\n index = 0\n @ignore_list.each do |attribute|\n #puts \"Attribute: #{attribute}\"\n #puts \"Result: #{@max_result_array[index]}\"\n #puts \"Count: #{@max_class_count_array[index]}\"\n\n @max_class_count_array[index].each do |label, count|\n isLeaf = false\n result = nil\n #puts \"Label: #{label}, Count: #{count}\"\n c1_count = count['<=50K.']\n c2_count = count['>50K.']\n ratio_a = c1_count.to_f / c2_count.to_f\n ratio_b = c2_count.to_f / c1_count.to_f\n #puts \"ratio_a: #{ratio_a} || ratio_b: #{ratio_b} || c1: #{c1_count} || c2: #{c2_count}\"\n if ratio_a >= 30 or ratio_b >= 30 then\n # Have a high ratio, thus we can declare a class\n if c1_count > c2_count\n # declare class 1\n #puts \"Ratio is HIGH, #{ratio_a}, declare any #{attribute} with a #{label} to be class <=50K.\"\n isLeaf = true\n result = '<=50k'\n else\n #puts \"Ratio B is HIGH, #{ratio_b}, declare any #{attribute} with a #{label} to be class >50K.\"\n isLeaf = true\n result = '>50k'\n end\n else\n #puts \"Ratio is too LOW for #{attribute} with label #{label}.\"\n end\n\n if index == 0 then parent = nil else parent = @ignore_list[index-1] end\n\n if isLeaf then\n @tree[label] = Hash['attribute' => attribute, 'label' => label, 'isLeaf' => isLeaf, 'result' => result, 'child' => nil, 'parent' => parent]\n else\n @tree[label] = Hash['attribute' => attribute, 'label' => label, 'isLeaf' => isLeaf, 'result' => result, 'child' => @ignore_list[index+1], 'parent' => parent]\n end\n\n end\n index += 1\n end\n\n @tree.each { |node| puts node }\n end", "def produce_tree(ary); end", "def build_score_tree\n tree_nodes = []\n root_node = nil\n\n @nodes.each do |n|\n if n['key'] == 1\n root_node = build_node_from_model(n)\n root_node['parent_id'] = 0\n else\n tree_nodes.push(build_node_from_model(n))\n end\n end\n\n node_list = { 1 => root_node }\n tree_nodes.each do |n|\n node_list[n['id']] = n\n node_list[n['parent_id']]['children'].push(node_list[n['id']])\n end\n root_node\n end", "def build_tree\n t = RDTree.new\n t.add_node(0, DummyRoot)\n root = root_node_of\n t.add_edge(0, root.attributes[\"ID\"])\n do_build_tree(root, 1, t) \n t\n end", "def build_tree(arr)\n\tend", "def build_tree(model)\n # inflate the node id to test id wrap around edge cases\n ENV[\"NODES\"].to_i.times { model.create!.destroy } if ENV[\"NODES\"]\n\n n1 = model.create!\n n2 = model.create!(:parent => n1)\n n3 = model.create!(:parent => n2)\n n4 = model.create!(:parent => n2)\n n5 = model.create!(:parent => n1)\n n6 = model.create!(:parent => n5)\n\n puts \"create: #{n1.id}..#{n6.id}\" if ENV[\"NODES\"]\n [n1, n2, n3, n4, n5, n6]\n end", "def gen_tree\n new_tree = {}\n node_list = {}\n @json_tree.each do |k, v|\n if v['child_of'].nil?\n # top\n new_tree[k] = v\n node_list[k] = new_tree[k]\n else\n parent = v['child_of']\n if v['condition'] == 'and'\n node_list[parent]['and'] ||= {}\n node_list[parent]['and'][k] = v\n node_list[k] = node_list[parent]['and'][k]\n elsif v['condition'] == 'or'\n node_list[parent]['or'] ||= {}\n node_list[parent]['or'][k] = v\n node_list[k] = node_list[parent]['or'][k]\n else\n # TODO: sink?\n node_list[parent]['or'] ||= {}\n node_list[parent]['or'][k] = v\n node_list[k] = node_list[parent]['or'][k]\n end\n end\n end\n\n @json_tree_type = 'tree'\n @json_tree = new_tree\n end", "def create_tree(father,tree)\n tree.each do |name|\n n = Meta::create_class(father, name[0], name[1])\n create_tree(n, name[2])\n end\nend", "def build_tree(unit, node, level = 0)\r\n return nil if level > @max_depth\r\n \t\r\n unit.next_move(node.current_case).each do |next_case|\r\n next if next_case[0] < 0 || next_case[0] > 7 ||\r\n next_case[1] < 0 || next_case[1] > 7 \r\n \r\n next_node = Node.new(next_case, node)\r\n node.children << next_node\r\n\r\n build_tree(unit, next_node, level + 1)\r\n end \r\n end", "def tree(capa = 1)\n R3::Tree.new(capa)\nend", "def generate_class_tree_level(parent='')\n $all.map { |klass|\n if parent == klass['parentname']\n [\n klass['name'],\n \"classes/#{klass['fullname']}.html\", # klass.path, \n '',\n generate_class_tree_level(klass['fullname'])\n ]\n else\n nil\n end\n }.compact\nend", "def generate_tree\n root =\tTreeNode.new(3)\n root.left =\tTreeNode.new(9)\n right = \t\tTreeNode.new(20)\n right.left = \tTreeNode.new(15)\n right.right = TreeNode.new(7)\n root.right = \tright\n root\nend", "def build_tree\n c1 = ComponentNode.new(110)\n c2 = ComponentNode.new(20)\n c3 = ComponentNode.new(20)\n c4 = ComponentNode.new(150)\n c5 = ComponentNode.new(80)\n c6 = ComponentNode.new(120, [c1, c2, c3])\n c7 = ComponentNode.new(180, [c4, c5])\n return(ComponentNode.new(200, [c6, c7]))\n end", "def build_tree(arr)\n #arr.shuffle!\n arr.each do |x|\n if @root == nil\n @root = Node.new(x)\n else\n current_node = @root\n until current_node == nil\n if x < current_node.value\n parent = current_node\n direction = \"left\"\n current_node = current_node.left_child\n elsif x > current_node.value\n parent = current_node\n direction = \"right\"\n current_node = current_node.right_child\n end\n end\n if direction == \"left\"\n parent.left_child = Node.new(x)\n elsif direction == \"right\"\n parent.right_child = Node.new(x)\n end\n end\n end\n end", "def solution(t)\n # write your code in Ruby 2.2\n depth = 0\n childs = []\n\n childs << t.l if t.l\n childs << t.r if t.r\n\n while not childs.empty? do\n depth += 1\n\n cc = []\n childs.each do |t|\n cc << t.l if t.l\n cc << t.r if t.r\n end\n\n childs = cc\n end\n\n depth\nend", "def tree\n @tree ||= build_tree\n end", "def build_tree(arr)\n #take array, turn into bt with node objs\n return nil if arr.empty?\n\n mid = (arr.size - 1)/2\n current_node = Node.new(arr[mid])\n\n current_node.left = build_tree(arr[0...mid])\n current_node.right = build_tree(arr[(mid+1)..-1])\n \n current_node\n end", "def code_tree\n kids = j_instance.getChildren\n\n kids.each_with_object([]) do |kid, acc|\n data = { type: kid.getType, parent_type: j_instance.getType, token: kid.toString }\n subtree = self.class.new(kid).code_tree\n data[:children] = subtree unless subtree.empty?\n acc << data\n end\n end", "def generate_class_tree\n debug_msg \"Generating class tree\"\n tree = generate_class_tree_level\n debug_msg \" writing class tree to %s\" % TREE_FILE\n File.open(TREE_FILE, \"w\", 0644) do |f|\n f.write('var tree = '); f.write(tree.to_json(:max_nesting => 0))\n end unless $dryrun\nend", "def build_ranked_tree(model)\n # inflate the node id to test id wrap around edge cases\n # NODES=4..9 seem like edge cases\n ENV[\"NODES\"].to_i.times { model.create!.destroy } if ENV[\"NODES\"]\n\n n1 = model.create!(:rank => 0)\n n2 = model.create!(:rank => 1)\n n3 = model.create!(:rank => 3, :parent => n1)\n n4 = model.create!(:rank => 0, :parent => n2)\n n5 = model.create!(:rank => 0, :parent => n1)\n n6 = model.create!(:rank => 1, :parent => n2)\n\n puts \"create: #{n1.id}..#{n6.id}\" if ENV[\"NODES\"]\n [n1, n2, n3, n4, n5, n6]\n end", "def build_tree(tree_size, input)\n nodes = Array.new(tree_size) { Node.new(nil, nil, nil) }\n\n tree_size.times do |i|\n line = input.next\n val, left, right = line.chomp.split.map(&:to_i)\n nodes[i].val = val\n nodes[i].left = nodes[left] unless left == -1\n nodes[i].right = nodes[right] unless right == -1\n end\n \n nodes.first\nend", "def build_tree( n , d )\n \n if d.key?('v')\n n < d['v'] ? build_tree(n , d['l']) : build_tree(n, d['r'])\n else\n d['l'] = {}\n d['v'] = n\n d['r'] = {}\n end\n \nend", "def build_tree(array)\n\t\t@root = Node.new(array.shift)\n\t\tarray.each { |value| add_node(value, @root)}\n\tend", "def tree\n @roots = @cards.roots\n # TODO: remove jbuilder?\n render :tree, status: :ok\n end", "def custom_tree\n\t\t#if they haven't made a shrink range/trunk yet, make one for them\n\t\tif $shrink_range.empty?\n\t\t\t$shrink_Range = (4..6).to_a\n\t\tend\n\t\tif $trunk.empty?\n\t\t\t$trunk = (175..250).to_a\n\t\tend\n\t\t\n\t\t@shrink = \"0.#{$shrink_range[0]}\".to_f\n\t\t#Height is 600, so y is in (0,600)\n\t\t$angle_of_separation = (@window.mouse_y / 10).to_i #this gives max of 60 degree angle, min of 0 (line)\n\t\t\n\t\t@branches = []\n\t\t@branches << [ [[@x, Height - @bot_margin], [@x, Height - $trunk[0]]] ]\n\t\t#Width is 800, so x is in (0,800)\n\t\t$num_splits = (((@window.mouse_x) / 100).to_i)+2 #this gives max of 8+2=10 splits, min of 2\n\t\t\n\t\tputs \"This output is from Custom Tree\"\n\t\tputs \"Number of splits: #{$num_splits}\"\t\n\t\tputs \"Angle of separation: #{$angle_of_separation}\"\n\t\tputs \"Shrink range: #{$shrink_range[0]} to #{$shrink_range[$shrink_range.length-1]}\"\n\t\tputs \"Split range: #{$split_range}\"\t\t\n\t\tputs \"Initial branch length: #{$trunk[0]} to #{$trunk[$trunk.length-1]}\"\n\t end", "def random_tree\n\t\t#range of possible angle separations between branches\n\t\t#big range seems to be ok, 30 to 60 works nice\n\t\t$angle_of_separation = (30..60).to_a\n\t\t#range of possible shrinkage values, will have a decimal in front of it\n\t\t#shrink determines how short each branch is\n\t\t$shrink_range = (4..6).to_a\n\t\t#split determines how many levels of branches there are\n\t\t#below 5 makes a pretty weak tree\n\t\t#above 7 makes a big blob of black\n\t\t$split_range = (5..7).to_a\n\t\t\n\t\t#Determines how many branches the current one splits off into\n\t\t$num_splits = rand(4)+2\n\t\t\n\t\t#how long the \"trunk\" is, height is 600\n\t\t#this gets ugly above 250\n\t\t$trunk = (150..250).to_a\n\t\t\n\t\t#pick a random number from the split range to be used as the number of splits\n\t\t$split_range = $split_range[rand($split_range.length)]\n\t\t#as a decimal, find the factor we will multiply future branches by\n\t\t@shrink = \"0.#{$shrink_range[rand($shrink_range.length)]}\".to_f\n\t\t#pick a random value for the angle of separation from the range\n\t\t$angle_of_separation = $angle_of_separation[rand($angle_of_separation.length)]\n\t\t\n\t\t#make a multidimensional array for branches\n\t\t@branches = []\n\t\t#start at the bottom, but not all the way down\n\t\t#move @x to the top of the trunk, ready for next branches\n\t\t@branches << [ [[@x, Height - @bot_margin], [@x, Height - $trunk[rand($trunk.length)]]] ] \n\t\t\n\t\tputs \"This output is from Random Tree\"\n\t\tputs \"Number of splits: #{$num_splits}\"\n\t\tputs \"Angle of separation: #{$angle_of_separation}\"\n\t\tputs \"Shrink range: #{$shrink_range[0]} to #{$shrink_range[$shrink_range.length-1]}\"\n\t\tputs \"Split range: #{$split_range}\"\n\t\tputs \"Initial branch length: #{$trunk[0]} to #{$trunk[$trunk.length-1]}\"\n\t\t\n\t end", "def make_tree(in_list, pid = self.pid)\n [].tap do |top_level|\n left_over = []\n # Categorize into top level, or not top level\n in_list.each do |node|\n if node['parent_page_id'].blank? || node['parent_page_id'] == pid\n top_level.unshift node\n else\n left_over.unshift node\n end\n end\n\n # For each of the top_level nodes make a subtree with the leftovers.\n top_level.each do |node|\n node['children'] = make_tree(left_over, node['id'])\n end\n end\n end", "def data_shapes tree\n acc = Array.new(MAX_DIM + 1) { [] }\n min_level = MAX_DIM + 1\n max_level = 0\n minmax = [min_level, max_level]\n\n search max_level, tree, acc, minmax\n\n min_level = minmax[0]\n max_level = minmax[1]\n\n if acc[max_level] && acc[max_level].all? { |a| a.nil? }\n # min_level is not set in this special case. Hence the check.\n elsif min_level != max_level\n raise ValueError, \"unbalanced tree: min depth #{min_level} and max depth #{max_level}\"\n end\n\n data = acc[max_level]\n shapes = acc[0...max_level].reverse\n\n [data, shapes]\n end", "def category_tree\n @category_tree = {}\n get_category_browse_nodes.each do |n|\n build_category_tree(n)\n end\n @category_tree\n end", "def build_tree array\n\t\t@root = Node.new array[0]\n\t\t@nodes += 1\n\t\tarray[1..-1].each do |var|\n\t\t\tinsert(@root,var)\n\t\tend\n\tend", "def build_hierarchy\n root = LetterNode.new(nil)\n\n # TODO: Limit word table to 50,000 highest ranking words\n\n words.each do |word|\n wl = root\n word.spelling.each_char do |letter|\n wl = wl.add(letter, word.count)\n end\n wl.word!(word.count)\n end\n\n root\n end", "def build_tree(array)\n array.sort!.uniq!\n left = 0\n right = array.length\n\n return build_driver(array, left, right)\n end", "def plant_tree\n @category = Category.new\n subject = @category.subjects.build\n subject.resources.build\n @categories = Category.all\n @subjects = Subject.all\n render 'new'\n end", "def build_tree(arr)\n\ntree = []\n\ntree.push(Node.new(arr[0]))\n\n arr[1..-1].each do |i|\n new_node = Node.new(i)\n\n condition = false\n current = tree[0]\n until condition == true\n if i > current.value && current.find_right_child.count == 0\n new_node.create_parent(current)\n current.create_right_child(new_node)\n tree.push(new_node)\n condition = true\n elsif i < current.value && current.find_left_child.count == 0\n new_node.create_parent(current)\n current.create_left_child(new_node)\n tree.push(new_node)\n condition = true\n elsif i > current.value && current.find_right_child.count == 1\n current = current.find_right_child[0]\n elsif i < current.value && current.find_left_child.count == 1\n current = current.find_left_child[0]\n end\n end\n end\n tree\nend", "def build_tree(ary)\n # If the array is sorted, the tree will not be balanced\n ary.shuffle!\n ary.each { |item| insert(item) }\n end", "def generate_tree_nodes(ttt)\n while !@avail_moves.empty?\n player_moves = create_new_players_moves_array\n player_makes_move(player_moves)\n create_new_child_node(ttt, player_moves)\n end\n end", "def build_tree(input_array)\n sorted_set = input_array.sort.uniq\n build_tree_aux(sorted_set, 0, sorted_set.length - 1)\n end", "def tree\n @treetop = @proj.default_ontology_class\n @proj.ontology_classes.first if !@treetop\n redirect_to :action => :new, :controller => :ontology_classes and return if !@treetop\n @colored_object_relationships = @proj.object_relationships.with_color_set\n @all_object_relationships = @proj.object_relationships \n render :action => 'ontology/tree/index'\n end", "def build_tree_arbitrary(arr)\n node = Node.new(arr[0])\n queue = [node]\n @root = node\n i = 0\n\n until queue.empty?\n node = queue.shift\n children = node_children(node, i, arr)\n queue.concat(children)\n i += 2\n end\n end", "def target_tree\n tree = []\n\n tree << self.level.build.target if self.level.build?\n tree << self.level.patch.target if self.level.patch? || self.level.build?\n tree << self.level.version.target if self.level.version? || self.level.patch? || self.level.build?\n tree << self.level.era.target\n\n tree\n end", "def class_tree\n @class_tree ||= generate_class_tree\n end", "def make_quadtree(pixels, width, height)\n $count = 0\n def make_quadtree_r(pixels, x, y, w, h)\n sum = 0\n (0..w-1).each do |x_off|\n (0..h-1).each do |y_off|\n sum += pixels[x+x_off][y+y_off]\n end\n end\n # all black or white test\n if sum == 0\n $count += 1\n sides = [\n CP::Shape::Segment.new($static_body, CP::Vec2.new(x,y), CP::Vec2.new(x+w,y), 0.1),\n CP::Shape::Segment.new($static_body, CP::Vec2.new(x+w,y), CP::Vec2.new(x+w,y+h), 0.1),\n CP::Shape::Segment.new($static_body, CP::Vec2.new(x+w,y+h), CP::Vec2.new(x,y+h), 0.1),\n CP::Shape::Segment.new($static_body, CP::Vec2.new(x,y+h), CP::Vec2.new(x,y), 0.1),\n ]\n sides.each{|x| x.e = 1.0; $space.add_static_shape(x)}\n Quadtree.new(0, nil, nil, nil, nil)\n elsif sum == 255*w*h\n $count += 1\n Quadtree.new(1, nil, nil, nil, nil)\n else\n Quadtree.new(nil, \n make_quadtree_r(pixels, x, y, w/2, h/2),\n make_quadtree_r(pixels, x+w/2, y, w/2, h/2),\n make_quadtree_r(pixels, x, y+h/2, w/2, h/2),\n make_quadtree_r(pixels, x+w/2, y+h/2, w/2, h/2))\n end\n end\n tree = make_quadtree_r(pixels, 0, 0, width, height)\n puts \"Number of nodes: #{$count} vs #{width*height} for full data (#{$count.to_f/(width*height)*100}%)\"\n tree\nend", "def tree_results(word_data)\n #get the data ready for d3 view\n tree_data = {\"name\"=> (@topic.name), \"info\" => \"tst\", \"children\" => []}\n \n word_data.each do |text, v|\n tree_data[\"children\"].push({\"name\" => text.to_s, \"children\" => []})\n end\n \n tree_data[\"children\"][0][\"children\"] << Hash[\"name\", word_data[:word]]\n \n word_data[:definitions].each do |text|\n tree_data[\"children\"][1][\"children\"] << Hash[\"name\", text[\"text\"]]\n end\n \n word_data[:word_associations].each do |text|\n tree_data[\"children\"][2][\"children\"] << Hash[\"name\", text[\"relationshipType\"], \"children\", []]\n end \n if word_data[:reverse_definitions][\"results\"].nil? \n tree_data[\"children\"][3][\"children\"] << nil\n else\n word_data[:reverse_definitions][\"results\"].each do |result| \n tree_data[\"children\"][3][\"children\"] << Hash[\"name\", result[\"text\"]]\n end\n end\n i = 0\n word_data[:word_associations].each do |text|\n text[\"words\"].each do |word|\n tree_data[\"children\"][2][\"children\"][i][\"children\"] << Hash[\"name\", word]\n end\n i+=1\n end\n #reduce duplicates in word_association hash\n tree_data[\"children\"][3][\"children\"].uniq!\n tree_data[\"children\"][2][\"children\"].uniq!\n return tree_data\n end", "def initialize(tree=nil)\n @visited = [] \n @tree = tree\n end", "def build_tree(arr)\n @root = Node.new(arr.shift)\n arr.each { |data| insert_data(data, @root) }\n end", "def construct_similarity_graph_for_given_level_of_separation(level, limit = 45)\n nodes = self.load_top_similar_artists()\n edges = Array.new\n nodes.each do |node|\n vals = [self.ArtistID, node.ArtistID].sort\n edge = {\"from\" => vals[0], \"to\" => vals[1]}\n edges.push(edge)\n end\n self.instance_variable_set(:@similar_artists_loaded, true)\n nodes.push(self)\n i = 1\n while i < level\n new_ids = nodes.map { |x| if !(x.instance_variable_get(:@similar_artists_loaded)==true) then x.ArtistID else nil end}.compact\n all_ids = nodes.map { |x| x.ArtistID }.compact\n data = load_connections(new_ids, all_ids, limit)\n nodes.each do |node|\n node.instance_variable_set(:@similar_artists_loaded, true)\n end\n ids_to_load = data.map { |entry| \n if (!nodes.include?(ArtistGroup.new({:ArtistID => entry[\"ArtistID2\"]})))\n entry[\"ArtistID2\"]\n else nil end\n }.compact\n nodes += ArtistGroup.find(ids_to_load)\n data.each do |entry|\n vals = [entry[\"ArtistID1\"], entry[\"ArtistID2\"]].sort\n edge = {\"from\" => vals[0], \"to\" => vals[1]} \n if (!edges.include?(edge) and nodes.include?(ArtistGroup.new({:ArtistID => entry[\"ArtistID2\"]})) and nodes.include?(ArtistGroup.new({:ArtistID => entry[\"ArtistID1\"]})))\n edges.push(edge)\n end\n end \n i += 1\n end\n return nodes, edges\n end", "def create_tree(node, elem, level, parent)\n node.level = level\n elemtype = check_type(elem[1])\n case elemtype\n when \"array\"\n node.kind = \"array\"\n node.arrsize = elem[1][\".array_size\"].to_i\n if elem[1].has_key?(\".subtype\") && elem[1][\".subtype\"].has_key?(\".members\")\n elem[1][\".subtype\"][\".members\"].each do |m|\n x = Tree.new(m[0], item_type(elem[1]), node)\n node.create_child(x)\n create_tree(x, m, level+1, node)\n end\n if elem[1][\".subtype\"].has_key?(\".type_or_id_name\")\n elem[1][\".subtype\"][\".type_or_id_name\"] =~ /\\((.+)\\): (\\w+)/\n node.s_u_name = $2.clone\n else\n node.s_u_name = \"__ANON__\"\n end\n node.basetype = node.data = elem[1][\".subtype\"][\".type\"].clone\n else\n subkind = check_type(elem[1][\".subtype\"])\n case subkind\n when \"enum\"\n node.basetype = \"enum\"\n node.data = {\".type\" => elem[1][\".subtype\"][\".type\"]}\n node.data[\".type_or_id_name\"] = elem[1][\".subtype\"][\".type_or_id_name\"]\n arr = []\n elem[1][\".subtype\"][\".values\"].each { |k,v| arr << [k,v] }\n node.data[\".values\"] = arr.clone\n node.data[\".values\"].sort! { |a,b| a[1] <=> b[1] }\n when \"numeric_ose\", \"boolean\"\n elem[1][\".subtype\"][\".type_or_id_name\"] =~ /\\((.+)\\): (\\w+)/\n node.basetype = $2.clone\n when \"native\", \"numeric_other\"\n node.basetype = \"OTHER\"\n node.data = {\".type\" => elem[1][\".subtype\"][\".type\"]}\n if elem[1][\".subtype\"].has_key?(\".signed\")\n node.data[\".signed\"] = elem[1][\".subtype\"][\".signed\"] \n end\n if elem[1][\".subtype\"].has_key?(\".type_or_id_name\")\n node.data[\".type_or_id_name\"] = elem[1][\".subtype\"][\".type_or_id_name\"]\n end\n end\n node.leaf = true\n end\n when \"struct\", \"union\"\n node.kind = elemtype\n if is_anon?(elem[1])\n node.s_u_name = \"__ANON__\"\n else\n node.s_u_name = item_name(elem[1])\n end\n elem[1][\".members\"].each do |m|\n x = Tree.new(m[0], item_type(elem[1]), node)\n node.create_child(x)\n create_tree(x, m, level+1, node)\n end\n when \"enum\"\n node.kind = \"enum\"\n node.basetype = \"enum\"\n node.s_u_name = item_name(elem[1])\n node.parent = parent\n node.leaf = true\n arr = []\n elem[1][\".values\"].each { |k,v| arr << [k,v] }\n node.data = arr.clone\n node.data.sort! { |a,b| a[1] <=> b[1] }\n when \"numeric_ose\"\n node.kind = \"numeric\"\n node.basetype = item_name(elem[1])\n node.parent = parent\n node.leaf = true\n when \"boolean\"\n node.kind = \"boolean\"\n node.basetype = item_name(elem[1])\n node.parent = parent\n node.leaf = true\n when \"native\", \"numeric_other\"\n node.kind = \"numeric\"\n node.basetype = \"OTHER\"\n node.data = {'.type' => elem[1][\".type\"]}\n node.data[\".signed\"] = elem[1][\".signed\"] if elem[1].has_key?(\".signed\")\n if elem[1].has_key?(\".type_or_id_name\")\n node.data[\".type_or_id_name\"] = elem[1][\".type_or_id_name\"]\n end\n node.parent = parent\n node.leaf = true\n else\n raise \"Node #{node.name} contains erroneous data\" \n end\n end", "def build_node_from_model( n )\n return {\n 'id' => n['key'].to_i,\n 'parent_id' => n['parent'].to_i,\n 'children' => [],\n 'weight' => n['weight'].to_i / 100.0,\n 'operation' => n['name'],\n 'metric' => n['dataname']\n }\n end", "def build_hierarchy(circles=nil, roles=nil)\n Glassfrog::Graph.hierarchy(self, circles, roles)\n end", "def calc_tree\n tree = []\n n = 1\n while n <= @n\n result = []\n result = [[0, 1]] if n == 1\n tree.each do |row|\n line1 = []\n line2 = []\n row.each_with_index do |elem, i|\n line1 << \"#{elem}0\" if i.positive?\n line2 << \"#{elem}0\" if i.zero?\n line2 << \"#{elem}1\"\n end\n result << line1 unless row.count == 1\n result << line2\n end\n tree = result\n n += 1\n end\n tree\n end", "def initialize(tree={})\n tree.each do |k,v|\n @node_name = k\n @children = v.map {|sk,sv| Tree.new({sk => sv}) }\n end\n end", "def build_tree(s)\n bytes = s.bytes\n uniq_b = bytes.uniq\n nodes = uniq_b.map { |byte| Leaf.new(byte, bytes.count(byte)) }\n until nodes.length == 1\n node1 = nodes.delete(nodes.min_by(&:count))\n node2 = nodes.delete(nodes.min_by(&:count))\n nodes << Node.new(node1, node2, node1.count + node2.count)\n end\n nodes.fetch(0)\nend", "def generate_class_tree_level(classes)\n tree = []\n list = classes.select{|c| c.with_documentation? }\n list = list.sort\n list.each do |c|\n item = c.to_h\n item[:methods] = c.method_list.map{ |m| m.to_h }\n item[:classes] = generate_class_tree_level(c.classes_and_modules)\n tree << item\n end\n tree\n end", "def build_move_tree\n move_q = [@root]\n while move_q.length > 0\n children = new_move_positions(move_q[0].value)\n children.each do |kid|\n move_q[0].add_child(PolyTreeNode.new(kid))\n end\n move_q += move_q[0].children\n move_q.shift\n end\n nil\n end", "def tree\n @vision = Vision.first\n end", "def tree\n {\n snp_sample_size: @tree_SNP_sample_size,\n snp_total_count: @tree_SNP_total_count,\n tree_node_min_size: @tree_node_min_size,\n classes: @classes\n }\n end", "def build_tree(array)\n tree = TreeNode.new(array[0], 0)\n (1..array.length-1).each {|i|\n insert_into_tree(tree, array[i], i)\n }\n tree\nend", "def build_tree\n roots = Set.new\n hash = {}\n nodes = selected_nodes\n\n nodes.each do |node|\n loop do\n id = node.id\n parent_id = node.parent_id\n\n hash[id] ||= {}\n if hash.key?(parent_id)\n # Another loop has already added our parent. Add ourself to its hash\n # and break early.\n hash[parent_id][id] = hash[id]\n break\n else\n if selected_node_ids.include?(parent_id)\n # Our parent is a selected node. Add a hash for it and add ourself\n # to that. Keep looping to add our parent's parent.\n hash[parent_id] = {}\n hash[parent_id][id] = hash[id]\n node = nodes_by_id[parent_id]\n else\n # Our parent isn't selected, so we must be a root.\n roots.add(id)\n break\n end\n end\n end\n end\n\n hash.keep_if { |k, _| roots.include?(k) }\n end", "def tree_recursive(parent)\n threshold ||= 2 * 12 # 8x8 by default\n\n parent.get_info do |offset_x, offset_y, width, height|\n if (width >= threshold || height >= threshold)\n child_1 = nil\n child_2 = nil\n if (height >= threshold) # cut horizontally\n child_1 = Node.new(parent.offset.clone, [width, height/2])\n child_2 = Node.new([(parent.offset[0] + height/2),parent.offset[1]], [width, height - height/2])\n else\n child_1 = Node.new(parent.offset.clone, [width/2, height])\n child_2 = Node.new([parent.offset[0], (parent.offset[1] + width/2)], [width - width/2, height])\n end\n parent.left = child_1\n parent.right = child_2\n child_1.parent = child_2.parent = parent\n\n tree_recursive(child_1)\n tree_recursive(child_2)\n end\n end\n end", "def build_tree(data)\n @root = Node.new(data[0])\n data.shift\n data.each { |value| @root.insert(value) }\n end", "def build_tree(array)\n\t\t@root = Node.new(array[0])\n\t\ttemp_root = @root\n\n\t\tarray[1..-1].each do |node_value|\n\t\t\tinsert_node(node_value, temp_root)\n\t\tend\n\tend", "def make_tree(pre, inord)\n return if pre.size == 0\n root_node = Node.new(pre[0])\n idx = inord.index(pre[0])\n root_node.left = make_tree(pre[1..idx], inord[0...idx])\n root_node.right = make_tree(pre[idx+1...pre.size], inord[idx+1...inord.size])\n return root_node\nend", "def build_category_tree(n, child = nil)\n amz_node = BrowseNode.parse(n.to_s)\n amz_node.child = child unless child.nil?\n\n if n.search(\"./IsCategoryRoot\").size > 0\n @category_tree[amz_node.name] ||= []\n @category_tree[amz_node.name] << amz_node\n else\n parents = n.search(\"./Ancestors/BrowseNode\")\n if parents.size > 0\n build_category_tree(parents[0], amz_node)\n end\n end\n\n\n end", "def generate_nodes(parent = nil, vectors = nil)\n #puts \"generate_nodes(#{[parent.name, parent.content].inspect}, [#{vectors.size} vectors])\" unless parent.nil?\n vectors ||= @set.vectors\n remaining_attributes = parent.nil? ? @set.non_decision_attributes.map(&:name) : (@set.non_decision_attributes.map(&:name) - ancestor_attributes(parent))\n unless parent.nil?\n \n #puts \"parent: #{parent.content} at depth #{depth(parent)}\"\n # if all examples associated with parent leaf have same target attribute value\n decision_values = vectors.map {|v| @set.decision_value_of_vector(v)}\n unique_decision_values = decision_values.uniq\n \n if unique_decision_values.size == 1\n #puts \" all examples associated with parent leaf have same target attribute value\"\n parent.content = @set.decision_attribute\n return unique_decision_values.first\n end\n \n # if each attribute has been used along this path\n # if remaining_attributes.empty?\n # #puts \" each attribute has been used along this path\"\n # return decision_values.first\n # end\n end\n evaulate_real_attributes(vectors, remaining_attributes)\n attribute = @set.max_gain_attribute(vectors, remaining_attributes)\n if attribute.nil?\n @root.printTree\n y vectors\n y remaining_attributes\n end\n #puts \" max gain attribute: #{attribute}\"\n if parent.nil?\n @root = TreeNode.new(\"ROOT\", attribute)\n generate_nodes(@root, vectors)\n else\n # if parent.content.nil?\n # @root.printTree\n # p parent\n # p attribute\n # end\n if parent.content == \"standby-pay\"\n p @set.values_of_attribute(parent.content)\n end\n @set.values_of_attribute(parent.content).each do |value|\n value_set = @set.subset(parent.content, value, vectors)\n # puts \"value_set = @set.subset(#{parent.content.inspect}, #{value.inspect}, [#{vectors.size} vectors])\"\n # puts \"value_set.size: #{value_set.size}\"\n node = TreeNode.new(value, attribute)\n parent << node\n if value_set.empty? || remaining_attributes.size == 1\n #p 'value_set is empty or remaining_attributes will be'\n end_value = @set.best_value(@set.decision_attribute, vectors)\n node.content = @set.decision_attribute\n node << TreeNode.new(end_value, nil)\n elsif end_value = generate_nodes(node, value_set)\n #p 'leaf children'\n node << TreeNode.new(end_value, nil)\n end\n #p end_value\n end\n end\n return false\n end", "def build_tree(data_array)\n @root = nil # overwrites tree, even if array is empty\n data_array.each_with_index do |data, index|\n if index == 0\n @root = Node.new(data)\n else\n set_next_node(data)\n end\n end\n end", "def trees\n nests.map do |tree_instance|\n tree_isntance.tree\n end\n end", "def parse_category_tree\n dry_run_notification\n\n page_html = get_page_html \"#{@donor.url}/mall/index.htm\"\n return display_error \"\\e[33;1m#{self.class}##{__method__}\\e[0m failed to get page html\" if page_html.blank?\n\n page_html.css('#headerWarp .cateAllList ul li').each do |menu_item|\n category_link_level_1 = get_link menu_item.at_css('dt a')\n category_level_1 = save_category(category_link_level_1) unless DRY_RUN\n display_category_structure category_link_level_1, \"#{'-' * 80}\\n\"\n\n menu_item.css('dd a').each do |menu_sub_item|\n category_link_level_2 = get_link menu_sub_item\n save_category(category_link_level_2, category_level_1.id) unless DRY_RUN\n display_category_structure category_link_level_2, ' '\n end\n end\n end", "def build_tree(array)\n return nil if array.empty?\n\n mid = (array.length - 1) / 2\n node = Node.new(array[mid])\n node.left = build_tree(array[0...mid])\n node.right = build_tree(array[mid+1..-1])\n node\n end", "def create_tree(start_tile)\n queue = [start_tile]\n visited.add(start_tile.pos)\n\n while !queue.empty?\n cur_tile = queue.shift\n tiles = adjacent_tiles(cur_tile.pos)\n\n tiles.each do |tile_pos|\n tile = self[tile_pos]\n tile.parent = cur_tile\n queue.push(tile)\n visited.add(tile.pos)\n end\n end\n start_tile\n end", "def build_tree array\n\t\t@root = Node.new(array.shift)\n\t\tparent = @root\n\t\tarray.each do |el|\n\t\t\twhile true\n\t\t\t\tif el <= parent.value\n\t\t\t\t\tif parent.left_child.nil?\n\t\t\t\t\t\tparent.left_child = Node.new(el,parent)\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse\n\t\t\t\t\t\tparent = parent.left_child\n\t\t\t\t\tend\n\t\t\t\telsif el > parent.value\n\t\t\t\t\tif parent.right_child.nil?\n\t\t\t\t\t\tparent.right_child = Node.new(el,parent)\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse\n\t\t\t\t\t\tparent = parent.right_child\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def tree\n return nil if messages.size == 0\n build_tree unless @tree\n @tree\n end", "def build_tree(arr)\n @root = insert_node(nil, arr.shift)\n arr.each { |value| insert_node(@root, value) }\n end", "def build_tree(data, parent = nil)\n return if data.size.zero?\n center = half(data)\n value = data[center]\n @depth_first << value\n\n # Recusion to split halves until zero then execute logic\n build_tree(l_half = data[0...center], value)\n build_tree(r_half = data[center + 1..-1], value)\n\n # Node creation and set node properties\n l_child = l_half[half(l_half)]\n r_child = r_half[half(r_half)]\n Node.new(value, parent, l_child, r_child)\n end", "def build_tree(elements)\n return if elements.empty?\n char = elements.shift\n node = BinaryTree.new(char)\n if char == \"I\"\n node.left = build_tree(elements)\n node.right = build_tree(elements)\n end\n return node\nend", "def build_graph(node = @root)\n node.make_knights(@target)\n if node.connected_knights.empty?\n return\n else\n node.connected_knights.each do |knight|\n build_graph(knight)\n end\n end\n end", "def create_class_tree(classtree = ClassTreeNode.new(Kernel),\n ignore = [ClassTreeNode, ObjectDescriber, ObjectBrowser, ObjectBrowser::UI, ObjectBrowser::UI::DescriptionFactory])\n ObjectSpace.each_object do | x |\n classnode = classtree\n x.class.ancestors.reverse[1..-1].inject(classtree){ | classnode, klass | classnode.add_class(klass) }.add_object(x)\n end \n classtree\n end", "def generate_toc_tree(toc, type, attr); end", "def get_tree(person)\n\n h = build_adjacency_list\n\n n = h[get_tree_top_id(person)] # start creating the tree at this person's supervisor, if there is one\n\n nodes = to_node(h, n) # recurse through the SQL results to construct a tree (nested hashes)\n\n nodes\n end", "def build_tree(array)\n return nil if array.empty?\n \n middle = (array.size - 1) / 2\n root_node = Node.new(array[middle])\n \n root_node.left = build_tree(array[0...middle])\n root_node.right = build_tree(array[(middle + 1)..-1])\n \n root_node\n end", "def parsed_tree; end", "def parse_category_tree\n dry_run_notification\n\n page_html = get_page_html @donor.url\n\n if page_html\n main_category_last = page_html.css('.content > .main-cat').last\n return false if main_category_last.nil?\n main_category_last.css('> .cat-item > .middle').each do |parent_category|\n parent_category_link = get_category_link(parent_category.at_css('a'))\n\n next if parent_category_link[:name].empty? && parent_category_link[:path].empty?\n\n category_parent = save_category(parent_category_link) unless DRY_RUN\n display_category_structure(parent_category_link, \"#{'-' * 80}\\n\")\n\n if parent_category\n parent_category.css('.main-cat > .cat-item > .middle').each do |subcategory_first_level_node|\n subcategory_first_level_link = get_category_link(subcategory_first_level_node.at_css('a'))\n\n subcategory_first_level = save_category(subcategory_first_level_link, category_parent.id) unless DRY_RUN\n display_category_structure(subcategory_first_level_link, ' ' * 2)\n\n subcategory_first_level_node.css('.main-cat > .cat-item > .middle').each do |subcategory_second_level_node|\n subcategory_second_level_link = get_category_link(subcategory_second_level_node.at_css('a'))\n\n save_category(subcategory_second_level_link, subcategory_first_level.id) unless DRY_RUN\n display_category_structure(subcategory_second_level_link, ' ' * 4)\n end\n end\n end\n end\n end\n end", "def build_tree(nodes_fragement)\n nodes_element = LonelyPlanet::Node.new nodes_fragement\n node = LonelyPlanet::TreeNode.new(nodes_element.name, nodes_element.id)\n if nodes_element.has_child?\n nodes_element.children.all? { |child_frag|\n node << build_tree(child_frag)\n }\n end\n node\n end", "def create_tree(items, rootpage)\n _, tree = visit_nodes(items, rootpage.lft + 1, rootpage.id, rootpage.depth + 1, {}, \"\", rootpage.restricted)\n tree\n end", "def create_tree(rules)\n # Combine all of our rules into one hash\n parsed_rules = rules.reduce({}) { |h, r| h.merge!(parse_rule(r)) }\n\n # Inner-function recursion which is useful because we want to use\n # closures to get at `parsed_rules` to grab rules for bag colors\n # since this thing nests deep.\n recurse = -> current_node do\n # One-line pattern match the color and count out\n current_node => { color:, count: }\n\n # Each color may well have more children below it, so we grab the\n # rule for that color and keep recursing down until we find an\n # instance of \"no other bags\".\n children = parsed_rules[color].flat_map(&recurse)\n\n # Now we have a count, so we need `count` instances of the node.\n [Node[color, children]] * count\n end\n\n # This drops us into the recursion. I could probably eliminate part\n # of this but don't quite want to at the moment.\n parsed_rules.map { |color, children| Node[color, children.flat_map(&recurse)] }\nend", "def build\n reset\n visit(root, @root)\n end", "def tree\n Tree.new(self)\n end", "def build_tree(arr)\n if arr.empty?\n return nil\n end\n\n mid = arr.length/2\n root = Node.new(arr[mid])\n\n root.left = build_tree(arr[0...mid])\n root.right = build_tree(arr[(mid+1)..-1])\n\n root\nend", "def make_tree_for(position)\n root = TreeNode.new(nil, position)\n\n\nend", "def parse_tree(*klasses)\n result = []\n klasses.each do |klass|\n klassname = klass.name rescue '' # HACK klass.name should never be nil\n # Tempfile's DelegateClass(File) seems to\n # cause this\n klassname = \"UnnamedClass_#{klass.object_id}\" if klassname.empty?\n klassname = klassname.to_sym\n\n code = if Class === klass then\n sc = klass.superclass\n sc_name = ((sc.nil? or sc.name.empty?) ? \"nil\" : sc.name).intern\n [:class, klassname, [:const, sc_name]]\n else\n [:module, klassname]\n end\n\n method_names = []\n method_names += klass.instance_methods false\n method_names += klass.private_instance_methods false\n # protected methods are included in instance_methods, go figure!\n\n method_names.sort.each do |m|\n r = parse_tree_for_method(klass, m.to_sym)\n code << r\n end\n\n klass.modules.each do |mod| # TODO: add a test for this \n mod.instance_methods.each do |m|\n r = parse_tree_for_method(mod, m.to_sym)\n code << r\n end\n end\n\n klass.singleton_methods(false).sort.each do |m|\n code << parse_tree_for_method(klass, m.to_sym, true)\n end\n\n result << code\n end\n return result\n end", "def build_tree(target_object)\n\n tree = {class: get_test_class(target_object), id: target_object.object_id, composition: []}\n if (target_object.is_a? Array)\n tree[:composition] = deconstruct_array(target_object)\n elsif target_object.is_a? Hash\n tree[:composition] = deconstruct_hash(target_object)\n elsif target_object.is_a? Pretentious::RecordedProc\n tree[:composition] = deconstruct_proc(target_object)\n tree[:given_block] = target_object.given_block?\n tree[:recorded_proc] = target_object\n tree[:id] = target_object.target_proc.object_id\n tree[:block_params] = self.class.block_param_names(target_object)\n elsif target_object.methods.include? :_get_init_arguments\n args = target_object._get_init_arguments\n\n unless args.nil?\n\n args[:params].each { |p|\n tree[:composition] << build_tree(p)\n }\n\n tree[:block] = build_tree(args[:block]) unless args[:block].nil?\n else\n tree[:composition] = target_object\n end\n\n else\n tree[:composition] = target_object\n end\n tree\n end", "def build_king_move_tree\n move_tree_template = MoveTree.new([0, 0])\n\n # Get the 8 surrounding spaces\n locations = [-1, 0, 1].repeated_permutation(2).to_a\n locations.delete([0, 0])\n\n locations.each do |loc|\n move_tree_template.root.add_child(loc)\n end\n\n move_tree_template\n end", "def build_tree(array)\n\t\t@root_node = Node.new(array[array.length / 2])\n\t\tarray[array.length / 2] = nil\n\t\tcounter = 0\n\t\tuntil counter == array.length\n\t\t\tset_value(array[counter], @root_node) if array[counter] != nil\n\t\t\tcounter += 1\n\t\tend\n\n\tend", "def build\n nodes = []\n chars = []\n\n expression.each_char do |character|\n\n if '(' == character\n\n chars << character\n\n elsif /\\d+/.match(character)\n\n nodes.push Tree.new(character.to_i)\n\n elsif operands.include?(character)\n\n while(chars.any? && chars.last != '(')\n t = Tree.new(chars.pop)\n t.right = nodes.pop\n t.left = nodes.pop\n nodes << t\n end\n\n chars << Operation::OPERATIONS[character].new\n\n elsif ')' == character\n\n while(chars.any? && chars.last != '(')\n t = Tree.new(chars.pop)\n t.right = nodes.pop\n t.left = nodes.pop\n nodes << t\n end\n\n chars.pop\n\n end\n\n end\n\n unless nodes.empty? && chars.empty?\n self.root = Tree.new(chars.pop)\n root.right = nodes.pop\n root.left = nodes.pop\n end\n\n raise \"Ka-Blam! You still have nodes and/or chars\" if nodes.any? || chars.any?\n\n root\n end", "def elegant_tree_by_levels(node)\n stack=[]\n stack.push node if node\n stack.each do |n|\n stack.push n.left if n.left\n stack.push n.right if n.right\n end\n stack.map! &:value\nend", "def category_tree\n cats = []\n categories.each do |cat|\n cats << cat\n cats = cats + cat.ancestors\n end\n return cats\n end", "def transform(tree); end", "def build_tree_2(data_array)\n root = nil\n \n data_array.each do |elem|\n node = insert_node(root, nil, elem) \n\troot ||= node\n end\n \n root\nend", "def build_tree tree_root=nil\n tree_root ||= self.tree_root\n Dir.mkdir(tree_root) unless File.directory?(tree_root)\n Dir.chdir(tree_root) do\n self.files.each do |entry|\n visit_tree entry do |type, name|\n case type\n when :file\n FileUtils.touch(name)\n when :directory\n Dir.mkdir(name)\n else\n throw \"BAD VISIT TREE TYPE. #{type}\"\n end\n end\n end\n end\n end", "def build_tree(data_array)\n root = nil\n \n data_array.each do |elem|\n cur_node = root\n \n node = Node.new(elem)\n\tnode.children = Array.new(2, nil)\n\t\n\twhile !cur_node.nil?\n\t if elem < cur_node.value\n\t if cur_node.children[0].nil?\n\t\t node.parent = cur_node\n\t\t cur_node.children[0] = node\n\t\t cur_node = node\n\t\tend\n\t\tcur_node = cur_node.children[0]\n\t else\n\t if cur_node.children[1].nil?\n\t\t node.parent = cur_node\n\t\t cur_node.children[1] = node\n\t\t cur_node = node\n\t\tend\n\t\tcur_node = cur_node.children[1]\n\t end\n\tend\n\t\n\troot ||= node\n\t \n end\n \n root\nend", "def build_accordions_and_trees_only\n # Build the Explorer screen from scratch\n allowed_features = ApplicationController::Feature.allowed_features(features)\n @trees = allowed_features.collect { |feature| feature.build_tree(@sb) }\n @accords = allowed_features.map(&:accord_hash)\n\n allowed_features\n end" ]
[ "0.686628", "0.63870203", "0.6285585", "0.6238042", "0.62215614", "0.6221035", "0.6182034", "0.61539394", "0.6019765", "0.5963613", "0.58705133", "0.5854121", "0.5821261", "0.58090204", "0.57919925", "0.578722", "0.5785339", "0.57389534", "0.5731139", "0.57135504", "0.5676343", "0.56703794", "0.56520176", "0.5650472", "0.5649187", "0.56231993", "0.56195474", "0.561872", "0.56167376", "0.56046814", "0.56043094", "0.5598117", "0.5589606", "0.55872005", "0.5586966", "0.55862767", "0.5565998", "0.55584544", "0.55430186", "0.55366457", "0.55229414", "0.5516805", "0.5493364", "0.549294", "0.54928595", "0.54847753", "0.5473047", "0.54596126", "0.5453859", "0.54507786", "0.54487115", "0.54460967", "0.5442069", "0.54411376", "0.5433803", "0.54155946", "0.54147154", "0.54067326", "0.5396929", "0.53966576", "0.53883743", "0.53859264", "0.5378377", "0.5374124", "0.5360055", "0.535998", "0.5359616", "0.53586125", "0.5348769", "0.5338079", "0.5335407", "0.5329122", "0.5317865", "0.5304558", "0.5301295", "0.5296407", "0.5294876", "0.5283863", "0.52673346", "0.5265577", "0.525239", "0.52509606", "0.5250404", "0.5244797", "0.5236763", "0.5235773", "0.52355736", "0.52334875", "0.5232515", "0.5231927", "0.5229131", "0.5224975", "0.52156186", "0.5215313", "0.52145284", "0.5211159", "0.52060294", "0.52055514", "0.5203978", "0.51969564" ]
0.6260847
3
Transfer the taxonomy to the current dataset
def transfer_taxonomy(tax) $stderr.puts 'Transferring taxonomy' return if tax.nil? pval = (project.metadata[:tax_pvalue] || 0.05).to_f tax_a = tax .select { |i| i[1] != '?' && i[2] <= pval } .map { |i| i[0, 2].join(':') } dataset.metadata[:tax] = MiGA::Taxonomy.new(tax_a) dataset.save end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_indicate_taxonomy\n @indicate_taxonomy = Indicate::Taxonomy.find(params[:id])\n end", "def taxonomy(context)\n taxonomy_drop(context).taxonomy\n end", "def set_taxonomy\n c = case self.class.base_class.name\n when 'CollectionObject'\n a = current_taxon_name\n\n # If we have no name, see if there is a Type reference and use it as proxy\n # !! Careful/TODO this is an arbitrary choice, technically can be only one primary, but not restricted in DB yet\n a ||= type_materials.primary.first&.protonym\n when 'Otu'\n taxon_name&.valid_taxon_name\n when 'AssertedDistribution'\n otu.taxon_name&.valid_taxon_name\n end\n\n if c\n @taxonomy = c.full_name_hash\n # Check for required 'Kingdom'\n if @taxonomy['kingdom'].blank?\n\n # Det is only to kingdom!\n if c.rank == 'kingdom'\n @taxonomy['kingdom'] = c.name\n else\n\n # Kindom is provided in ancestors\n if a = c.ancestor_at_rank(:kingdom)\n @taxonomy['kingdom'] = a.name\n else\n\n # TODO: re-add when dwc_fields merged\n # Very edge case for single kingom nomenclatures (almost none)\n # if c.rank_class::KINGDOM.size == 1\n # @taxonomy['kingdom'] = c.rank_class::KINGDOM.first\n # end\n\n end\n end\n end\n @taxonomy\n else\n @taxonomy ||= {}\n end\n end", "def update!(**args)\n @taxonomies = args[:taxonomies] if args.key?(:taxonomies)\n end", "def update!(**args)\n @taxonomies = args[:taxonomies] if args.key?(:taxonomies)\n end", "def update!(**args)\n @taxonomies = args[:taxonomies] if args.key?(:taxonomies)\n end", "def set_luxire_taxonomy\n @luxire_taxonomy = LuxireTaxonomy.find(params[:id])\n end", "def import_taxonomy\n\n parser = XML::Parser.file(@taxonomy_file_full_path, :encoding => XML::Encoding::UTF_8)\n taxonomy_document = parser.parse\n\n # root node\n root_node = taxonomy_document.find_first('//taxonomy_name')\n @taxonomy.add_node('0', root_node.content, nil)\n @logger.debug \"Root: #{root_node.content}\"\n\n # parsing the taxonomy doc into my Taxonomy class\n taxonomy_document.find('//node').each do |node|\n\n @logger.debug \"Node: #{node.attributes['atlas_node_id']}\"\n\n if node.children?\n\n node_id = node.attributes['atlas_node_id']\n node_name = node.find_first('./node_name').content\n @taxonomy.add_node(node_id, node_name, '0')\n\n node.find('./node').each do |child|\n\n @logger.debug \"Child #{child.attributes['atlas_node_id']}\"\n\n child_id = child.attributes['atlas_node_id']\n child_name = child.find_first('./node_name').content\n @taxonomy.add_node(child_id, child_name, node_id)\n\n end\n\n end\n\n end\n\n end", "def touch_taxons\n Amz::Taxon.where(id: taxon_and_ancestors.map(&:id)).update_all(updated_at: Time.current)\n Amz::Taxonomy.where(id: taxonomy_ids).update_all(updated_at: Time.current)\n end", "def add_taxons\n # TODO smart column ordering to ensure always valid by time we get to associations\n product_load_object.save_if_new\n\n chain_list = value.to_s.split(multi_assoc_delim) # potentially multiple chains in single column (delimited by multi_assoc_delim)\n\n chain_list.each do |chain|\n\n # Each chain can contain either a single Taxon, or the tree like structure parent>child>child\n name_list = chain.split(/\\s*>\\s*/)\n\n parent_name = name_list.shift\n\n parent_taxonomy = taxonomy_klass.where(:name => parent_name).first_or_create\n\n raise DataShift::DataProcessingError.new(\"Could not find or create Taxonomy #{parent_name}\") unless parent_taxonomy\n\n parent = parent_taxonomy.root\n\n # Add the Taxons to Taxonomy from tree structure parent>child>child\n taxons = name_list.collect do |name|\n\n begin\n taxon = taxon_klass.where(:name => name, :parent_id => parent.id, :taxonomy_id => parent_taxonomy.id).first_or_create\n\n # pre Rails 4 - taxon = taxon_klass.find_or_create_by_name_and_parent_id_and_taxonomy_id(name, parent && parent.id, parent_taxonomy.id)\n\n unless(taxon)\n logger.warn(\"Missing Taxon - could not find or create #{name} for parent #{parent_taxonomy.inspect}\")\n end\n rescue => e\n logger.error(e.inspect)\n logger.error \"Cannot assign Taxon ['#{taxon}'] to Product ['#{product_load_object.name}']\"\n next\n end\n\n parent = taxon # current taxon becomes next parent\n taxon\n end\n\n taxons << parent_taxonomy.root\n\n unique_list = taxons.compact.uniq - (@product_load_object.taxons || [])\n\n logger.debug(\"Product assigned to Taxons : #{unique_list.collect(&:name).inspect}\")\n\n @product_load_object.taxons << unique_list unless(unique_list.empty?)\n # puts @product_load_object.taxons.inspect\n\n end\n\n end", "def taxonomy_drop(context)\n drop = context[\"taxonomies.#{@reference}\"]\n unless drop\n raise StandardError, \"No taxonomy found with reference: #{@reference}\"\n end\n drop\n end", "def assign_category\n path = @row[:category]\n root = path.shift\n\n # this just needs to be set, for apparently no valid reason\n # I think think model is complely useless\n taxonomy = Spree::Taxonomy.find_or_create_by!(name:root)\n\n # here is real root of taxonomy tree\n taxon = Spree::Taxon.find_or_create_by!(parent_id: nil, taxonomy_id: taxonomy.id, name: root)\n\n # now check for existance of 2 parent elements, 3 and n+ is ignorred\n taxon = Spree::Taxon.find_or_create_by!(parent_id: taxon.id, taxonomy_id: taxonomy.id, name: path[0]) if path[0]\n taxon = Spree::Taxon.find_or_create_by!(parent_id: taxon.id, taxonomy_id: taxonomy.id, name: path[1]) if path[1]\n\n # it is weird why this model is named Spree::Classification instead of Spree::ProductsTaxon\n # it maps to \"spree_products_taxons\" table\n Spree::Classification.find_or_create_by! product_id: @product.id, taxon_id: taxon.id\n end", "def create\n @indicate_taxonomy = Indicate::Taxonomy.new(indicate_taxonomy_params)\n\n respond_to do |format|\n if @indicate_taxonomy.save\n format.html { redirect_to @indicate_taxonomy, notice: 'Taxonomy was successfully created.' }\n format.json { render :show, status: :created, location: @indicate_taxonomy }\n else\n format.html { render :new }\n format.json { render json: @indicate_taxonomy.errors, status: :unprocessable_entity }\n end\n end\n end", "def category_taxonomy\n @category_taxonomy ||= Spree::Taxonomy.find_or_create_by(name: 'Category')\n end", "def setup_taxons(record, data)\n taxon_list = split_data(data)\n\n taxon_list.each do |taxon_str|\n taxon_names = taxon_str.split(/\\s*>\\s*/)\n taxonomy = Spree::Taxonomy.find_or_create_by(name: taxon_names.shift)\n parent = taxonomy.root\n associate_to_product(record, 'taxons', parent)\n\n taxon_names.each do |taxon_name|\n taxon = Spree::Taxon.find_or_create_by(name: taxon_name,\n taxonomy: taxonomy,\n parent: parent)\n associate_to_product(record, 'taxons', taxon)\n parent = taxon\n end\n end\n end", "def set_tax_category\n @tax_category = current_store.tax_categories.find(params[:id])\n end", "def ingest\n return \"filename is blank\" if @taxonomy_file == \"\"\n taxonomy_doc = read_taxonomy\n\n xpath = find_deepest_node(taxonomy_doc)\n destinations_lookup = {}\n get_place_info_and_parent_place_info_from_node_xpath(taxonomy_doc,xpath).each do |data_object|\n destinations_lookup = build_data_objects_from_place_info_data(destinations_lookup,data_object)\n end\n destinations_lookup\n end", "def _parse_taxonomy(tax)\n\t\t\t\ttax['id'].each_index do |index|\n\t\t\t\t\ttaxon = get_item_by_id(tax['id'][index])\n\t\t\t\t\tif (! taxon.nil?) then\n\t\t\t\t\t\ttaxon.trans_table = tax['code'][index].to_i\n\t\t\t\t\telse\n\t\t\t\t\t\t# then there is a taxon not in the file: we need to update:\n\t\t\t\t\t\twarn \"[WARNING]\".red + \" a taxon not in the ncbi taxonomy (\" + tax['id'] + \") was detected. redownloading ncbi taxonomy file...\"\n\t\t\t\t\t\treturn nil\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\treturn true\n\t\t\tend", "def setup_taxons(record, data)\n taxon_list = split_data(data)\n\n taxon_list.each do |taxon_str|\n taxon_names = taxon_str.split(/\\s*>\\s*/)\n taxonomy = Spree::Taxonomy.find_or_create_by(name: taxon_names.shift)\n parent = taxonomy.root\n associate(record, 'taxons', parent)\n\n taxon_names.each do |taxon_name|\n taxon = Spree::Taxon.find_or_create_by(name: taxon_name,\n taxonomy: taxonomy,\n parent: parent)\n associate(record, 'taxons', taxon)\n parent = taxon\n end\n end\n end", "def source_taxonomy\n \"source_taxonomy\"\n end", "def set_tax_information\n @tax_information = TaxInformation.find(params[:id])\n end", "def save\n self.metadata[:type] = :metagenome if !metadata[:tax].nil? and\n !metadata[:tax][:ns].nil? and metadata[:tax][:ns]==\"COMMUNITY\"\n self.metadata.save\n end", "def create\n @taxonomy_term = TaxonomyTerm.new(params[:taxonomy_term])\n\n respond_to do |format|\n if @taxonomy_term.save\n format.html { redirect_to admin_taxonomy_term_path(@taxonomy_term), notice: 'Taxonomy term was successfully created.' }\n format.json { render json: @taxonomy_term, status: :created, location: @taxonomy_term }\n else\n \tset_site_entities @taxonomy_term\n \t\n format.html { render action: \"new\" }\n format.json { render json: @taxonomy_term.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_search_terms\n if relevent_dish\n self.search_terms = self.name_translations.collect do |key,value|\n next value\n end.join(\" \")\n if self.restaurant\n self.restaurant_name = self.restaurant.name\n end\n if img = self.image.first\n self.top_image = img.img_url_medium\n end\n else\n self.search_terms = nil\n end\n save\n end", "def create\n @taxonomy = Taxonomy.new(params[:taxonomy])\n\n respond_to do |format|\n if @taxonomy.save\n format.html { redirect_to edit_admin_taxonomy_path(@taxonomy), notice: 'Taxonomy was successfully updated.' }\n format.json { render json: @taxonomy, status: :created, location: @taxonomy }\n else\n format.html { render action: \"new\" }\n format.json { render json: @taxonomy.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_dataset_rel_and_attr\n @dataset.database = @database\n @dataset_id = @dataset.id\n organization = Organization.find_by_id(@organization_id)\n organization.datasets << @dataset\n @dataset.organization = organization\n end", "def propagate_classification\n raise(\"Name#propagate_classification only works on genera for now.\") \\\n if rank != \"Genus\"\n\n subtaxa = subtaxa_whose_classification_needs_to_be_changed\n Name.where(id: subtaxa).\n update_all(classification: classification)\n NameDescription.where(name_id: subtaxa).\n update_all(classification: classification)\n Observation.where(name_id: subtaxa).\n update_all(classification: classification)\n end", "def set_tax\n @tax = Tax.find(params[:id])\n end", "def set_tax\n @tax = Tax.find(params[:id])\n end", "def set_term_relationship\n @term_relationship = TermRelationship.find(params[:id])\n end", "def create_taxonomy(rid, add_params = nil)\n params = {\n uid: uid,\n rid: rid,\n }\n api_call('/stores/:uid/taxonomies/:rid(.:format)',:post,params,add_params)\n end", "def set_taxi\n @taxi = Taxi.find(params[:id])\n end", "def set_taxi\n @taxi = Taxi.find(params[:id])\n end", "def handle_taxa(data, import)\n print \"Handling taxa \"\n if import.metadata['taxa']\n print \"from database. Indexing OTUs by TaxonCode...\"\n Otu.includes(:identifiers).each do |o|\n # There is only one identifier added at this point, so we are safe here. If this changes specify here.\n data.otus.merge!(o.identifiers.first.identifier => o)\n end\n print \"done.\\n\" \n else\n print \"as newly parsed.\\n\"\n puts\n\n path = @args[:data_directory] + 'TXT/taxa_hierarchical.txt'\n raise 'file not found' if not File.exists?(path)\n\n parent_index = {}\n f = CSV.open(path, col_sep: \"\\t\", :headers => true)\n\n\n code = :iczn\n\n f.first(500).each_with_index do |row, i| #f.first(500).each_with_index\n name = row['Name']\n author = (row['Parens'] ? \"(#{row['Author']})\" : row['Author']) unless row['Author'].blank?\n author ||= nil\n code = :icn if code == :iczn && row['Name'] == 'Plantae'\n rank = Ranks.lookup(code, row['Rank'])\n rank ||= NomenclaturalRank\n\n p = Protonym.new(\n name: name,\n verbatim_author: author,\n year_of_publication: row['Year'],\n rank_class: rank,\n created_by_id: find_or_create_collection_user(row['CreatedBy'], data),\n updated_by_id: find_or_create_collection_user(row['ModifiedBy'], data),\n #creator: find_or_create_user(row['CreatedBy'], data),\n #updater: find_or_create_user(row['ModifiedBy'], data),\n created_at: time_from_field(row['CreatedOn']),\n updated_at: time_from_field(row['ModifiedOn'])\n )\n p.parent_id = parent_index[row['Parent'].to_s].id unless row['Parent'].blank? || parent_index[row['Parent'].to_s].nil?\n if rank == NomenclaturalRank || !p.parent_id.blank?\n bench = Benchmark.measure {\n p.save\n build_otu(row, p, data)\n }\n\n if p.valid?\n parent_index.merge!(row['ID'] => p)\n TAXA.merge!(row['TaxonCode'] => p)\n print \"\\r#{i}\\t#{bench.to_s.strip} #{name} \" # \\t\\t#{rank}\n else\n puts \"\\n#{p.name}\"\n puts p.errors.messages\n puts\n end\n else\n puts \"\\n No parent for #{p.name}.\\n\"\n end\n\n\n p.data_attributes.create(type: 'InternalAttribute', predicate: data.keywords['Taxa:Synonyms'], value: row['Synonyms']) unless row['Synonyms'].blank?\n p.data_attributes.create(type: 'InternalAttribute', predicate: data.keywords['Taxa:References'], value: row['References']) unless row['References'].blank?\n p.notes.create(text: row['Remarks']) unless row['Remarks'].blank?\n\n #p.parent_id = p.parent.id if p.parent && !p.parent.id.blank?\n\n end\n\n import.metadata['taxa'] = true\n end\n end", "def set_taxon\n @taxon = Taxon.find(params[:id])\n end", "def set_taxon\n @taxon = Taxon.find(params[:id])\n end", "def create_taxonomy_node\n Taxonomite::Species.new(name: self.name)\n end", "def overwrite(to)\n to.taggings.clear\n self.copy(to)\n end", "def assign_tags(tag_titles)\n update_counters_before\n tags = tag_titles.split(\",\").strip\n tags.each do |t|\n post_tag = self.post_type.post_tags.where(name: t).first_or_create!\n self.term_relationships.where({term_taxonomy_id: post_tag.id}).first_or_create!\n end\n update_counters(\"tags\")\n end", "def set_taxon_name_relationship\n @taxon_name_relationship = TaxonNameRelationship.find(params[:id])\n end", "def associate_product_with_taxon(product, taxonomy, taxon_hierarchy)\r\n return if product.nil? || taxonomy.nil? || taxon_hierarchy.nil?\r\n\r\n #Using find_or_create_by_name is more elegant, but our magical params code automatically downcases\r\n # the taxonomy name, so unless we are using MySQL, this isn't going to work.\r\n # taxonomy_name = taxonomy\r\n # taxonomy = Taxonomy.find(:first, :conditions => [\"lower(name) = ?\", taxonomy])\r\n # taxonomy = Taxonomy.create(:name => taxonomy_name.capitalize) if taxonomy.nil? && ProductImport.settings[:create_missing_taxonomies]\r\n\r\n taxon_hierarchy.split(/\\s*\\|\\s*/).each do |hierarchy|\r\n hierarchy = hierarchy.split(/\\s*>\\s*/)\r\n taxonomy = Spree::Taxonomy.where(\"name = ?\", hierarchy.first.downcase).first\r\n taxonomy = Taxonomy.create(:name => hierarchy.first.capitalize) if taxonomy.nil? && ProductImport.settings[:create_missing_taxonomies]\r\n last_taxon = taxonomy.root\r\n\r\n hierarchy.shift\r\n hierarchy.each do |taxon|\r\n #last_taxon = last_taxon.children.find_or_create_by_name_and_taxonomy_id(taxon, taxonomy.id)\r\n last_taxon = last_taxon.children.find_or_create_by(name: taxon, taxonomy_id: taxonomy.id)\r\n end\r\n\r\n #Spree only needs to know the most detailed taxonomy item\r\n product.taxons << last_taxon unless product.taxons.include?(last_taxon)\r\n end\r\n end", "def output_tax(refseq_data)\n rs = refseq_data\n taxid = rs[:taxid]\n gene_label_url = URI.escape(rs[:gene_label])\n\n $output_ttl.puts triple(\"<http://togogenome.org/gene/#{taxid}:#{gene_label_url}>\", \"rdfs:seeAlso\", \"tax:#{rs[:taxid]}\") unless $gene_list[rs[:gene_rsrc]]\n $output_ttl.puts triple(\"<http://togogenome.org/gene/#{taxid}:#{gene_label_url}>\", \"skos:exactMatch\", \"<http://identifiers.org/refseq/#{rs[:gene_rsrc]}>\") unless $gene_list[rs[:gene_rsrc]]\n $output_ttl.puts triple(\"tax:#{rs[:taxid]}\", \"rdf:type\", \"<http://identifiers.org/taxonomy>\") unless $tax_type_list[rs[:taxid]]\n $tax_type_list[rs[:taxid]] = true # to prevent duplicate output\n $gene_list[rs[:gene_rsrc]] = true # to prevent duplicate output\nend", "def set_taxon_name_classification\n @taxon_name_classification = TaxonNameClassification.find(params[:id])\n end", "def output_uptax(up_data)\n taxup = up_data[:taxid]\n $output_ttl.puts triple(\"tax:#{taxup}\", \"rdf:type\", \"<http://identifiers.org/taxonomy>\") unless $tax_type_list[taxup]\n $tax_type_list[taxup] = true # to prevent duplicate output\nend", "def perform\n PgSearch::Multisearch.rebuild(Doc)\n end", "def transfer\n\t\t\[email protected]\n\t\tend", "def transfer\n\t\t\[email protected]\n\t\tend", "def _associated_dataset\n associated_class.dataset.clone\n end", "def add_taxons\n save_if_new\n chain_list = get_each_assoc\n chain_list.each do |chain|\n # Each chain can contain either a single Taxon,\n # or the tree like structure parent>child>child\n name_list = chain.split(/\\s*>\\s*/)\n taxonomy_name = name_list.shift\n taxonomy = @@taxonomy_klass.find_or_create_by_name(taxonomy_name)\n raise DataShift::DataProcessingError.new(\"Could not find or create Taxonomy #{taxonomy_name}\") unless taxonomy\n taxon = taxonomy.root\n name_list.each do |taxon_name|\n taxon = @@taxon_klass.find_or_create_by_name_and_parent_id_and_taxonomy_id(taxon_name, taxon.id, taxonomy.id)\n end\n\n if taxon\n @product.taxons << taxon\n puts \" Added to taxon #{taxon.pretty_name}\"\n else\n puts \" Taxon not found or created: #{name}\"\n end\n\n end\n end", "def tax_index\n\n end", "def get_gtdb_taxonomy\n gtdb_genome = metadata[:gtdb_assembly] or return\n\n doc = MiGA::Json.parse(\n MiGA::RemoteDataset.download(\n :gtdb, :genome, gtdb_genome, 'taxon-history', nil, ['']\n ),\n contents: true\n )\n lineage = { ns: 'gtdb' }\n lineage.merge!(doc.first) # Get only the latest available classification\n release = lineage.delete(:release)\n @metadata[:gtdb_release] = release\n lineage.transform_values! { |v| v.gsub(/^\\S__/, '') }\n MiGA.DEBUG \"Got lineage from #{release}: #{lineage}\"\n MiGA::Taxonomy.new(lineage)\n end", "def new_word_relation(sax, author_id)\n AntonomyRelation.new.tap do |relation|\n relation.author_id = author_id\n relation.synset1_id = sax.synset1_id\n relation.synset2_id = sax.synset2_id\n relation.word1_id = sax.word1_id\n relation.word2_id = sax.word2_id\n end\nend", "def _update_dataset\n this\n end", "def _update_dataset\n this\n end", "def add_dataset_ids(taxonomies, tax_hash, dat_counts_seq)\n # puts \"=\" * 8\n # puts \"\\ntax_hash = \" + tax_hash.inspect\n # puts \"\\ndat_counts_seq = \" + dat_counts_seq.inspect\n \n taxonomies.each do |tax_obj|\n # dat_counts_seq_t = get_dat_counts_seq_by_t(tax_obj, dat_counts_seq)\n # puts \"\\ntax_obj = \" + tax_obj.inspect\n \n dat_counts_seq.each do |dat_cnt_seq_t| \n \n if (dat_cnt_seq_t[:taxonomy_id] == tax_obj[:id]) \n # (1..RANKS_AMOUNT).each do |n|\n # puts \"\\ndat_cnt_seq_t = \" + dat_cnt_seq_t.inspect\n # puts \"\\ntax_obj.attributes.values[1, n] = \" + tax_obj.attributes.values[1, RANKS_AMOUNT].inspect\n \n add_dat_id_knt_to_tax_hash(tax_hash, tax_obj.attributes.values[1, RANKS_AMOUNT], dat_cnt_seq_t)\n # end\n end\n end \n end\n return tax_hash\n end", "def set_term\n @term = Term.find(params[:id])\n end", "def set_term\n @term = Term.find(params[:id])\n end", "def index\n @luxire_taxonomies = LuxireTaxonomy.all\n end", "def set_term\n @term = Term.find(params[:id])\n end", "def selected\n @taxons = @product.taxons\n set_available\n end", "def set_pagto_taxa\n @pagto_taxa = PagtoTaxa.find(params[:id])\n end", "def update\n respond_to do |format|\n if @indicate_taxonomy.update(indicate_taxonomy_params)\n format.html { redirect_to @indicate_taxonomy, notice: 'Taxonomy was successfully updated.' }\n format.json { render :show, status: :ok, location: @indicate_taxonomy }\n else\n format.html { render :edit }\n format.json { render json: @indicate_taxonomy.errors, status: :unprocessable_entity }\n end\n end\n end", "def find_taxonomies\n @document.xpath('.//taxonomy').each do |taxonomy_node|\n taxonomy_name = taxonomy_node.at_xpath('.//taxonomy_name')\n tax_node = insert_node(SecureRandom.uuid, taxonomy_name.content, @root_node)\n @taxonomies << tax_node\n add_node(taxonomy_node, tax_node, skip_add: true)\n end\n end", "def admin_term_of_use_update\n @admin.terms_of_use = GlobalConstant::Admin.accepted_terms_of_use\n @admin.save!\n end", "def set_taxon_determination\n @taxon_determination = TaxonDetermination.find(params[:id])\n end", "def backup\n if Setting.getValue('backup') && Setting.getValue('backup_location').present?\n File.open(\"#{Setting.getValue('backup_location')}/taxonomy/#{self.seo_url}.json\", 'w+') do |fh|\n fh.write self.to_json\n end\n end\n end", "def set_dataset\n # TODO\n #@dataset = DatasetService.get_dataset\n end", "def to_term\n ::HubEdos::StudentApi::V2::Term::Term.new(@data['toTerm']) if @data['toTerm']\n end", "def to_term\n ::HubEdos::StudentApi::V2::Term::Term.new(@data['toTerm']) if @data['toTerm']\n end", "def establish_dataset( dataset )\n #print 'Dataset established: ', dataset.name if dataset.respond_to? :name and dataset.name\n @@dataset = dataset\n end", "def set_forest\n @forest = Forest.find(params[:id])\n end", "def sync_tax_percentage\n subscription = as_stripe_subscription\n\n subscription.tax_percentage = user.tax_percentage\n\n subscription.save\n end", "def update!(**args)\n @next_page_token = args[:next_page_token] if args.key?(:next_page_token)\n @taxonomies = args[:taxonomies] if args.key?(:taxonomies)\n end", "def add_to_regimen_type(regimen_concept)\n return nil if regimen_concept.blank?\n drug_concept = self.concept\n return nil if drug_concept.blank? or User.current_user.nil?\n concept_set = ConceptSet.new(:concept_id => drug_concept.id, :concept_set => regimen_concept.id,\n :creator => User.current_user.id, :date_created => Time.now)\n concept_set.save\n end", "def index\n @indicate_taxonomies = Indicate::Taxonomy.all\n @indicate_taxonomies = @indicate_taxonomies.by_towns(params['town_select']) unless params['town_select'].blank?\n end", "def datos_descarga(taxa)\n return unless taxa.any?\n self.taxones = []\n\n taxa.each do |taxon|\n self.taxon = taxon\n asigna_datos\n self.taxones << taxon\n end\n end", "def set_taxi_image\n @taxi_image = TaxiImage.find(params[:id])\n end", "def add_taxa_from_observations\n self.user.observations.all(:select => 'taxon_id', \n :group => 'taxon_id', \n :conditions => 'taxon_id IS NOT NULL').each do |observation|\n self.add_taxon(observation.taxon_id)\n end\n end", "def update\n @taxonomy_term = TaxonomyTerm.find(params[:id])\n\n respond_to do |format|\n if @taxonomy_term.update_attributes(params[:taxonomy_term])\n format.html { redirect_to admin_taxonomy_terms_path , notice: 'Taxonomy term was successfully updated.' }\n format.json { head :no_content }\n else\n \tset_site_entities @taxonomy_term\n format.html { render action: \"edit\" }\n format.json { render json: @taxonomy_term.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_continents(taxonomies_fragement)\n taxonomies_fragement.each { |taxonomy|\n continent = build_tree(taxonomy)\n @continents << continent\n }\n end", "def save\n ::Classifier.dataset.delete\n\n @classifiers.each do |section, reference_values|\n ::Classifier.create(\n section: section.to_s,\n reference_values: JSON.generate(reference_values)\n )\n end\n end", "def update!(**args)\n @category = args[:category] if args.key?(:category)\n @classifier_version = args[:classifier_version] if args.key?(:classifier_version)\n @taxonomy = args[:taxonomy] if args.key?(:taxonomy)\n @taxonomy_name = args[:taxonomy_name] if args.key?(:taxonomy_name)\n end", "def indicate_taxonomy_params\n params[:indicate_taxonomy]\n end", "def update\n @taxonomy = Taxonomy.find(params[:id])\n\n respond_to do |format|\n if @taxonomy.update_attributes(params[:taxonomy])\n format.html { redirect_to edit_admin_taxonomy_path(@taxonomy), notice: 'Taxonomy was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { redirect_to :action => 'edit', alert: 'Updating taxonomy was failed.' }\n format.json { render json: @taxonomy.errors, status: :unprocessable_entity }\n end\n end\n end", "def change_classification(new_str)\n root = below_genus? && accepted_genus || self\n root.synonyms.each do |name|\n name.update(classification: new_str)\n name.description.update(classification: new_str) if name.description_id\n end\n root.propagate_classification if root.rank == \"Genus\"\n end", "def set_taxes\n @taxes = Tax.find(params[:id])\n end", "def update!(**args)\n @tax_amount = args[:tax_amount] if args.key?(:tax_amount)\n @tax_name = args[:tax_name] if args.key?(:tax_name)\n @tax_type = args[:tax_type] if args.key?(:tax_type)\n end", "def set_datasets\n # Force admin token for getting user information (show/hide delete button)\n datasets = @site.get_datasets(current_user)\n @datasets = process_datasets datasets\n end", "def new\n @taxonomy_term = TaxonomyTerm.new\n\tset_site_entities @taxonomy_term\n\t\n\trespond_to do |format|\n format.html # new.html.erb\n format.json { render json: @taxonomy_term }\n end\n end", "def clone_branch( )\n raise \"only support taxon root\" unless self.root?\n #raise \"only copy taxon from design site\" unless taxon.site.design?\n #raise \"taxon exists in current site\" if self.class.exists(:permalink=>self.permalink)\n cloned_branch = nil\n current_site_id = Spree::Site.current.id\n #maybe clone taxon from other site\n Spree::MultiSiteSystem.with_context_free_taxon{\n #copy from http://stackoverflow.com/questions/866528/how-to-best-copy-clone-an-entire-nested-set-from-a-root-element-down-with-new-tr\n new_taxonomy = self.taxonomy.dup\n new_taxonomy.site_id = current_site_id\n # should not save new_taxonomy here, or new_taxonomy.root.site_id is not current site id\n h = { self => self.custom_duplicate } #we start at the root\n ordered = self.descendants\n #clone subitems\n ordered.each do |item|\n h[item] = item.custom_duplicate\n end\n #resolve relations\n ordered.each do |item|\n cloned = h[item]\n item_parent = h[item.parent]\n item_parent.children << cloned if item_parent\n # handle icon\n end\n h.values.each{|cloned|\n cloned.site_id = new_taxonomy.site_id\n cloned.taxonomy = new_taxonomy\n }\n new_taxonomy.root = h[self]\n cloned_branch = h[self]\n }\n cloned_branch\n end", "def copy(to)\n if self == to\n raise ArgumentError, I18n.t(\"winnow.errors.tag.copy_name_error\")\n end\n \n if to.taggings.size > 0\n raise ArgumentError, I18n.t(\"winnow.errors.tag.copy_exists_error\", :to => to.name)\n end\n \n Tagging.connection.execute(%Q|\n INSERT INTO taggings(feed_item_id, strength, classifier_tagging, created_on, tag_id, user_id)\n (SELECT feed_item_id, strength, classifier_tagging, created_on, #{to.id}, #{to.user_id} FROM taggings WHERE tag_id = #{self.id})\n |)\n \n to.bias = self.bias \n to.description = self.description\n to.last_classified_at = self.last_classified_at\n to.save!\n end", "def create\n @luxire_taxonomy = LuxireTaxonomy.new(luxire_taxonomy_params)\n\n respond_to do |format|\n if @luxire_taxonomy.save\n format.html { redirect_to @luxire_taxonomy, notice: 'Luxire taxonomy was successfully created.' }\n format.json { render :show, status: :created, location: @luxire_taxonomy }\n else\n format.html { render :new }\n format.json { render json: @luxire_taxonomy.errors, status: :unprocessable_entity }\n end\n end\n end", "def update!(**args)\n @data_taxonomies = args[:data_taxonomies] if args.key?(:data_taxonomies)\n @next_page_token = args[:next_page_token] if args.key?(:next_page_token)\n @unreachable_locations = args[:unreachable_locations] if args.key?(:unreachable_locations)\n end", "def add_tax(tax)\n tax_breakdown(tax)[0]\n end", "def pivot(new_domain, new_name)\n self.domain = new_domain\n self.name = new_name\n end", "def set_taxfree\n @taxfree = Taxfree.find(params[:id])\n end", "def set_dataset\n @dataset = Dataset.find(params[:id])\n end", "def set_dataset\n @dataset = Dataset.find(params[:id])\n end", "def set_dataset\n @dataset = Dataset.find(params[:id])\n end", "def set_dataset\n @dataset = Dataset.find(params[:id])\n end" ]
[ "0.6211107", "0.61210275", "0.60703415", "0.5641416", "0.5640258", "0.5640258", "0.5596159", "0.5530919", "0.5463734", "0.5462066", "0.54161364", "0.53748494", "0.5367793", "0.53317016", "0.5306021", "0.52899534", "0.52686036", "0.5265831", "0.5253677", "0.52399653", "0.5214879", "0.5207059", "0.51995254", "0.5198284", "0.5165968", "0.5158194", "0.5130103", "0.5111335", "0.5111335", "0.5061021", "0.5046909", "0.5024036", "0.5024036", "0.5000421", "0.49901158", "0.49901158", "0.49770492", "0.49134958", "0.48827383", "0.48746535", "0.486552", "0.4855207", "0.48471367", "0.48465976", "0.4830541", "0.47985652", "0.47985652", "0.4791696", "0.47760126", "0.47756806", "0.47679558", "0.4763114", "0.4761304", "0.4761304", "0.47599614", "0.47554383", "0.47554383", "0.47452113", "0.47405007", "0.4734039", "0.4688099", "0.4686656", "0.46862635", "0.46742368", "0.46728835", "0.46602842", "0.46599427", "0.46554965", "0.46554965", "0.46517104", "0.46482837", "0.46475455", "0.46388924", "0.4635922", "0.46335658", "0.46328658", "0.46226427", "0.46209395", "0.46166715", "0.46154156", "0.46096742", "0.4604626", "0.46041387", "0.45960274", "0.4584972", "0.4580052", "0.45731804", "0.45730522", "0.4572562", "0.45705783", "0.45697662", "0.45657867", "0.45579284", "0.45376655", "0.4537257", "0.4533512", "0.45191365", "0.45191365", "0.45191365", "0.45191365" ]
0.6942107
0
tablas de CRUDig funciones comunes
def ordenar_create( tabla, params ) order = '' if (params[:g_g] && (params[:g_g]==tabla)) (params[:g_o] && params[:g_o]!='') ? order = params[:g_o] : order = 'asc' (params[:g_f] && params[:g_f]!='') ? order = params[:g_f]+' '+order : order = '' else (params[:order] && params[:order]!='') ? order = params[:order] : order = 'asc' (params[:field] && params[:field]!='') ? order = params[:field]+' '+order : order = '' end #(order=='asc') ? order='desc' : order='asc' return ' ORDER BY '+order if (order != '') return '' end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def editar\n end", "def index\n self.validar_admin\n @inventarios = Inventario.all\n end", "def set_tabla\n @objeto = Tabla.find(params[:id])\n end", "def index\n @crud_municipios = CrudMunicipio.all\n end", "def index\n @tipo_funcionarios = TipoFuncionario.all\n end", "def _crud(for_select = true)\n fetch_array_for $_crud, for_select\n end", "def index\n @funcionarios = Funcionario.all\n end", "def index\n @funcionarios = Funcionario.all\n end", "def plantilla_colocar_tabla(usuarios,historiales,cabecera_notas, tipo_evaluaciones, accion, editar)\n form_tag accion do\n haml_tag(:table, :class => 'tablesorter', :id => \"ingles\") do\n haml_tag :thead do\n haml_tag :tr do\n haml_tag :th, '#'\n haml_tag :th, 'Nombres'\n haml_tag :th, 'Cédula'\n haml_tag :th, cabecera_notas[0]\n haml_tag :th, cabecera_notas[1]\n haml_tag :th, cabecera_notas[2]\n haml_tag :th, cabecera_notas[3]\n haml_tag :th, 'Final'\n haml_tag :th, 'Descripción'\n end\n end\n haml_tag :tbody do \n historiales.each_with_index{ |h,i|\n haml_tag :tr do\n haml_tag :td, i+1\n haml_tag :td, h.usuario.nombre_completo\n haml_tag :td, h.usuario.ci\n valor = nil\n valor = h.nota_en_evaluacion(tipo_evaluaciones[0]).nota_valor\n if editar\n haml_tag :td do\n if valor != HistorialAcademico::SC\n haml_concat (text_field :nota1,h.usuario.ci, \\\n {:value => valor, :maxlength => 5})\n else\n haml_concat(text_field :nota1,h.usuario.ci,{:placeholder => \"SC\",:maxlength => 5})\n end\n end\n else\n haml_tag :td, valor\n end\n \n valor = h.nota_en_evaluacion(tipo_evaluaciones[1]).nota_valor\n \n if editar\n haml_tag :td do\n if valor != HistorialAcademico::SC\n haml_concat (text_field :nota2,h.usuario.ci, \\\n {:value => valor, :maxlength => 5})\n else\n haml_concat(text_field :nota2,h.usuario.ci,{:placeholder => \"SC\",:maxlength => 5})\n end\n end\n else\n haml_tag :td, valor\n end\n\n valor = h.nota_en_evaluacion(tipo_evaluaciones[2]).nota_valor\n \n if editar\n haml_tag :td do\n if valor != HistorialAcademico::SC\n haml_concat (text_field :nota3,h.usuario.ci, \\\n {:value => valor, :maxlength => 5})\n else\n haml_concat(text_field :nota3,h.usuario.ci,{:placeholder => \"SC\",:maxlength => 5})\n end\n end\n else\n haml_tag :td, valor\n end\n\n valor = h.nota_en_evaluacion(tipo_evaluaciones[3]).nota_valor\n\n if editar\n haml_tag :td do\n if valor != HistorialAcademico::SC\n haml_concat (text_field :nota4,h.usuario.ci, \\\n {:value => valor, :maxlength => 5})\n else\n haml_concat(text_field :nota4,h.usuario.ci,{:placeholder => \"SC\",:maxlength => 5})\n end\n end\n else\n haml_tag :td, valor\n end\n \n if h.nota_final != HistorialAcademico::SC\n haml_tag(:td,:id => \"nota_final_\"+h.usuario.ci) do\n haml_concat HistorialAcademico.colocar_nota(h.nota_final)\n end\n else \n haml_tag(:td,:id => \"nota_final_\"+h.usuario.ci) do\n haml_concat \"SC\"\n end\n end\n if h.nota_final == -1\n valor = -1\n else\n valor = h.nota_final\n end\n if editar\n haml_concat(hidden_field :notafinal,h.usuario.ci,{:value => valor})\n end\n \n haml_tag :td do\n haml_tag(:div, :id => \"descripcion_#{h.usuario.ci}\") do\n haml_concat HistorialAcademico::NOTASPALABRAS[h.nota_final+2]\n end\n end\n end\n }\n end\n end \n if editar\n haml_tag :br\n haml_concat(submit_tag :Calificar)\n end\n end \n end", "def index\n @contajes = Contaje.all\n #Sandra:\n # se crea un objeto paralelo que solamente contega 12 registros de la tabla tcontajes con la\n # condición que su código de contaje este entre 200 y 300 que son los que corresponden a \n #telefonía fija y además con la instrucción NEWID() en el orderby indicamos que sean aleatorios\n @contajes_fijas = Contaje.select(\"TOP 11 *\").where(\"nCodContaje>=200 and nCodContaje<299\").order(\"NEWID()\");\n @contajes_electronica = Contaje.select(\"TOP 11 *\").where(\"nCodContaje>=700 and nCodContaje<799\").order(\"NEWID()\");\n @contajes_movil = Contaje.select(\"TOP 11 *\").where(\"nCodContaje>=120 and nCodContaje<199\").order(\"NEWID()\");\n\n end", "def add_table_actions(table)\n action_col_show(table)\n action_col_edit(table)\n action_col_destroy(table)\n end", "def tabla_sin_registros(modelo)\n unless modelo.first\n # flash[:notice] = 'Ud. no tiene registros creados.\\n \\n Cuando los haya creado se listaran aqui.'\n # A la vista tenes que mandar por content_tag (ActionView::Helpers::TagHelper)\n @content = content_tag(:tr, content_tag(:td, 'Ud. no tiene registros creados.'))\n @content << content_tag(:tr, content_tag(:td, 'Cuando los haya creado se listaran aqui.'))\n end\n end", "def index\n @funcoes = Funcao.all\n end", "def edit\n \n end", "def index\n @coleccion = Tabla.all\n end", "def index\n @orden_trabajos = OrdenTrabajo.all\n\n end", "def botonMinarAccion(tabla)\n\t\ts=ControlDeBase.new\n\t\ts.creaBase()\n\t\telementos=Minero.new.cuentaElementos()\n\t\tMinero.new.registraElementos()\n\t\ttitulos=s.tablaGeneralTitulos\n\t\tartistas=s.tablaGeneralArtistas\n\t\talbums=s.tablaGeneralAlbum\n\t\tgenero=s.tablaGeneralGenero\n\t\tpath=s.tablaGeneralPath\n\t\ti=0\n\t\te=0\n\t\tcount=0.0\n\t\twhile i<path.length\n\t\t\twhile e<tabla.numRows\n\t\t\t\tif path[i].to_s==tabla.getItemText(e,4).to_s and path[i].to_s!=\"\" and tabla.getItemText(e,4).to_s!= \"\"\n\t\t\t\t\te=0\n\t\t\t\t\ti=i+1\n\t\t\t\t\tnext\n\t\t\t\telse\n\t\t\t\t\te=e+1\n\t\t\t\tend\n\t\t\tend\n\t\t\tif(!path[i].nil?)\n\t\t\t\ttabla.appendRows(1)\n\t\t\t\ttabla.setItemText(i,0,titulos[i][0].to_s)\n\t\t\t\ttabla.setItemText(i,1,artistas[i][0].to_s)\n\t\t\t\ttabla.setItemText(i,2,albums[i][0].to_s)\n\t\t\t\ttabla.setItemText(i,3,genero[i][0].to_s)\n\t\t\t\ttabla.setItemText(i,4,path[i].to_s)\n\t\t\t\ttabla.setItemJustify(i,0,FXTableItem::LEFT)\n\t\t\t\ttabla.setItemJustify(i,1,FXTableItem::LEFT)\n\t\t\t\ttabla.setItemJustify(i,2,FXTableItem::LEFT)\n\t\t\t\ttabla.setItemJustify(i,3,FXTableItem::LEFT)\n\t\t\t\ti=i+1\n\t\t\t\te=0\n\t\t\tend\n\t\tend\n\tend", "def index\n @traslados = Traslado.all\n end", "def index\n @tipo_trabajadors = TipoTrabajador.all\n end", "def index\n @persona = Persona.where(usuarioId: session[:usuario_id]).take\n \n @planformacions = Planformacion.where(tutorId: session[:usuario_id]).take\n #@usuarios= Usuario.all #se quiere acceder a la informacion del usuario como el nombre, para agregarlo en la tabla pero aun no sabemos como\n #@personas= Persona.all\n end", "def add_table_actions(table)\n action_col_edit(table)\n action_col_destroy(table)\n end", "def edit; end", "def edit; end", "def edit; end", "def edit; end", "def edit; end", "def edit; end", "def edit; end", "def edit; end", "def edit; end", "def edit; end", "def edit; end", "def edit; end", "def edit; end", "def edit; end", "def edit; end", "def edit; end", "def edit; end", "def edit; end", "def edit; end", "def edit; end", "def edit; end", "def create_table_actions atable, todo, data, categ\n #@new_act = Action.new(\"New Row\", \"mnemonic\"=>\"N\") { \n @new_act = Action.new(\"&New Row\") { \n cc = atable.get_table_column_model.column_count\n if atable.row_count < 1\n categ = nil\n frow = 0\n else\n frow = atable.focussed_row\n categ = atable.get_value_at(frow,1)\n frow += 1\n end\n tmp = [nil, categ, \"\", 5, \"\", \"TODO\", Time.now]\n tm = atable.table_model\n tm.insert frow, tmp\n atable.set_focus_on frow\n @status_row.text = \"Added a row. Please press Save before changing Category.\"\n alert(\"Added a row below current one. Use C-k to clear task.\")\n }\n @new_act.accelerator \"Alt-N\"\n @save_cmd = lambda {\n todo.set_tasks_for_category categ, data\n todo.dump\n alert(\"Rewritten yaml file\")\n }\n @del_cmd = lambda { \n row = atable.focussed_row\n if confirm(\"Do your really want to delete row #{row+1}?\")== :YES\n tm = atable.table_model\n tm.delete_at row\n else\n @status_row.text = \"Delete cancelled\"\n end\n }\n\n end", "def edit\n\t\t\n\tend", "def index\n @datos_usuarios = DatosUsuario.all\n @talla = Talla.all\n end", "def atributos_index\n [ :id,\n :nusuario,\n :nombre,\n :email,\n :grupo_ids,\n :foto,\n :habilitado,\n ]\n end", "def index\n @trabajos = Trabajo.all\n end", "def index\n @gdocs = Gdoc.all\n @datee = Gdoc.obtain_date\n @rowss = Gdoc.obtain_rows\n\n# @filas.each do |n|\n# ProductosNuevos.create(:SKU => n[0], :cliente => n[1], :cantidad => n[2], :utilizado => n[3])\n# end\n end", "def index\n @pre_contratos = PreContrato.all\n end", "def docentes\n\t\t@seccion = \"Docentes\"\n @titulo = \"Docentes\"\n\n if Docente.all().size > 0\n \t\tif params[:orden]\n \t\t\t@orden = params[:orden]\n \t\telse\n \t\t\t@orden = \"Cédula\"\n \t\tend\n\n \t\t#Guardo todos los docentes\n \t\tcase @orden\n \t\twhen \"Cédula\"\n \t\t\t@usuarios = Usuario.order('cedula').where(:id => Docente.all)\n \t\twhen \"Nombre\"\n \t\t\t@usuarios = Usuario.order('nombre').where(:id => Docente.all)\n \t\twhen \"Apellido\"\n \t\t\t@usuarios = Usuario.order('apellido').where(:id => Docente.all)\n \t\twhen \"Correo\"\n \t\t\t@usuarios = Usuario.order('correo').where(:id => Docente.all)\n \t\tend\n\n end\n\t\t\n\t\t @categorias = ['Cédula', 'Nombre', 'Apellido', 'Correo'] #Este es el orden que se mostrará en el select de la vista\n\n \t\t@docente_datos = [] #En este arreglo se guardan los pares \"Cedula - Nombre Apellido\" de cada usuario para mostrar en el campo de busqueda\n \t\tUsuario.order('nombre').where(:id => Docente.all).each do |usuario|\n \t\t\t#En este foro se agregan uno a uno los valores de cada docente al arreglo de la manera indicada arriba\n \t\t\t@docente_datos << usuario.cedula.to_s + \" - \" + usuario.nombre_y_apellido.to_s\n \t\tend\n\tend", "def index \n # listagem de documentos\n @tipo_documento = []\n if !params[:tipo] or params[:tipo][:tipo_documento_id].blank?\n @tipo_documento << ['- Selecione -',''] \n else\n TipoDocumento.find_all_by_id( params[:tipo][:tipo_documento_id]).each do |t|\n @tipo_documento << [t.tipo, t.id]\n end\n end\n TipoDocumento.all.each do |t|\n @tipo_documento << [t.tipo, t.id] if !@tipo_documento.include? [t.tipo, t.id]\n end\n \n \n # Novo Documento\n @documento = Documento.new\n \n # Listagem de Documentos\n @documentos = [] \n condition = ''\n if current_usuario.entidade.nil?\n condition = \"and cliente_id = #{current_usuario.id}\" \n else\n condition = \"and cartorio_id = #{current_usuario.entidade_id}\" \n end\n \n if params[:tipo] and !params[:tipo][:tipo_documento_id].blank?\n @documentos = Documento.all(:conditions => \"tipo_documento_id = #{params[:tipo][:tipo_documento_id]} #{condition}\" ).paginate(:page =>params[:page], :per_page =>10)\n end\n \n \n # Resposta \n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @documentos }\n end\n end", "def tablero_params\n params.require(:tablero).permit(:nombre, :descripcion, :horainicio, :horafin, :puntos, :abierto, :e1, :e2, :e3, :cronometro)\n \n end", "def create\n @objeto = Tabla.new(tabla_params)\n\n respond_to do |format|\n if @objeto.save\n set_redireccion\n format.html { redirect_to @redireccion, notice: 'Tabla was successfully created.' }\n format.json { render :show, status: :created, location: @objeto }\n else\n format.html { render :new }\n format.json { render json: @objeto.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @crediarios = Crediario.all\n end", "def colocar_tabla_30(usuarios,historiales,editar)\n form_tag \"guardar_notas_30\" do\n haml_tag(:table, :class => 'tablesorter', :id => \"ingles\") do\n haml_tag :thead do\n haml_tag :tr do\n haml_tag :th, \"#\"\n haml_tag :th, \"Nombre\"\n haml_tag :th, \"Cédula\"\n haml_tag :th, \"E. Teórico 1 (30%)\"\n haml_tag :th, \"E. Teórico 2 (30%)\"\n haml_tag :th, \"E. Oral (30%)\"\n haml_tag :th, \"Otros (10%)\"\n haml_tag :th, \"Final\"\n haml_tag :th, \"Descripción\"\n end\n end\n haml_tag :tbody do \n historiales.each_with_index{ |h,i|\n haml_tag :tr do\n haml_tag :td, i+1\n haml_tag :td, h.usuario.nombre_completo\n haml_tag :td, h.usuario.ci\n valor = nil\n valor = h.nota_en_evaluacion(HistorialAcademico::EXAMENESCRITO1).nota_valor\n if editar\n haml_tag :td do\n if valor != HistorialAcademico::SC\n haml_concat (text_field :nota1,h.usuario.ci, \\\n {:value => valor, :maxlength => 5})\n else\n haml_concat(text_field :nota1,h.usuario.ci,{:placeholder => \"SC\",:maxlength => 5})\n end\n end\n else\n haml_tag :td, valor\n end\n \n valor = h.nota_en_evaluacion(HistorialAcademico::EXAMENESCRITO2).nota_valor\n \n if editar\n haml_tag :td do\n if valor != HistorialAcademico::SC\n haml_concat (text_field :nota2,h.usuario.ci, \\\n {:value => valor, :maxlength => 5})\n else\n haml_concat(text_field :nota2,h.usuario.ci,{:placeholder => \"SC\",:maxlength => 5})\n end\n end\n else\n haml_tag :td, valor\n end\n\n valor = h.nota_en_evaluacion(HistorialAcademico::EXAMENORAL).nota_valor\n \n if editar\n haml_tag :td do\n if valor != HistorialAcademico::SC\n haml_concat (text_field :nota3,h.usuario.ci, \\\n {:value => valor, :maxlength => 5})\n else\n haml_concat(text_field :nota3,h.usuario.ci,{:placeholder => \"SC\",:maxlength => 5})\n end\n end\n else\n haml_tag :td, valor\n end\n\n valor = h.nota_en_evaluacion(HistorialAcademico::OTRAS).nota_valor\n\n if editar\n haml_tag :td do\n if valor != HistorialAcademico::SC\n haml_concat (text_field :nota4,h.usuario.ci, \\\n {:value => valor, :maxlength => 5})\n else\n haml_concat(text_field :nota4,h.usuario.ci,{:placeholder => \"SC\",:maxlength => 5})\n end\n end\n else\n haml_tag :td, valor\n end\n \n if h.nota_final != HistorialAcademico::SC\n haml_tag(:td,:id => \"nota_final_\"+h.usuario.ci) do\n haml_concat HistorialAcademico.colocar_nota(h.nota_final)\n end\n else \n haml_tag(:td,:id => \"nota_final_\"+h.usuario.ci) do\n haml_concat \"SC\"\n end\n end\n if h.nota_final == -1\n valor = -1\n else\n valor = h.nota_final\n end\n if editar\n haml_concat(hidden_field :notafinal,h.usuario.ci,{:value => valor})\n end\n \n haml_tag :td do\n haml_tag(:div, :id => \"descripcion_#{h.usuario.ci}\") do\n haml_concat HistorialAcademico::NOTASPALABRAS[h.nota_final+2]\n end\n end\n end\n }\n end\n end \n if editar\n haml_tag :br\n haml_concat(submit_tag :Calificar)\n end\n end \n end", "def index\n customer_reports = ModuleControl.find_by_name(\"Reportes de clientes\")\n\n create = current_user.rol.accion_modules.where(module_control_id: customer_reports.id).where(name: \"Crear\").exists?\n edit = current_user.rol.accion_modules.where(module_control_id: customer_reports.id).where(name: \"Editar\").exists?\n delete = current_user.rol.accion_modules.where(module_control_id: customer_reports.id).where(name: \"Eliminar\").exists?\n generate_pdf = current_user.rol.accion_modules.where(module_control_id: customer_reports.id).where(name: \"Generar pdf\").exists?\n send_email = current_user.rol.accion_modules.where(module_control_id: customer_reports.id).where(name: \"Enviar para aprobaciòn\").exists?\n edit_email = current_user.rol.accion_modules.where(module_control_id: customer_reports.id).where(name: \"Editar email\").exists?\n download_file = current_user.rol.accion_modules.where(module_control_id: customer_reports.id).where(name: \"Descargar excel\").exists?\n edit_all = current_user.rol.accion_modules.where(module_control_id: customer_reports.id).where(name: \"Editar todos\").exists?\n\n @estados = { \n create: (current_user.rol.name == \"Administrador\" ? true : create),\n edit: (current_user.rol.name == \"Administrador\" ? true : edit),\n edit_all: (current_user.rol.name == \"Administrador\" ? true : edit_all),\n delete: (current_user.rol.name == \"Administrador\" ? true : delete),\n generate_pdf: (current_user.rol.name == \"Administrador\" ? true : generate_pdf),\n send_email: (current_user.rol.name == \"Administrador\" ? true : send_email),\n edit_email: (current_user.rol.name == \"Administrador\" ? true : edit_email),\n download_file: (current_user.rol.name == \"Administrador\" ? true : download_file)\n }\n end", "def new\n @realiza = Realiza.new\n @pessoas=Pessoa.select(\"clientes.id,pessoas.nome\").joins(:cliente)\n @funcionarios=Pessoa.select(\"usuarios.id,pessoas.nome\").joins(:usuario)\n #@pessoas=Pessoa.select(\"clientes.id,pessoas.nome\").joins(:clientes)\n #@funcionarios=Pessoa.where(\"id in (?)\",Usuario.select(\"pessoa_id as id\").map(&:id))\n @servicos=Servico.all\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @realiza and @pessoas and @funcionarios and @servicos}\n end\n end", "def admin\n @pagina = params[:pagina].present? ? params[:pagina].to_i : 1\n @por_pagina = params[:por_pagina].present? ? params[:por_pagina].to_i : Comentario::POR_PAGINA_PREDETERMINADO\n offset = (@pagina-1)*@por_pagina\n\n tax_especifica = current_usuario.usuario_especies\n contenido_especifico = current_usuario.categorias_contenidos\n\n consulta = Comentario.datos_basicos\n\n if params[:comentario].present?\n params = comentario_params\n\n if params[:categorias_contenido_id].present?\n consulta = consulta.where(categorias_contenido_id: params[:categorias_contenido_id].to_i)\n end\n\n if params[:estatus].present?\n consulta = consulta.where('comentarios.estatus = ?', params[:estatus].to_i)\n else\n consulta = consulta.where('comentarios.estatus < ?', Comentario::OCULTAR)\n end\n if tax_especifica.length > 0\n or_taxa = []\n tax_especifica.each do |e|\n or_taxa << \" #{Especie.attribute_alias(:id)} = #{e.especie_id}\"\n or_taxa << \" #{Especie.attribute_alias(:ancestry_ascendente_directo)} LIKE '%#{e.especie_id}%' \"\n end\n consulta = consulta.where(or_taxa.join(' OR '))\n end\n\n if contenido_especifico.length > 0\n consulta = consulta.where(:categorias_contenido_id => contenido_especifico.map(&:subtree_ids).flatten)\n end\n\n # Comentarios totales\n @totales = consulta.count(:all)\n\n # Para ordenar por created_at, nombre_cientifico o ambos\n if params[:created_at].present? && params[:nombre_cientifico].present?\n consulta = consulta.order(\"#{Especie.attribute_alias(:nombre_cientifico)} #{params[:nombre_cientifico]}, comentarios.created_at #{params[:created_at]}\")\n elsif params[:created_at].present?\n consulta = consulta.order(\"comentarios.created_at #{params[:created_at]}\")\n elsif params[:nombre_cientifico].present?\n consulta = consulta.order(\"#{Especie.attribute_alias(:nombre_cientifico)} #{params[:nombre_cientifico]}\")\n else\n consulta = consulta.order('comentarios.created_at DESC')\n end\n\n @comentarios = consulta.offset(offset).limit(@por_pagina)\n\n else\n # estatus = 5 quiere decir oculto a la vista\n consulta = consulta.where('comentarios.estatus < ?', Comentario::OCULTAR)\n if tax_especifica.length > 0\n or_taxa = []\n tax_especifica.each do |e|\n or_taxa << \" #{Especie.attribute_alias(:id)} = #{e.especie_id}\"\n or_taxa << \" #{Especie.attribute_alias(:ancestry_ascendente_directo)} LIKE '%#{e.especie_id}%' \"\n end\n consulta = consulta.where(or_taxa.join(' OR '))\n end\n if contenido_especifico.length > 0\n consulta = consulta.where(:categorias_contenido_id => contenido_especifico.map(&:subtree_ids).flatten)\n end\n # Comentarios totales\n @totales = consulta.count(:all)\n @comentarios = consulta.order('comentarios.created_at DESC').offset(offset).limit(@por_pagina)\n end\n\n @comentarios.each do |c|\n c.cuantos = c.descendants.count\n c.completa_info(c.root.usuario_id)\n end\n\n @categorias_contenido = CategoriasContenido.grouped_options\n\n response.headers['x-total-entries'] = @totales.to_s\n\n if (@pagina > 1 && @comentarios.any?) || (params.present? && params[:ajax].present? && params[:ajax] == '1')\n # Tiene resultados el scrollling o peticiones de ajax\n render :partial => 'comentarios/admin'\n elsif @pagina > 1 && @comentarios.empty? # Fin del scrolling\n render text: ''\n end\n\n end", "def crud\n # TODO: The `Array` below has the four letters that make up the `CRUD`\n # acronym. Update each element of the array so that you write out the\n # four verbs that describe the CRUD actions.\n\n ['C', 'R', 'U', 'D']\nend", "def create_table objects, columns, title, date_param = nil, nosort = false\n\t\tcurr_user = current_user\n\t\n\t\tid_to_names = [\"trip_id\",\"destination_id\",\"bus_id\"]\n\t\ttimes = [\"depart_time\",\"arrive_time\",\"return_time\"]\n\t\tdates = [\"date\",\"start\",\"expiry\",\"offset_date\",\"start_date\",\"end_date\",\"created_at\",\"updated_at\"]\n\t\tno_management = [\"permissions\", \"roles\"]\n\t\tmanagement_headers = [\"updated_by\",\"created_at\",\"updated_at\"]\n\t\t\n\t\thtml = \"\"\n\t\thtml << '<h1>'.html_safe\n\t\thtml << title\n\t\t\n\t\thtml << '</h1>'.html_safe\n\t\t\n\t\thtml << '<table class=\"admin_table\">'.html_safe\n\t\t\n\t\thtml << '<tr class=\"tr_header\">'.html_safe\n\t\tcolumns.each do |col|\n\t\t\t\n\t\t\tcol_title = col\n\t\t\t\n\t\t\tif col.include? '_id' then col_title = col.split('_id')[0] end\n\t\t\t\n\t\t\tif management_headers.include? col\n\t\t\t\tif curr_user.has_permission? :management\n\t\t\t\t\thtml << '<th>'.html_safe\n\t\t\t\t\tif !nosort \n\t\t\t\t\t\thtml << sort_table(col, col_title.humanize, date_param).html_safe\n\t\t\t\t\telse\n\t\t\t\t\t\thtml << col_title.humanize\n\t\t\t\t\tend\n\t\t\t\t\thtml << '</th>'.html_safe\n\t\t\t\tend\n\t\t\telse\n\t\t\t\thtml << '<th>'.html_safe\n\t\t\t\tif !nosort \n\t\t\t\t\thtml << sort_table(col, col_title.humanize, date_param).html_safe\n\t\t\t\telse\n\t\t\t\t\thtml << col_title.humanize\n\t\t\t\tend\n\t\t\t\thtml << '</th>'.html_safe\n\t\t\tend\n\t\t\t\n\t\tend\n\t\t\n\t\t# Show Column\n\t\thtml << '<th></th>'.html_safe\n\t\t\n\t\t# Edit Column\n\t\tif (curr_user.has_permission? :admin) || (!(no_management.include? objects[0].class.name.tableize) && (curr_user.has_permission? :management))\n\t\t\thtml << '<th></th>'.html_safe\n\t\tend\n\t\t\n\t\t# Destroy Column\n\t\tif curr_user.has_permission? :admin\n\t\t\thtml << '<th></th>'.html_safe\n\t\tend\n\t\t\n\t\thtml << '</tr>'.html_safe\n\t\t\n\t\ti = 0\n\t\tobjects.each do |obj|\n\t\t\tif i.even?\n\t\t\t\thtml << '<tr class=\"tr_alt_1\">'.html_safe\n\t\t\telse\n\t\t\t\thtml << '<tr class=\"tr_alt_2\">'.html_safe\n\t\t\tend\n\t\t\t\tcolumns.each do |col|\n\t\t\t\t\t\n\t\t\t\t\tif id_to_names.include? col\n\t\t\t\t\t\thtml << '<td>'.html_safe\n\t\t\t\t\t\tcol = col.split('_id')[0]\n\t\t\t\t\t\thtml << (link_to obj.send(col).id.to_s + \": \" + obj.send(col).name, obj.send(col)).html_safe\n\t\t\t\t\telsif col == \"user_id\" || col == \"updated_by\"\n\t\t\t\t\t\thtml << '<td>'.html_safe\n\t\t\t\t\t\tcol = col.split('_id')[0]\n\t\t\t\t\t\tif obj.send(col)\n\t\t\t\t\t\t\thtml << (link_to obj.send(col).userid, obj.send(col)).html_safe\n\t\t\t\t\t\tend\n\t\t\t\t\telsif col == \"id\"\n\t\t\t\t\t\thtml << '<td class=\"td_links\">'.html_safe\n\t\t\t\t\t\thtml << obj.send(col).to_s\n\t\t\t\t\telsif col == \"weekday\"\n\t\t\t\t\t\thtml << '<td>'.html_safe\n\t\t\t\t\t\thtml << Date::DAYNAMES[obj.send(col)]\n\t\t\t\t\telsif times.include? col\n\t\t\t\t\t\thtml << '<td>'.html_safe\n\t\t\t\t\t\thtml << obj.send(col).strftime(\"%I:%M %p\")\n\t\t\t\t\telsif dates.include? col\n\t\t\t\t\t\thtml << '<td>'.html_safe\n\t\t\t\t\t\thtml << obj.send(col).strftime(\"%B %d, %Y\")\n\t\t\t\t\telsif col.include? \"_id\"\n\t\t\t\t\t\thtml << '<td>'.html_safe\n\t\t\t\t\t\tcol = col.split('_id')[0]\n\t\t\t\t\t\tif obj.send(col)\n\t\t\t\t\t\t\thtml << (link_to obj.send(col).id.to_s, obj.send(col)).html_safe\n\t\t\t\t\t\tend\n\t\t\t\t\telse\n\t\t\t\t\t\thtml << '<td>'.html_safe\n\t\t\t\t\t\thtml << obj.send(col).to_s\n\t\t\t\t\tend\n\t\t\t\t\t\n\t\t\t\t\thtml << '</td>'.html_safe\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\t# Show Column\n\t\t\t\thtml << '<td class=\"td_links\">'.html_safe\n\t\t\t\thtml << (link_to \"Show\", obj).html_safe\n\t\t\t\thtml << '</td>'.html_safe\n\t\t\t\t\n\t\t\t\t# Edit Column\n\t\t\t\tif (curr_user.has_permission? :admin) || (!(no_management.include? objects[0].class.name.tableize) && (curr_user.has_permission? :management))\n\t\t\t\t\thtml << '<td class=\"td_links\">'.html_safe\n\t\t\t\t\thtml << (link_to \"Edit\", \"/\" + obj.class.name.tableize + \"/\" + obj.id.to_s + \"/edit\").html_safe\n\t\t\t\t\thtml << '</td>'.html_safe\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\t# Destroy Column\n\t\t\t\tif curr_user.has_permission? :admin\n\t\t\t\t\thtml << '<td class=\"td_links\">'.html_safe\n\t\t\t\t\thtml << (link_to \"Destroy\", obj, :confirm => 'Are you sure?', :method => :delete).html_safe\n\t\t\t\t\thtml << '</td>'.html_safe\n\t\t\t\tend\n\t\t\n\t\t\thtml << '</tr>'.html_safe\n\t\t\ti = i + 1\n\t\tend\n\t\t\n\t\thtml << '</table>'.html_safe\n\t\t\n\t\thtml.html_safe\n\tend", "def index\n @cliente = Cliente.find(params[:cliente_id])\n @trabajos = Trabajo.where(:cliente_id => @cliente.id).paginate(:page => params[:page]).order('id DESC')\n end", "def crud *args\n @crud = args.first if args.size > 0\n end", "def index\n @operacioncontroldetes = Operacioncontroldete.all\n end", "def index\n @dado_inseridos = DadoInserido.all\n end", "def editar\n \t@asignaturas=Asignatura.all\n end", "def edit\r\n end", "def index\n permission_denied and return if current_user.cannot 'read_odt'\n @odts = Odt.all\n @new_odt = Odt.new\n @new_odt.comision_odts.build \n @new_odt.deducciones_odts.build\n end", "def index\n @cuarteles = Cuartel.select(:id, :nombre).order(:nombre)\n\n # Control de los botones activos\n @gu_active = ''\n @rm_active = ''\n @cuarteles_active = 'active'\n end", "def index\n @contratantes = Contratante.all\n end", "def index\n @modelos = Modelo.all\n end", "def edit\n # TODO: ensure is admin\n operation = params[:oper]\n if operation == 'edit'\n update\n elsif operation == 'del'\n destroy\n elsif operation == 'add'\n create\n end \n end", "def index\n @contrato_abonos = ContratoAbono.all\n end", "def table\n end", "def edit\n \n end", "def edit\n \n end", "def edit\n \n end", "def edit\n \n end", "def edit\n \n end", "def edit\n \n end", "def edit\n \n end", "def edit\n\n end", "def edit\r\n \r\n end", "def table_list(objetos, show_all_actions = true, options = {})\n render :partial => '/admin/shared/table_list', :locals => { :objetos => objetos, :show_all_actions => show_all_actions, :options => options }\n end", "def index\n @usuario = User.where(:id => current_user.id).pluck(:id).first\n @registros = Registro.where(:grupo_id => params[:clave]).paginate(:page => params[:page]).order('id DESC')\n @name = Grupo.where(:clave => params[:clave]).pluck(:nombre).first\n @grupos = Grupo.all\n @grupo = Grupo.new\n end", "def create\n @tablero = Tablero.new(tablero_params)\n m= params.require(:tablero).permit(:idusuario, :grupo, :descripcion, :e1, :e2, :e3, :puntaje)\n\n params[idusuario.each] do |i|\n miembros=[params[:idusuario[i]]:grupo[i], :descripcion[i], :e1[i], :e2[i], :e3[i], :puntaje[i]]\n end\n\n respond_to do |format|\n if @tablero.save\n format.html { redirect_to @tablero, notice: \"El tablero se creó correctamente\" }\n format.json { render :show, status: :created, location: @tablero }\n else\n format.html { render :new }\n format.json { render json: @tablero.errors, status: :unprocessable_entity }\n end\n end\n end", "def tabla_params\n params.require(:tabla).permit(:tabla, :padre_id, :padre_class, :archivo, :orden, :archivos, :imagenes)\n end", "def index\n\t\t @trabajos = Trabajo.all\n\t\t end", "def index\n @coleccion = Requisito.all\n end", "def index\n @tipo_ordens = TipoOrden.all\n end", "def index\n @ferias_funcionarios = FeriasFuncionario.all\n end", "def index\n @daw_tablas = DawTabla.all\n end", "def index\n @veiculos = Veiculo.where(usuario_id: current_usuario)\n @abastecimentos = Abastecimento.where(:veiculo_id => @veiculos)\n end", "def index\n if !params[:orgao_id].blank? && current_user.admin\n @treinamentos_ti = TreinamentoTi.where(orgao_id: params[:orgao_id])\n elsif current_user.admin\n @treinamentos_ti = TreinamentoTi.all\n else\n @treinamentos_ti = TreinamentoTi.where(orgao_id: current_user.orgao_id)\n end \n #@treinamentos_ti = TreinamentoTi.all\n end", "def edit\n end", "def edit\n end", "def edit\n end", "def edit\n end", "def edit\n end", "def edit\n end", "def edit\n end", "def edit\n end" ]
[ "0.6436675", "0.6322331", "0.6315084", "0.6300498", "0.6237227", "0.62296414", "0.6210463", "0.6210463", "0.61749816", "0.615349", "0.61149585", "0.6107555", "0.6072892", "0.6063122", "0.6059731", "0.6029649", "0.6021682", "0.60033965", "0.59989977", "0.59905064", "0.59726995", "0.5968293", "0.5968293", "0.5968293", "0.5968293", "0.5968293", "0.5968293", "0.5968293", "0.5968293", "0.5968293", "0.5968293", "0.5968293", "0.5968293", "0.5968293", "0.5968293", "0.5968293", "0.5968293", "0.5968293", "0.5968293", "0.5968293", "0.5968293", "0.5968293", "0.596471", "0.5956427", "0.59543425", "0.59517646", "0.59232825", "0.5922449", "0.591641", "0.5909524", "0.5909389", "0.5896644", "0.58965725", "0.58948845", "0.5893963", "0.58812916", "0.58760124", "0.5875725", "0.5874094", "0.5867132", "0.58669853", "0.58565426", "0.585606", "0.5854148", "0.58473325", "0.58470744", "0.5837776", "0.5809801", "0.58095104", "0.5808262", "0.58082396", "0.5790287", "0.57887155", "0.578634", "0.578634", "0.578634", "0.578634", "0.578634", "0.578634", "0.578634", "0.57801765", "0.57702315", "0.57694995", "0.57686037", "0.5763868", "0.57627976", "0.5758334", "0.5755485", "0.57512665", "0.57463646", "0.5742887", "0.57428825", "0.5741848", "0.5738268", "0.5738268", "0.5738268", "0.5738268", "0.5738268", "0.5738268", "0.5738268", "0.5738268" ]
0.0
-1
=> buscamos la Key entre las FKs que apuntan a la tabla => return la columna de la tabla
def getCol_from_fk(tabla, claveFK) @aplicacion[:tablas][tabla]['columnas'].each {|key, value| if (value[:column_rel] && value[:column_rel].eql?(claveFK)) return key end } return '' end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def essential_columns(model_class)\n model_class.reflect_on_all_associations.inject([@primary_key]) do |arr, assoc|\n if assoc.options[:dependent] && assoc.macro == :belongs_to\n arr << assoc.association_foreign_key\n end\n arr\n end\n end", "def key_columns\n @key_columns ||= [\"#{self.table_name}__id\".to_sym]\n end", "def foreign_key_fields\n keys = []\n database_field_names.each do |param|\n if self.send(param).is_a? ForeignKey\n keys << param\n end\n end\n keys\n end", "def foreign_key\n association.foreign_key \n end", "def foreign_key\n self.name + \"_id\"\n end", "def scaf_foreign_keys\n scaf_belongs_tos.collect(&:primary_key_name)\n end", "def foreign_key_column_name\n @foreign_key_column_name ||= begin\n out = options[:foreign_key]\n\n unless out\n out = \"#{@model_class.name.underscore}_#{association_name}\"\n out = $1 if out =~ %r{/([^/]+)$}i\n out = out + \"_id\"\n end\n\n out = out.to_s if out.kind_of?(Symbol)\n\n out\n end\n end", "def foreign_keys(table_name)\n stmt = @connection.foreign_keys(native_case(table_name.to_s))\n result = stmt.fetch_all || []\n stmt.drop unless stmt.nil?\n\n result.map do |key|\n fk_from_table = key[2] # PKTABLE_NAME\n fk_to_table = key[6] # FKTABLE_NAME\n\n ActiveRecord::ConnectionAdapters::ForeignKeyDefinition.new(\n fk_from_table,\n fk_to_table,\n name: key[11], # FK_NAME\n column: key[3], # PKCOLUMN_NAME\n primary_key: key[7], # FKCOLUMN_NAME\n on_delete: key[10], # DELETE_RULE\n on_update: key[9] # UPDATE_RULE\n )\n end\n end", "def key\n get_primary_key_value_map[self.class.table_name]\n end", "def foreign_key\n meta(foreign_key: true)\n end", "def key\n stores_foreign_key? ? foreign_key : primary_key\n end", "def owner_key_name\n reflection.join_foreign_key\n end", "def owner_key_name\n reflection.join_foreign_key\n end", "def scaffold_foreign_key(reflection)\n get_key_array_safe(reflection.child_key).name\n end", "def association_key\n table[association_key_name]\n end", "def foreign_key\n association ? association.foreign_key : name\n end", "def remember_foreign_key_columns(node)\n table_name = @table_name\n foreign_key_column = node.arguments.all.first.to_s\n @foreign_keys[table_name] ||= []\n if foreign_key_column =~ /(.*?)_id$/\n @foreign_keys[table_name] <<\n if @foreign_keys[table_name].delete(\"#{Regexp.last_match(1)}_type\")\n [\"#{Regexp.last_match(1)}_id\", \"#{Regexp.last_match(1)}_type\"]\n else\n foreign_key_column\n end\n foreign_id_column = foreign_key_column\n elsif foreign_key_column =~ /(.*?)_type$/\n @foreign_keys[table_name] <<\n if @foreign_keys[table_name].delete(\"#{Regexp.last_match(1)}_id\")\n [\"#{Regexp.last_match(1)}_id\", \"#{Regexp.last_match(1)}_type\"]\n else\n foreign_key_column\n end\n foreign_id_column = \"#{Regexp.last_match(1)}_id\"\n end\n\n if foreign_id_column\n index_node = node.arguments.all.last.hash_value('index')\n if index_node.present? && (index_node.to_s != 'false')\n @index_columns[table_name] ||= []\n @index_columns[table_name] << foreign_id_column\n end\n end\n end", "def foreign_keys\n vals = []\n foreign_key_fields.each do |field|\n vals << self.send(field)\n end\n vals\n end", "def find_table_by_foreign_key(column_name)\n @opts[:foreign_key][:alias].values_at(column_name).first\n end", "def scaf_foreign_key_name( assoc )\n assoc.primary_key_name\n end", "def primary_key_columns\n @columns.values.find_all { |c| c.primary_key? }\n end", "def foreign_key_for(association)\n model_instance[association.foreign_key_column_name]\n end", "def remember_foreign_key_columns(node)\n table_name = @table_name\n foreign_key_column = node.arguments[1].to_s\n @foreign_keys[table_name] ||= []\n if foreign_key_column =~ /(.*?)_id$/\n if @foreign_keys[table_name].delete(\"#{$1}_type\")\n @foreign_keys[table_name] << [\"#{$1}_id\", \"#{$1}_type\"]\n else\n @foreign_keys[table_name] << foreign_key_column\n end\n elsif foreign_key_column =~ /(.*?)_type$/\n if @foreign_keys[table_name].delete(\"#{$1}_id\")\n @foreign_keys[table_name] << [\"#{$1}_id\", \"#{$1}_type\"]\n else\n @foreign_keys[table_name] << foreign_key_column\n end\n end\n end", "def distribution_key\n return foreign_key_column_name_to_optimised_table if can_optimise_for_different_table?\n\n primary_key_column_name\n end", "def sub_querier_keys()\n ret = @columnNames\n ret << :user_id\n ret << :milestone_id\n return ret\n end", "def associated_key_column\n self[:left_key]\n end", "def association_key_name\n reflection.join_primary_key(klass)\n end", "def foreign_keys\n @foreign_keys ||= connection.foreign_keys(table_name, \"#{name} Foreign Keys\")\n end", "def foreign_key_list(table, opts=OPTS)\n m = output_identifier_meth\n fks = ado_schema_foreign_keys(table).inject({}) do |memo, fk|\n name = m.call(fk['FK_NAME'])\n specs = memo[name] ||= {\n :columns => [],\n :table => m.call(fk['PK_TABLE_NAME']),\n :key => [],\n :deferrable => fk['DEFERRABILITY'],\n :name => name,\n :on_delete => fk['DELETE_RULE'],\n :on_update => fk['UPDATE_RULE']\n }\n specs[:columns] << m.call(fk['FK_COLUMN_NAME'])\n specs[:key] << m.call(fk['PK_COLUMN_NAME'])\n memo\n end\n fks.values\n end", "def association_key_name\n reflection.join_primary_key(klass)\n end", "def foreign_key_list(table, opts=OPTS)\n m = output_identifier_meth\n schema, _ = opts.fetch(:schema, schema_and_table(table))\n\n h = {}\n fklod_map = FOREIGN_KEY_LIST_ON_DELETE_MAP \n reverse = opts[:reverse]\n\n (reverse ? _reverse_foreign_key_list_ds : _foreign_key_list_ds).where_each(Sequel[:cl][:oid]=>regclass_oid(table)) do |row|\n if reverse\n key = [row[:schema], row[:table], row[:name]]\n else\n key = row[:name]\n end\n\n if r = h[key]\n r[:columns] << m.call(row[:column])\n r[:key] << m.call(row[:refcolumn])\n else\n entry = h[key] = {\n :name=>m.call(row[:name]),\n :columns=>[m.call(row[:column])],\n :key=>[m.call(row[:refcolumn])],\n :on_update=>fklod_map[row[:on_update]],\n :on_delete=>fklod_map[row[:on_delete]],\n :deferrable=>row[:deferrable],\n :table=>schema ? SQL::QualifiedIdentifier.new(m.call(row[:schema]), m.call(row[:table])) : m.call(row[:table]),\n }\n\n unless schema\n # If not combining schema information into the :table entry\n # include it as a separate entry.\n entry[:schema] = m.call(row[:schema])\n end\n end\n end\n\n h.values\n end", "def foreign_key(class_name, key = \"id\")\n underscore(demodulize(class_name.to_s)) << \"_\" << key.to_s\n end", "def keys\n @keys ||= [column_for_order_by(relation), primary_key].compact.uniq\n end", "def primary_key\n fields.select { |f| f.key }.map(&:name)\n end", "def column_references_table_constraint_sql(constraint)\n \"FOREIGN KEY #{literal(constraint[:columns])}#{column_references_sql(constraint)}\"\n end", "def association_foreign_keys(assoc_record)\n association_foreign_keys_names.map { |name| assoc_record.public_send(name) }\n end", "def foreign_key_name(table_name, columns)\n keys = foreign_key_list(table_name).select{|key| key[:columns] == columns}\n raise(Error, \"#{keys.empty? ? 'Missing' : 'Ambiguous'} foreign key for #{columns.inspect}\") unless keys.size == 1\n keys.first[:name]\n end", "def foreign_key\n @foreign_key ||= (@options[:foreign_key] || \"#{@name}_id\").to_s\n end", "def match_foreign_key(column)\n if column.ref_table == @name || foreign_keys.include?(column.name.downcase)\n @name if primary_key\n end\n end", "def primary_key(_table_name)\n []\n end", "def to_sql_with_foreign_keys\n from_table = AirBlade::Migrations::SchemaStatements.table_name\n fks = @@foreign_keys.map{ |column, options| foreign_key_constraint from_table, column, options }\n [ to_sql_without_foreign_keys, fks ].reject{ |x| x.blank? }.join ', '\n end", "def keys\n @klass.column_names\n end", "def relation_foreign_key(relation)\n relation_reflect(relation).foreign_key\n end", "def keys\n\t\t@name_table\n\tend", "def pkey\n table = self.class.table_name\n key = get_primary_key_values.first\n return key\n end", "def find_relations\n sql = <<-eos\n SELECT\n tc.constraint_name, tc.table_name, kcu.column_name,\n ccu.table_name AS foreign_table_name,\n ccu.column_name AS foreign_column_name\n FROM\n information_schema.table_constraints AS tc\n JOIN information_schema.key_column_usage AS kcu ON tc.constraint_name = kcu.constraint_name\n JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name\n WHERE constraint_type = 'FOREIGN KEY'\n eos\n @relations = @connection.exec(sql).values\n end", "def parent_table_for(possible_foreign_key)\n pluralize singular_association_name(possible_foreign_key) if possible_foreign_key =~ foreign_key_regex\n end", "def primary_key\n case primary_key_prefix_type\n when :table_name\n Inflector.foreign_key(class_name_of_active_record_descendant(self), false)\n when :table_name_with_underscore\n Inflector.foreign_key(class_name_of_active_record_descendant(self))\n else\n \"id\"\n end\n end", "def hash_fk_model\n foreign_keys = {}\n @model_class.reflect_on_all_associations(:belongs_to).map{ |r|\n foreign_keys[r.association_foreign_key.to_sym] = r.name\n }\n foreign_keys\n end", "def foreign_key_list(table, opts=OPTS)\n super\n rescue Sequel::DatabaseError => e\n raise unless foreign_key_error?(e)\n []\n end", "def primary_key\n \"#{quoted_table_name}.#{model_class.send :primary_key}\"\n end", "def primary_key\n \"#{quoted_table_name}.#{model_class.send :primary_key}\"\n end", "def columns\n unless defined?(@columns) && @columns\n @columns = connection.columns(table_name, \"#{name} Columns\").select do |column| \n column.name =~ Regexp.new(\"^#{self.to_s.underscore}__\") || column.name == primary_key\n end\n @columns.each { |column| column.primary = column.name == primary_key }\n end\n @columns\n end", "def __foreign_key_list_ds(reverse)\n if reverse\n ctable = Sequel[:att2]\n cclass = Sequel[:cl2]\n rtable = Sequel[:att]\n rclass = Sequel[:cl]\n else\n ctable = Sequel[:att]\n cclass = Sequel[:cl]\n rtable = Sequel[:att2]\n rclass = Sequel[:cl2]\n end\n\n if server_version >= 90500\n cpos = Sequel.expr{array_position(co[:conkey], ctable[:attnum])}\n rpos = Sequel.expr{array_position(co[:confkey], rtable[:attnum])}\n # :nocov:\n else\n range = 0...32\n cpos = Sequel.expr{SQL::CaseExpression.new(range.map{|x| [SQL::Subscript.new(co[:conkey], [x]), x]}, 32, ctable[:attnum])}\n rpos = Sequel.expr{SQL::CaseExpression.new(range.map{|x| [SQL::Subscript.new(co[:confkey], [x]), x]}, 32, rtable[:attnum])}\n # :nocov:\n end\n\n ds = metadata_dataset.\n from{pg_constraint.as(:co)}.\n join(Sequel[:pg_class].as(cclass), :oid=>:conrelid).\n join(Sequel[:pg_attribute].as(ctable), :attrelid=>:oid, :attnum=>SQL::Function.new(:ANY, Sequel[:co][:conkey])).\n join(Sequel[:pg_class].as(rclass), :oid=>Sequel[:co][:confrelid]).\n join(Sequel[:pg_attribute].as(rtable), :attrelid=>:oid, :attnum=>SQL::Function.new(:ANY, Sequel[:co][:confkey])).\n join(Sequel[:pg_namespace].as(:nsp), :oid=>Sequel[:cl2][:relnamespace]).\n order{[co[:conname], cpos]}.\n where{{\n cl[:relkind]=>%w'r p',\n co[:contype]=>'f',\n cpos=>rpos\n }}.\n select{[\n co[:conname].as(:name),\n ctable[:attname].as(:column),\n co[:confupdtype].as(:on_update),\n co[:confdeltype].as(:on_delete),\n cl2[:relname].as(:table),\n rtable[:attname].as(:refcolumn),\n SQL::BooleanExpression.new(:AND, co[:condeferrable], co[:condeferred]).as(:deferrable),\n nsp[:nspname].as(:schema)\n ]}\n\n if reverse\n ds = ds.order_append(Sequel[:nsp][:nspname], Sequel[:cl2][:relname])\n end\n\n ds\n end", "def keys\n @table.keys.inject(@parent ? @parent.keys : []) do |res, k1|\n @table[k1].keys.inject(res) do |_res, k2|\n ref = make_reference(k1, k2)\n _res.include?(ref) ? _res : res << ref\n end\n end\n end", "def association_keys_for(klass, association_name)\n select_table_fields = []\n \n # make sure there is a reflection with this name\n if r = klass.reflections[association_name]\n if r.macro == :belongs_to\n # A :belongs_to B => [a, r.primary_key], [b, b.primary_key]\n select_table_fields << [klass.table_name, r.primary_key_name.to_s]\n select_table_fields.concat(class_primary_key_fields(r.klass))\n elsif r.macro == :has_one\n # A :has_one B => [b, r.primary_key]\n select_table_fields << [r.klass.table_name, r.primary_key_name.to_s]\n elsif r.macro == :has_many\n if r.options[:through] && r.source_reflection\n # A :has_many B, :through C => [b, b.primary_key]\n select_table_fields.concat(class_primary_key_fields(r.source_reflection.klass))\n else\n # A :has_many B => [b, r.primary_key]\n select_table_fields << [r.klass.table_name, r.primary_key_name.to_s]\n end\n elsif r.macro == :has_and_belongs_to_many\n # A :has_and_belongs_to_many B => [b, b.primary_key]\n select_table_fields.concat(class_primary_key_fields(r.klass))\n end\n end\n select_table_fields\n end", "def foreign_key(relation)\n detect { |attr| attr.foreign_key? && attr.target == relation }\n end", "def foreign_key_name(class_name)\n Inflector.foreign_key(class_name).to_sym\n end", "def foreign_key(clazz=nil)\n @foreign_key || begin\n if @type == :t_belongs_to\n belongs_to_foreign_key\n elsif @type == :t_has_one || @type == :t_has_many\n has_x_foreign_key(clazz)\n end\n end\n end", "def keys!\n @table.keys\n end", "def primary_key_names\n @primary_key_names ||= session.left.primary_key_names(left_table)\n end", "def default_primary_key\n model_name.foreign_key.to_s\n end", "def quote_constraint_name(foreign_key)\n quote_table_name(foreign_key)\n end", "def get_keys\n table_cond = @files ? \"AND r.relname IN (#{@files.map{|(t,f)|\"'#{t}'\"}.join(', ')})\" : ''\n results = query(<<-SQL)\n SELECT\n r.relname,\n c.conname,\n c.contype,\n pg_get_constraintdef(c.oid)\n FROM\n pg_class r,\n pg_constraint c\n WHERE\n c.conrelid = r.oid\n AND c.contype IN ('f', 'p')\n AND r.relkind = 'r'\n AND r.relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = '#{@config[:schema]}')\n #{table_cond}\n SQL\n\n hash = {}\n results.map do |row|\n table, key, type, create_sql = row.split(/\\t/)\n hash[key] = {:table => table, :type => type == 'p' ? :primary_key : :foreign_key, :create_sql => create_sql}\n end\n hash\n end", "def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)\n Geode::FastInflector.foreign_key(class_name, separate_class_name_and_id_with_underscore)\n end", "def combine_polymorphic_foreign_keys\n @index_columns.each do |_table, foreign_keys|\n foreign_id_keys = foreign_keys.select { |key| key.size == 1 && key.first =~ /_id/ }\n foreign_type_keys = foreign_keys.select { |key| key.size == 1 && key.first =~ /_type/ }\n foreign_id_keys.each do |id_key|\n next unless type_key =\n foreign_type_keys.detect { |type_key| type_key.first == id_key.first.sub(/_id/, '') + '_type' }\n\n foreign_keys.delete(id_key)\n foreign_keys.delete(type_key)\n foreign_keys << id_key + type_key\n end\n end\n end", "def default_columns\n columns = model.columns - Array(model.primary_key)\n model.all_association_reflections.each do |reflection|\n next unless reflection[:type] == :many_to_one\n if i = columns.index(reflection[:key])\n columns[i] = reflection[:name]\n end\n end\n columns.sort!\n end", "def column_name; end", "def primary_key table\n return nil unless table\n table = self[table]\n pk = table.column_names.find{ |c| table[c].primary_key? }\n end", "def foreign_keys_from_associations(fields = association_fields)\n fields.each_with_object([]) do |(_field_name, metadata), keys|\n keys << metadata[:foreign_key] if metadata[:foreign_key]\n keys << metadata[:polymorphic_type] if metadata[:polymorphic_type]\n keys\n end\n end", "def foreign_keys_from_associations(fields = association_fields)\n fields.each_with_object([]) do |(_field_name, metadata), keys|\n keys << metadata[:foreign_key] if metadata[:foreign_key]\n keys << metadata[:polymorphic_type] if metadata[:polymorphic_type]\n keys\n end\n end", "def link_belongs_to(reflection)\n reflection.foreign_key.to_sym\n end", "def primary_keys(table)\n row = exec_query(<<-end_sql, 'SCHEMA').rows.map do |row|\n SELECT DISTINCT(attr.attname)\n FROM pg_attribute attr\n INNER JOIN pg_depend dep ON attr.attrelid = dep.refobjid AND attr.attnum = dep.refobjsubid\n INNER JOIN pg_constraint cons ON attr.attrelid = cons.conrelid AND attr.attnum = cons.conkey[1]\n WHERE cons.contype = 'p'\n AND dep.refobjid = '#{quote_table_name(table)}'::regclass\n end_sql\n row && row.first\n end\n end", "def foreign_key(separate_class_name_and_id_with_underscore = true)\n MotionSupport::Inflector.foreign_key(self, separate_class_name_and_id_with_underscore)\n end", "def foreign_key\n @foreign_key ||= @options[:foreign_key] ? @options[:foreign_key].to_s :\n default_foreign_key_field\n end", "def default_associated_key_alias\n self[:uses_left_composite_keys] ? (0...self[:through].first[:left].length).map{|i| :\"x_foreign_key_#{i}_x\"} : :x_foreign_key_x\n end", "def class_primary_key_fields(klass)\n fields = []\n if klass.primary_key.class == Array || klass.primary_key.class == CompositePrimaryKeys::CompositeKeys\n klass.primary_key.each do |pk|\n fields << [klass.table_name, pk.to_s]\n end\n else\n fields << [klass.table_name, klass.primary_key]\n end\n fields\n end", "def constraint_name(table, field)\n \"fk_#{table}_#{field_list_name(field)}\"\n end", "def record_foreign_keys(parent_record)\n association_foreign_keys(parent_record)\n end", "def non_foreign_key_fields\n self.database_field_names - self.foreign_key_fields\n end", "def using_key(foreign_key)\n @column = foreign_key\n self\n end", "def foreign_key\n @resource_options.fetch :foreign_key,\n :\"#{tools.string.singularize association_name}_id\"\n end", "def table_id\n\n end", "def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)\n underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? \"_id\" : \"id\")\n end", "def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)\n underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? \"_id\" : \"id\")\n end", "def column_definition_references_sql(sql, column)\n if column[:table]\n if name = column[:foreign_key_constraint_name]\n sql << \" CONSTRAINT #{quote_identifier(name)}\"\n end\n sql << column_references_column_constraint_sql(column)\n end\n end", "def keys\n in_transaction\n @table.keys\n end", "def pk_and_sequence_for(table_name)\n (owner, table_name) = @connection.describe(table_name)\n\n # RSI: changed select from all_constraints to user_constraints - much faster in large data dictionaries\n pks = select_values(<<-SQL, 'Primary Key')\n select cc.column_name\n from user_constraints c, user_cons_columns cc\n where c.owner = '#{owner}'\n and c.table_name = '#{table_name}'\n and c.constraint_type = 'P'\n and cc.owner = c.owner\n and cc.constraint_name = c.constraint_name\n SQL\n\n # only support single column keys\n pks.size == 1 ? [oracle_downcase(pks.first), nil] : nil\n end", "def col_names_for_insert\n self.class.column_names.delete_if {|col| col == \"id\"}.join(\", \")\n #\n end", "def find_left_table_pk o\n return visit o.primary_key if o.instance_of? Arel::Table\n find_left_table_pk o.left if o.kind_of? Arel::Nodes::Join\n end", "def sql_columns\n \"(#{attributes.keys.join(\", \")})\"\n end", "def primary_keys(table)\n pks = query(<<-end_sql, 'SCHEMA')\n SELECT DISTINCT attr.attname\n FROM pg_attribute attr\n INNER JOIN pg_depend dep ON attr.attrelid = dep.refobjid AND attr.attnum = dep.refobjsubid\n INNER JOIN pg_constraint cons ON attr.attrelid = cons.conrelid AND attr.attnum = any(cons.conkey)\n WHERE cons.contype = 'p'\n AND dep.refobjid = '#{quote_table_name(table)}'::regclass\n end_sql\n pks.present? ? pks[0] : pks\n end", "def omim_ids\n @table.keys\n end", "def association_keys\n association\n .__send__(:join_key_map, container.relations)\n end", "def associated_new_column_values(obj, assoc)\n ref = model.association_reflection(assoc)\n ref[:keys].zip(ref[:primary_keys].map{|k| obj.send(k)})\n end", "def get_table_column_names(table)\r\n @db[table].columns\r\n end", "def association_id_method\n self.class.foreign_key_name(@options[\"name\"])\n end", "def column_names\n self[0].keys\n end", "def association_key(assoc)\n model.association_reflection(assoc)[:key]\n end", "def foreign_key(separate_class_name_and_id_with_underscore = true)\n # TODO\n # Inflector.foreign_key(self, separate_class_name_and_id_with_underscore)\n end" ]
[ "0.70305985", "0.6934662", "0.6860085", "0.6801162", "0.67920816", "0.6746138", "0.67425704", "0.66787606", "0.6655856", "0.66209376", "0.66142535", "0.6610513", "0.6610513", "0.6595162", "0.658286", "0.6569761", "0.65458333", "0.6541611", "0.651242", "0.64937085", "0.64856297", "0.6475348", "0.64719504", "0.6425011", "0.6414566", "0.64082026", "0.6380257", "0.63776016", "0.6338827", "0.631796", "0.63103455", "0.63051784", "0.63050544", "0.6294642", "0.6294608", "0.6283786", "0.62792414", "0.6241939", "0.62384653", "0.62366664", "0.62322795", "0.6203003", "0.6190886", "0.61341935", "0.61114347", "0.608876", "0.6079867", "0.6062826", "0.60582", "0.6050158", "0.60382754", "0.60382754", "0.6012241", "0.6006833", "0.5998118", "0.5989561", "0.59823096", "0.5975047", "0.5971434", "0.594182", "0.5935297", "0.5932347", "0.5929379", "0.59226066", "0.59174263", "0.5915943", "0.5910539", "0.5897728", "0.5893871", "0.5881455", "0.5881455", "0.5875216", "0.5874882", "0.58727455", "0.5868232", "0.58626467", "0.5855954", "0.5855009", "0.5853689", "0.58222747", "0.5817183", "0.580756", "0.58052397", "0.5789938", "0.5789938", "0.57831544", "0.5778498", "0.577354", "0.57700956", "0.5770028", "0.5768414", "0.57661396", "0.5763444", "0.57631356", "0.5748885", "0.5747905", "0.57452375", "0.57436454", "0.57414585", "0.573875" ]
0.76632375
0
Si en :order viene en los parametros lo invertimos sino devolvemos siempre ASC
def set_order( params ) return 'desc' if (params[:order]=='asc') return 'asc' end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def sort_direction\n # karakter kontrol yapiliyor security icin \n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\" \n end", "def sort_direction\n # karakter kontrol yapiliyor security icin \n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\" \n end", "def sort_direction\n # karakter kontrol yapiliyor security icin \n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\" \n end", "def sort_direction\n # karakter kontrol yapiliyor security icin \n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\" \n end", "def sort_direction\n # karakter kontrol yapiliyor security icin \n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\" \n end", "def sort_direction\n # karakter kontrol yapiliyor security icin \n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\" \n end", "def define_order(s_order)\n s_order=='Crescente' ? :asc : :desc\n end", "def order_string\n \"#{params[:sort]} #{params[:direction]}\"\n end", "def sort_order(order)\n \"#{(params[:order] || order.to_s).gsub(/[\\s;'\\\"]/,'')} #{params[:direction] == 'up' ? 'ASC' : 'DESC'}\"\n end", "def sort_direction\n params[\"order\"][\"0\"][\"dir\"] == \"desc\" ? \"desc\" : \"asc\"\n end", "def sort_order(default) \n sql_order = [] \n sort_array = (params[:c] || default.to_s).gsub(/[\\s;'\\\"]/,'').split(/,/)\n \n sort_array.each do |c|\n sql_order << c + \" #{params[:d] == 'down' ? 'DESC' : 'ASC'}\"\n end\n \n sql_order.join(', ')\n end", "def set_order\n sort = params[:sort].present? ? params[:sort] : 'id'\n # FIXME cambiar puntos por guiones para tener automagia\n if sort == 'terceros_nombre'\n sort = 'terceros.nombre'\n end\n ord = params[:order].present? ? params[:order].upcase() : 'ASC'\n @order = sort + ' ' + ord\n end", "def opposite_sort_order\n sort_order == \"ASC\" ? \"DESC\" : \"ASC\"\n end", "def sort_order(default)\n\n \"#{(params[:c] || default.to_s).gsub(/[\\s;'\\\"]/,'')} #{params[:d] == 'down' ? 'DESC' : 'ASC'}\"\n\n end", "def getSortingOrder #:doc:\n sorting = @default_sorting.dup\n ordering = [\"DESC\", \"ASC\", \"ASC\", \"ASC\"] # default ordering\n \n if @queryparams[:sort_by]\n # get given sort_by-values\n sorts = @queryparams[:sort_by].split(\" \")\n # get given order-values and make sure sorts.size == orders.size\n orders = Array.new(sorts.size, \"DESC\")\n if @queryparams[:order]\n orders = @queryparams[:order].split(\" \")\n if orders.size < sorts.size\n orders += Array.new(sorts.size - orders.size, \"DESC\")\n elsif orders.size > sorts.size\n orders = orders.slice(0, sorts.size)\n end\n orders.each do |o|\n if not (o.upcase == \"ASC\" or o.upcase == \"DESC\") then o = \"ASC\" end\n end \n end\n \n # first sort_by-value has to be processed last (so it gets first on the list)\n sorts = sorts.reverse\n orders = orders.reverse\n \n # check sort_by-values\n sorts.each_index do |i|\n if @sort_by.has_key?(sorts[i])\n # move the sort-attribute to first\n sort_value = @sort_by[sorts[i]]\n ind = sorting.index(\"LOWER(\" + @sort_by[sorts[i]] + \")\")\n if ind != nil\n sorting.delete_at(ind)\n ordering.delete_at(ind)\n sort_value = \"LOWER(\" + sort_value + \")\"\n end\n sorting.unshift(sort_value)\n ordering.unshift(orders[i].upcase)\n end\n end\n end\n \n #combine everything together\n returnable = sorting[0] + \" \" + ordering[0]\n sorting.each_index do |i|\n next if i == 0\n returnable += \", \" + sorting[i] + \" \" + ordering[i]\n end\n return returnable\n end", "def normalize_order(order); end", "def sort_direction\n params[:direction] || \"asc\"\n end", "def ordering_params(params)\n # For example it retrieves a list of experiences in descending order of price.\n # Within a specific price, older experiences are ordered first\n #\n # GET /api/v1/experiences?sort=-price,created_at\n # ordering_params(params) # => \"price desc, created_at asc\"\n # Experience.order(\"price desc, created_at asc\")\n #\n ordering = []\n return join_params(ordering) unless params[:sort]\n\n ordering = params[:sort].split(',').each_with_object(ordering) do |attr, memo|\n sort_sign = (attr =~ /\\A[+-]/) ? attr.slice!(0) : \"+\"\n memo << \"#{attr} #{SIGN_OPDERS[sort_sign]}\"\n end\n join_params(ordering)\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"desc\"\n end", "def order\n \"#{sort} #{dir}\"\n end", "def sort_params params\n if @sortable\n pairs = sort_pairs(params)\n found_pair = false\n pairs.each_with_index{|pair,index|\n if pair[0] == self.name.to_s\n pairs[index][1] = pair[1] == \"asc\" ? \"desc\" : \"asc\"\n found_pair = true\n end\n }\n unless found_pair\n pairs << [self.name.to_s,\"asc\"]\n end\n (pairs.map{|pair| pair.join(\",\")}).join(\"|\")\n else\n \"\"\n end\n end", "def add_sort_order_to_title\n return unless params[:by]\n\n self.title_tag = :query_title_all_by\n title_args[:order] = :\"sort_by_#{params[:by].sub(/^reverse_/, \"\")}\"\n end", "def orders\n params.fetch(:sort).split(',').map do |string|\n next unless string =~ /\\A-?\\w+\\z/ # allow only word chars\n\n order(string)\n end.compact\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"desc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"desc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"desc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : 'asc'\n end", "def order(*args)\n with_opts(:order=>args.freeze)\n end", "def sort_direction\n params[:dir] == \"asc\" ? \"asc\" : \"desc\"\n end", "def sort_params; end", "def sort_params; end", "def orders\n \"intake, matrixno ASC\"\n # \"course_id, intake, matrixno ASC\"\n end", "def another_order_direction\n @mg_params.key?(:order_direction) ? (%w(asc desc) - [@mg_params[:order_direction].to_s]).first : MightyGrid.order_direction\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def normalize_order!(default = :asc)\n replace normalize_order(default)\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def arel_order\n text_columns = if params[:order]\n params[:order].split(' ')\n elsif self.default_sort\n [self.default_sort].flatten\n else\n [model_class.primary_key].flatten\n end\n sort_columns = text_columns.map do |column|\n if column.to_s.include?('.')\n name,direction = column.to_s.split('.',2)\n raise \"Illegal sort direction: #{direction} in #{column}\" unless %w{asc desc}.include?(direction)\n table[name].send(direction)\n else\n table[column]\n end\n end\n sort_columns\n end", "def ordering_by\n order && order.to_s.gsub(/^(ascend|descend)_by_/, '')\n end", "def sort_direction\n %w[asc, desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"desc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"desc\"\n end", "def set_OrderBy(value)\n set_input(\"OrderBy\", value)\n end", "def set_OrderBy(value)\n set_input(\"OrderBy\", value)\n end", "def set_OrderBy(value)\n set_input(\"OrderBy\", value)\n end", "def set_OrderBy(value)\n set_input(\"OrderBy\", value)\n end", "def set_OrderBy(value)\n set_input(\"OrderBy\", value)\n end", "def set_OrderBy(value)\n set_input(\"OrderBy\", value)\n end", "def set_OrderBy(value)\n set_input(\"OrderBy\", value)\n end", "def set_OrderBy(value)\n set_input(\"OrderBy\", value)\n end", "def set_sub_grid_order( params )\n return 'desc' if (params[:g_o]=='asc')\n return 'asc'\n end", "def sort_params\n return [] unless params['sort_by']\n\n orders = (params['sort_order'] ? params['sort_order'].split(\",\") : [\"\"])\n sort_order = params['sort_by'].split(\",\").zip(orders).collect do |attr, order|\n next if attr.blank?\n sort_item = attr\n sort_item << \" ASC\" if order && order.downcase.start_with?(\"asc\")\n sort_item << \" DESC\" if order && order.downcase.start_with?(\"desc\")\n sort_item\n end\n sort_order.compact\n end", "def sort_sql_helper(param)\n return param.gsub('_reverse',\" DESC\")\n end", "def set_order\n unless params[:order_by]\n @order = @model.typus_order_by\n else\n @order = \"#{params[:order_by]} #{params[:sort_order]}\"\n end\n end", "def toggle_order(order)\n (@current_order = order;@list = 1;@message = nil;return true) if order.match('ascending')\n (@current_order = order;@list = uids;@message = nil;return true) if order.match('descending')\n end", "def sort_order(default)\n if params[:c].blank? && default == \"created_at\"\n \"created_at DESC\"\n elsif params[:c].blank? && default == \"total\"\n \"total DESC\"\n else\n \"#{(params[:c] || default.to_s).gsub(/[\\s;'\\\"]/,'')} #{params[:d] == 'down' ? 'DESC' : 'ASC'}\"\n end\n end", "def order\n order = single_param(\"order\")\n if order.nil?\n return nil\n end\n if order.start_with?('-')\n field = order[1..-1]\n dir = \"desc\"\n else\n field = order\n dir = \"asc\"\n end\n unless ALLOWED_SORT_FIELDS.include?(field)\n @errors << %{\"#{field}\" is not a valid sort field}\n return nil\n end\n return [SORT_MAPPINGS.fetch(field, field), dir]\n end", "def get_sort_order (get_param, column_name)\r\n\t\tif params[get_param] && !params[get_param].empty?\r\n\t\t\tif params[get_param].downcase == \"asc\"\r\n\t\t\t\tif column_name.kind_of?(Array)\r\n\t\t\t\t\t\"#{column_name.join(' ASC, ')} ASC\"\r\n\t\t\t\telse\r\n\t\t\t\t\t\"#{column_name} ASC\"\r\n\t\t\t\tend\r\n\t\t\telse\r\n\t\t\t\tif column_name.kind_of?(Array)\r\n\t\t\t\t\t\"#{column_name.join(' DESC, ')} DESC\"\r\n\t\t\t\telse\r\n\t\t\t\t\t\"#{column_name} DESC\"\r\n\t\t\t\tend\r\n\t\t\tend\r\n\t\tend\r\n\tend", "def inverse\n OrderBy.new(@field, @dir == :asc ? :desc : :asc)\n end", "def normalize_order(order)\n\t\t\t\torder = Array(order)\n\t\t\t\tif order.length == 2 && !order[0].is_a?(Array) && [:asc, :desc].include?(order[1])\n\t\t\t\t\torder = [order]\n\t\t\t\telse\n\t\t\t\t\torder = order.map {|pair| pair.is_a?(Array) ? pair : [pair, :asc] }\n\t\t\t\tend\n\t\t\t\torder.each do |pair|\n\t\t\t\t\tpair.length == 2 or raise ArgumentError, \"each order clause must be a pair (unknown clause #{pair.inspect})\"\n\t\t\t\t\t[:asc, :desc].include?(pair[1]) or raise ArgumentError, \"order must be specified with :asc or :desc (unknown key #{pair[1].inspect})\"\n\t\t\t\tend\n\t\t\t\torder\n\t\t\tend", "def attrs_to_orderings(order)\n order.map do |o|\n Arel::Attribute === o ? o.asc : o\n end\n end", "def index_sort_order\n @query = {}\n @query['sort_key'] = params['sort_key'] unless params['sort_key'].blank?\n\n if @query['sort_key']&.starts_with?('-')\n \"#{@query['sort_key'].delete_prefix('-')} DESC\"\n elsif @query['sort_key'].present?\n \"#{@query['sort_key']} ASC\"\n else\n 'updated_at DESC'\n end\n end", "def orders\n \"assetcode ASC\"# \"staffgrade_id ASC\"\n end", "def order(field='id',order='desc')\n case order.downcase.to_s\n when 'asc'\n self.sort { |a,b| b.send(field.to_s) <=> a.send(field.to_s) }\n when 'desc' \n self.sort { |a,b| a.send(field.to_s) <=> b.send(field.to_s) }\n end\n end", "def order(order)\n params[:sort] = if order.is_a?(Hash) then\n order.reduce([]) do |memo, obj|\n key, value = obj\n\n if (value.to_s != \"asc\" && value.to_s != \"desc\") then\n raise ArgumentError, \"Order must be either :asc or :desc\"\n end\n\n key = \"-#{key}\" if value.to_s == \"desc\"\n memo.push(key)\n end.join(\",\")\n elsif order.is_a?(String) then\n order\n end\n\n self\n end", "def set_OrderBy(value)\n set_input(\"OrderBy\", value)\n end", "def set_OrderBy(value)\n set_input(\"OrderBy\", value)\n end", "def set_OrderBy(value)\n set_input(\"OrderBy\", value)\n end", "def set_OrderBy(value)\n set_input(\"OrderBy\", value)\n end", "def order=(_arg0); end", "def sort_order\n 0\n end", "def ordering_params(params)\n ordering = {}\n if params[:sort]\n sort_order = { '-' => :asc, '+' => :desc }\n\n sorted_params = params[:sort].split(',')\n sorted_params.each do |attr|\n sort_sign = attr.match?(/\\A[+-]/) ? attr.slice!(0) : '+'\n model = controller_name.classify.constantize\n if model.attribute_names.include?(attr)\n ordering[attr] = sort_order[sort_sign]\n end\n end\n end\n ordering\n end", "def calc_order\n @order_by = (['name', 'popularity'].include?(params[:order_by]) ? params[:order_by] : 'popularity')\n\n order = (params[:order_name] or '').upcase\n @order_name = (!order.blank? and ['ASC', 'DESC'].include?(order)) ? order : 'ASC'\n\n order = (params[:order_popularity] or '').upcase\n @order_popularity = (!order.blank? and ['ASC', 'DESC'].include?(order)) ? order : 'ASC'\n end", "def original_order\n end", "def sort_params=(_arg0); end", "def sort_params=(_arg0); end", "def sort_param_with_url(sortable_name, *args)\n params.delete(:sortasc)\n params.delete(:sortdesc)\n params.merge(sort_param_without_url(sortable_name, *args))\n end", "def ordering\n if params[:order]\n Hash[params[:order].values.map{ |ordering|\n [COLUMNS_TO_ORDER_FIELD[ordering[\"column\"].to_i], ordering[\"dir\"].to_sym]\n }]\n elsif params[:sort]\n params[:sort]\n else\n {_score: :desc}\n end\n end", "def sort\n params[:order].each do |key, value|\n Portfolio.find(value[:id]).update(position: value[:postion])\n end\n \n #render :nothing => true\n end", "def sort_direction\n %w[asc desc].include?(params[:sort]) ? params[:sort] : nil\n end", "def sort_direction\n %w[asc desc].include?(params[:sort]) ? params[:sort] : nil\n end", "def ordered_expression_sql(oe)\n \"#{literal(oe.expression)} #{oe.descending ? 'DESC' : 'ASC'}\"\n end", "def order(value)\n\t\t\tparam(\"order\", value)\n\t\tend", "def tie_breaking_sort\n { \"content_id\" => { order: \"asc\" } }\n end", "def normalize_order(order)\n order = Array(order)\n\n if order.length == 2 && !order[0].is_a?(Array) && [:asc, :desc].include?(order[1])\n order = [order]\n else\n order = order.map {|pair| pair.is_a?(Array) ? pair : [pair, :asc] }\n end\n\n order.each do |pair|\n pair.length == 2 or raise ArgumentError, \"each order clause must be a pair (unknown clause #{pair.inspect})\"\n [:asc, :desc].include?(pair[1]) or raise ArgumentError, \"order must be specified with :asc or :desc (unknown key #{pair[1].inspect})\"\n end\n\n order\n end", "def sort_dir\n params[:sort_dir] == 'desc' ? 'desc' : 'asc'\n end" ]
[ "0.7538117", "0.7538117", "0.7538117", "0.7538117", "0.7538117", "0.7538117", "0.73701024", "0.729054", "0.724826", "0.71240824", "0.70787895", "0.70771384", "0.7031609", "0.70219976", "0.69541156", "0.68781275", "0.6877097", "0.6868974", "0.68656623", "0.6857382", "0.6857382", "0.6857382", "0.6843492", "0.68084437", "0.6800214", "0.67924905", "0.6784839", "0.67800814", "0.67800814", "0.67800814", "0.67800814", "0.67800814", "0.67800814", "0.67800814", "0.6762296", "0.6762296", "0.6762296", "0.6761183", "0.6751003", "0.6739131", "0.67259824", "0.67259824", "0.6711796", "0.67003846", "0.6693014", "0.66664785", "0.665262", "0.665262", "0.665262", "0.665262", "0.665262", "0.6648567", "0.66453147", "0.6625986", "0.6622442", "0.6622442", "0.65996635", "0.65996635", "0.65996635", "0.65996635", "0.65996635", "0.65996635", "0.65996635", "0.65996635", "0.6593576", "0.6591086", "0.657076", "0.65573376", "0.6549855", "0.652792", "0.6523272", "0.65187854", "0.6516791", "0.6515014", "0.65095025", "0.6506967", "0.6490389", "0.64884406", "0.6486001", "0.648304", "0.648304", "0.648304", "0.648304", "0.6480438", "0.6478127", "0.6474653", "0.646471", "0.6445236", "0.6441481", "0.6441481", "0.6424184", "0.6414515", "0.6403988", "0.64034975", "0.64034975", "0.6383646", "0.6382561", "0.63799584", "0.6372932", "0.63695556" ]
0.7752323
0
Si en :order viene en los parametros lo invertimos sino devolvemos siempre ASC
def set_sub_grid_order( params ) return 'desc' if (params[:g_o]=='asc') return 'asc' end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_order( params )\n return 'desc' if (params[:order]=='asc')\n return 'asc'\n end", "def sort_direction\n # karakter kontrol yapiliyor security icin \n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\" \n end", "def sort_direction\n # karakter kontrol yapiliyor security icin \n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\" \n end", "def sort_direction\n # karakter kontrol yapiliyor security icin \n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\" \n end", "def sort_direction\n # karakter kontrol yapiliyor security icin \n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\" \n end", "def sort_direction\n # karakter kontrol yapiliyor security icin \n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\" \n end", "def sort_direction\n # karakter kontrol yapiliyor security icin \n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\" \n end", "def define_order(s_order)\n s_order=='Crescente' ? :asc : :desc\n end", "def order_string\n \"#{params[:sort]} #{params[:direction]}\"\n end", "def sort_order(order)\n \"#{(params[:order] || order.to_s).gsub(/[\\s;'\\\"]/,'')} #{params[:direction] == 'up' ? 'ASC' : 'DESC'}\"\n end", "def sort_direction\n params[\"order\"][\"0\"][\"dir\"] == \"desc\" ? \"desc\" : \"asc\"\n end", "def sort_order(default) \n sql_order = [] \n sort_array = (params[:c] || default.to_s).gsub(/[\\s;'\\\"]/,'').split(/,/)\n \n sort_array.each do |c|\n sql_order << c + \" #{params[:d] == 'down' ? 'DESC' : 'ASC'}\"\n end\n \n sql_order.join(', ')\n end", "def set_order\n sort = params[:sort].present? ? params[:sort] : 'id'\n # FIXME cambiar puntos por guiones para tener automagia\n if sort == 'terceros_nombre'\n sort = 'terceros.nombre'\n end\n ord = params[:order].present? ? params[:order].upcase() : 'ASC'\n @order = sort + ' ' + ord\n end", "def opposite_sort_order\n sort_order == \"ASC\" ? \"DESC\" : \"ASC\"\n end", "def sort_order(default)\n\n \"#{(params[:c] || default.to_s).gsub(/[\\s;'\\\"]/,'')} #{params[:d] == 'down' ? 'DESC' : 'ASC'}\"\n\n end", "def getSortingOrder #:doc:\n sorting = @default_sorting.dup\n ordering = [\"DESC\", \"ASC\", \"ASC\", \"ASC\"] # default ordering\n \n if @queryparams[:sort_by]\n # get given sort_by-values\n sorts = @queryparams[:sort_by].split(\" \")\n # get given order-values and make sure sorts.size == orders.size\n orders = Array.new(sorts.size, \"DESC\")\n if @queryparams[:order]\n orders = @queryparams[:order].split(\" \")\n if orders.size < sorts.size\n orders += Array.new(sorts.size - orders.size, \"DESC\")\n elsif orders.size > sorts.size\n orders = orders.slice(0, sorts.size)\n end\n orders.each do |o|\n if not (o.upcase == \"ASC\" or o.upcase == \"DESC\") then o = \"ASC\" end\n end \n end\n \n # first sort_by-value has to be processed last (so it gets first on the list)\n sorts = sorts.reverse\n orders = orders.reverse\n \n # check sort_by-values\n sorts.each_index do |i|\n if @sort_by.has_key?(sorts[i])\n # move the sort-attribute to first\n sort_value = @sort_by[sorts[i]]\n ind = sorting.index(\"LOWER(\" + @sort_by[sorts[i]] + \")\")\n if ind != nil\n sorting.delete_at(ind)\n ordering.delete_at(ind)\n sort_value = \"LOWER(\" + sort_value + \")\"\n end\n sorting.unshift(sort_value)\n ordering.unshift(orders[i].upcase)\n end\n end\n end\n \n #combine everything together\n returnable = sorting[0] + \" \" + ordering[0]\n sorting.each_index do |i|\n next if i == 0\n returnable += \", \" + sorting[i] + \" \" + ordering[i]\n end\n return returnable\n end", "def normalize_order(order); end", "def sort_direction\n params[:direction] || \"asc\"\n end", "def ordering_params(params)\n # For example it retrieves a list of experiences in descending order of price.\n # Within a specific price, older experiences are ordered first\n #\n # GET /api/v1/experiences?sort=-price,created_at\n # ordering_params(params) # => \"price desc, created_at asc\"\n # Experience.order(\"price desc, created_at asc\")\n #\n ordering = []\n return join_params(ordering) unless params[:sort]\n\n ordering = params[:sort].split(',').each_with_object(ordering) do |attr, memo|\n sort_sign = (attr =~ /\\A[+-]/) ? attr.slice!(0) : \"+\"\n memo << \"#{attr} #{SIGN_OPDERS[sort_sign]}\"\n end\n join_params(ordering)\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"desc\"\n end", "def order\n \"#{sort} #{dir}\"\n end", "def sort_params params\n if @sortable\n pairs = sort_pairs(params)\n found_pair = false\n pairs.each_with_index{|pair,index|\n if pair[0] == self.name.to_s\n pairs[index][1] = pair[1] == \"asc\" ? \"desc\" : \"asc\"\n found_pair = true\n end\n }\n unless found_pair\n pairs << [self.name.to_s,\"asc\"]\n end\n (pairs.map{|pair| pair.join(\",\")}).join(\"|\")\n else\n \"\"\n end\n end", "def add_sort_order_to_title\n return unless params[:by]\n\n self.title_tag = :query_title_all_by\n title_args[:order] = :\"sort_by_#{params[:by].sub(/^reverse_/, \"\")}\"\n end", "def orders\n params.fetch(:sort).split(',').map do |string|\n next unless string =~ /\\A-?\\w+\\z/ # allow only word chars\n\n order(string)\n end.compact\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"desc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"desc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"desc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : 'asc'\n end", "def order(*args)\n with_opts(:order=>args.freeze)\n end", "def sort_direction\n params[:dir] == \"asc\" ? \"asc\" : \"desc\"\n end", "def sort_params; end", "def sort_params; end", "def orders\n \"intake, matrixno ASC\"\n # \"course_id, intake, matrixno ASC\"\n end", "def another_order_direction\n @mg_params.key?(:order_direction) ? (%w(asc desc) - [@mg_params[:order_direction].to_s]).first : MightyGrid.order_direction\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def normalize_order!(default = :asc)\n replace normalize_order(default)\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def arel_order\n text_columns = if params[:order]\n params[:order].split(' ')\n elsif self.default_sort\n [self.default_sort].flatten\n else\n [model_class.primary_key].flatten\n end\n sort_columns = text_columns.map do |column|\n if column.to_s.include?('.')\n name,direction = column.to_s.split('.',2)\n raise \"Illegal sort direction: #{direction} in #{column}\" unless %w{asc desc}.include?(direction)\n table[name].send(direction)\n else\n table[column]\n end\n end\n sort_columns\n end", "def ordering_by\n order && order.to_s.gsub(/^(ascend|descend)_by_/, '')\n end", "def sort_direction\n %w[asc, desc].include?(params[:direction]) ? params[:direction] : \"asc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"desc\"\n end", "def sort_direction\n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"desc\"\n end", "def set_OrderBy(value)\n set_input(\"OrderBy\", value)\n end", "def set_OrderBy(value)\n set_input(\"OrderBy\", value)\n end", "def set_OrderBy(value)\n set_input(\"OrderBy\", value)\n end", "def set_OrderBy(value)\n set_input(\"OrderBy\", value)\n end", "def set_OrderBy(value)\n set_input(\"OrderBy\", value)\n end", "def set_OrderBy(value)\n set_input(\"OrderBy\", value)\n end", "def set_OrderBy(value)\n set_input(\"OrderBy\", value)\n end", "def set_OrderBy(value)\n set_input(\"OrderBy\", value)\n end", "def sort_params\n return [] unless params['sort_by']\n\n orders = (params['sort_order'] ? params['sort_order'].split(\",\") : [\"\"])\n sort_order = params['sort_by'].split(\",\").zip(orders).collect do |attr, order|\n next if attr.blank?\n sort_item = attr\n sort_item << \" ASC\" if order && order.downcase.start_with?(\"asc\")\n sort_item << \" DESC\" if order && order.downcase.start_with?(\"desc\")\n sort_item\n end\n sort_order.compact\n end", "def sort_sql_helper(param)\n return param.gsub('_reverse',\" DESC\")\n end", "def set_order\n unless params[:order_by]\n @order = @model.typus_order_by\n else\n @order = \"#{params[:order_by]} #{params[:sort_order]}\"\n end\n end", "def toggle_order(order)\n (@current_order = order;@list = 1;@message = nil;return true) if order.match('ascending')\n (@current_order = order;@list = uids;@message = nil;return true) if order.match('descending')\n end", "def sort_order(default)\n if params[:c].blank? && default == \"created_at\"\n \"created_at DESC\"\n elsif params[:c].blank? && default == \"total\"\n \"total DESC\"\n else\n \"#{(params[:c] || default.to_s).gsub(/[\\s;'\\\"]/,'')} #{params[:d] == 'down' ? 'DESC' : 'ASC'}\"\n end\n end", "def order\n order = single_param(\"order\")\n if order.nil?\n return nil\n end\n if order.start_with?('-')\n field = order[1..-1]\n dir = \"desc\"\n else\n field = order\n dir = \"asc\"\n end\n unless ALLOWED_SORT_FIELDS.include?(field)\n @errors << %{\"#{field}\" is not a valid sort field}\n return nil\n end\n return [SORT_MAPPINGS.fetch(field, field), dir]\n end", "def get_sort_order (get_param, column_name)\r\n\t\tif params[get_param] && !params[get_param].empty?\r\n\t\t\tif params[get_param].downcase == \"asc\"\r\n\t\t\t\tif column_name.kind_of?(Array)\r\n\t\t\t\t\t\"#{column_name.join(' ASC, ')} ASC\"\r\n\t\t\t\telse\r\n\t\t\t\t\t\"#{column_name} ASC\"\r\n\t\t\t\tend\r\n\t\t\telse\r\n\t\t\t\tif column_name.kind_of?(Array)\r\n\t\t\t\t\t\"#{column_name.join(' DESC, ')} DESC\"\r\n\t\t\t\telse\r\n\t\t\t\t\t\"#{column_name} DESC\"\r\n\t\t\t\tend\r\n\t\t\tend\r\n\t\tend\r\n\tend", "def normalize_order(order)\n\t\t\t\torder = Array(order)\n\t\t\t\tif order.length == 2 && !order[0].is_a?(Array) && [:asc, :desc].include?(order[1])\n\t\t\t\t\torder = [order]\n\t\t\t\telse\n\t\t\t\t\torder = order.map {|pair| pair.is_a?(Array) ? pair : [pair, :asc] }\n\t\t\t\tend\n\t\t\t\torder.each do |pair|\n\t\t\t\t\tpair.length == 2 or raise ArgumentError, \"each order clause must be a pair (unknown clause #{pair.inspect})\"\n\t\t\t\t\t[:asc, :desc].include?(pair[1]) or raise ArgumentError, \"order must be specified with :asc or :desc (unknown key #{pair[1].inspect})\"\n\t\t\t\tend\n\t\t\t\torder\n\t\t\tend", "def inverse\n OrderBy.new(@field, @dir == :asc ? :desc : :asc)\n end", "def attrs_to_orderings(order)\n order.map do |o|\n Arel::Attribute === o ? o.asc : o\n end\n end", "def index_sort_order\n @query = {}\n @query['sort_key'] = params['sort_key'] unless params['sort_key'].blank?\n\n if @query['sort_key']&.starts_with?('-')\n \"#{@query['sort_key'].delete_prefix('-')} DESC\"\n elsif @query['sort_key'].present?\n \"#{@query['sort_key']} ASC\"\n else\n 'updated_at DESC'\n end\n end", "def orders\n \"assetcode ASC\"# \"staffgrade_id ASC\"\n end", "def order(field='id',order='desc')\n case order.downcase.to_s\n when 'asc'\n self.sort { |a,b| b.send(field.to_s) <=> a.send(field.to_s) }\n when 'desc' \n self.sort { |a,b| a.send(field.to_s) <=> b.send(field.to_s) }\n end\n end", "def order(order)\n params[:sort] = if order.is_a?(Hash) then\n order.reduce([]) do |memo, obj|\n key, value = obj\n\n if (value.to_s != \"asc\" && value.to_s != \"desc\") then\n raise ArgumentError, \"Order must be either :asc or :desc\"\n end\n\n key = \"-#{key}\" if value.to_s == \"desc\"\n memo.push(key)\n end.join(\",\")\n elsif order.is_a?(String) then\n order\n end\n\n self\n end", "def set_OrderBy(value)\n set_input(\"OrderBy\", value)\n end", "def set_OrderBy(value)\n set_input(\"OrderBy\", value)\n end", "def set_OrderBy(value)\n set_input(\"OrderBy\", value)\n end", "def set_OrderBy(value)\n set_input(\"OrderBy\", value)\n end", "def order=(_arg0); end", "def ordering_params(params)\n ordering = {}\n if params[:sort]\n sort_order = { '-' => :asc, '+' => :desc }\n\n sorted_params = params[:sort].split(',')\n sorted_params.each do |attr|\n sort_sign = attr.match?(/\\A[+-]/) ? attr.slice!(0) : '+'\n model = controller_name.classify.constantize\n if model.attribute_names.include?(attr)\n ordering[attr] = sort_order[sort_sign]\n end\n end\n end\n ordering\n end", "def sort_order\n 0\n end", "def calc_order\n @order_by = (['name', 'popularity'].include?(params[:order_by]) ? params[:order_by] : 'popularity')\n\n order = (params[:order_name] or '').upcase\n @order_name = (!order.blank? and ['ASC', 'DESC'].include?(order)) ? order : 'ASC'\n\n order = (params[:order_popularity] or '').upcase\n @order_popularity = (!order.blank? and ['ASC', 'DESC'].include?(order)) ? order : 'ASC'\n end", "def original_order\n end", "def sort_params=(_arg0); end", "def sort_params=(_arg0); end", "def sort_param_with_url(sortable_name, *args)\n params.delete(:sortasc)\n params.delete(:sortdesc)\n params.merge(sort_param_without_url(sortable_name, *args))\n end", "def ordering\n if params[:order]\n Hash[params[:order].values.map{ |ordering|\n [COLUMNS_TO_ORDER_FIELD[ordering[\"column\"].to_i], ordering[\"dir\"].to_sym]\n }]\n elsif params[:sort]\n params[:sort]\n else\n {_score: :desc}\n end\n end", "def sort\n params[:order].each do |key, value|\n Portfolio.find(value[:id]).update(position: value[:postion])\n end\n \n #render :nothing => true\n end", "def sort_direction\n %w[asc desc].include?(params[:sort]) ? params[:sort] : nil\n end", "def sort_direction\n %w[asc desc].include?(params[:sort]) ? params[:sort] : nil\n end", "def ordered_expression_sql(oe)\n \"#{literal(oe.expression)} #{oe.descending ? 'DESC' : 'ASC'}\"\n end", "def order(value)\n\t\t\tparam(\"order\", value)\n\t\tend", "def tie_breaking_sort\n { \"content_id\" => { order: \"asc\" } }\n end", "def normalize_order(order)\n order = Array(order)\n\n if order.length == 2 && !order[0].is_a?(Array) && [:asc, :desc].include?(order[1])\n order = [order]\n else\n order = order.map {|pair| pair.is_a?(Array) ? pair : [pair, :asc] }\n end\n\n order.each do |pair|\n pair.length == 2 or raise ArgumentError, \"each order clause must be a pair (unknown clause #{pair.inspect})\"\n [:asc, :desc].include?(pair[1]) or raise ArgumentError, \"order must be specified with :asc or :desc (unknown key #{pair[1].inspect})\"\n end\n\n order\n end", "def sort_dir\n params[:sort_dir] == 'desc' ? 'desc' : 'asc'\n end" ]
[ "0.77514964", "0.75367886", "0.75367886", "0.75367886", "0.75367886", "0.75367886", "0.75367886", "0.7369766", "0.7290562", "0.7246361", "0.71222764", "0.70779127", "0.70770496", "0.70284855", "0.70206004", "0.6953256", "0.68783253", "0.68757725", "0.6869807", "0.68636024", "0.6855435", "0.6855435", "0.6855435", "0.68414456", "0.68065655", "0.67998284", "0.6792183", "0.6785509", "0.6777992", "0.6777992", "0.6777992", "0.6777992", "0.6777992", "0.6777992", "0.6777992", "0.6760103", "0.6760103", "0.6760103", "0.6758895", "0.6750172", "0.6737402", "0.67268187", "0.67268187", "0.6712058", "0.6699129", "0.6690761", "0.66643786", "0.66503024", "0.66503024", "0.66503024", "0.66503024", "0.66503024", "0.6648619", "0.6645679", "0.662365", "0.6620031", "0.6620031", "0.6599959", "0.6599959", "0.6599959", "0.6599959", "0.6599959", "0.6599959", "0.6599959", "0.6599959", "0.6591899", "0.65697986", "0.65578824", "0.6549371", "0.65266156", "0.65225583", "0.6517189", "0.65158665", "0.6515517", "0.65097576", "0.65056354", "0.6491004", "0.64872694", "0.6486011", "0.64831764", "0.64831764", "0.64831764", "0.64831764", "0.64808506", "0.64756155", "0.64755183", "0.6464539", "0.64438206", "0.64423645", "0.64423645", "0.64243674", "0.6414802", "0.64034563", "0.64018357", "0.64018357", "0.6383319", "0.6383299", "0.63785464", "0.6373629", "0.63679326" ]
0.6593067
65
funciones de los CHARTS select salary, first_name from employees as emp inner join salaries as sala on emp.emp_no=sala.emp_no group by salary, first_name select count(title) as cantidades, titles.title as elementos from employees as emp inner join titles on emp.emp_no=titles.emp_no group by title SELECT departments.dept_name as elementos, count(employees.first_name) as cantidades FROM departments inner join dept_emp on departments.dept_no = dept_emp.dept_no inner join employees on employees.emp_no=dept_emp.emp_no GROUP BY departments.dept_name ORDER BY departments.dept_name
def testingCircle( params ) result = {} cantidad = params[:cantidades].split('.') elemento = params[:elementos].split('.') select = params[:elementos]+' as elementos, count('+params[:cantidades]+') as cantidades ' group_by = ' GROUP BY '+params[:elementos] ordenar_sql = ' ORDER BY '+params[:elementos] from = 'FROM '+make_form( elemento[0], cantidad[0], '' ) type_col_cantidades = @aplicacion[:tablas][cantidad[0]]['columnas'][cantidad[1]][:data_type] #if ('varchar'.eql?(type_col_cantidades) || 'char'.eql?(type_col_cantidades)) if ('int'.eql?(type_col_cantidades)) select = params[:elementos]+' as elementos, sum('+params[:cantidades]+') as cantidades ' end if (from != 'FROM ' && @conexion) #puts 'SELECT '+select+' '+from+' '+group_by+' '+ordenar_sql #result = @conexion.query('SELECT '+select+' '+from+' '+group_by+' '+ordenar_sql) #puts 'SELECT '+select+' '+from+' '+group_by+' '+ordenar_sql result = @conexion['SELECT '+select+' '+from+' '+group_by+' '+ordenar_sql] end return result end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def select_character_names_and_number_of_books_they_are_in\n \"SELECT characters.name, COUNT(books.title)\n FROM characters\n JOIN character_books\n ON characters.id = character_books.character_id\n JOIN books\n ON books.id = character_books.book_id\n GROUP BY characters.name\n ORDER BY COUNT(books.title) DESC;\"\nend", "def select_character_names_and_number_of_books_they_are_in\n \"\n SELECT characters.name, COUNT(character_books.book_id) AS cameos\n FROM characters\n JOIN character_books\n ON character_books.character_id = characters.id\n GROUP BY characters.id\n ORDER BY cameos DESC, characters.name\n \"\nend", "def show\n @page_title = \"CBCL - Detaljer om bruger \" + (@user && @user.login || \"\")\n @groups = @user.center_and_teams\n group_ids = @groups.map {|g| g.id }.join(',')\n\n query = \"select center_id, count(*) as count from journals where center_id IN (#{group_ids}) group by center_id\"\n # puts query\n @groups_count = ActiveRecord::Base.connection.execute(query).each(:as => :hash).inject({}) do |col,j| \n col[j['center_id']] = j['count']; col\n end\n end", "def select_character_names_and_number_of_books_they_are_in\n \"select characters.name, count(book_id)\n from character_books\n inner join characters \n \n on characters.id = character_books.character_id\n group by characters.name\n order by count(book_id) desc\"\nend", "def select_character_names_and_number_of_books_they_are_in\n \"SELECT characters.name, COUNT(*) \n FROM character_books INNER JOIN characters\n ON character_books.character_id = characters.id\n INNER JOIN books\n ON character_books.book_id = books.id\n GROUP BY characters.name\n ORDER BY COUNT(*) DESC;\" \nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n #\"SELECT DISTINCT SUM(pledges.amount) FROM pledges INNER JOIN projects WHERE pledges.project_id = projects.id ORDER BY title ASC;\"\n #\"SELECT projects.title, SUM(pledges.amount) FROM pledges GROUP BY aisle ORDER BY SUM(quantity);\"\n #\"SELECT projects.title, SUM(pledges.amount), count(projects.title) FROM pledges INNER JOIN projects ON pledges.project_id = projects.id GROUP BY projects.title ORDER BY projects.title ASC;\"\n \"SELECT projects.title, SUM(pledges.amount) FROM pledges INNER JOIN projects ON pledges.project_id = projects.id GROUP BY projects.title ORDER BY projects.title ASC;\"\nend", "def select_character_names_and_number_of_books_they_are_in\n \"SELECT characters.name, COUNT(character_books.book_id) as book_count FROM characters INNER JOIN character_books ON characters.id = character_books.character_id GROUP BY characters.name ORDER BY book_count DESC\"\nend", "def select_character_names_and_number_of_books_they_are_in\n \"SELECT characters.name, COUNT(cb.book_id)\n FROM character_books cb\n INNER JOIN characters ON cb.character_id == characters.id\n GROUP BY characters.name\n ORDER BY COUNT(cb.book_id) DESC\n \"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT PR.TITLE , SUM(PL.AMOUNT) FROM PROJECTS PR INNER JOIN PLEDGES PL ON PR.ID = PL.PROJECT_ID\nGROUP BY PR.TITLE;\n\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n #SELECT title, SUM(quantity) FROM groceries GROUP BY aisle ORDER BY SUM(quantity);\n\n \"SELECT projects.title, sum( pledges.amount)\nFROM projects\nJOIN pledges\nwhere projects.id=pledges.project_id\ngroup by projects.title order by projects.title\n;\"\n\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n \"SELECT projects.title,(SELECT SUM(pledges.amount))\n FROM projects\n INNER JOIN pledges ON projects.id = pledges.project_id\n GROUP BY projects.title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n #a project has many pledges. u have to sum the pledges up\n #there are many ways to get a solution right but u need to make sure it's right for many occasions. like colliding titles, names. note how i group by pledges.project_id. those are unique. earlier i grouped by project title. mostl ikely unique but u never know.\n \"SELECT projects.title, SUM(pledges.amount) FROM pledges INNER JOIN projects ON pledges.project_id = projects.id GROUP BY pledges.project_id ORDER BY title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT projects.title, SUM(pledges.amount) FROM projects JOIN pledges ON projects.id = pledges.project_id GROUP BY projects.title\";\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n\"SELECT projects.title, SUM(pledges.amount) FROM projects INNER JOIN pledges ON projects.id = pledges.project_id GROUP BY projects.title;\"\n\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"select projects.title, sum(pledges.amount) from projects inner join pledges where projects.id = pledges.project_id group by projects.title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT title , SUM(amount) FROM pledges, projects WHERE pledges.project_id = projects.id GROUP BY(title);\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n\"select title, sum(amount)\nfrom projects \ninner join pledges \non projects.id = pledges.project_id\ngroup by title\" \nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n \"SELECT projects.title as title, SUM(pledges.amount)\n FROM projects\n INNER JOIN pledges\n ON projects.id = pledges.project_id\n GROUP BY title\";\n\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT pr.title, sum(pl.amount) FROM projects pr join pledges pl ON pr.id = pl.project_id GROUP BY pr.title ORDER BY pr.title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT pr.title, SUM(pl.amount)\n FROM projects pr\n JOIN pledges pl\n ON pr.id = pl.project_id\n GROUP BY(pr.title);\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"select projects.title,sum(amount) from projects inner join pledges on projects.id = pledges.project_id group by projects.title\"\nend", "def select_series_title_with_most_human_characters\n \"SELECT series.title FROM characters INNER JOIN series ON series.id = characters.series_id GROUP BY(characters.species) ORDER BY(COUNT(characters.species)) LIMIT 1;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"select title,sum(amount) from projects inner join pledges on projects.id=pledges.project_id group by title order by title\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT projects.title, Sum(pledges.amount)\nfrom projects inner join pledges\nOn pledges.project_id = projects.id\ngroup by projects.title\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT Projects.title, SUM(pledges.amount) \nFROM projects \nJOIN pledges \nON Projects.id = pledges.project_id \nGROUP BY title\"; \nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n\"SELECT projects.title, SUM(pledges.amount) FROM pledges \nINNER JOIN projects \nON pledges.project_id = projects.id \nGROUP BY projects.title\"\n\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT title,sum(pledges.amount) FROM projects\n INNER JOIN pledges\n ON pledges.project_id = projects.id\n GROUP BY (title)\n ORDER BY (title);\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT projects.title, SUM(pledges.amount) FROM pledges INNER JOIN projects ON pledges.project_id = projects.id GROUP BY projects.title\"\nend", "def count_per_period_all\n \tcount = Center.all.inject({}) do |col,center|\n \t\tcol[center.id] = count_sum_per_period(center.id)\n \t\tcol\n \tend\n end", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n # SELECT titles, amounts FROM projects, pledges ORDER BY titles ASC\n #SELECT titles.projects, pledges.amounts ORDER BY titles ASC\n \"SELECT projects.title, SUM(pledges.amount) FROM projects\n JOIN pledges \n ON pledges.project_id = projects.id \n GROUP BY(pledges.project_id)\n ORDER BY projects.title ASC\n \";\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"\nSELECT \nProjects.title,\nSUM(Pledges.amount)\nFROM Pledges\nINNER JOIN Projects\nON Pledges.project_id = Projects.id\nGROUP BY Projects.title\nORDER BY Projects.title\n\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"select\nprojects.title,\nsum(pledges.amount) as sum_all_pledges\nfrom projects\ninner join pledges\non projects.id = pledges.project_id\ngroup by projects.title\norder by projects.title;\n\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title,SUM(pledges.amount) FROM projects INNER JOIN pledges ON projects.id=pledges.project_id GROUP BY projects.title\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT prj.title, sum(plg.amount) FROM pledges plg\n INNER JOIN projects prj ON plg.project_id = prj.id\n GROUP BY prj.title\n ORDER BY prj.title\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT projects.title, SUM(pledges.amount) FROM projects JOIN pledges ON projects.id=pledges.project_id GROUP BY projects.title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT projects.title, SUM(pledges.amount) FROM pledges INNER JOIN projects ON pledges.project_id=projects.id GROUP BY pledges.project_id ORDER BY projects.title\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT projects.title, SUM(pledges.amount) FROM projects JOIN pledges ON projects.id = pledges.project_id GROUP BY projects.title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n \"SELECT projects.title, SUM(pledges.amount) FROM projects INNER JOIN pledges ON projects.id = pledges.project_id GROUP BY projects.title\";\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title, SUM(pledges.amount )\nFROM projects \nJOIN pledges\nON projects.id = pledges.project_id \nGROUP BY projects.title \nORDER BY projects.title \";\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT projects.title, SUM (pledges.amount) FROM projects \n INNER JOIN pledges ON projects.id = pledges.project_id\n GROUP BY (projects.title)\";\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT projects.title, SUM(pledges.amount) FROM projects JOIN pledges ON projects.id = pledges.project_id GROUP BY projects.title\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"Select projects.title, SUM(amount) FROM pledges INNER JOIN projects ON pledges.project_id = projects.id GROUP BY projects.title\"\nend", "def select_value_and_count_of_most_prolific_species\n # \"SELECT species, COUNT(species) AS 'color_current' \n # FROM characters\n # GROUP BY species\n # ORDER BY 'color_current' DESC\n # LIMIT 1\"\n\n 'SELECT species, COUNT(species) AS \"color_current\" \n FROM characters \n GROUP BY species \n ORDER BY \"color_current\" DESC \n LIMIT 1'\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title,SUM(pledges.amount) FROM projects LEFT JOIN pledges ON projects.id=pledges.project_id GROUP BY projects.title Order By title\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT p.title, SUM(pl.amount) FROM pledges pl INNER JOIN projects p ON pl.project_id = p.id GROUP BY pl.project_id ORDER BY p.title\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT title, SUM(amount) FROM pledges INNER JOIN projects ON projects.id = pledges.project_id GROUP BY projects.title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT projects.title, sum_pledges FROM (SELECT pledges.project_id, SUM(pledges.amount) AS sum_pledges FROM pledges GROUP BY pledges.project_id) INNER JOIN projects ON projects.id = project_id ORDER BY projects.title\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT projects.title, SUM(pledges.amount)\n FROM projects\n INNER JOIN pledges ON projects.id = pledges.project_id\n GROUP BY projects.title\n ORDER BY projects.title ASC;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title, SUM(pledges.amount) \n FROM projects INNER JOIN pledges\n ON projects.id = pledges.project_id\n GROUP BY projects.title\n ORDER BY projects.title\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT p.title, SUM(pl.amount) FROM projects p JOIN pledges pl ON p.id = pl.project_id GROUP BY p.title ORDER BY p.title ASC\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT title, SUM(pledges.amount) \n FROM projects \n JOIN pledges\n ON projects.id = pledges.project_id\n GROUP BY title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT projects.title, SUM(amount)\n FROM pledges\n INNER JOIN projects\n ON pledges.project_id = projects.id\n GROUP BY title\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n'SELECT projects.title, SUM(pledges.amount) FROM projects LEFT JOIN pledges ON projects.id=pledges.project_id GROUP BY title'\n\nend", "def counts_number_of_bears_with_goofy_temperaments\n \"SELECT COUNT(temperament) FROM bears WHERE temperament = 'goofy' GROUP BY (temperament)\" \nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n \"SELECT projects.title, SUM(pledges.amount) FROM projects INNER JOIN pledges ON pledges.project_id=projects.id GROUP BY projects.title ORDER BY projects.title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n \"SELECT title, SUM(amount) FROM projects INNER JOIN pledges ON projects.id = pledges.project_id GROUP BY projects.title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT projects.title, SUM(pledges.amount)\n FROM projects\n INNER JOIN pledges\n ON projects.id = pledges.project_id\n GROUP BY projects.title\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title, SUM (pledges.amount)\nFROM projects\nINNER JOIN pledges\nON projects.id = pledges.project_id\nGROUP BY title\nORDER BY title ASC;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n \"SELECT projects.title, SUM(pledges.amount) FROM projects JOIN pledges ON projects.id = pledges.project_id GROUP BY projects.title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title, SUM(pledges.amount)\nFROM projects\nINNER JOIN pledges\nON projects.id = pledges.project_id GROUP BY projects.title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"select projects.title, SUM(pledges.amount) from projects LEFT JOIN pledges ON projects.id = pledges.project_id group by title order by title\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT p.title, SUM(pl.amount) FROM projects AS p\nJOIN pledges AS pl ON p.id = pl.project_id\nGROUP BY p.title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title, SUM(pledges.amount) FROM projects INNER JOIN pledges ON projects.id = pledges.project_id GROUP BY projects.title ORDER BY projects.title ASC;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT title, SUM(amount)\n FROM projects\n INNER JOIN pledges\n ON projects.id = pledges.project_id\n GROUP BY title\n ORDER BY title ASC;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title, SUM(pledges.amount)\nFROM projects\nINNER JOIN pledges \nON projects.id=pledges.project_id\nGROUP BY projects.id\nORDER BY projects.title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT projects.title, SUM(pledges.amount)\n FROM projects\n INNER JOIN pledges\n ON projects.id = pledges.project_id\n GROUP BY projects.title\n ORDER BY SUM (projects.title) ASC;\"\nend", "def exercise1\n @content = ActiveRecord::Base.connection.execute(\"\n SELECT\n u.name as user_name,\n COUNT(gr.name) as groups_count,\n CONCAT('[', COALESCE(STRING_AGG(gr.name, ', ' ), ''),']') as groups\n FROM ((users as u\n LEFT JOIN groups_users as gu ON u.id=gu.user_id)\n LEFT JOIN groups as gr ON gr.id = gu.group_id)\n GROUP BY user_name\n ORDER BY groups_count;\");\n\n @results1 = []\n\n index = 0\n @content.each do |r|\n @results1[index] = Result1.new r\n index = index + 1;\n end\n\n return @results1\n end", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n<<-SQL\n SELECT DISTINCT title ,SUM(amount) FROM projects INNER JOIN pledges ON projects.id = pledges.project_id\n GROUP BY projects.title\n SQL\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title, \nSUM(pledges.amount) \nFROM projects\nJOIN pledges ON pledges.project_id = projects.id\nGROUP BY projects.title\nORDER BY projects.title ASC;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title, SUM(pledges.amount)\nFROM projects\nJOIN pledges\nON projects.id = pledges.project_id\nGROUP BY projects.title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title, SUM(pledges.amount) FROM projects INNER JOIN pledges ON pledges.project_id = projects.id GROUP BY projects.title ORDER BY projects.title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n # select the titles from projects and sum all the pledges\n # from pledges\n # join with the project table \n # group by pledges.project id\n # order by project.title ASC\n \n \"SELECT projects.title, SUM(pledges.amount)\n FROM pledges\n JOIN projects on projects.id = pledges.project_id\n GROUP BY pledges.project_id\n ORDER BY projects.title ASC;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title, sum(pledges.amount) FROM projects INNER JOIN pledges on pledges.project_id=projects.id group by pledges.project_id ORDER BY projects.title ASC\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT title, SUM(pledges.amount) FROM projects\nJOIN pledges\nON projects.id = pledges.project_id\nGROUP BY (projects.title)\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n \"SELECT projects.title, SUM(pledges.amount)\n FROM projects\n INNER JOIN pledges\n ON projects.id = pledges.project_id\n GROUP BY projects.title\n ORDER BY projects.title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n \"SELECT projects.title, SUM (pledges.amount)\n FROM projects INNER JOIN pledges\n ON projects.id = pledges.project_id\n GROUP BY projects.title\n ORDER BY projects.title\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title,sum(pledges.amount) FROM projects JOIN pledges WHERE projects.id=pledges.project_id GROUP BY projects.title ORDER BY projects.title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n \"SELECT projects.title, SUM(pledges.amount) FROM projects\n INNER JOIN pledges ON projects.id = pledges.project_id\n GROUP BY projects.title\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"Write your SQL query Here\"\n\"SELECT projects.title, SUM(pledges.amount) FROM projects INNER JOIN pledges ON projects.id = pledges.project_id GROUP BY(projects.title) ;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT title, SUM(amount)\n FROM projects\n INNER JOIN pledges\n ON projects.id = pledges.project_id\n GROUP BY title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT title, SUM(pledges.amount) FROM projects JOIN pledges ON projects.id = pledges.project_id GROUP BY projects.title ORDER BY projects.title ASC\"\nend", "def cargar_resultados\n preguntas.each do |pregunta|\n pregunta.respuestas.each do |respuesta|\n # resultados = ResultadoPregunta.where(recorrido: recorrido.id, pregunta: pregunta, respuesta: respuesta).count\n sql = \"select count(1)\n from resultado_preguntas r_preg join resultado_recorridos r_rec on r_preg.resultado_recorrido_id = r_rec.id join\n recorridos recorrido on r_rec.recorrido_id = recorrido.id\n where recorrido.id = #{recorrido.id} and r_preg.pregunta_id = #{pregunta.id} and r_preg.respuesta_id = #{respuesta.id}\"\n respuesta.cantidad_elegida = ActiveRecord::Base.connection.execute(sql)[0][\"count\"].to_i\n # respuesta.cantidad_elegida = resultados\n end\n end\n end", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title,SUM(pledges.amount) FROM projects LEFT JOIN pledges ON projects.id = pledges.project_id GROUP BY projects.title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title, SUM(pledges.amount) \n FROM projects JOIN pledges ON pledges.project_id = projects.id\n GROUP BY title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT title, SUM(pledges.amount) FROM projects \n INNER JOIN pledges\n ON projects.id = pledges.project_id GROUP BY title ORDER BY title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title, SUM(pledges.amount)\n FROM pledges\n INNER JOIN projects\n ON pledges.project_id = projects.id\n GROUP BY projects.title\n ORDER BY projects.title\n\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n # group pledge sum by title\n # return titles\n # order by\n \"SELECT projects.title, \n SUM(pledges.amount) \n FROM projects \n JOIN pledges ON projects.id=pledges.project_id \n GROUP BY projects.title \n ORDER BY projects.title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title, SUM(pledges.amount)\nFROM pledges\nINNER JOIN projects \nON pledges.project_id = projects.id\nGROUP BY project_id\nORDER BY projects.title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT title, SUM(amount)\nFROM projects\nINNER JOIN pledges\nON projects.id = pledges.project_id\nGROUP BY projects.title\nORDER BY projects.title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n \"SELECT title, (select sum(amount) from pledges where project_id = projects.id) FROM projects Order by projects.title\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT projects.title AS project_title, SUM(pledges.amount) AS sum_of_pledges\n FROM projects JOIN pledges\n ON projects.id = pledges.project_id\n GROUP BY projects.title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT projects.title, SUM(pledges.amount) FROM projects\nJOIN pledges ON projects.id = pledges.project_id\nGROUP BY title\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT title, SUM(amount) FROM projects \n JOIN pledges ON projects.id = pledges.project_id\n GROUP BY title ORDER BY title ASC;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT title, SUM(amount) FROM projects\n INNER JOIN pledges ON pledges.project_id = projects.id\n GROUP BY title ORDER BY title ASC;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n #project.title. SUM pledge.amount ORDER BY project.title ASC\n \"SELECT projects.title, SUM(pledges.amount)\n FROM projects\n INNER JOIN pledges ON pledges.project_id = projects.id\n GROUP BY projects.title\n ORDER BY projects.title\"\nend", "def chart_data(codes, hospitals, num_cases)\n data = []\n identifiers = [I18n.t('hospitals')] + codes.map{|code| code.code_display_long }\n hospitals.each do |h|\n ncs = num_cases[h.hospital_id]\n a = [h.name]\n codes.each {|code| a << numcase_number(ncs[code.code]); a << numcase_display(ncs[code.code]) }\n data << a\n end\n [identifiers, data]\n end", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n 'select p.title, sum(pl.amount) from projects p\n LEFT JOIN pledges pl\n where p.id = pl.project_id\n group by p.title\n order by p.title;'\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title\n \"SELECT projects.title, sum(pledges.amount)\n FROM projects\n JOIN pledges ON projects.id=pledges.project_id\n GROUP BY projects.title\n ORDER BY sum(projects.title) ASC\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT title, SUM(amount) FROM projects\nJOIN pledges\non projects.id = pledges.project_id\nGROUP BY projects.title;\"\nend", "def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name\n\"SELECT title, SUM(amount) FROM pledges INNER JOIN projects ON projects.id = pledges.project_id GROUP BY projects.id ORDER BY title;\"\nend" ]
[ "0.59568244", "0.5948838", "0.5763102", "0.5753427", "0.5696337", "0.56681186", "0.56150657", "0.5605416", "0.5572776", "0.55337006", "0.54528964", "0.5427158", "0.5397447", "0.5387074", "0.53855616", "0.53821063", "0.5377702", "0.5370028", "0.5366083", "0.5349785", "0.5345083", "0.5342785", "0.5342347", "0.533922", "0.53382176", "0.53338534", "0.53291506", "0.5326968", "0.5325567", "0.53218603", "0.53158253", "0.53086776", "0.530686", "0.5298037", "0.52975446", "0.5291441", "0.5282904", "0.52815026", "0.52762526", "0.52728164", "0.52710646", "0.52647024", "0.52622014", "0.5251357", "0.52462107", "0.5244494", "0.5239781", "0.5238229", "0.5236566", "0.52305585", "0.5226391", "0.5225585", "0.5225061", "0.5223023", "0.52226305", "0.52188724", "0.5218666", "0.5211979", "0.5208229", "0.5206627", "0.520513", "0.52050066", "0.5202128", "0.5200396", "0.5200141", "0.51993006", "0.5197276", "0.5196434", "0.519641", "0.5194987", "0.5191207", "0.5191071", "0.5187386", "0.5186781", "0.51826787", "0.5180629", "0.5177958", "0.5177772", "0.517624", "0.5174425", "0.51726353", "0.517083", "0.5170757", "0.51699746", "0.51652616", "0.5165076", "0.5156826", "0.51545656", "0.51520526", "0.515086", "0.5147642", "0.5146882", "0.5146095", "0.5143897", "0.51414764", "0.51397395", "0.513701", "0.5136061", "0.5134936", "0.5134586" ]
0.55489564
9
We don't compare the sizes, because RSpec will add some classes that we don't care about...
def check_descendent_array clazz, expected actual = TypeUtils.descendents(clazz) expected.each {|c| actual.should include(c)} end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def size\n specs.size\n end", "def test_size\n assert_equal(1, @root.size, \"Root's size should be 1\")\n setup_test_tree\n\n assert_equal(5, @root.size, \"Root's size should be 5\")\n assert_equal(2, @child3.size, \"Child 3's size should be 2\")\n end", "def test_file_size_differs\n TestHelper::FillContents($source_dir, {\n 'A.txt' => {\n type: 'file',\n contents: 'SuperLongFileThatHasLotsOfStuff',\n }\n })\n TestHelper::FillContents($backup_dir, {\n 'A.txt' => {\n type: 'file',\n contents: 'ShortFile',\n }\n })\n expected_results = {\n items_processed: 2,\n similarities: 1,\n differences: 1,\n skipped: 0,\n errors: 0,\n }\n actual_results = TestHelper::RunVerification(\n [$source_dir, $backup_dir]\n )\n assertResultsAsExpected(expected_results, actual_results)\n end", "def test_sizes\n output = tested('sizes rms.jpg')\n\n assert errors_ok? output\n\n assert_equal '(max-width: 600px) 80vw, 50%', output.at_css('img')['sizes']\n end", "def test_method_size\n width, height = (1..100).to_a.sample( 2 )\n base_image = Magick::Image.new( width, height )\n image_adapter = Image::AdapterMagickImage.new( base_image )\n \n # maps width/height to size( :x ) / size ( :y )\n assert_equal width, image_adapter.size( :x )\n assert_equal height, image_adapter.size( :y )\n end", "def test_length_is_size\n setup_test_tree\n assert_equal(@root.size, @root.length, \"Length and size methods should return the same result\")\n end", "def test_deck_size_fullDeck\n deck = Deck.new\n assert_equal(81, deck.size, \"Expected size of 81.\")\n end", "def assert_size(expected_count, actual_collection)\n assert_equal expected_count, actual_collection.size, \"collection expected size was '#{expected_count}' but actually was '#{actual_collection.size}'\"\n end", "def should_validate_attachment_size name, options = {}\n klass = self.name.gsub(/Test$/, '').constantize\n min = options[:greater_than] || (options[:in] && options[:in].first) || 0\n max = options[:less_than] || (options[:in] && options[:in].last) || (1.0/0)\n range = (min..max)\n context \"Class #{klass.name} validating file size on #{name}\" do\n context \"with an attachment that is #{max+1} bytes\" do\n setup do\n @file = StringIO.new(\".\" * (max+1))\n @attachment = klass.new.send(name)\n @attachment.assign(@file)\n end\n\n should \"have a :size validation error\" do\n assert @attachment.errors[:size]\n end\n end\n context \"with an attachment that us #{max-1} bytes\" do\n setup do\n @file = StringIO.new(\".\" * (max-1))\n @attachment = klass.new.send(name)\n @attachment.assign(@file)\n end\n\n should \"not have a :size validation error\" do\n assert ! @attachment.errors[:size]\n end\n end\n\n if min > 0\n context \"with an attachment that is #{min-1} bytes\" do\n setup do\n @file = StringIO.new(\".\" * (min-1))\n @attachment = klass.new.send(name)\n @attachment.assign(@file)\n end\n\n should \"have a :size validation error\" do\n assert @attachment.errors[:size]\n end\n end\n context \"with an attachment that us #{min+1} bytes\" do\n setup do\n @file = StringIO.new(\".\" * (min+1))\n @attachment = klass.new.send(name)\n @attachment.assign(@file)\n end\n\n should \"not have a :size validation error\" do\n assert ! @attachment.errors[:size]\n end\n end\n end\n end\n end", "def test_deck_display_size_fullDeck\n print \"Expected size of 81: Found \"\n Deck.new.display_size\n end", "def test_total_codings\n assert_equal 25, @mk.codings.size\n # assert_equal 25, @mk.codings_old.size\n # assert_equal @mk.codings.size, @mk.codings_old.size\n end", "def size\n raise Exception.new(\"This should be subclassed.\")\n end", "def test_size\r\n assert_respond_to(File, :size)\r\n assert_equal(17, File.size(@file))\r\n end", "def test_size\n @results.map {|node_name, classes|\n classes.size\n }.reduce(:+) || 0\n end", "def size\n tests.size\n end", "def test_png_size_determined_correctly\n assert_equal [120, 175], @page.get_png_size(@test_png)\n end", "def test_world_size\n world = World.new\n assert_equal(5, world.width)\n assert_equal(5, world.height)\n end", "def size(*) end", "def size(*) end", "def expected_size\n fixity_graph.query({ predicate: ::RDF::Vocab::PREMIS.hasSize }).first.try(:object).try(:to_s).try(:to_i)\n end", "def validate_entry_sizes; end", "def test_data_img_yes_size\n output = tested('data_img_yes_size rms.jpg')\n\n assert errors_ok? output\n\n assert_equal '(max-width: 600px) 80vw, 50%',\n output.at_css('img')['data-sizes']\n end", "def test_srcset_and_sizes\n stub_sizes_srcset\n\n correct = <<~HEREDOC\n <img src=\"good_url\" srcset=\"width srcset\" sizes=\"correct sizes\">\n HEREDOC\n\n assert_equal correct, @tested.to_s\n end", "def test_data_img_no_size\n output = tested('data_img_no_size rms.jpg')\n\n assert errors_ok? output\n\n assert_equal '(max-width: 600px) 80vw, 50%',\n output.at_css('img')['sizes']\n end", "def check_size(&block)\n self.instance_eval(&block)\n end", "def test_that_grids_do_not_work_for_small_imgs\n end", "def test_size\n assert_equal(3, @list.size)\n end", "def test_empty_tile_rack_should_need_max_tiles\n assert_equal(7,@newTileRack.number_of_tiles_needed)\n end", "def size; end", "def size; end", "def size; end", "def size; end", "def size; end", "def size; end", "def size; end", "def size; end", "def size; end", "def size; end", "def size; end", "def size; end", "def size; end", "def size; end", "def size; end", "def size; end", "def size; end", "def size; end", "def size; end", "def size; end", "def size; end", "def all_sizes\n [0.1, 0.5, 1, 5, 10]\n end", "def test_0020_size\n @@log.debug \"test_0020_size starts\" if @@log.debug?\n assert_equal(4, @list.size)\n @list << Person.new(\"Robert\", \"NMN\", \"Zimmerman\", 5)\n assert_equal(5, @list.size)\n @@log.debug \"test_0020_size ends\" if @@log.debug?\n end", "def human_size(*args); end", "def test_check_driver_array_size\r\n\t\tall_drivers = [d1 = Driver.new(1), d2 = Driver.new(2)]\r\n\t\tassert_equal all_drivers.length, 2\r\n\tend", "def size()\n #This is a stub, used for indexing\n end", "def test_tile_rack_with_several_tiles_should_need_some_tiles\n [:A,:B,:C].each{|x| @newTileRack.append(x)}\n assert_equal(4,@newTileRack.number_of_tiles_needed)\n end", "def size\nend", "def interpret_size(size); end", "def more_bytes_than?(other)\n possible_byte_sizes.min > other.possible_byte_sizes.max\n end", "def size\n super\n end", "def size\n super\n end", "def size\n end", "def size\n end", "def size\n end", "def size\n end", "def size\n end", "def size\n end", "def size\n end", "def sizes\n images.collect(&:classifier).sort\n end", "def size\n\n end", "def assert_openshift_objects_count(cnt)\n expect(kube_client.config_maps.size).to eq(cnt)\n expect(kube_client.deployment_configs.size).to eq(cnt)\n expect(kube_client.secrets.size).to eq(cnt)\n expect(kube_client.services.size).to eq(cnt)\n end", "def size\n @sizes ||= strip(:size)\n end", "def test_card_length_equals_card_count \n assert_equal(@deck.cards.length, @deck.count)\n end", "def size\n end", "def size\n end", "def size\n end", "def validate_entry_sizes=(_arg0); end", "def size\n\n\n end", "def my_size\n 1\n end", "def test_thumb_size_too_big\n assert @photo.valid?\n @photo.thumb_l = 169\n assert [email protected]?\n end", "def test_size\n assert_equal 0, Cfg.test.count\n assert_equal Cfg.test.size, Cfg.test.count\n Cfg.test.save(\"x\" => 1)\n Cfg.test.save(\"x\" => 2)\n assert_equal Cfg.test.size, Cfg.test.count\n end", "def test_Range_InstanceMethods_size\n\t\t# New in 2.0!\n\t\t# assert_equal(26, (1..26).size)\n\tend", "def size?() end", "def size(verbose: false)\n size_from_java(verbose: verbose) ||\n size_from_win_api(verbose: verbose) ||\n size_from_ioctl ||\n size_from_io_console(verbose: verbose) ||\n size_from_readline(verbose: verbose) ||\n size_from_tput ||\n size_from_stty ||\n size_from_env ||\n size_from_ansicon ||\n size_from_default\n end", "def size() end", "def size() end", "def size() end", "def size() end", "def size() end", "def size() end", "def size()\n #This is a stub, used for indexing\n end", "def size()\n #This is a stub, used for indexing\n end", "def size\n raise NotImplementedError\n end", "def test_06a\r\n db = build\r\n assert_equal 6,db.images.size\r\n end", "def size; @size end", "def size_check\n @size_check = [0,0,0]\n self.rewards.each do |reward|\n @size_check[reward.size] = 1\n end\n return @size_check\n end", "def size\n @size \n end", "def size\n @size \n end", "def be_compatible\n @size = if @results.class == Array\n @results.size\n else\n @results.values.size\n end\n end", "def size=(_); end", "def size=(_); end", "def test_deck_display_size_emptyDeck\n deck = Deck.new\n 81.times {deck.draw}\n print \"Expected size of 0: Found \"\n deck.display_size\n end" ]
[ "0.6665844", "0.6473106", "0.6378862", "0.63026774", "0.62916136", "0.6287386", "0.6208231", "0.6196033", "0.61894614", "0.61816835", "0.6136922", "0.61112225", "0.6109822", "0.60631025", "0.6062682", "0.6062652", "0.60292006", "0.59741724", "0.59741724", "0.5971382", "0.5966057", "0.59556794", "0.593043", "0.59071195", "0.59042126", "0.58943075", "0.5885074", "0.58749545", "0.5866432", "0.5866432", "0.5866432", "0.5866432", "0.5866432", "0.5866432", "0.5866432", "0.5866432", "0.5866432", "0.5866432", "0.5866432", "0.5866432", "0.5866432", "0.5866432", "0.5866432", "0.5866432", "0.5866432", "0.5866432", "0.5866432", "0.5866432", "0.5866432", "0.58459735", "0.5837698", "0.5833652", "0.581295", "0.5807205", "0.5800392", "0.57997346", "0.5795822", "0.57903665", "0.5780216", "0.5780216", "0.57681215", "0.57681215", "0.57681215", "0.57681215", "0.57681215", "0.57681215", "0.57681215", "0.5766164", "0.5762516", "0.57578397", "0.5728872", "0.57232267", "0.57078487", "0.57078487", "0.57078487", "0.5703365", "0.56898165", "0.56824654", "0.5674953", "0.56699204", "0.5666758", "0.56567484", "0.5656115", "0.5652772", "0.5652772", "0.5652772", "0.5652772", "0.5652772", "0.5652772", "0.5648371", "0.5648371", "0.56301063", "0.56232417", "0.56198186", "0.5617349", "0.5616568", "0.5616568", "0.5612878", "0.5606009", "0.5606009", "0.56010497" ]
0.0
-1
Make record an orphan by deleting its parent member. Since we use delete rather than destroy, member's child records should not be deleted.
def make_orphan(record) m = Member.find_by_id(record.member_id) m.delete if m record.reload end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def orphan\n parent.disown self if parent\n @parent = nil\n end", "def orphan\n self[foreign_key_column] = 0\n self.save\n end", "def orphan_self_and_children\n self.class.transaction do\n orphan_children\n orphan\n end\n end", "def orphan_self_and_parent_adopts_children\n self.class.transaction do\n parent_adopts_children\n orphan\n end\n end", "def after_create_save(record)\n record.move_to_child_of record.parent.id unless record.parent.nil?\n end", "def remove_child(node)\n if node.parent == nil\n raise \"this is an orphan\"\n end \n node.parent = nil\n end", "def orphan_child_categories\n self.children.each do |child|\n child.parent_id = nil\n child.save\n end\n end", "def delete!\n if parent\n parent.remove_child(id)\n @parent = nil\n end\n collection.remove(_id: id)\n self.id = nil\n true\n end", "def delete_with_no_child(parent, direction)\n parent.send \"#{direction}=\".to_sym, nil\n end", "def destroy_record_of_self()\n \tdb_parent.remove_from_db(self)\n \treturn self\n end", "def delete(resource)\n orphan_resource(super)\n end", "def orphan_children\n self.class.transaction do\n children(true).each{|child| child.orphan}\n end\n end", "def removing_plan_relation(transaction, parent, child, relations); end", "def orphan_member(trigger_id)\n http_post \"triggers/groups/members/#{trigger_id}/orphan\", {}\n get_single_trigger trigger_id, false\n end", "def perform_some_actions\n # It is to be called while destroying a Child record\n # But must not be called while destroying the parent record\n unless self.parent.destroyed?\n\n end\n end", "def destroy\n r = self.class.delete(\"/domains/#{@@parent_id}/records/#{self.id}\")\n if r.code == 200\n self\n else\n raise StandardError, 'Could not delete the record'\n end \n end", "def destroy\n #primitives in structs are without parent\n parent and parent.children.delete self\n end", "def orphan_resource(resource)\n return if resource.nil?\n\n if resource.collection.equal?(self)\n resource.collection = nil\n end\n\n unless resource.new_record?\n @cache.delete(resource.key)\n @orphans << resource\n end\n\n resource\n end", "def test_override_apply_orphan_strategy\n AncestryTestDatabase.with_model orphan_strategy: :destroy do |model, roots|\n root = model.create!\n child = model.create!(:parent => root)\n model.class_eval do\n def apply_orphan_strategy\n # disabling destoy callback\n end\n end\n assert_difference 'model.count', -1 do\n root.destroy\n end\n # this should not throw an ActiveRecord::RecordNotFound exception\n assert child.reload.root_id == root.id\n end\n end", "def before_destroy\n return false unless super\n\n parent = self.parent\n parent.comment_count -= 1\n parent.skip_timestamp_update = true\n parent.save\n\n true\n end", "def delete_if\n super { |r| yield(r) && orphan_resource(r) }\n end", "def soft_deleting_work\n # be sure to clear plan_member_id\n self.plan_member.destroy if self.plan_member\n self.update_attribute(:deleted_at, Time.now)\n end", "def detach parent\n\n # the ordinary *able table\n parent.send( self.class.to_s.underscore.pluralize).delete self\n\n # case child.class.to_s\n # when \"Event\",\"WageEvent\"\n # ev = Eventable.where( event: child, eventable: self)\n # ev.delete_all\n # when \"Printer\"\n # pr = Printable.where( printer: child, printable: self)\n # pr.delete_all\n # else\n # children = eval child.class.to_s.downcase.pluralize\n # children.delete child\n # end\n rescue\n false\n end", "def delete_nested_document!(parent, child_assoc, child_model, child_id)\n if child_model.embeddable?\n children = parent.send(child_assoc)\n child = find_child!(children, child_id)\n children.delete(child)\n unless parent.save\n error 400, convert(body_for(:internal_server_error))\n end\n child\n else\n delete_document!(child_model, child_id)\n end\n end", "def detach_from_parent\n return nil if parent.nil? # root\n oci = own_child_index\n parent.children.delete_at(oci) if oci\n self.parent = nil\n oci\n end", "def update_collection_parent\n old_parent = @collection.parent\n old_parent.delete_member_by_id(@collection.id)\n old_parent.save\n\n new_parent = find_new_parent\n new_parent.member_ids = [@collection.id] + new_parent.member_ids\n new_parent.save\n end", "def destroy\n @relationship = @assembly.relationships.find(params[:id])\n child = @relationship.child\n child.used = false\n child.save\n @relationship.destroy\n\n respond_to do |format|\n format.html { redirect_to [@plan, @assembly], notice: 'Relationship was deleted.' }\n format.json { head :no_content }\n end\n end", "def remove_inverse_instance(record)\n if inverse = inverse_association_for(record)\n inverse.inversed_from(nil)\n end\n end", "def remove_parent\n # has to go from parent to child\n self.parent.remove_child(self)\n end", "def remove_from_parent\n @change_set = ChangeSet.for(resource)\n parent_resource = find_resource(parent_resource_params[:id])\n authorize! :update, parent_resource\n\n parent_change_set = ChangeSet.for(parent_resource)\n current_member_ids = parent_resource.member_ids\n parent_change_set.member_ids = current_member_ids - [resource.id]\n\n obj = nil\n change_set_persister.buffer_into_index do |persist|\n obj = persist.save(change_set: parent_change_set)\n end\n after_update_success(obj, @change_set)\n rescue Valkyrie::Persistence::ObjectNotFoundError => e\n after_update_error e\n end", "def delete\n del unless new_record?\n set_deleted_properties\n end", "def prune!\n return if root? #you cannot prune the root\n if normal?\n parent.normal_children.delete(self)\n else\n parent.fallback_child = nil\n end\n old_parent = parent\n @parent = nil\n old_parent.prune! if old_parent.useless?\n end", "def remove_parent(parent)\n ActsAsDAG::HelperMethods.unlink(parent, self)\n return parent\n end", "def disassociate\n _parent = parent_document\n _type = self.type.sub('associated:', '')\n _parent.doc_refs.delete(_type)\n self.parent_id = 0\n self.parent_ref = nil\n self.root_document_id = 0\n self.root_ref = nil\n DocumentRepository.update(_parent)\n DocumentRepository.update(self)\n end", "def delete_at(offset)\n orphan_resource(super)\n end", "def delete(object_or_id)\n\t\t\t\t\tobject = case object_or_id\n\t\t\t\t\twhen String, Moped::BSON::ObjectId\n\t\t\t\t\t\[email protected] object_or_id\n\t\t\t\t\telse\n\t\t\t\t\t\tobject_or_id\n\t\t\t\t\tend\n\n\t\t\t\t\tobject.write_attribute object.parent_id_field, nil\n\t\t\t\t\tobject[object.path_field] = []\n\t\t\t\t\tobject[object.depth_field] = 0\n\t\t\t\t\tobject.save\n\n\t\t\t\t\tsuper(object)\n\t\t\t\tend", "def safe_destroy\n if self.is_root? && self.original_post?\n Comment.transaction do\n self.descendants.each{|c| c.destroy }\n end\n self.destroy\n else\n self.update_attribute('deleted', true)\n end\n end", "def orphan?\n false\n end", "def destroy\n super do\n graph.delete [source.to_term, nil, nil]\n parent.delete [parent, nil, source.to_term]\n end\n end", "def destroy_zombies(parent_model, parent_association_name)\n if zombies_possible?(parent_association_name)\n destroy_zombie_child_of(parent_model)\n end\n end", "def clear\n @parent = nil\n end", "def removeFromParent\n @parent.remove(self) if @parent\n end", "def dont_destroy\n errors.add(:family,\"can't destroy any record\")\n throw(:abort)\n \n end", "def delete_relationship_of_parent_with_child(parent_ou_id, child_ou_id)\n path = \"/d2l/api/lp/#{$lp_ver}/orgstructure/#{child_ou_id}/parents/#{parent_ou_id}\"\n _delete(path)\nend", "def test_check_before_destroy(parent, child)\n # Ensure that can destroy parent without child\n @parent = Factory(parent)\n lambda do\n @parent.destroy\n end.should change(parent.to_s.camelcase.constantize, :count).by(-1)\n \n @parent = Factory(parent)\n # Stub so that it appears @parent does have child records.\n @parent.stub(child.to_s.pluralize).and_return([1])\n @parent.stub(child).and_return([1])\n lambda do\n @parent.destroy\n end.should_not change(parent.to_s.camelcase.constantize, :count)\n end", "def remove_parent_object(parent, relation = nil)\n\t parent.remove_child_object(self, relation)\n\tend", "def destroy\n @parent = nil\n @root = nil\n end", "def delete_with_one_child(parent, target, direction)\n # if child's left exists, assign it to parent's left/right, else assign child's right\n parent.send \"#{direction}=\".to_sym, (target.left || target.right)\n end", "def destroy!\n destroy || _raise_record_not_destroyed\n end", "def new_child\n nil\n end", "def node_leave_parent(node, parent)\n node.parents.delete(parent)\n end", "def delete_relationship_of_child_with_parent(parent_ou_id, child_ou_id)\n path = \"/d2l/api/lp/#{$lp_ver}/orgstructure/#{parent_ou_id}/children/#{child_ou_id}\"\n _delete(path)\nend", "def remove_parent_if_empty_string\n self[:parent_id] = nil if self[:parent_id] == \"\"\n end", "def destroy\n\t\t@parent_child.destroy\n\t\trespond_to do |format|\n\t \t\tformat.html { redirect_to parent_children_url, notice: 'Parent child was successfully destroyed.' }\n\t \t\tformat.json { head :no_content }\n\t\tend\n \tend", "def remove_from_parents\n ordered_by.each do |parent|\n parent.ordered_members.delete(self) # Delete the list node\n parent.members.delete(self) # Delete the indirect container Proxy\n parent.save! # record the changes to the ordered members\n end\n end", "def set_allowed_parent!(p)\n unless p.nil? || p.is_a?(Warehouse)\n if p.to_s.blank?\n p = nil\n else\n p = Warehouse.find_by_id(p)\n return false unless p\n end\n end\n if p.nil?\n if !new_record? && allowed_parents.empty?\n return false\n end\n elsif !allowed_parents.include?(p)\n return false\n end\n set_parent!(p)\n end", "def assign_to_parent(element)\n element.remove!\n element.parent = parent\n end", "def destroy\n @parent_of.destroy\n respond_to do |format|\n format.html { redirect_to parent_ofs_url }\n format.json { head :no_content }\n end\n end", "def parent=(new_parent) \n parent.children.delete(self) if @parent #=> this is the old parent removing the child that is being adopted \n @parent = new_parent #=> I have a new mommy! \n new_parent.children << self unless @parent == nil || new_parent.children.include?(self) \n end", "def remove_member(member)\n return unless self.organizations.include?(member)\n\n if member.association_can_delete? then\n member.destroy\n else\n member.associations.delete(self)\n end\n end", "def remove_act\n # select rep_parent if it exists\n node = self\n if !self.rep_parent.nil?\n node = self.rep_parent\n end\n\n # outdent children in case remove_act doesn't delete\n node.children.each do |child|\n child.outdent\n child.remove_act\n end\n\n # hold parent in case it need be updated\n old_parent = node.parent\n \n node.repititions.destroy_all\n node.destroy\n\n if !old_parent.nil?\n old_parent.is_complete?\n end\n end", "def destroy\n\t\t@parent = Parent.find(params[:id])\n @parent.destroy\n respond_to do |format|\n format.html { redirect_to '/parent', notice: 'Parent was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def root_relation?; !parent end", "def remove(child)\n# if children.delete(child)\n# scene.unindex_prop(child) if scene\n @peer.remove(child.peer)\n# end\n end", "def delete_record\n self.remote_attributes = self.class.identify(self).delete_instance if persisted?\n @destroyed = true\n end", "def remove_child(child)\n if @children.delete(child)\n child.parent = nil\n end\n end", "def remove_child node, idx, opts={}\n no('no') unless node.children[idx]\n removed = node.children[idx]\n removed.parent_clear!\n tomb = Tombstone.build removed, opts\n node.children[idx] = tomb\n removed\n end", "def nullify\n target.send(metadata.foreign_key_setter, nil)\n target.send(:remove_instance_variable, \"@#{metadata.inverse(target)}\")\n base.send(:remove_instance_variable, \"@#{metadata.name}\")\n target.save\n end", "def delete(node=nil, root=nil, &block)\n return super(node, root) do | dn | \n block.call(dn) if block\n dn.update_left_size(:deleted, -1) if dn\n end\n end", "def exclusive_child(parent)\n\t\t\t\tparent.children = @children\n\t\t\t\t\n\t\t\t\t@children&.each_value do |child|\n\t\t\t\t\tchild.parent = parent\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tparent.clear_cache!\n\t\t\t\t\n\t\t\t\t@children = {parent.id => parent}\n\t\t\t\tself.clear_cache!\n\t\t\t\t\n\t\t\t\tparent.parent = self\n\t\t\tend", "def delete_node\n node.destroy if node\n end", "def move_orphans_to_parent\n orphan_questions = Question.where(qset_id: self.id)\n orphan_questions.update_all(qset_id: self.parent.id)\n end", "def remove_child child\n throw 'Removing self as child' if child == self\n\n if self.categoryChilds\n self.categoryChilds.all(target_id: child.id).destroy\n end\n\n if child.categoryParent\n if child.categoryParent.source_id == self.id\n child.categoryParent.destroy\n end\n end\n\n self.reload\n self\n end", "def delete!\n PoolNode.rmdir(@id)\n super\n Address.delete(@id)\n Subnet.delete(@subnet)\n end", "def destroy\n @child_record.destroy\n respond_to do |format|\n format.html { redirect_to child_records_url, notice: 'Child record was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def remove_relationship_under\n authorize! :edit, form_params[:parent_id]\n\n if form.remove\n notice = I18n.t('removed_relationship', scope: 'hyrax.dashboard.nest_collections_form', child_title: form.child.title.first, parent_title: form.parent.title.first)\n redirect_to redirect_path(item: form.parent), notice: notice\n else\n redirect_to redirect_path(item: form.parent), flash: { error: form.errors.full_messages }\n end\n end", "def destroy\n @orphan.destroy\n respond_to do |format|\n format.html { redirect_to orphans_url }\n format.json { head :no_content }\n end\n end", "def record_destroy\n paper_trail.record_destroy\n end", "def delete_if(&block)\n objects = @members.select(&block)\n\n objects.reject! { |obj| @members.delete(obj) if obj.unsaved? }\n return if objects.empty?\n\n @owner.transaction do\n objects.each do |obj|\n obj.delete\n @members.delete(obj)\n end\n end\n end", "def orphan(title, key, args = {})\n args = args.merge(save: false)\n add_with_date(key, args)\n add_entry(escape(title))\n clear_target_id\n save_without_our_callbacks\n end", "def create_inverse\n if !_without_inverse &&\n relation.inverse.present? &&\n Tie.inverse(self).blank?\n t = Tie.inverse(self).build\n t._without_inverse = true\n t.save!\n end\n end", "def remove_child child\n @children.delete child\n end", "def remove_relationship_above\n authorize! :edit, form_params[:parent_id]\n if form.remove\n notice = I18n.t('removed_relationship', scope: 'hyrax.dashboard.nest_collections_form', child_title: form.child.title.first, parent_title: form.parent.title.first)\n redirect_to redirect_path(item: form.child), notice: notice\n else\n redirect_to redirect_path(item: form.child), flash: { error: form.errors.full_messages }\n end\n end", "def create\n if self.send(self.class.parent_association_name).valid?\n self.send(self.class.parent_association_name).save!\n self.id = self.send(self.class.parent_association_name).id\n self.instance_variable_set(:@new_record, false)\n ret = self.save\n self.reload\n return ret\n else\n self.errors.add(self.class.parent_association_name, 'has errors')\n end\n end", "def delete_member_by_id(pid)\n if posn = member_ids.index(pid)\n delete_member_at(posn)\n end\n end", "def test_movie_invalid_parent\n movie = Movie.find( movies(:king_kong).id )\n parent = Movie.find( movies(:lili_marleen).id )\n movie.parent = parent\n assert !movie.valid?\n# assert !movie.save\n end", "def parent=(par)\n if self.parent\n self.parent.children.delete(self) #delete ourselves \n end\n \n @parent = par\n self.parent.children << self unless self.parent.nil?\n end", "def nuke(nuker_id)\n if self.creator_id == nuker_id || Person.find(nuker_id).is_admin\n begin\n Proj.transaction do\n # deal with the HABTM\n self.people.clear\n self.refs.clear \n \n self.destroy\n end\n return true\n rescue Exception => e\n # flash[:notice] = e.message \n end\n end \n false\n end", "def delete\n if self.father\n if self.is_left_son?\n self.father.copy(self.father.right_sentence)\n elsif self.is_right_son?\n self.father.copy(self.father.left_sentence)\n end\n aux = self.father\n while aux != nil\n aux.update\n aux = aux.father\n end\n return true\n else\n return false\n end\n end", "def destroy! #TODO\n destroy || raise(ActiveRecord::RecordNotDestroyed)\n end", "def restore_parent\n Page.with_deleted\n .find(parent_id)\n .restore(recursive: true) if parent_id\n\n rebuild!\n end", "def delete\n Mutagen::Util::delete_bytes(@fileobj, @size, @offset)\n @parent_chunk.resize(@parent_chunk.data_size - @size) unless @parent_chunk.nil?\n end", "def delete_member(id)\n @m = Member.find_by_society_id_and_user_id(self.id, id) #not using .where method as just 1 record is expected to be found\n if @m != nil and [email protected]\n @m.destroy\n\t\t\tadd_post(id, \"Left the society\")\n end\n end", "def destroy_record(record)\n record&.destroy\n end", "def delete_member path\n rewrite_members member_paths.delete(path)\n end", "def destroy\n raise ReadOnlyRecord if readonly?\n delete\n end", "def remove_act\n # outdent children in case remove_act doesn't delete\n self.children.each do |child|\n child.outdent\n child.remove_act\n end\n \n # check if parent should update completeness\n old_parent = self.parent\n\n self.permissions.destroy_all\n self.destroy\n \n # refresh parent completeness\n if !old_parent.nil?\n old_parent.is_complete?\n end\n end", "def destroy!\n destroy || raise(RecordNotDestroyed)\n end", "def stub_parent(klass, options = {})\n offspring = options.delete(:child)\n returning stub_find_one(klass, options) do |member|\n params[klass.name.foreign_key] = member.id\n member.stub!(offspring).and_return(class_for(offspring))\n end\n end", "def destroy(record)\n record.destroy\n end" ]
[ "0.74852765", "0.66529375", "0.6562246", "0.6269693", "0.62692726", "0.6183468", "0.61821836", "0.61697876", "0.6165588", "0.61017454", "0.60970914", "0.6079622", "0.6068483", "0.60582846", "0.60120195", "0.5941644", "0.590946", "0.5889548", "0.5856497", "0.5709339", "0.5697624", "0.5691873", "0.5683152", "0.56818473", "0.5673372", "0.56598276", "0.5622077", "0.5618945", "0.56181616", "0.56040734", "0.5572642", "0.5542865", "0.55202514", "0.55192024", "0.55190265", "0.5517543", "0.5514797", "0.55043876", "0.5504318", "0.5492126", "0.54774964", "0.54707414", "0.54693395", "0.5467561", "0.546409", "0.5462635", "0.5453147", "0.544961", "0.5441445", "0.5423025", "0.54167235", "0.5377804", "0.53724515", "0.5367643", "0.5363312", "0.5355036", "0.5349619", "0.533774", "0.53317285", "0.53155196", "0.5311715", "0.5310125", "0.5298231", "0.5298209", "0.52958304", "0.528296", "0.5278214", "0.5272969", "0.52605414", "0.5258529", "0.52572316", "0.52381366", "0.5213958", "0.5207268", "0.5198574", "0.51840746", "0.51744807", "0.517125", "0.5167924", "0.516354", "0.5163021", "0.5161867", "0.5157689", "0.51558566", "0.5151627", "0.5145574", "0.51455563", "0.51372063", "0.5121601", "0.5119991", "0.5109518", "0.5100589", "0.51001716", "0.5099928", "0.5096021", "0.5093139", "0.5091734", "0.5090281", "0.50782543", "0.5072983" ]
0.7578648
0
Sets payment method as default on Stripe
def make_default! result = gateway.customer.update(customer.processor_id, default_payment_method_token: processor_id) raise Pay::Braintree::Error, result unless result.success? result.success? end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def make_default!\n ::Stripe::Customer.update(customer.processor_id, {invoice_settings: {default_payment_method: processor_id}}, stripe_options)\n end", "def default_payment_method\n payment_methods.find { |payment_instrument| payment_instrument.default? }\n end", "def payment_method\n @payment_method ||= PAYMENT_METHOD[mapping_for(:payment_method)]\n end", "def payment_method\n @payment_method ||= PAYMENT_METHOD[mapping_for(:payment_method)]\n end", "def set_payment_with!(method)\n\t\tself.update_column(:payment_method, method)\n\tend", "def save_payment_method(payment_method, default:)\n pay_payment_method = pay_customer.payment_methods.where(processor_id: payment_method.id).first_or_initialize\n\n attributes = Pay::Stripe::PaymentMethod.extract_attributes(payment_method).merge(default: default)\n\n # Ignore the payment method if it's already in the database\n pay_customer.payment_methods.where.not(id: pay_payment_method.id).update_all(default: false) if default\n pay_payment_method.update!(attributes)\n\n # Reload the Rails association\n pay_customer.reload_default_payment_method\n\n pay_payment_method\n end", "def set_payment_with!(method)\n\t\tself.update_columns(payment_method: method)\n\tend", "def set_payment_method\n @payment_method = @user.payment_method.find(params[:id])\n end", "def get_default_payment_method\n @customer = get_braintree_customer\n return nil if @customer.nil?\n # get default payment_method of customer\n @customer.payment_methods.each do |payment|\n return payment if payment.default?\n end\n end", "def payment_method\n 'N/A'\n end", "def set_default_payment_method(account_id, payment_method_id, opts = {})\n set_default_payment_method_with_http_info(account_id, payment_method_id, opts)\n return nil\n end", "def payment_method\n if payment_method_id.nil?\n return nil \n else\n @payment_method ||= Payments::PaymentMethod.get(payment_method_id.to_sym)\n end\n end", "def preferred_payment_method_name\n case self.preferred_payment_method.to_s\n when /debit/ then \"Zahlung per Lastschrift\"\n when /invoice/ then \"Zahlung per Rechnung\"\n when /paypal/ then \"Zahlung per Paypal\"\n end\n end", "def set_as_default\n store = Breeze::Commerce::Store.first\n unless store.default_shipping_method\n store.default_shipping_method = self\n store.save\n end\n end", "def set_as_default(payment_gateway_id, payment_method_id)\n\t\t\tkparams = {}\n\t\t\tclient.add_param(kparams, 'paymentGatewayId', payment_gateway_id)\n\t\t\tclient.add_param(kparams, 'paymentMethodId', payment_method_id)\n\t\t\tclient.queue_service_action_call('householdpaymentmethod', 'setAsDefault', 'bool', kparams)\n\t\t\tif (client.is_multirequest)\n\t\t\t\treturn nil\n\t\t\tend\n\t\t\treturn client.do_queue()\n\t\tend", "def set_payment_method\n @payment_method = PaymentMethod.find(params[:id])\n end", "def set_payment_method\n @payment_method = PaymentMethod.find(params[:id])\n end", "def payment_type\n return \"none\" unless online_payment?\n\n if paypal_account?\n \"paypal\"\n elsif stripe_secret_key?\n if stripe_webhook_secret?\n \"advanced_stripe\"\n else\n \"stripe\"\n end\n else\n \"none\"\n end\n end", "def payment_method\n Zapi::Models::PaymentMethod.new\n end", "def assign_default\n siblings.each do |s|\n if s.remote_data\n Braintree::PaymentMethod.update(s.vault_token, options: {make_default: false})\n s.update_column(:default, false)\n else\n # With no remote data, this method has been removed on the gateway. Mark it as dead.\n s.update_columns(default: false, status: 'removed')\n end\n end\n\n Braintree::PaymentMethod.update(vault_token, options: {make_default: true})\n self.default = true\n end", "def set_default\n self.member.payout_methods.active_only.each do |pm|\n pm.update_attribute(:default, false) if pm.default?\n end\n self.update_attribute(:default, true)\n end", "def set_person_default_payment\n @person_payment = PersonDefaultPayment.find(params[:id])\n end", "def payment_method\n self.payments.last.andand.payment_method || \"none\"\n end", "def payment_type\n :credit_card\n end", "def set_payment_method\n @payment_method = PaymentMethod.find_by(id: params[:id],site_id: @site.id)\n redirect_to admin_errors_url(error_template: '403') unless @payment_method\n end", "def set_user_payment_method\n @user_payment_method = UserPaymentMethod.find(params[:id])\n end", "def payment_type=(value)\n @payment_type = value\n unless value == :piggy_bank\n# raise \"Only :piggy_bank is supported as payment type with this method. \" +\n# \"To use other payment types use @kase.payment_object = PaymentType.build(:visa)\"\n end\n end", "def payment_type\n @payment_object ? PaymentMethod.payment_type(@payment_object) : @payment_type || :piggy_bank\n end", "def payment\n @payment ||= user.try(:payment_method).try(:to_payment)\n end", "def assign_default_credit_card\n true\n end", "def set_payment_mode\n @payment_mode = PaymentMode.find(params[:id])\n end", "def set_default_rate\n currency_rates[base_currency] = DEFAULT_RATE\n end", "def payment_method=(payment_method)\n validator = EnumAttributeValidator.new('String', [\"Cheque\", \"Electronically\", \"Manual\"])\n unless validator.valid?(payment_method)\n fail ArgumentError, \"invalid value for \\\"payment_method\\\", must be one of #{validator.allowable_values}.\"\n end\n @payment_method = payment_method\n end", "def set_backoffice_payment_method\n @backoffice_payment_method = PaymentMethod.find(params[:id])\n end", "def payment_gateway_type=(type)\n gateway_setting.gateway_type = type\n end", "def payment_method\n @payment_method ||= Gateway::AdyenHPP.last # find(params[:merchantReturnData])\n end", "def default_delivery_method=(delivery_method)\n @default_delivery_method = delivery_method\n end", "def add_payment_method(token, last4, type)\n # TODO: This currently replaces the 'active' card with a new card\n if self.stripe_customer_token\n customer = Stripe::Customer.retrieve(self.stripe_customer_token)\n customer.card = token\n customer.save\n else\n customer = Stripe::Customer.create( description: self.username, email: self.email, card: token)\n self.update_attribute(:stripe_customer_token, customer.id)\n end\n\n payment_method = PaymentMethod.new(stripe_customer_token: customer.id, last4: last4, user_id: self)\n payment_method.expiration = Time.new(customer.active_card.exp_year,customer.active_card.exp_month) \n payment_method.card_type = type\n payment_method.save!\n\n customer.id\n end", "def clear_payment_method\n session[:payment_method] = nil\n end", "def payment_gateway(**options)\n return if payment_gateway_type.blank?\n\n PaymentGateway.implementation(payment_gateway_type, options).new(payment_gateway_options || {})\n end", "def create_stripe_payment_method(card_number)\n payment_method.gateway.request do\n Stripe::PaymentMethod.create({\n type: 'card',\n card: {\n number: card_number,\n exp_month: 12,\n exp_year: (Time.zone.now.year + 1),\n cvc: '123',\n },\n })\n end\n end", "def payment_type\n :credit_card\n end", "def payment_method(type)\n payment_method = payment_methods.actives.detect do |payment_method|\n payment_method.get_option('type') == type\n end\n if payment_method.nil?\n raise ArgumentError, \"Payment method #{type} is not found\"\n end\n payment_method\n end", "def set_payment_mode\n @payment_mode = PaymentMode.find(params[:id])\n end", "def set_pay_method\n @pay_method = PayMethod.find(params[:id])\n end", "def set_active_payment\n @payment ||= session[:payment_data][:billing_class].constantize.find(session[:payment_data][:billing_id])\n rescue\n render text: \"No valid payment\", status: 400\n end", "def payment\n order.credit_card || payment_empty\n end", "def set_payment_provider\n @payment_provider = PaymentProvider.find(params[:id])\n end", "def set_default_payment_method_with_http_info(account_id, payment_method_id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: AccountsApi.set_default_payment_method ...\"\n end\n # verify the required parameter 'account_id' is set\n if @api_client.config.client_side_validation && account_id.nil?\n fail ArgumentError, \"Missing the required parameter 'account_id' when calling AccountsApi.set_default_payment_method\"\n end\n if @api_client.config.client_side_validation && account_id !~ Regexp.new(/\\\\w+-\\\\w+-\\\\w+-\\\\w+-\\\\w+/)\n fail ArgumentError, \"invalid value for 'account_id' when calling AccountsApi.set_default_payment_method, must conform to the pattern /\\\\w+-\\\\w+-\\\\w+-\\\\w+-\\\\w+/.\"\n end\n\n # verify the required parameter 'payment_method_id' is set\n if @api_client.config.client_side_validation && payment_method_id.nil?\n fail ArgumentError, \"Missing the required parameter 'payment_method_id' when calling AccountsApi.set_default_payment_method\"\n end\n if @api_client.config.client_side_validation && payment_method_id !~ Regexp.new(/\\\\w+-\\\\w+-\\\\w+-\\\\w+-\\\\w+/)\n fail ArgumentError, \"invalid value for 'payment_method_id' when calling AccountsApi.set_default_payment_method, must conform to the pattern /\\\\w+-\\\\w+-\\\\w+-\\\\w+-\\\\w+/.\"\n end\n\n # resource path\n local_var_path = \"/1.0/kb/accounts/{accountId}/paymentMethods/{paymentMethodId}/setDefault\".sub('{' + 'accountId' + '}', account_id.to_s).sub('{' + 'paymentMethodId' + '}', payment_method_id.to_s)\n\n # query parameters\n query_params = {}\n query_params[:'payAllUnpaidInvoices'] = opts[:'pay_all_unpaid_invoices'] if !opts[:'pay_all_unpaid_invoices'].nil?\n query_params[:'pluginProperty'] = @api_client.build_collection_param(opts[:'plugin_property'], :multi) if !opts[:'plugin_property'].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 header_params[:'X-Killbill-CreatedBy'] = opts[:'x_killbill_created_by'] if !opts[:'x_killbill_created_by'].nil?\n header_params[:'X-Killbill-Reason'] = opts[:'x_killbill_reason'] if !opts[:'x_killbill_reason'].nil?\n header_params[:'X-Killbill-Comment'] = opts[:'x_killbill_comment'] if !opts[:'x_killbill_comment'].nil?\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\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: AccountsApi#set_default_payment_method\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def default_currency\n self[:currency] || 'USD'\n end", "def payment_source_class\n nil\n end", "def payment(method, data = {})\n call_endpoint(Endpoint::Payment, method, data)\n end", "def payment_gateway_type\n gateway_setting.gateway_type\n end", "def set_default_source(stripe_customer, stripe_card)\n # Only credit cards should be set as the default source\n return unless stripe_card.object == \"card\"\n\n customer = ::Stripe::Customer.retrieve(stripe_customer.id)\n\n customer.default_source = stripe_card.id\n customer.save\n\n customer\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def default_wallet_payment_source\n user.wallet_payment_sources.find_by(default: true)\n end", "def payment_methods(method, data = {})\n call_endpoint(Endpoint::PaymentMethods, method, data)\n end", "def payment_method_params\n params.require(:payment_method).permit(\n :name,\n :locale,\n :site_id,\n :payment_type_id,\n :active,\n :instructions,\n :summary_page_html,\n :user_mail_template_id,\n :admin_mail_template_id)\n end", "def default_wallet_payment_source=(wallet_payment_source)\n if wallet_payment_source && !find(wallet_payment_source.id)\n raise Unauthorized, \"wallet_payment_source #{wallet_payment_source.id} does not belong to wallet of user #{user.id}\"\n end\n\n # Do not update the payment source if the passed source is already default\n if default_wallet_payment_source == wallet_payment_source\n return\n end\n\n Spree::WalletPaymentSource.transaction do\n # Unset old default\n default_wallet_payment_source.try!(:update!, default: false)\n # Set new default\n wallet_payment_source.try!(:update!, default: true)\n end\n end", "def payment_gateway\n return Spree::BogusGateway.new if ENV['RAILS_ENV'] == \"development\" and Spree::Gateway::Config[:use_bogus]\n\n # retrieve gateway configuration from the database\n gateway_config = GatewayConfiguration.find :first\n config_options = {}\n gateway_config.gateway_option_values.each do |option_value|\n key = option_value.gateway_option.name.to_sym\n config_options[key] = option_value.value\n end\n gateway = gateway_config.gateway.clazz.constantize.new(config_options)\n\n return gateway\n end", "def payment_method\n PaymentMethod.find(params[:payment_method_id])\n end", "def payment_method\n PaymentMethod.find(params[:payment_method_id])\n end", "def payment_to_database(customer)\n if self.payment_method.blank?\n self.build_payment_method\n end\n self.payment_method.stripe_card_id = customer[:sources][:data].last[:id]\n self.payment_method.last_4 = customer[:sources][:data].last[:last4]\n self.payment_method.brand = customer[:sources][:data].last[:brand]\n self.payment_method.exp_m = customer[:sources][:data].last[:exp_month]\n self.payment_method.exp_y = customer[:sources][:data].last[:exp_year]\n end", "def payment_options(options={})\n {}.merge(options)\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end", "def set_payment\n @payment = Payment.find(params[:id])\n end" ]
[ "0.7564746", "0.7424524", "0.73193496", "0.73193496", "0.6966798", "0.69363505", "0.6818548", "0.67787534", "0.67312056", "0.6719104", "0.6668703", "0.6649052", "0.6620557", "0.6507257", "0.645748", "0.6454149", "0.6454149", "0.64396995", "0.63896215", "0.636981", "0.6295887", "0.6234478", "0.6234285", "0.61998504", "0.6199513", "0.6190436", "0.6179428", "0.6171607", "0.6148787", "0.6130428", "0.6118297", "0.6109121", "0.6037284", "0.6011189", "0.59878373", "0.5986951", "0.5975244", "0.59567267", "0.5948599", "0.59095", "0.5846488", "0.5842989", "0.58422774", "0.5839798", "0.583498", "0.5823634", "0.5791442", "0.5766027", "0.5676574", "0.5661355", "0.5660574", "0.56396717", "0.56199354", "0.5616636", "0.560105", "0.558579", "0.55837965", "0.55572635", "0.55513805", "0.55426574", "0.5538582", "0.5538582", "0.5536022", "0.5535782", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737", "0.5521737" ]
0.64011097
19
Utility methods Gets a given URL's response (following any redirects) Code tweaked from: AND: Parameters: url = URL to connect to max_redirects = Max number of redirects to follow (default = 6) timeout = Response timeout in seconds Returns the following: 1. Final URL (after following any redirects) 2. Response object 3. Parsed HTML response (from Nokogiri)
def url_response(url, max_redirects=6, timeout=7) response = nil parsed_page = nil seen = Set.new loop do url = URI.parse(url) break if seen.include? url.to_s break if seen.size > max_redirects seen.add(url.to_s) # initialize our http connection http = Net::HTTP.new(url.host, url.port) http.open_timeout = timeout http.read_timeout = timeout # Determine path to access # Treat an empty path as "/" path = (url.path.nil? or url.path.empty?) ? "/" : url.path # Append querystring to path if found path = path + "?" + url.query if !url.query.nil? # Initialize our HTTP request req = Net::HTTP::Get.new(path) # Handle HTTPS as needed if url.instance_of? URI::HTTPS http.use_ssl=true http.verify_mode = OpenSSL::SSL::VERIFY_NONE end # Get back the response (i.e. actually perform request) response = http.request(req) if response.kind_of?(Net::HTTPRedirection) url = response['location'] parsed_page = nil elsif response.kind_of?(Net::HTTPSuccess) # Parse the HTML using Nokogiri parsed_page = Nokogiri::HTML(response.body) # Check for a <meta http-equiv="refresh"> type of redirect # If found, we will parse out the redirect URL and load it # NOTE: The following is a case insensitive XPATH search for <meta http-equiv="refresh"> # returning the value of the "content" attribute. meta_refresh = parsed_page.xpath("//meta[translate( @http-equiv, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz' ) = 'refresh' ]/@content").to_s # Attempt to parse out a URL="" from @content attribute if meta_refresh and result = meta_refresh.match(/URL=(.+)/i) # Found a redirect URL, we'll load that one next in our loop url = result.captures[0].gsub(/['"]/, '') parsed_page = nil else # Otherwise, we have a valid response & parsed page break end else # Else, response was an error (4xx or 5xx) break end end # return final URL response (after redirects) # AND the parsed page (from Nokogiri) return url, response, parsed_page end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_response(uri, limit = 5)\n response = Net::HTTP.get_response(URI(uri))\n case response\n when Net::HTTPSuccess then\n response\n when Net::HTTPRedirection then\n location = response['location']\n get_response(location, limit - 1)\n else\n response.value\n end\nend", "def get_final_url(uri_str,limit=5)\n# puts \"getting final url for #{uri_str} ... \"\n if limit==0\n puts \"HTTP redirect too deep\"\n end\n uri = URI.parse(uri_str)\n# raise ArgumentError, 'HTTP redirect too deep' if limit == 0\n response=Object.new\n begin\n timeout(7) do\n Net::HTTP.start(uri.host) {|http|\n response = http.request_head(uri.path)\n case response\n when Net::HTTPSuccess then \n# puts \"\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t!!!success\"\n response\n when Net::HTTPRedirection then \n puts \"redirecting to #{response['location']}\"\n uri_str = get_final_url(response['location'].gsub(/\\s/,\"%20\"), limit - 1)\n else\n response.error!\n end\n }\n# puts \"response headers:\"\n response.each_key{|key|\n# puts \"#{key}: #{response[key]}\"\n }\n end\n rescue TimeoutError\n puts \"\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t???timed out\"\n rescue => e\n puts \"\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t???#{e}\"\n end\n# puts \"returning #{uri_str} from get_final_url\"\n uri_str\n end", "def get_response(uri, limit = 10)\n response = Net::HTTP.get_response(uri)\n case response\n when Net::HTTPRedirection\n if limit == 0\n response\n else\n get_response(URI.parse(response['location']), limit - 1)\n end\n else\n response\n end\nend", "def fetch(url, limit = 10)\n raise ArgumentError, \"HTTP Redirect too deep\" if limit.zero?\n res = Net::HTTP.get_response(URI.parse(url))\n case res\n when Net::HTTPSuccess\n res.body\n when Net::HTTPRedirection\n fetch(res['location'], limit - 1)\n else\n raise ArgumentError, res.error!\n end\n end", "def get(url, referer = nil)\n response, response_time = get_response(url, referer)\n code = Integer(response.code)\n loc = url\n \n limit = REDIRECTION_LIMIT\n while response.is_a?(Net::HTTPRedirection) and limit > 0\n loc = URI(response['location'])\n loc = url.merge(loc) if loc.relative?\n response, response_time = get_response(loc, referer)\n limit -= 1\n end\n\n return response, code, loc, response_time\n end", "def fetch(uri_str, limit = 10)\n raise TooManyRedirectsError, 'too many HTTP redirects' if limit == 0\n\n response = Net::HTTP.get_response(URI(uri_str))\n\n case response\n when Net::HTTPSuccess then\n response\n when Net::HTTPRedirection then\n fetch(response['location'], limit - 1)\n else\n response.value\n end\nend", "def fetch(uri_str, limit = 10)\n raise TooManyRedirectsError, 'too many HTTP redirects' if limit == 0\n\n response = Net::HTTP.get_response(URI(uri_str))\n\n case response\n when Net::HTTPSuccess then\n response\n when Net::HTTPRedirection then\n fetch(response['location'], limit - 1)\n else\n response.value\n end\nend", "def fetch(uri_str, limit = 10)\n # You should choose a better exception.\n raise ArgumentError, 'too many HTTP redirects' if limit == 0\n response = Net::HTTP.get_response(URI(uri_str))\n case response\n when Net::HTTPSuccess then\n response\n when Net::HTTPRedirection then\n location = response['location']\n # print redirect\n redirected_to = location\n fetch(location, limit - 1)\n return redirected_to\n else\n response.value\n end\nend", "def http_response(url)\n uri = URI.parse(url)\n\n response = nil\n retry_url_trailing_slash = true\n retry_url_execution_expired = true\n begin\n Net::HTTP.start(uri.host,uri.port) {|http|\n http.open_timeout = TIMEOUT_LENGTH\n req = Net::HTTP::Get.new(uri.path) \n response = http.request(req) \n }\n rescue Exception => e\n\n # forgot the trailing slash...add and retry\n if e.message == \"HTTP request path is empty\" and retry_url_trailing_slash\n url += '/'\n uri = URI.parse(url)\n h = Net::HTTP.new(uri.host)\n retry_url_trailing_slash = false\n retry\n elsif e.message =~ /execution expired/ and retry_url_execution_expired\n retry_url_execution_expired = false\n retry\n else\n response = e.to_s\n end\n end\n\n return response\n end", "def fetch(uri_str, limit = 10)\n # You should choose a better exception.\n raise ArgumentError, 'too many HTTP redirects' if limit == 0\n\n response = Net::HTTP.get_response(URI(uri_str))\n\n case response\n when Net::HTTPSuccess then\n response\n when Net::HTTPRedirection then\n location = response['location']\n warn \"redirected to #{location}\"\n fetch(location, limit - 1)\n else\n response.value\n end\nend", "def fetch(uri_str, limit = 10)\n # You should choose a better exception.\n raise ArgumentError, 'too many HTTP redirects' if limit == 0\n\n response = Net::HTTP.get_response(URI(uri_str))\n\n case response\n when Net::HTTPSuccess then\n response\n when Net::HTTPRedirection then\n location = response['location']\n warn \"redirected to #{location}\"\n fetch(location, limit - 1)\n else\n response.value\n end\nend", "def get_http(url)\n http_basic_authentication = SS::MessageEncryptor.http_basic_authentication\n\n redirection = 0\n max_redirection = SS.config.cms.check_links[\"max_redirection\"].to_i\n\n if url.match?(/^\\/\\//)\n url = @base_url.sub(/\\/\\/.*$/, url)\n elsif url[0] == \"/\"\n url = File.join(@base_url, url)\n end\n\n begin\n Timeout.timeout(@html_request_timeout) do\n data = []\n ::URI.open(url, proxy: true, redirect: false, http_basic_authentication: http_basic_authentication) do |f|\n f.each_line { |line| data << line }\n end\n return data.join\n end\n rescue OpenURI::HTTPRedirect => e\n return if redirection >= max_redirection\n redirection += 1\n url = e.uri\n retry\n rescue Timeout::Error\n nil\n rescue => e\n nil\n end\n end", "def get_http(url)\n http_basic_authentication = SS::MessageEncryptor.http_basic_authentication\n\n redirection = 0\n max_redirection = SS.config.cms.check_links[\"max_redirection\"].to_i\n\n if url.match?(/^\\/\\//)\n url = @base_url.sub(/\\/\\/.*$/, url)\n elsif url[0] == \"/\"\n url = File.join(@base_url, url)\n end\n\n begin\n Timeout.timeout(@html_request_timeout) do\n data = []\n ::URI.open(url, proxy: true, redirect: false, http_basic_authentication: http_basic_authentication) do |f|\n f.each_line { |line| data << line }\n end\n return data.join\n end\n rescue OpenURI::HTTPRedirect => e\n return if redirection >= max_redirection\n redirection += 1\n url = e.uri\n retry\n rescue Timeout::Error\n nil\n rescue => e\n nil\n end\n end", "def http_get_with_redirect(url:, limit: 5, verify_mode: OpenSSL::SSL::VERIFY_PEER)\n limit = Integer(limit)\n raise ArgumentError, 'limit cannot be negative' if limit < 0\n raise 'too many HTTP redirects' if limit.zero?\n\n # configure Net::HTTP\n http = Net::HTTP.new(url.host, url.port)\n http.open_timeout = fetch :http_open_timeout\n http.read_timeout = fetch :http_read_timeout\n if url.scheme == 'https'\n http.use_ssl = true\n http.verify_mode = verify_mode\n end\n request = Net::HTTP::Get.new(url.path) # build request\n response = http.request(request) # call url\n if response.is_a? Net::HTTPRedirection\n # Does not handle multiple redirects. Code/idea from http://stackoverflow.com/a/7210600/1796645\n location = URI.parse(response.header['location'])\n info \"redirected to #{location}\"\n response = http_get_with_redirect(url: location, limit: limit - 1, verify_mode: verify_mode)\n end\n response\n end", "def fetch(uri_str, limit = 10)\n # You should choose a better exception.\n raise ArgumentError, 'too many HTTP redirects' if limit == 0\n\n response = Net::HTTP.get_response(URI(uri_str))\n\n case response\n when Net::HTTPSuccess then\n response\n when Net::HTTPRedirection then\n location = response['location']\n warn \"redirected to #{location}\"\n fetch(location, limit - 1)\n end\nend", "def fetch_html(url, limit = 10, useragent)\n\t\t# You should choose a better exception.\n\t\traise ArgumentError, 'too many HTTP redirects' if limit == 0\n\n\t\turi = URI.parse(url)\n\t\thttp = Net::HTTP.new(uri.host, uri.port)\n\t\tif uri.scheme == \"https\"\n\t\t\t# gets https sites\n\t\t\thttp.use_ssl = true\n\t\t\thttp.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\t\tend\n\n\t\treq = Net::HTTP::Get.new(\n\t\t\turi.request_uri,\n\t\t\t{'User-Agent' => useragent}\n\t\t)\n\t\tresponse = http.request(req)\n\n\t\tcase response\n\t\twhen Net::HTTPSuccess then\n\t\t\t@return = {\n\t\t\t\t:body=>response.body,\n\t\t\t\t:http_code=>response.code,\n\t\t\t}\n\t\twhen Net::HTTPRedirection then\n\t\t\tlocation = response['location']\n\t\t\twarn \"redirected to #{location}\"\n\t\t\tnewlimit = limit - 1\n\t\t\tfetch_html(location, newlimit, useragent)\n\t\telse\n\t\t\tresponse.error!\n\t\tend\n\tend", "def get_response(url, referer = nil)\n full_path = url.query.nil? ? url.path : \"#{url.path}?#{url.query}\"\n user_agent = Anemone.options.user_agent rescue nil\n \n opts = {}\n opts['User-Agent'] = user_agent if user_agent\n opts['Referer'] = referer.to_s if referer\n\n retries = 0\n begin\n start = Time.now()\n response = connection(url).get(full_path, opts)\n finish = Time.now()\n response_time = ((finish - start) * 1000).round\n return response, response_time \n rescue EOFError\n refresh_connection(url)\n retries += 1\n retry unless retries > 1\n end\n end", "def http_response \n url = @options['url'] || @options[:url]\n\n uri = URI.parse(url)\n\n response = nil\n retry_url_trailing_slash = true\n retry_url_execution_expired = true\n begin\n Net::HTTP.start(uri.host) {|http|\n http.open_timeout = TIMEOUT_LENGTH\n req = Net::HTTP::Get.new((uri.path != '' ? uri.path : '/' ) + (uri.query ? ('?' + uri.query) : ''))\n if uri.user && uri.password\n req.basic_auth uri.user, uri.password\n end\n response = http.request(req)\n }\n rescue Exception => e\n # forgot the trailing slash...add and retry\n if e.message == \"HTTP request path is empty\" and retry_url_trailing_slash\n url += '/'\n uri = URI.parse(url)\n h = Net::HTTP.new(uri.host)\n retry_url_trailing_slash = false\n retry\n elsif e.message =~ /execution expired/ and retry_url_execution_expired\n retry_url_execution_expired = false\n retry\n else\n response = e.to_s\n end\n end\n \n return response\n end", "def getResponse url\n code = \"\"\n body = \"\"\n while code != \"200\" or body.include? \"DOCTYPE HTML\" \n begin\n uriList = URI.parse(url)\n http = Net::HTTP.new(uriList.host,uriList.port)\n http.read_timeout = 500\n request = Net::HTTP::Get.new(uriList.request_uri)\n response = http.request(request)\n code = response.code.to_s\n body = response.body.to_s\n rescue\n puts \"Problem with the Connection !\"\n puts \"Will wait 25 before retry .. \"\n sleep 25\n retry\n end\n end\n return body\nend", "def fetch( uri_str, limit = 10 )\n # You should choose better exception.\n raise ArgumentError, 'HTTP redirect too deep' if limit == 0\n response = get_response(URI.parse(uri_str))\n case response\n when Net::HTTPSuccess then response\n when Net::HTTPRedirection then fetch(response['location'], limit - 1)\n else\n response.error!\n end\n end", "def get_response( src )\n uri = URI.parse( src )\n\n # new code: honor proxy env variable HTTP_PROXY\n proxy = ENV['HTTP_PROXY']\n proxy = ENV['http_proxy'] if proxy.nil? # try possible lower/case env variable (for *nix systems) is this necessary??\n\n if proxy\n proxy = URI.parse( proxy )\n logger.debug \"using net http proxy: proxy.host=#{proxy.host}, proxy.port=#{proxy.port}\"\n if proxy.user && proxy.password\n logger.debug \" using credentials: proxy.user=#{proxy.user}, proxy.password=****\"\n else\n logger.debug \" using no credentials\"\n end\n else\n logger.debug \"using direct net http access; no proxy configured\"\n proxy = OpenStruct.new # all fields return nil (e.g. proxy.host, etc.)\n end\n\n http_proxy = Net::HTTP::Proxy( proxy.host, proxy.port, proxy.user, proxy.password )\n\n redirect_limit = 6\n response = nil\n cookie_jar = nil\n original_uri = uri\n retried_once = 0\n\n until false\n raise ArgumentError, 'HTTP redirect too deep' if redirect_limit == 0\n redirect_limit -= 1\n\n http = http_proxy.new( uri.host, uri.port )\n\n logger.debug \"GET #{uri.request_uri} uri=#{uri}, redirect_limit=#{redirect_limit}\"\n\n headers = { 'User-Agent' => \"fetcher gem v#{VERSION}\" }\n headers['Cookie'] = cookie_jar unless cookie_jar.nil?\n\n if use_cache?\n ## check for existing cache entry in cache store (lookup by uri)\n ## todo/fix: normalize uri!!!! - how?\n ## - remove query_string ?? fragement ?? why? why not??\n\n ## note: using uri.to_s should return full uri e.g. http://example.com/page.html\n\n\n cache_entry = cache[ uri.to_s ]\n if cache_entry\n logger.info \"found cache entry for >#{uri.to_s}<\"\n if cache_entry['etag']\n logger.info \"adding header If-None-Match (etag) >#{cache_entry['etag']}< for conditional GET\"\n headers['If-None-Match'] = cache_entry['etag']\n end\n if cache_entry['last-modified']\n logger.info \"adding header If-Modified-Since (last-modified) >#{cache_entry['last-modified']}< for conditional GET\"\n headers['If-Modified-Since'] = cache_entry['last-modified']\n end\n end\n end\n\n request = Net::HTTP::Get.new( uri.request_uri, headers )\n if uri.instance_of? URI::HTTPS\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n end\n\n response = http.request( request )\n\n if response.code == '200'\n logger.debug \"#{response.code} #{response.message}\"\n logger.debug \" content_type: #{response.content_type}, content_length: #{response.content_length}\"\n break # will return response\n elsif( response.code == '304' ) # -- Not Modified - for conditional GETs (using etag,last-modified)\n logger.debug \"#{response.code} #{response.message}\"\n break # will return response\n elsif( response.code == '301' || response.code == '302' || response.code == '303' || response.code == '307' )\n # 301 = moved permanently\n # 302 = found\n # 303 = see other\n # 307 = temporary redirect\n logger.debug \"#{response.code} #{response.message} location=#{response.header['location']}\"\n newuri = URI.parse( response.header['location'] )\n if newuri.relative?\n logger.debug \"url relative; try to make it absolute\"\n newuri = uri + response.header['location']\n end\n\n cookie = response.get_fields('set-cookie')\n if cookie.respond_to?('each')\n cookies_array = Array.new\n cookie.each { | cookie |\n cookies_array.push(cookie.split('; ')[0])\n }\n cookie_jar = cookies_array.join('; ')\n end\n\n if (cookie_jar.to_s.strip.empty?) && ((newuri.host != original_uri.host) || (retried_once == 1))\n uri = newuri\n else\n logger.debug \"Detected redirection to original host. Trying the original request with cookie.\"\n uri = original_uri\n redirect_limit = 6\n retried_once = 1\n end\n\n logger.debug \"Set cookie: #{cookie_jar}\"\n else\n puts \"*** error - fetch HTTP - #{response.code} #{response.message}\"\n break # will return response\n end\n end\n\n response\n end", "def http_fetch(uri_str, limit = 3)\n raise ArgumentError, 'HTTP redirect too deep' if limit <= 0\n\n uri = URI.parse(uri_str)\n request = Net::HTTP::Get.new(uri.path, {'User-Agent' => 'MetaBroadcast image resizer'})\n response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') { |http| http.request(request) }\n\n case response\n when Net::HTTPRedirection then http_fetch(response['location'], limit - 1)\n else\n response\n end\nend", "def html_get(url)\n resp = Net::HTTP.get_response(url)\n if ['301', '302', '307'].include? resp.code\n url = URI.parse resp['location']\n elsif resp.code.to_i >= 400\n $stderr.puts \"[#{resp.code}] #{url}\"\n return\n end\n Net::HTTP.get url\n end", "def fetch(uri_str, limit = 10)\n # You should choose better exception.\n raise ArgumentError, 'HTTP redirect too deep' if limit == 0\n\n begin \n # url = URI.parse(uri_str)\n url = URI(uri_str)\n req = Net::HTTP::Get.new(url, { 'User-Agent' => 'Mozilla/5.0 (etc...)' })\n response = Net::HTTP.start(url.host, url.port, use_ssl: url.scheme == 'https') { |http| http.request(req) }\n case response\n when Net::HTTPSuccess then {:content_type => response['Content-type'], :body => response.body}\n when Net::HTTPRedirection then fetch(response['location'], limit - 1)\n else\n response.error!\n end\n rescue OpenSSL::SSL::SSLError => e \n $stderr.puts(\"Failed to download #{uri_str}\")\n $stderr.puts(\"#{e.message}\")\n exit 1;\n end\nend", "def initialize(url)\n @url = url\n @follow_redirect = false\n max_redirects(5)\n @retval = Array.new\n end", "def fetch(uri_str, limit = 10)\n # You should choose better exception.\n raise ArgumentError, 'HTTP redirect too deep' if limit == 0\n\n response = Net::HTTP.get_response(URI.parse(uri_str))\n case response\n when Net::HTTPSuccess then response\n when Net::HTTPRedirection then fetch(response['location'], limit - 1)\n else\n response.error!\n end\n end", "def get_remote_string url, limit=5\n raise InstallFailedError.new url, 'HTTP redirect too deep' if limit == 0\n\n begin\n puts \"Requesting #{url}\"\n url = URI.parse(url)\n\n request = Net::HTTP::Get.new(url.path || '/')\n \n http = Net::HTTP.new url.host, url.port\n #http.set_debug_output($stderr)\n http.use_ssl = url.scheme == 'https' \n\n response = http.start { |http2| \n http2.request(request)\n }\n\n rescue StandardError => error\n raise InstallFailedError.new url, error.to_s\n end\n \n case response\n when Net::HTTPSuccess then \n return response.body\n when Net::HTTPRedirection then\n puts \"Redirecting to #{response['location']}\"; \n return get_remote_string(response['location'], limit - 1)\n end\n\n raise InstallFailedError.new url, \"#{response.code} \\\"#{response.message}\\\"\", response.body\n end", "def fetch(url)\n begin\n uri = URI.parse(url)\n if !uri.is_a?(URI::HTTP)\n \t return\n end\n\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = (http.port == 443)\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n request = Net::HTTP::Get.new(uri.request_uri)\n res = http.request(request)\n\n case res\n when Net::HTTPSuccess then\n\t puts \"#{res.code}: #{url}\"\n when Net::HTTPRedirection then\n \t redirect = res['location']\n\t puts \"#{res.code}: #{url}\"\n\t fetch redirect\n else\n\t puts \"#{res.code}: #{url}\"\n end\n rescue\n end\nend", "def execute\n response = send_request\n response.body.to_s\n rescue HTTP::Redirector::TooManyRedirectsError\n raise ProxyFetcher::Exceptions::MaximumRedirectsReached\n end", "def fetch\n def get_response url\n self.status = response = nil\n begin\n uri = URI.parse(url)\n if uri.host &&\n uri.port &&\n (http = Net::HTTP.new(uri.host, uri.port)) &&\n (request = Net::HTTP::Get.new(uri.request_uri))\n response = http.request(request)\n self.status = response.code.to_i\n else # Invalid URL\n self.status = 400\n end\n rescue Exception => e\n # If the server doesn't want to talk, we assume that the URL is okay, at least\n case e\n when Errno::ECONNRESET\n self.status = 401\n else\n self.status = -1 # Undifferentiated error during fetch, possibly a parsing problem\n end\n end\n response\n end\n\n # get_response records the status of the last HTTP access in self.status\n tried = {}\n next_try = url\n until tried[next_try]\n tried[next_try] = true\n response = get_response next_try\n case status\n when 200\n return response.body\n when 301, 302 # Redirection\n next_try = response.header[\"location\"]\n when 401 # Unauthorized\n next_try.sub! /^https/, 'http'\n end\n end\n end", "def resolve_url url_array\n url_array.each do |url_str|\n url = URI.parse(url_str)\n req = Net::HTTP.new(url.host, url.port)\n\n begin\n Timeout.timeout(5) do\n res = req.request_head(url.path)\n\n if res.code == \"200\"\n return url_str\n end\n end\n rescue Timeout::Error\n puts \"URL #{url_str} did not respond in 5 seconds.\"\n next\n end\n end\n return \"\"\nend", "def get_web_document(url)\n uri = URI.parse(url)\n response = Net::HTTP.get_response(uri)\n\n case response \n when Net::HTTPSuccess\n return response.body\n when Net::HTTPRedirection\n return get_web_document(response['Location'])\n else\n return nil\n end\nend", "def working_url?(url, max_redirects=5)\r\n response = nil\r\n seen = Set.new \t\t\t#Ensures no duplicate entries\r\n loop do\r\n url = URI.parse(url)\r\n break if seen.include? url.to_s\t\t\t\t#Break out of the loop is the url argument is found in the set\r\n break if seen.size > max_redirects\t\t\t#Break out of the loop if you're redirected more than 5 times\r\n seen.add(url.to_s)\r\n request = Net::HTTP.new(url.host, url.port)\r\n request.use_ssl = true\r\n response = request.request_head(url.path)\r\n if response.kind_of?(Net::HTTPRedirection) #Detect a HTTP redirect\r\n url = response['location'] \t\t\t #Add the new redirect location to the set if detected\r\n else\r\n break\t\t\t\t\t\t\t\t\t\t#This means there were no redirects\r\n end\r\n end\r\n response.kind_of?(Net::HTTPSuccess) && url.to_s #Return true only if a URL argument was passed to the method and it was reached successfully\r\nend", "def fetch(uri_str, limit = 10)\n # You should choose better exception.\n raise ArgumentError, 'HTTP redirect too deep' if limit == 0\n\n response = Net::HTTP.get_response(URI.parse(uri_str))\n case response\n when Net::HTTPSuccess\n response\n when Net::HTTPRedirection\n fetch(response['location'], limit - 1)\n else\n response.error!\n end\n end", "def http_parse_response(r, url)\n if r.is_a?(RestClient::Response)\n case r.code\n when 200..299 # success\n return r.headers[:content_location] || url\n when 300..399 # redirection\n return r.headers[:location] || url\n end\n end\n nil\n end", "def fetch(uri_str, limit = 10)\n\t\t\t raise ArgumentError, 'HTTP redirect too deep' if limit == 0\n\n\t\t\t url = URI.parse(uri_str)\n\t\t\t req = Net::HTTP::Get.new(url.path, { 'User-Agent' => \"Agent\" })\n\t\t\t \n\t\t\t response = Net::HTTP.start(url.host, url.port) do |http| \n\t\t\t \thttp.request(req) \n\t\t\t end\n\n\t\t\t case response\n\t\t\t \twhen Net::HTTPSuccess\n\t\t\t \t\tthen response\n\t\t\t \twhen Net::HTTPRedirection \n\t\t\t \t\tthen fetch(response['location'], limit - 1)\n\t\t\t \telse\n\t\t\t \tresponse.error!\n\t\t\t end\n\t\t\tend", "def request\n Timeout::timeout(timeout) { @request ||= open(url, {:allow_redirections => allow_redirections, 'User-Agent' => user_agent}) }\n\n rescue TimeoutError\n add_fatal_error 'Timeout!!!'\n rescue SocketError\n add_fatal_error 'Socket error: The url provided does not exist or is temporarily unavailable'\n rescue Exception => e\n add_fatal_error \"Scraping exception: #{e.message}\"\n end", "def get_response_with_redirect(uri)\n r = Net::HTTP.get_response(uri)\n if r.code == \"301\"\n r = Net::HTTP.get_response(URI.parse(r.header['location']))\n end\n r\nend", "def http_peek(url)\n @log.debug \"http_peek... #{url}\"\n uri = Addressable::URI.parse url\n if uri.port\n http = Net::HTTP.new(uri.host, uri.port)\n else\n http = Net::HTTP.new(uri.host,\n Addressable::URI.port_mapping[uri.scheme])\n end\n http.open_timeout = 5\n\n # Unfortunately the net/http(s) API can't seem to do this for us,\n # even if we require net/https from the beginning (ruby 1.8)\n if uri.scheme == \"https\"\n require 'net/https'\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n end\n\n if bot.config[\"log_level\"] == \"debug\"\n http.set_debug_output $stderr\n end\n\n begin\n res = http.start { |http|\n @log.debug \"http.start, http object: \" + \n PP.singleline_pp(http, '')\n req = Net::HTTP::Get.new(uri.request_uri,\n { 'User-Agent' => 'campfire-bot/20110709 ' +\n '(x86_64-unknown-linux-gnu) ruby-stdlib-net/1.8.7' })\n\n if uri.user != nil && uri.user != \"\" &&\n uri.password != nil && uri.password != \"\"\n req.basic_auth uri.user, uri.password\n end\n\n response = http.request req\n @log.debug \"http.start, response: \" + \n PP.singleline_pp(response, '')\n response\n }\n\n rescue Exception => e\n @log.error \"Exception... #{e.class.name}, #{e.message}\"\n end\n\n case res\n when Net::HTTPRedirection\n uri.merge({ :host => res.header['Location'] })\n @log.debug \"following HTTPRedirection... res: #{res}, uri: \" +\n \"#{uri.omit(:user, :password)}, header: #{res.header['Location']}\"\n [res.header['Location'], res]\n\n else # Net::HTTPSuccess or error\n @log.debug \"proper non-redirected location... res: #{res}, uri: #{uri.omit(:user, :password)}\"\n [url, res]\n end\n end", "def read_url(url, sec = nil, prefix = nil, limit = 10)\n status = :ok\n content = nil\n\n begin\n if sec\n begin\n Timeout::timeout(sec) do\n content = fetch(url, prefix, limit)\n end\n rescue Timeout::Error\n status = :timeout\n content = nil\n end\n else\n content = fetch(url, prefix, limit)\n end\n rescue Exception => e\n status = :error\n content = e\n end\n\n return status,content\nend", "def http_get(uri_string, headers={}, limit = 10, open_timeout=15, read_timeout=15)\n\n #@task_result.logger.log \"http_get Connecting to #{uri}\" if @task_result\n response = nil\n begin\n\n attempts=0\n max_attempts=10\n user_agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36\"\n found = false\n\n uri = URI.parse uri_string\n\n until( found || attempts >= max_attempts)\n #@task_result.logger.log \"Getting #{uri}, attempt #{attempts}\" if @task_result\n attempts+=1\n\n http = Net::HTTP.new(uri.host,uri.port)\n http.read_timeout = 10\n http.open_timeout = 10\n\n path = uri.path\n path = \"/\" if path==\"\"\n\n #request = Net::HTTP::Get.new(path,{'User-Agent'=>user_agent})\n if uri.instance_of? URI::HTTPS\n http.use_ssl=true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n end\n\n response = http.get(path)\n\n if response.code==\"200\"\n break\n end\n\n if (response.header['location']!=nil)\n newuri=URI.parse(response.header['location'])\n if(newuri.relative?)\n #@task_result.logger.log \"url was relative\" if @task_result\n newuri=uri+response.header['location']\n end\n uri=newuri\n\n else\n found=true #resp was 404, etc\n end #end if location\n end #until\n\n ### TODO - this code may be be called outside the context of a task,\n ### meaning @task_result is not available to it. Below, we check to\n ### make sure that it exists before attempting to log anything,\n ### but there may be a cleaner way to do this (hopefully?). Maybe a\n ### global logger or logging queue?\n ###\n #rescue TypeError\n # # https://github.com/jaimeiniesta/metainspector/issues/125\n # @task_result.logger.log_error \"TypeError - unknown failure\" if @task_result\n rescue Net::OpenTimeout => e\n @task_result.logger.log_error \"Timeout : #{e}\" if @task_result\n rescue Net::ReadTimeout => e\n @task_result.logger.log_error \"Timeout : #{e}\" if @task_result\n rescue URI::InvalidURIError => e\n #\n # XXX - This is an issue. We should catch this and ensure it's not\n # due to an underscore / other acceptable character in the URI\n # http://stackoverflow.com/questions/5208851/is-there-a-workaround-to-open-urls-containing-underscores-in-ruby\n #\n @task_result.logger.log_error \"Unable to request URI: #{uri} #{e}\" if @task_result\n rescue OpenSSL::SSL::SSLError => e\n @task_result.logger.log_error \"SSL connect error : #{e}\" if @task_result\n rescue Errno::ECONNREFUSED => e\n @task_result.logger.log_error \"Unable to connect: #{e}\" if @task_result\n rescue Errno::ECONNRESET => e\n @task_result.logger.log_error \"Unable to connect: #{e}\" if @task_result\n rescue Net::HTTPBadResponse => e\n @task_result.logger.log_error \"Unable to connect: #{e}\" if @task_result\n rescue Zlib::BufError => e\n @task_result.logger.log_error \"Unable to connect: #{e}\" if @task_result\n rescue Zlib::DataError => e # \"incorrect header check - may be specific to ruby 2.0\"\n @task_result.logger.log_error \"Unable to connect: #{e}\" if @task_result\n rescue EOFError => e\n @task_result.logger.log_error \"Unable to connect: #{e}\" if @task_result\n rescue SocketError => e\n @task_result.logger.log_error \"Unable to connect: #{e}\" if @task_result\n #rescue SystemCallError => e\n # @task_result.logger.log_error \"Unable to connect: #{e}\" if @task_result\n #rescue ArgumentError => e\n # @task_result.logger.log_error \"Argument Error: #{e}\" if @task_result\n rescue Encoding::InvalidByteSequenceError => e\n @task_result.logger.log_error \"Encoding error: #{e}\" if @task_result\n rescue Encoding::UndefinedConversionError => e\n @task_result.logger.log_error \"Encoding error: #{e}\" if @task_result\n end\n\n response\n end", "def fetch(uri_str, limit = 10)\n raise ArgumentError, 'HTTP redirect too deep' if limit == 0\n\n if FARENHEIT and uri_str =~ FIVEDAY\n uri_str = uri_str.dup\n uri_str[FIVEDAY] = '5day_f.shtml'\n end\n\n response = Net::HTTP.get_response(URI.parse(uri_str))\n case response\n when Net::HTTPSuccess then response\n when Net::HTTPRedirection then fetch(response['location'], limit - 1)\n else\n response.error!\n end\nend", "def get_response(url)\n uri = URI(url)\n Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|\n request = Net::HTTP::Get.new uri\n return http.request(request).body\n end\nend", "def get_real_url(url)\n begin\n puts \"Getting real URL for: #{url}\"\n doc = Nokogiri::HTML(open(url))\n rescue OpenURI::HTTPError\n puts 'Too many requests, waiting 2 min then retrying...'\n sleep(120)\n doc = Nokogiri::HTML(open(url))\n end\n real_url = 'https://untappd.com' + doc.search('.details').search('a').first['href']\n puts \"Real URL is: #{real_url}\"\n real_url\nend", "def fetch(uri_str, limit = 5, page_type = \"search\")\n if limit > 0\n uri = URI.parse(uri_str)\n\n # header\n header = {\n \"User-Agent\" => \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.75 Safari/535.7\",\n \"Referer\" => LIBRARY_REFERER_URL,\n \"Host\" => uri.host,\n \"Accept-Encoding\" => \"gzip,deflate,sdch\"\n }\n\n # reference: http://ruby-doc.org/stdlib/libdoc/net/http/rdoc/classes/Net/HTTP.html\n request = Net::HTTP::Get.new(uri.request_uri)\n request.initialize_http_header(header)\n response = Net::HTTP.start(uri.host, uri.port) { |http| http.request(request) }\n case response\n when Net::HTTPSuccess then { :response => response, :page_type => page_type }\n when Net::HTTPRedirection then fetch(\"#{LIBRARY_BASE_URL + response['location']}\", limit - 1, \"detail\")\n else\n response.error!\n end\n else\n # todo\n raise \"TOO MANY REDIRECTS\"\n end\nend", "def get_request(session, url, limit = 10)\n # Get the cached page\n $cache_mutex.synchronize do\n if $cache.has_key?(url)\n # Check if cache has expired\n if Time.now.to_i - $cache_data[url]['time'] < $default_cache_age\n $cache_heap[url] = cache_score($cache_data[url])\n $cache[url].rewind\n session.puts $cache[url].read\n return\n end\n end\n end\n\n uri = URI(url)\n res = Net::HTTP.get_response(uri)\n\n case res\n when Net::HTTPRedirection then\n # If we get redirected, try to find the right page\n location = res['location']\n puts \"redirected to #{location}\"\n if limit == 0\n puts \"redirect limit reached\"\n send_browser_response(session, res)\n else\n get_request(session, location, limit - 1)\n end\n when Net::HTTPSuccess then\n # On a successful GET, cache the page if it is small enough\n if res.body and res.body.bytesize <= $max_page_size\n $cache_mutex.synchronize do\n # Reduce size of cache if necessary\n while $max_cache_size - $cache_size < res.body.bytesize\n deleted = $cache_heap.delete_min\n url = deleted[0]\n $cache[url].close\n $cache.delete(url)\n $cache_size -= $cache_data[url]['byte_size']\n $cache_data.delete(url)\n end\n # Add new value to cache unless the response tells us not to\n cache_file = Tempfile.new('rbcache')\n $cache[url] = cache_file\n $cache_data[url] = {'time' => Time.now.to_i, 'freq' => 0, 'byte_size' => res.body.bytesize}\n $cache_heap[url] = cache_score($cache_data[url])\n $cache_size += res.body.bytesize\n cache_file.puts(res.body)\n cache_file.flush\n end\n end\n send_browser_response(session, res)\n else\n # Even if the request was unsuccessful we should probably send something\n send_browser_response(session, res)\n end\nend", "def get(url)\n uri = URI.parse(url)\n response = nil\n opt = {:use_ssl => true}\n #start(address, port=nil, p_addr=nil, p_port=nil, p_user=nil, p_pass=nil, opt, &block)\n Net::HTTP.start(uri.host, uri.port, p_addr=nil, p_port=nil, p_user=nil, p_pass=nil, opt) { |http|\n request = Net::HTTP::Get.new uri\n request['Referer'] = REFERER\n response = http.request request # Net::HTTPResponse object\n }\n return response\nend", "def check_response(response)\n case response\n when Net::HTTPSuccess then\n #puts response\n when Net::HTTPRedirection then\n location = response['location']\n warn \"redirected to #{location}\"\n fetch(location, limit - 1)\n else\n puts response.value\n end\nend", "def go_get_raw(url)\n begin\n puts \"Connecting to URL: \" + url\n response = HTTParty.get(url, timeout: Rails.configuration.x.network_time_out)\n rescue Exception => e\n puts \"Connection ERROR: \" + e.message\n return nil\n end\n return response\n end", "def get_url(url, opts)\n begin\n Timeout::timeout(opts.giveup) do\n client = HTTPAccess2::Client.new\n\t# FIXME: set additional client options here\n\tclient.ssl_config.verify_mode = nil\n\tclient.proxy = opts.proxy\n\turi = URI.parse(url.to_s)\n\tclient.set_basic_auth(url, uri.user, uri.password ) if uri.user and uri.password\n return client.get(url, nil, opts.extra)\n end\n rescue URI::InvalidURIError => error\n raise RuntimeError, \"Invalid URL (#{error})\"\n\n rescue TimeoutError => error\n raise RuntimeError, \"Connection timeout (#{error})\"\n\n rescue SocketError => error\n raise RuntimeError, \"Socket error (#{error})\"\n\n rescue\n raise RuntimeError, \"can't fetch feed (#{$!})\"\n else\n return nil\n end\n end", "def read_response(t = -1, opts = {})\n # Return a nil response if timeout is nil or 0\n return if t.nil? || t == 0\n\n resp = Response.new\n resp.max_data = config['read_max_data']\n\n Timeout.timeout((t < 0) ? nil : t) do\n\n rv = nil\n while (\n not conn.closed? and\n rv != Packet::ParseCode::Completed and\n rv != Packet::ParseCode::Error\n )\n\n begin\n\n buff = conn.get_once(resp.max_data, 1)\n rv = resp.parse(buff || '')\n\n # Handle unexpected disconnects\n rescue ::Errno::EPIPE, ::EOFError, ::IOError\n case resp.state\n when Packet::ParseState::ProcessingHeader\n resp = nil\n when Packet::ParseState::ProcessingBody\n # truncated request, good enough\n resp.error = :truncated\n end\n break\n end\n\n # This is a dirty hack for broken HTTP servers\n if rv == Packet::ParseCode::Completed\n rbody = resp.body\n rbufq = resp.bufq\n\n rblob = rbody.to_s + rbufq.to_s\n tries = 0\n begin\n # XXX: This doesn't deal with chunked encoding or \"Content-type: text/html; charset=...\"\n while tries < 1000 and resp.headers[\"Content-Type\"]== \"text/html\" and rblob !~ /<\\/html>/i\n buff = conn.get_once(-1, 0.05)\n break if not buff\n rblob += buff\n tries += 1\n end\n rescue ::Errno::EPIPE, ::EOFError, ::IOError\n end\n\n resp.bufq = \"\"\n resp.body = rblob\n end\n end\n end\n\n return resp if not resp\n\n # As a last minute hack, we check to see if we're dealing with a 100 Continue here.\n # Most of the time this is handled by the parser via check_100()\n if resp.proto == '1.1' and resp.code == 100 and not opts[:skip_100]\n # Read the real response from the body if we found one\n # If so, our real response became the body, so we re-parse it.\n if resp.body.to_s =~ /^HTTP/\n body = resp.body\n resp = Response.new\n resp.max_data = config['read_max_data']\n rv = resp.parse(body)\n # We found a 100 Continue but didn't read the real reply yet\n # Otherwise reread the reply, but don't try this hack again\n else\n resp = read_response(t, :skip_100 => true)\n end\n end\n\n resp\n rescue Timeout::Error\n # Allow partial response due to timeout\n resp if config['partial']\n end", "def getToolsUrl_details( url, max_redirects)\n params = Hash.new\n params['url'] = url\n params['max_redirects'] = max_redirects\n return doCurl(\"get\",\"/tools/url_details\",params)\n end", "def get_page(url, matcher = /.*/, retry_count = 1)\n begin\n page = @mech.get(url)\n if page.uri.to_s =~ matcher\n page\n else\n #try a force login and retry once (in case the session is stale)\n if retry_count > 0 && login(true)\n STDERR.puts \"Attn: get_page problem, overwrote stale session, retrying...\"\n get_page(url, matcher, retry_count - 1)\n else STDERR.puts \"Error: Can't retrieve valid response page for <#{url}>\"\n end\n end\n rescue Mechanize::ResponseCodeError => e\n STDERR.puts \"ResponseError!\"\n puts url if DEBUG\n puts e if DEBUG\n end\n end", "def http_get_direct(url)\n log(\"http get : #{url}\") if $opt[\"debug\"]\n begin\n html = Net::HTTP.get_response(URI.parse(url)).body\n # XXX must fix the rescue its not working\n rescue => err\n log(\"Error: #{err}\")\n exit 2\n end\n html\nend", "def openurl(url, code = '200', use_proxy = true, timeout = 5)\n data = nil\n uri = URI.parse(url)\n proxy_uri = nil\n proxy_uri = self.getproxyuri if use_proxy\n debug(\"#{uri.host} #{uri.port} #{proxy_uri.host} #{proxy_uri.port}\") if proxy_uri != nil\n debug(\"#{uri.host} #{uri.port}\") if proxy_uri == nil\n http = (proxy_uri != nil) ? Net::HTTP.new(uri.host, uri.port, proxy_uri.host, proxy_uri.port) : Net::HTTP.new(uri.host, uri.port)\n save_timeout = http.read_timeout\n http.read_timeout = timeout # provide a short timeout for facter\n if uri.scheme == \"https\"\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n end\n begin\n http.start {\n http.request_get(uri.path) {|res|\n debug(\"res code = #{res.code}\")\n data = res.body if res.code == code\n }\n }\n rescue Timeout::Error => detail\n http.read_timeout = save_timeout # reset the timeout that it was before\n raise(Timeout::Error, detail)\n end\n http.read_timeout = save_timeout\n return data\n end", "def get_stage_and_fetch_cookie(request_url = @url , limit = 10)\n # You should choose better exception.\n raise ArgumentError, 'HTTP redirect too deep' if limit <= 0\n puts \"Trying to GET #{request_url}\".yellow\n url = URI.parse(request_url)\n req = Net::HTTP::Get.new(url.request_uri)\n if @cookie != \"\"\n req['Cookie'] = get_cookie\n end\n if @host_url \n req.add_field(\"Host\", @host_url)\n end\n use_ssl = false\n if url.instance_of? URI::HTTPS\n use_ssl = true\n end\n begin\n response = Net::HTTP.start(url.host, url.port, use_ssl: use_ssl, verify_mode: OpenSSL::SSL::VERIFY_NONE) { |http| http.request(req) }\n if response['set-cookie']\n @cookie = response['set-cookie'].split('; ')[0]\n response['set-cookie'].split(';').each do |part|\n if ((part and part.include? \"atl.xsrf.token\") and (part.match(/atl.xsrf.token=(.*)/)))\n # parse only the token\n @atl_token = part.match(/atl.xsrf.token=(.*)/).captures[0]\n break\n end\n end\n puts \"Found new cookie #{get_cookie}\".yellow\n end\n if response['location']\n redirection_url = compose_redirection_url(response['location'])\n puts \"Redirected to: #{redirection_url}\".yellow\n else\n @current_url = url.request_uri\n puts \"Ended in: #{@current_url}\".yellow\n end\n case response\n when Net::HTTPSuccess then response.code.to_i\n when Net::HTTPRedirection then get_stage_and_fetch_cookie(redirection_url, limit - 1)\n else\n puts response.body\n puts response.code.to_s\n response.code.to_i\n end\n rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, Errno::ECONNREFUSED,\n Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e\n @current_url = request_url\n 404\n end\n end", "def make_request(url, limit = 0)\n return nil if limit > 5\n\n Typhoeus.get url, followlocation: true, connecttimeout: 5\n rescue StandardError => e\n Honeybadger.notify \"Problem retrieving RSS content: #{e.message}\"\n end", "def target_url(options = {})\n return @target_url unless @target_url.nil?\n\n # Perform an HTTP request but don't follow the first redirect\n case @backend\n when 'curb'\n client = Curl::Easy.new(url) do |c|\n c.max_redirects = 0\n c.follow_location = false\n c.timeout = options[:timeout] || READ_TIMEOUT\n end\n client.perform\n location = client.header_str.scan(/location:\\s+(\\S+)/i).flatten.first if REDIR_CODES.include? client.response_code.to_i\n when 'net/http'\n uri = URI.parse url\n request_use_ssl = uri.scheme == 'https'\n client = Net::HTTP.new uri.host, (request_use_ssl ? Net::HTTP.https_default_port : Net::HTTP.http_default_port)\n client.use_ssl = request_use_ssl\n client.read_timeout = options[:timeout] || READ_TIMEOUT\n\n request = Net::HTTP::Get.new uri.request_uri\n response = client.request request\n location = response['location'] if REDIR_CODES.map(&:to_s).include? response.code\n end\n @target_url = location\n end", "def response\n @response ||= Nokogiri::HTML(open(url))\n end", "def redirect_url(url, params={}, headers={}, http_options=@options)\n # determine the http options\n redirect_limit = http_options[:max_redirects] || max_redirects\n gateway_retries = http_options[:gateway_retry_limit] || gateway_retry_limit\n gateway_delay = http_options[:gateway_retry_delay] || gateway_retry_delay\n\n # parse the URL\n uri = URI.parse(url)\n # add URL parameters\n uri.query = URI.encode_www_form(params)\n\n # build the http object\n http = build_http(uri)\n # build the request\n request = Net::HTTP::Head.new(uri.request_uri, headers)\n\n # send the request\n response = http.request(request)\n # handle the response\n case response\n when Net::HTTPRedirection then\n if redirect_limit > 0\n url = response['location']\n head(response['location'], params, headers, http_options.merge({\n :max_redirects => redirect_limit - 1\n }))\n end\n # handle 502, 503, 504\n when Net::HTTPBadGateway, Net::HTTPServiceUnavailable, Net::HTTPGatewayTimeOut then\n if gateway_retries == -1\n KineticHttpResponse.new(response)\n elsif gateway_retries == 0\n @logger.info(\"HTTP response: #{response.code} #{response.message}\") unless @logger.debug?\n raise Net::HTTPFatalError.new(\"#{response.code} #{response.message}\", response)\n else\n @logger.info(\"#{response.code} #{response.message}, retrying in #{gateway_delay} seconds\")\n sleep(gateway_delay)\n redirect_url(url, params, headers, http_options.merge({\n :gateway_retry_limit => gateway_retries - 1\n }))\n end\n end\n url\n end", "def read_http(url)\n uri = URI(url)\n Net::HTTP.get_response(uri)\nend", "def read_http(url)\n uri = URI(url)\n Net::HTTP.get_response(uri)\nend", "def crawl(options = {})\n unless @proxy_addr.nil? || @proxy_port.nil?\n @agent.set_proxy @proxy_addr, @proxy_port\n end\n\n @errors = []\n i = 0\n each_url do |url, handler, default_data|\n break if options[:max_urls] && i >= options[:max_urls]\n begin\n if @random_proxy == true\n proxy = ip_cycle\n @proxy_addr = proxy[:ip]\n @proxy_port = proxy[:port]\n @agent.set_proxy @proxy_addr, @proxy_port\n end\n page = @agent.get(url)\n Spidey.logger.info \"Handling #{url.inspect} - Proxy:#{@proxy_addr}:#{@proxy_port}\"\n send handler, page, default_data\n rescue => ex\n add_error url: url, handler: handler, error: ex\n end\n sleep request_interval if request_interval > 0\n i += 1\n end\n end", "def http_get(uri, options = {})\n found = false\n remaining_redirects = options[:max_redirects] ? options[:max_redirects].to_i : 4\n until found\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = uri.scheme == 'https'\n http.verify_mode = OpenSSL::SSL::VERIFY_PEER\n http.read_timeout = http.open_timeout = options[:timeout] if options[:timeout]\n\n methods = if RUBY_VERSION < \"2.2\"\n %w{scheme userinfo host port registry}\n else\n %w{scheme userinfo host port}\n end\n methods.each { |method| uri.send(\"#{method}=\", nil) }\n req = Net::HTTP::Get.new(uri.to_s)\n req['User-Agent'] = \"Mozilla/5.0 (compatible; ruby-oembed/#{OEmbed::VERSION})\"\n res = http.request(req)\n\n if remaining_redirects == 0\n found = true\n elsif res.is_a?(Net::HTTPRedirection) && res.header['location']\n uri = URI.parse(res.header['location'])\n remaining_redirects -= 1\n else\n found = true\n end\n end\n\n case res\n when Net::HTTPNotImplemented\n raise OEmbed::UnknownFormat\n when Net::HTTPNotFound\n raise OEmbed::NotFound, uri\n when Net::HTTPSuccess\n res.body\n else\n raise OEmbed::UnknownResponse, res && res.respond_to?(:code) ? res.code : 'Error'\n end\n rescue StandardError\n # Convert known errors into OEmbed::UnknownResponse for easy catching\n # up the line. This is important if given a URL that doesn't support\n # OEmbed. The following are known errors:\n # * Net::* errors like Net::HTTPBadResponse\n # * JSON::JSONError errors like JSON::ParserError\n if defined?(::JSON) && $!.is_a?(::JSON::JSONError) || $!.class.to_s =~ /\\ANet::/\n raise OEmbed::UnknownResponse, res && res.respond_to?(:code) ? res.code : 'Error'\n else\n raise $!\n end\n end", "def http_get(url)\n response = HTTParty.get(url)\n\n puts url\n\n if response.key?('errorMessage')\n puts 'error, retry...'\n begin\n http_get(url)\n rescue Net::ReadTimeout\n puts 'takes too long to respond, retry...'\n http_get(url)\n end\n else\n puts 'no error, return'\n response\n end\nend", "def get(url, **options)\n\n # TODO: Have a base-URL option\n\n #if relative?(url)\n # url = URI.join(\"http://base-url/\", url).to_s\n #end\n\n # Determine the cache setting\n use_cache = options[:cached].nil? ? @use_cache : options[:cached]\n\n cached_already = cache.include?(url) if use_cache\n\n puts\n puts \"[ GET #{url} (using cache: #{!!use_cache}) ]\"\n\n delay unless cached_already\n max_retries = 4\n retries = 0\n\n begin\n\n if use_cache and page = cache.get(url)\n puts \" |_ cached (#{page.content_type})\"\n else\n page = agent.get(url, [], options[:referer])\n @last_get = Time.now\n cache_put(page, url) if use_cache\n end\n\n puts\n\n rescue Net::HTTPBadResponse, Errno::ECONNRESET, SocketError, Timeout::Error, SOCKSError => e\n raise if e.message == \"getaddrinfo: Name or service not known\"\n\n retries += 1\n return if retries >= max_retries\n\n puts \" |_ ERROR: #{e.inspect} -- retrying\"\n delay(5)\n retry\n\n=begin\n rescue Mechanize::ResponseCodeError => e\n\n case e.response_code\n when \"401\" #=> Net::HTTPUnauthorized\n p e\n login!\n page = get(url)\n puts\n when \"404\"\n p e\n raise e\n when \"503\"\n puts \" |_ ERROR: #{e.inspect} -- retrying\"\n delay(5)\n retry\n else\n raise e\n end\n=end\n\n end\n\n page\n end", "def apiFetch(url) \n\n retries = 10\n\n begin\n Timeout::timeout(150){\n open(url) do |f|\n \treturn f.read\t\n end\n }\n rescue Timeout::Error\n retries -= 1\n if (retries >= 0) then\n \t puts \"open uri request fail, sleep 4 sec, retry #{10-retries} of 10\"\n sleep 4 and retry\n else\n raise\n end\n\n \t\trescue\n \tputs \"Connection failed: #{$!}\\n\"\n \n \tend\n \nend", "def fetch\n hydra = Typhoeus::Hydra.new(:max_concurrency => @threads)\n page, pages = nil, []\n\n @urls.each do |url|\n request = Typhoeus::Request.new(url, :timeout => @timeout, :followlocation => false, :headers => {\"Accept\" => \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\", \"Cache-Control\" => \"no-cache\", \"Pragma\" => \"no-cache\", \"User-Agent\" => UserAgents.random})\n request.on_complete do |response|\n uri = URI(url)\n if response.success?\n puts \"fetching #{url}\".green.on_black\n page = Page.new(uri, response_code: response.code,\n response_head: response.headers,\n response_body: response.body,\n response_time: response.time*1000,\n crawled_time: (Time.now.to_f*1000).to_i)\n elsif (300..307).include?(response.code)\n puts \"fetching #{url}\".green.on_black\n puts \"### #{response.code} ### redirect to #{response.headers['Location']}\".white.on_black\n page = Page.new(uri, response_code: response.code,\n response_head: response.headers,\n response_body: response.body,\n response_time: response.time*1000,\n redirect_url: response.headers['Location'])\n elsif 404 == response.code\n puts \"fetching #{url}\".green.on_black\n puts \"### #{response.code} ### not found #{url}\".magenta.on_black\n page = Page.new(uri, response_code: response.code,\n response_time: response.time*1000)\n else\n puts \"fetching #{url}\".green.on_black\n puts \"### #{response.code} ### failed #{url}\".magenta.on_black\n puts \"### Time: #{response.time} ### #{response.return_message}\".magenta.on_black\n page = Page.new(uri, response_code: response.code,\n response_time: response.time*1000)\n end\n pages << page\n end\n hydra.queue(request)\n end\n hydra.run\n return pages\n end", "def fetch_uri(uri_as_string, limit, options = {})\n raise @invalid_uri_error if invalid_uri_error?\n \n uri = URI.parse(uri_as_string)\n # handle relative URLs\n if (uri.instance_of?(URI::Generic)) && options[:previous_uri]\n previous_uri = options[:previous_uri]\n new_uri_as_string = \"#{previous_uri.scheme}://#{previous_uri.host}\"\n unless (previous_uri.port == 80 && previous_uri.scheme == 'http') ||\n (previous_uri.port == 443 && previous_uri.scheme == 'https')\n new_uri_as_string += \":#{previous_uri.port}\"\n end\n if uri_as_string.strip =~ /^\\//\n # given path is relative to root => just append\n uri_as_string = new_uri_as_string + uri_as_string.strip\n elsif previous_uri.path.strip =~ /^(.+\\/)[^\\/]*$/ \n # given path is relative to previous directory => remove last part from previous path\n path = $1\n path = $1 if path =~ /^(.*)(\\?.*)$/ # -> remove query string\n uri_as_string = new_uri_as_string + path + uri_as_string.strip\n else\n # this should not happen => in case it does, leave URI as it was before\n end\n uri = URI.parse(uri_as_string)\n end\n \n # get HTTP / HTTPS response\n if uri.scheme == 'https'\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n path = uri.path.strip.empty? ? '/' : uri.path\n response = http.request(Net::HTTP::Get.new(path))\n else\n response = Net::HTTP.get_response(uri)\n end\n @redirect_log.push(Response.new(uri_as_string, response.code))\n \n # handle redirects\n if limit > 1 && response.is_a?(Net::HTTPRedirection)\n response = fetch_uri(response['location'], limit - 1, {:previous_uri => uri})\n end\n return response\n end", "def getFinalUrl(url)\n return Net::HTTP.get_response(URI(url))['location']\nend", "def get(url, params={}, headers={}, http_options=@options)\n # determine the http options\n redirect_limit = http_options[:max_redirects] || max_redirects\n gateway_retries = http_options[:gateway_retry_limit] || gateway_retry_limit\n gateway_delay = http_options[:gateway_retry_delay] || gateway_retry_delay\n\n # parse the URL\n uri = URI.parse(url)\n # add URL parameters\n uri.query = URI.encode_www_form(params)\n\n @logger.debug(\"GET #{uri} #{headers.inspect}\")\n\n # build the http object\n http = build_http(uri)\n # build the request\n request = Net::HTTP::Get.new(uri.request_uri, headers)\n\n # send the request\n begin\n response = http.request(request)\n # handle the response\n case response\n # handle 302\n when Net::HTTPRedirection then\n if redirect_limit == -1\n @logger.info(\"HTTP response code: #{response.code}\") unless @logger.debug?\n KineticHttpResponse.new(response)\n elsif redirect_limit == 0\n raise Net::HTTPFatalError.new(\"Too many redirects\", response)\n else\n get(response['location'], params, headers, http_options.merge({\n :max_redirects => redirect_limit - 1\n }))\n end\n # handle 502, 503, 504\n when Net::HTTPBadGateway, Net::HTTPServiceUnavailable, Net::HTTPGatewayTimeOut then\n if gateway_retries == -1\n KineticHttpResponse.new(response)\n elsif gateway_retries == 0\n @logger.info(\"HTTP response: #{response.code} #{response.message}\") unless @logger.debug?\n raise Net::HTTPFatalError.new(\"#{response.code} #{response.message}\", response)\n else\n @logger.info(\"#{response.code} #{response.message}, retrying in #{gateway_delay} seconds\")\n sleep(gateway_delay)\n get(url, params, headers, http_options.merge({\n :gateway_retry_limit => gateway_retries - 1\n }))\n end\n when Net::HTTPUnknownResponse, NilClass then\n @logger.info(\"HTTP response code: 0\") unless @logger.debug?\n e = Net::HTTPFatalError.new(\"Unknown response from server\", response)\n KineticHttpResponse.new(e)\n else\n @logger.info(\"HTTP response code: #{response.code}\") unless @logger.debug?\n KineticHttpResponse.new(response)\n end\n rescue Net::HTTPBadResponse => e\n @logger.info(\"HTTP bad response: #{e.inspect}\") unless @logger.debug?\n KineticHttpResponse.new(e)\n rescue StandardError => e\n @logger.info(\"HTTP error: #{e.inspect}\") unless @logger.debug?\n KineticHttpResponse.new(e)\n end\n end", "def get_webpage(url)\n uri = URI.parse(url)\n Net::HTTP.get_response(uri)\nend", "def retrieve_response(url)\n response = response(url)\n response = response(url) unless response[:code].present?\n response\n end", "def curl\n puts \"fetching #{@uri.to_s}\".green.on_black\n start_time = Time.now\n begin\n c = @c\n c.url = @uri.to_s\n c.perform\n end_time = Time.now\n case c.response_code\n when 200 then\n page = Page.new(@uri, response_code: c.response_code,\n response_head: c.header_str,\n response_body: c.body_str,\n response_time: ((end_time-start_time)*1000).round,\n crawled_time: (Time.now.to_f*1000).to_i)\n when 300..307 then\n page = Page.new(@uri, response_code: c.response_code,\n response_head: c.header_str,\n response_body: c.body_str,\n response_time: ((end_time-start_time)*1000).round,\n redirect_url: c.redirect_url)\n when 404 then\n page = Page.new(@uri, response_code: c.response_code,\n response_time: ((end_time-start_time)*1000).round)\n end\n rescue Exception => e\n puts e.inspect\n puts e.backtrace\n end\n end", "def get_article_urls(url, article_urls)\n uri = URI.parse(URI.encode(url.to_s.strip))\n # doc = Nokogiri::HTML(open(uri, \"User-Agent\" => \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:30.0) Gecko/20100101 Firefox/30.0\", :allow_redirections => :all))\n\n response_page = \"\"\n begin\n Timeout.timeout(25) do\n response_page = open(uri, \"User-Agent\" => \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:30.0) Gecko/20100101 Firefox/30.0\", :allow_redirections => :all)\n end\n rescue Exception => e\n response_page = \"\"\n end\n doc = Nokogiri::HTML(response_page)\n\n articles = doc.xpath(\".//article\")\n\n articles.each do |article|\n begin\n article_urls << article.at(\".entry-post-thumbnail\")[\"href\"]\n rescue Exception => e\n p e.backtrace\n end\n end\nend", "def fetch\n headers = {\n \"User-Agent\" => \"#{HTTP::Request::USER_AGENT} (rubyland aggregator)\"\n }\n\n unless refresh == :hard\n if db_feed.http_etag\n headers[\"If-None-Match\"] = db_feed.http_etag\n end\n if db_feed.http_last_modified\n headers['If-Modified-Since'] = db_feed.http_last_modified\n end\n end\n\n # Loop redirects, marking new permanent url if all 304s\n tries = 0\n fetch_url = feed_url\n new_url = nil\n response = nil\n permanent_new_url = nil\n all_301s = true\n\n while tries < max_redirects\n tries += 1\n response = HTTP.use(:auto_inflate).headers(headers).get(fetch_url)\n\n if HTTP::Redirector::REDIRECT_CODES.include? response.status\n if response.status != 301\n all_301s = false\n end\n fetch_url = response.headers[\"Location\"]\n else\n break\n end\n end\n\n return response, (tries > 1 && all_301s ? fetch_url : nil)\n end", "def retrieve_url(url)\n uri = URI::parse(url)\n http = Net::HTTP.new(uri.host, uri.port).start\n res = http.get(url,HEADERS)\n http.finish\n return res\n rescue Timeout::Error\n return false\n end", "def url_tester(method,schema,base_domain,page,query,expected_code,timeout,headers,https_verify,logger)\n\n uri = URI.join(\"#{schema}://#{base_domain}\",page)\n http = Net::HTTP.new(uri.host, uri.port)\n if schema == \"https\"\n http.use_ssl = true\n http.verify_mode = https_verify ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE\n end\n http.open_timeout = timeout\n\n # Catch errors and set http status codes manually\n begin\n request = Net::HTTP::Get.new(uri.request_uri)\n if !headers.empty?\n headers.each { |header|\n header_array = header.split(':', 2)\n logger.debug_message \"header_array: #{header_array}\"\n request.initialize_http_header({header_array[0] => header_array[1]})\n }\n end\n start_time = Time.now\n response = http.request(request)\n end_time = Time.now\n response_time = end_time - start_time\n return uri.to_s, response.code.to_i, response_time \n # Catch time outs and set code to HTTPGatewayTimeOut: 504.\n rescue Net::OpenTimeout\n return uri.to_s, 504\n end\nend", "def http_request(url_s, method, body = nil, headers = {}, www_authenticate = nil, redirect_limit = 5)\n cachekey = url_s.to_s\n\n cached_value = @cache[cachekey]\n if cached_value\n sock = Net::BufferedIO.new(StringIO.new(cached_value))\n info = Net::HTTPResponse.read_new(sock)\n info.reading_body(sock, true) {}\n\n if method == Net::HTTP::Put and info.key? 'etag' and not headers['If-Match']\n headers['If-Match'] = info['etag']\n end\n end\n\n if cached_value and not [Net::HTTP::Get, Net::HTTP::Head].member? method\n @cache.delete(cachekey)\n elsif cached_value\n entry_disposition = _entry_disposition(info, headers)\n\n if entry_disposition == :FRESH\n info.extend Atom::HTTPResponse\n\n return info\n elsif entry_disposition == :STALE\n if info.key? 'etag' and not headers['If-None-Match']\n headers['If-None-Match'] = info['etag']\n end\n if info.key? 'last-modified' and not headers['Last-Modified']\n headers['If-Modified-Since'] = info['last-modified']\n end\n end\n end\n\n req, url = new_request(url_s, method, headers)\n\n # two reasons to authenticate;\n if @always_auth\n self.send(\"#{@always_auth}_authenticate\", req, url)\n elsif www_authenticate\n dispatch_authorization www_authenticate, req, url\n end\n\n http_obj = Net::HTTP.new(url.host, url.port)\n http_obj.use_ssl = true if url.scheme == \"https\"\n\n res = http_obj.start do |h|\n h.request(req, body)\n end\n\n # a bit of added convenience\n res.extend Atom::HTTPResponse\n\n case res\n when Net::HTTPUnauthorized\n if @always_auth or www_authenticate or not res[\"WWW-Authenticate\"] # XXX and not stale (Digest only)\n # we've tried the credentials you gave us once\n # and failed, or the server gave us no way to fix it\n raise Unauthorized, \"Your authorization was rejected\"\n else\n # once more, with authentication\n res = http_request(url_s, method, body, headers, res[\"WWW-Authenticate\"])\n\n if res.kind_of? Net::HTTPUnauthorized\n raise Unauthorized, \"Your authorization was rejected\"\n end\n end\n when Net::HTTPRedirection\n if res.code == \"304\" and method == Net::HTTP::Get\n res.end2end_headers.each { |k| info[k] = res[k] }\n\n res = info\n\n res[\"Content-Length\"] = res.body.length\n\n res.extend Atom::HTTPResponse\n\n _updateCache(headers, res, @cache, cachekey)\n elsif res[\"Location\"] and (allow_all_redirects or [Net::HTTP::Get, Net::HTTP::Head].member? method)\n raise HTTPException, \"Too many redirects\" if redirect_limit.zero?\n\n res = http_request res[\"Location\"], method, body, headers, nil, (redirect_limit - 1)\n end\n when Net::HTTPOK, Net::HTTPNonAuthoritativeInformation\n unless res.key? 'Content-Location'\n res['Content-Location'] = url_s\n end\n _updateCache(headers, res, @cache, cachekey)\n end\n\n res\n end", "def fetch\n puts \"fetching #{@uri.to_s}\".green.on_black\n start_time = Time.now\n begin\n request = Net::HTTP::Get.new(@uri.request_uri)\n request[\"User-Agent\"] = UserAgents.random\n response = @http.request(request) \n end_time = Time.now\n case response\n when Net::HTTPSuccess then\n page = Page.new(@uri, response_code: response.code.to_i,\n response_head: response.instance_variable_get(\"@header\"),\n response_body: response.body,\n response_time: (end_time-start_time).to_f,\n crawled_time: (Time.now.to_f*1000).to_i)\n when Net::HTTPRedirection then\n page = Page.new(@uri, response_code: response.code.to_i,\n response_head: response.instance_variable_get(\"@header\"),\n response_body: response.body,\n response_time: (end_time-start_time).to_f,\n redirect_url: response['location'])\n when Net::HTTPNotFound then\n page = Page.new(@uri, response_code: response.code.to_i,\n response_time: (end_time-start_time).to_f)\n end\n rescue Exception => e\n puts e.inspect\n puts e.backtrace\n end\n end", "def retrieve_page(url)\n begin \n page = Timeout::timeout(5) {$agent.get(url)}\n if page.is_a?(Mechanize::Page)\n return page\n else\n return nil\n end\n rescue\n return nil\n end\nend", "def getPage(link)\n\n\t\t# sleep needed to avoid being banned from website\n\t\tsleep(@waitTime)\n\t\n\t\tbegin\n\t\t\ttempDoc = Nokogiri::HTML(open(link))\n\t\trescue RuntimeError => e\n\t\t\tputs e\n\t\t\tredirect = e.to_s.scan(/redirection forbidden:/)\n\t\t\tif(redirect[0] == nil)\n\t\t\t\treturn false;\n\t\t\telse\n\t\t\t\tnewLink = e.to_s.scan(/-> (\\S+)/)\n\t\t\t\treturn getPage(newLink[0].to_s.gsub(/\\[/, \"\").gsub(/\\]/, \"\").gsub(/\"/,\"\"))\n\t\t\tend\n\t\trescue SocketError => e\n\t\t\tputs e\n\t\t\tputs \"connection error .. will attempt again\"\n\t\t\treturn getPage(link)\n\t\trescue OpenURI::HTTPError => e\n\t\t\tputs e\n\t\t\taccess_forbidden = e.to_s.scan(/403/)\n\t\t\tnot_found = e.to_s.scan(/404/)\n\t\t\tif(access_forbidden[0] != nil)\n\t\t\t\tputs \"#{link} not open to the public\" \n\t\t\t\treturn false\n\t\t\telsif(not_found[0] != nil)\n\t\t\t\tputs \"#{link} not found\"\n\t\t\t\treturn false\n\t\t\tend\n\t\t\tputs \"connection problem ... will attempt again\"\n\t\t\treturn getPage(link)\n\t\tend\n\n\t\treturn tempDoc\n\tend", "def ident_http_request(method, uri_string, credentials=nil, headers={}, data=nil, limit = 3, open_timeout=15, read_timeout=15)\n\n response = nil\n begin\n\n # set user agent\n user_agent = \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36\"\n headers[\"User-Agent\"] = user_agent\n\n attempts=0\n max_attempts=limit\n found = false\n timeout = false\n\n uri = URI.parse uri_string\n\n # keep track of redirects\n response_urls = [\"#{uri}\"]\n\n unless uri\n _log error \"Unable to parse URI from: #{uri_string}\"\n return\n end\n\n until( found || attempts >= max_attempts)\n @task_result.logger.log \"Getting #{uri}, attempt #{attempts}\" if @task_result\n attempts+=1\n\n if $global_config\n if $global_config.config[\"http_proxy\"]\n proxy_config = $global_config.config[\"http_proxy\"]\n proxy_addr = $global_config.config[\"http_proxy\"][\"host\"]\n proxy_port = $global_config.config[\"http_proxy\"][\"port\"]\n proxy_user = $global_config.config[\"http_proxy\"][\"user\"]\n proxy_pass = $global_config.config[\"http_proxy\"][\"pass\"]\n end\n end\n\n # set options\n opts = {}\n if uri.instance_of? URI::HTTPS\n opts[:use_ssl] = true\n opts[:verify_mode] = OpenSSL::SSL::VERIFY_NONE\n end\n\n http = Net::HTTP.start(uri.host, uri.port, proxy_addr, proxy_port, opts)\n http.open_timeout = open_timeout\n http.read_timeout = read_timeout\n\n path = \"#{uri.path}\"\n path = \"/\" if path==\"\"\n\n # add in the query parameters\n if uri.query\n path += \"?#{uri.query}\"\n end\n\n ### ALLOW DIFFERENT VERBS HERE\n if method == :get\n request = Net::HTTP::Get.new(uri)\n elsif method == :post\n # see: https://coderwall.com/p/c-mu-a/http-posts-in-ruby\n request = Net::HTTP::Post.new(uri)\n request.body = data\n elsif method == :head\n request = Net::HTTP::Head.new(uri)\n elsif method == :propfind\n request = Net::HTTP::Propfind.new(uri.request_uri)\n request.body = \"Here's the body.\" # Set your body (data)\n request[\"Depth\"] = \"1\" # Set your headers: one header per line.\n elsif method == :options\n request = Net::HTTP::Options.new(uri.request_uri)\n elsif method == :trace\n request = Net::HTTP::Trace.new(uri.request_uri)\n request.body = \"blah blah\"\n end\n ### END VERBS\n\n # set the headers\n headers.each do |k,v|\n request[k] = v\n end\n\n # handle credentials\n if credentials\n request.basic_auth(credentials[:username],credentials[:password])\n end\n\n # USE THIS TO PRINT HTTP REQUEST\n #request.each_header{|h| _log_debug \"#{h}: #{request[h]}\" }\n # END USE THIS TO PRINT HTTP REQUEST\n\n # get the response\n response = http.request(request)\n\n if response.code==\"200\"\n break\n end\n\n if (response.header['location']!=nil)\n newuri=URI.parse(response.header['location'])\n if(newuri.relative?)\n newuri=URI.parse(\"#{uri}#{response.header['location']}\")\n end\n response_urls << ident_encode(newuri.to_s)\n uri=newuri\n\n else\n found=true #resp was 404, etc\n end #end if location\n end #until\n\n final_url = uri\n\n ### TODO - create a global $debug config option\n \n rescue ArgumentError => e\n #puts \"Unable to connect #{uri}: #{e}\"\n rescue Net::OpenTimeout => e\n #puts \"Unable to connect #{uri}: #{e}\"\n timeout = true\n rescue Net::ReadTimeout => e\n #puts \"Unable to connect #{uri}: #{e}\"\n timeout = true\n rescue Errno::ENETDOWN => e\n #puts \"Unable to connect #{uri}: #{e}\" \n rescue Errno::ETIMEDOUT => e\n #puts \"Unable to connect #{uri}: #{e}\" \n timeout = true\n rescue Errno::EINVAL => e\n #puts \"Unable to connect #{uri}: #{e}\"\n rescue Errno::ENETUNREACH => e\n #puts \"Unable to connect #{uri}: #{e}\"\n rescue Errno::EHOSTUNREACH => e\n #puts \"Unable to connect #{uri}: #{e}\"\n rescue URI::InvalidURIError => e\n #\n # XXX - This is an issue. We should catch this and ensure it's not\n # due to an underscore / other acceptable character in the URI\n # http://stackoverflow.com/questions/5208851/is-there-a-workaround-to-open-urls-containing-underscores-in-ruby\n #\n #puts \"Unable to connect #{uri}: #{e}\"\n rescue OpenSSL::SSL::SSLError => e\n #puts \"Unable to connect #{uri}: #{e}\" \n rescue Errno::ECONNREFUSED => e\n #puts \"Unable to connect #{uri}: #{e}\" \n rescue Errno::ECONNRESET => e\n #puts \"Unable to connect #{uri}: #{e}\" \n rescue Net::HTTPBadResponse => e\n #puts \"Unable to connect #{uri}: #{e}\" \n rescue Zlib::BufError => e\n #puts \"Unable to connect #{uri}: #{e}\" \n rescue Zlib::DataError => e # \"incorrect header check - may be specific to ruby 2.0\"\n #puts \"Unable to connect #{uri}: #{e}\" \n rescue EOFError => e\n #puts \"Unable to connect #{uri}: #{e}\" \n rescue SocketError => e\n #puts \"Unable to connect #{uri}: #{e}\" \n rescue Encoding::InvalidByteSequenceError => e\n #puts \"Encoding issue #{uri}: #{e}\" \n rescue Encoding::UndefinedConversionError => e\n #puts \"Encoding issue #{uri}: #{e}\" \n end\n\n # generate our output\n out = {\n :timeout => timeout,\n :start_url => uri_string,\n :final_url => final_url.to_s,\n :request_type => :ruby,\n :request_method => method,\n :request_credentials => credentials,\n :request_headers => headers,\n :request_data => data,\n :request_attempts_limit => limit,\n :request_attempts_used => attempts,\n :request_user_agent => user_agent,\n :request_proxy => proxy_config,\n :response_urls => response_urls,\n :response_object => response\n }\n\n # verify we have a response before adding these\n if response\n out[:response_headers] = response.each_header.map{|x| ident_encode \"#{x}: #{response[x]}\" }\n out[:response_body] = ident_encode(response.body)\n end\n\n out\n end", "def getOriginalHTML url\n timer = WebCrawler::startTime\n res = WebCrawler::getURLRedirectResponse(URI(url))\n if res.code==\"403\" || res.code ==\"404\"\n puts '[HTTP STATUS] '+res.code\n raise \"Page Not Found\"\n end\n\n begin\n @session.visit url\n rescue Selenium::WebDriver::Error::WebDriverError ,\n Selenium::WebDriver::Error::UnknownError => e\n WebCrawler::logError 'webcrawler.driver', e.message\n rescue Capybara::Poltergeist::JavascriptError => e\n WebCrawler::logError 'webcrawler.javascript', e.message\n end\n WebCrawler::logTime timer, 'page.visit', url\n end", "def request(url, options)\n\t\tmy_url = URI.parse(URI.encode(url))\n\n\t\tbegin\n\t\t\tmy_url = URI.parse(url)\n\t\trescue URI::InvalidURIError\n\t\t\tmy_url = URI.parse(URI.encode(url))\n\t\tend\n\nstart_time = Time.now\n\t\tproxy_host = 'ubio.cnio.es'\n\t\tproxy_port = 3128\n\t\treq = Net::HTTP::Get.new(my_url.request_uri)\n#\t\tres = Net::HTTP.start(my_url.host, my_url.port, proxy_host, proxy_port) { |http|\n\t\tres = Net::HTTP.start(my_url.host, my_url.port) { |http|\n\t\t\thttp.request(req)\n\t\t}\n\n\n\n\t\t#http_session = proxy.new(my_url.host, my_url.port)\n\t\t#\n\t\t#res = nil\n\t\t#proxy.new(my_url.host, my_url.port).start { |http|\n\t\t#Net::HTTP::Proxy(proxy_host, proxy_port).start(my_url.host) { |http|\n\t\t#\treq = Net::HTTP::Get.new(my_url.request_uri)\n\t\t#\tres, data = http.request(req)\n\t\t#\n\t\t#\tputs \"shitting data: #{data}\\n\"\n\t\t#\tputs \"res.code: #{res.code}\\n\"\n\t\t#}\n\t\t#\n\t\t#\n\t\t#res = Net::HTTP.start(my_url.host, my_url.port) { |http|\n\t\t#\treq = Net::HTTP::Get.new(my_url.request_uri)\n\t\t#\thttp.request(req)\n\t\t#}\n\n\n#end_time = Time.now\n#elapsed_time = (end_time - start_time) * 1000\n#puts \"***=> Time elapsed for #{url}: #{elapsed_time} ms\\n\"\n#\n#puts \"response code: #{res ? res.code: 'res not available here'}\"\n\n\t\tres\n\tend", "def get(url)\n uri = URI.parse(url)\n http = Net::HTTP.new(uri.host, uri.port)\n\n response = http.get(\"#{uri.path}?auto\")\n\n unless response.code == \"200\"\n puts \"Failed to retrieve #{url}: #{response.code}\"\n exit 3\n end\n\n response.body\nend", "def get_response(url)\n logger.debug \"GET (response) #{url}\"\n uri = normalize_url(url)\n\n req = Net::HTTP::Get.new(uri.request_uri)\n http = authenticate_request(uri, req)\n response = nil\n http.request(req) do |res|\n logger.debug \"GOT (#{res.code}) #{url}\"\n response = res\n end\n response\n end", "def http_request(url, options = {})\n\t\t\treq = Net::HTTP::Get.new(url)\n\t\t\treq[\"user-agent\"] = @@user_agent # ensure returns XML\n\t\t\treq[\"cookie\"] = \"cookieMenu=all; cookieLangId=\" + options[:lang] + \"; cookies=true;\"\n\t\t\t\n\t\t\treq[\"cookie\"] += options[:cookie] if options[:cookie]\n\n\t\t\turi = URI.parse(URI.escape(url))\n\t\t\t\n\t\t\thttp = Net::HTTP.new(uri.host, uri.port)\n\t\t\t\n\t\t\tif (options[:secure])\n\t\t\t\tputs \"Secure authentication\" if options[:debug]\n\n\t\t\t\thttp.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\t\t\t\thttp.use_ssl = true\n\t\t\tend\n\t\t \n\t\t\t\n\t\t\tbegin\n\t\t\t\ttries = 0\n\t\t\t http.start do\n\t\t\t\t puts \"Get URL \"+ url if options[:debug]\n\t\t\t res = http.request req\n\t\t\t\t\t# response = res.body\n\t\t\t\t\t\n\t\t\t\t\t# FIXME WoW Armory rate limiter. Simple version\n\t\t\t\t\t# Needs to work across instances and not sleep for 1.5 if the\n\t\t\t\t\t# request took more than 1.5\n\t\t\t\t\t# just need a 1.5 second wait until the start of the next request\n \n if options[:rate_limit]\n\t\t\t\t\t puts \"Sleeping for 1.5 seconds\" if options[:debug]\n \t\t\t\t\tsleep 1.5\n\t\t\t\t\tend\n\n\t\t\t\t\tresponse = case res\n\t\t\t\t\t\twhen Net::HTTPSuccess, Net::HTTPRedirection\n\t\t\t\t\t\t\tres.body\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\ttries += 1\n\t\t\t\t\t\t\tif tries > @@max_connection_tries\n\t\t\t\t\t\t\t\traise Wowr::Exceptions::NetworkTimeout.new('Timed out')\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tredo\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\t\t\t end\n\t\t\trescue Timeout::Error => e\n raise Wowr::Exceptions::NetworkTimeout.new('Timed out - Timeout::Error Exception')\n\t\t\trescue SocketError, Net::HTTPExceptions => e\n\t\t\t\traise Wowr::Exceptions::ServerDoesNotExist.new('Specified server at ' + url + ' does not exist.')\n\t\t\tend\n\t\tend", "def initialize(url_str)\n $LOG.info \"Getting URL '#{url_str}'\"\n uri = URI.parse(url_str)\n unless VALID_SCHEMES.include?(uri.scheme)\n $LOG.fatal \"URL protocol is not one of #{VALID_SCHEMES.join(',')}\"\n exit 1\n end\n if proxy = ENV['HTTP_PROXY']\n prx_uri = URI.parse(proxy)\n prx_host = prx_uri.host\n prx_port = prx_uri.port\n end\n\n h = Net::HTTP.new(uri.host, uri.port, prx_host, prx_port)\n h.set_debug_output($stderr) if $DEBUG\n h.use_ssl = uri.scheme == \"https\"\n h.verify_mode = OpenSSL::SSL::VERIFY_NONE # OpenSSL::SSL::VERIFY_PEER\n\n @body = ''\n begin\n @get_resp = h.get2(uri.request_uri, Config[:http_get_header]){|resp| @body += resp.body}\n rescue Exception => ex\n $LOG.fatal \"Unable to get web page. Error: #{ex}\"\n exit 1\n end\n\n if http_redirect?\n $LOG.debug \"#{@get_resp.class} is a kind of HTTPRedirection\"\n $LOG.debug \"Redirect location = #{redirect_location}\"\n elsif http_success?\n $LOG.debug \"#{@get_resp.class} is a kind of HTTPSuccess\"\n else\n $LOG.debug \"#{@get_resp.class} is neither HTTPSuccess nor HTTPRedirection!!!\"\n end\n\n end", "def get_single_url(url)\n\n useragent = \"NotubeMiniCrawler/0.1\"\n u = URI.parse url \n req = Net::HTTP::Get.new(u.request_uri,{'User-Agent' => useragent})\n begin \n res2 = Net::HTTP.new(u.host, u.port).start {|http|http.request(req) }\n end\n\n r = \"\"\n begin\n r = res2.body\n rescue OpenURI::HTTPError=>e\n case e.to_s \n when /^404/\n raise 'Not Found'\n when /^304/\n raise 'No Info'\n end\n end\n return r\n end", "def get(path, redirect_limit=5)\n parse_json do |parser|\n @http_client.get(path, redirect_limit) {|chunk| parser << chunk }\n end\n end", "def http_request(url)\n uri = URI.parse(url)\n begin\n http = uri.read(read_timeout: 4)\n rescue OpenURI::HTTPError => e\n raise RequestError, YAML::dump(e)\n end\n end", "def get(url, params={}, headers={}, redirect_limit=max_redirects)\n # parse the URL\n uri = URI.parse(url)\n # add URL parameters\n uri.query = URI.encode_www_form(params)\n\n debug(\"GET #{uri} #{headers.inspect}\")\n\n # build the http object\n http = build_http(uri)\n # build the request\n request = Net::HTTP::Get.new(uri.request_uri, headers)\n\n # send the request\n begin\n response = http.request(request)\n # handle the response\n case response\n when Net::HTTPRedirection then\n raise Net::HTTPFatalError.new(\"Too many redirects\", response) if redirect_limit == 0\n get_raw(response['location'], params, headers, redirect_limit - 1)\n else\n KineticHttpResponse.new(response)\n end\n rescue StandardError => e\n KineticHttpResponse.new(e)\n end\n end", "def get_redirect_code(url)\n passed = true\n bad_codes = [204,206,400,404,408,500,501,502,503,504,505]\n\n\n\n counter = 0\n possible_redirect = []\n code = nil\n\n # Collect codes\n while code != 200 && bad_codes.include?(code) == false do\n possible_redirect << @entries[counter].response.status\n \n puts @entries[counter].response.status\n code = @entries[counter].response.status\n counter = counter + 1\n end\n\n # 301 Wrong Scenario test\n if(@url.include? \"maxRedirect=true\")\n if(possible_redirect.include?(301))\n # begin\n # campaign = @browser.evaluate_script(\"omnCampaignID\")\n # rescue\n # campaign = @browser.evaluate_script(\"app.omniMap.CampaignID\")\n # end\n\n # if campaign.downcase.include?(\"core\") == false\n passed == false\n # end\n end\n end\n\n possible_redirect.each do |code_to_check|\n if bad_codes.include?(code_to_check)\n passed == false\n end\n end\n\n\n return {result: passed, codes: possible_redirect}\n end", "def get_url(url)\n url = URI.parse(URI.escape(url))\n res = Net::HTTP.get_response(url)\n return res\nend", "def goto_url(url)\n response = Net::HTTP.get_response(URI.parse(url))\n status = response.code.to_i\n \n if status >= 300 and status < 400\n url = response['Location']\n # TODO - put general url beggining instead\n url = \"http://magiccards.info\" + url unless url.start_with?('http://')\n goto_url(url)\n else\n return url, response.body\n end\n end", "def response\n @response ||= Net::HTTP.new(uri.host).request(request)\n end", "def http_get(url)\n response = client.get(url, follow_redirect: true)\n\n raise HTTPClient::BadResponseError, response.reason unless HTTP::Status.successful?(response.status)\n\n response\n end", "def get_response_body\n uri = URI.parse(@url) #parse the url being passed in with 'URI.parse'\n response = Net::HTTP.get_response(uri) # 'GET' the response of the uri with 'Net::HTTP.get_resonse' and pass in the uri variable\n response.body #return the 'body' from the 'response' variable\n end", "def get_response_body\n uri = URI.parse(@url)\n response = Net::HTTP.get_response(uri)\n response.body\n end" ]
[ "0.7163484", "0.70454776", "0.7043237", "0.7037283", "0.6894828", "0.6820514", "0.6820514", "0.6786093", "0.67844546", "0.67166764", "0.67166764", "0.6669712", "0.6669712", "0.6665687", "0.66245437", "0.66215193", "0.66007584", "0.6472299", "0.64491177", "0.6439345", "0.6436848", "0.6431458", "0.6427762", "0.6422832", "0.63880926", "0.6377807", "0.6360013", "0.63278306", "0.63254577", "0.62852323", "0.6277869", "0.62700915", "0.62539226", "0.62488544", "0.62419164", "0.6194243", "0.6176305", "0.61623085", "0.615679", "0.61242956", "0.6122336", "0.6097818", "0.6024911", "0.60143167", "0.601405", "0.60127467", "0.6003065", "0.59839195", "0.5968429", "0.596689", "0.5950462", "0.5946943", "0.59258103", "0.5924487", "0.59206665", "0.58862114", "0.58850545", "0.5883983", "0.5880663", "0.58539677", "0.58462596", "0.58462596", "0.5844698", "0.58302784", "0.58271956", "0.5800511", "0.5792796", "0.57875454", "0.57299453", "0.5729793", "0.57216257", "0.57213444", "0.57208836", "0.5718699", "0.5718651", "0.57139176", "0.567393", "0.56723833", "0.56712097", "0.56659025", "0.5665697", "0.56611764", "0.56549156", "0.56527656", "0.5646514", "0.5640478", "0.56115186", "0.558679", "0.55754465", "0.5568486", "0.5568131", "0.55588186", "0.55581266", "0.5545242", "0.5540339", "0.55297095", "0.552721", "0.55229396", "0.5511491", "0.54936093" ]
0.86533403
0
Get DSpace information (version, uitype, etc) from a given URL / parsed HTML page. This method takes in the output of url_response() and attempts to determine if this is a DSpace site or not. Parameters: url = URL of the (supposed) DSpace site parsed_page = HTML Response parsed by Nokogiri Returns the following: 1. DSpace Version info (or "UNKNOWN") 2. DSpace UI type (or "UNKNOWN")
def dspace_info(url, parsed_page) #------------------------- # Get DSpace Version Info #------------------------- # Check the parsed page's <meta name="Generator"> tag value) # This is the DSpace Version info # NOTE: The following is a case insensitive XPATH search for <meta name="generator"> # returning the value of the "content" attribute. generator = parsed_page.xpath("//meta[translate( @name, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz' ) = 'generator' ]/@content").to_s # If generator with @content found, then this is the DSpace Version. # Otherwise, version is "UNKNOWN" (or possibly < 1.6.0 when this <meta> tag was added) version = (generator and !generator.empty?) ? generator : "UNKNOWN (possibly < 1.6.0)" #------------------------- # Get DSpace UI Type #------------------------- # Quick check. Does this URL include either "jspui" or "xmlui". # If so, let's trust the URL path is accurate if url.to_s.match(/\bjspui\b/i) ui_type = "JSPUI" elsif url.to_s.match(/\bxmlui\b/i) ui_type = "XMLUI" end # If URL match didn't work, we'll have to parse to determine UI type if ui_type.nil? or ui_type.empty? # To determine XML vs JSPUI we need to send a second request # Append "?XML" or "&XML" on original URL path to check if this is XMLUI xml_url = url.to_s.include?("?") ? url.to_s + "&XML" : url.to_s + "?XML" begin xml_url,response,parsed_xml_page = url_response(xml_url) rescue => e response = nil response_error = e end # If second response was successful if !response.nil? if response.kind_of?(Net::HTTPSuccess) # Try to parse this result as XML xml = Nokogiri::XML(response.body) # If the result is an XML document with a <document> root node, # Then this is definitely the XMLUI. if xml.root and xml.root.name == "document" ui_type = "XMLUI" # If our parsed version said this was DSpace, and it is NOT XMLUI, then it must be JSPUI elsif(version.include?("DSpace")) ui_type = "JSPUI" # Else if the response body includes the word "mydspace", this is definitely JSPUI elsif(response.body.match(/\bmydspace\b/i)) ui_type = "JSPUI" # Else if the response body includes the word "htmlmap", this is definitely JSPUI elsif(response.body.match(/\bhtmlmap\b/i)) ui_type = "JSPUI" # Else if none of the above match, but the response body includes the word "dspace" # it's *possibly* JSPUI (but no guarantees) elsif(response.body.match(/\bdspace\b/i)) ui_type = "JSPUI (possibly)" else # Otherwise, this really may not be a DSpace UI ui_type = "UNKNOWN (may not be DSpace)" end else # Else if response returned but not a "SUCCESS" ui_type = "RESPONSE FAILED: (#{response.code} #{response.message})" end else # Else if response was nil ui_type = "RESPONSE ERROR: (#{response_error})" end # End if ?XML response end # End if ui_type empty # Return parsed DSpace info return version, ui_type end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fetchPage(url)\n Nokogiri::HTML(open(url, 'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.152 Safari/535.19').read, nil, 'utf-8')\n end", "def visit_url(url)\n url_link = url\n begin\n linked_page = url_link.click\n rescue Exception => e\n puts \"\\033[37m#{e.inspect}\\033[0m\\n\"\n linked_page = @page\n end\n #initialize vars for return\n server_status_delivery = true\n determined_server = \"determined_server_default\"\n server_status = \"server_status_default\"\n check_for_key = \"page-wrap\"\n determined_server = check_header(linked_page)\n # check if page contain something\n if linked_page.body.include?(check_for_key)\n server_status_delivery = get_status(linked_page)\n else\n raise (\"page of #{linked_page.uri.to_s} do not include #{check_for_key}\")\n end\n server_status = \"#{determined_server}:#{server_status_delivery}\"\n return server_status\n end", "def checkAndOpen(url)\n\tuserAgent = \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36\"\n\tbegin\n\t\topenURLpage = open(url, {'User-Agent' => userAgent})\n\trescue OpenURI::HTTPError => ex\n\t\tFile.open(\"log.txt\",\"a\") do |f|\n\t \t\tf.write(Time.new.utc.to_s + \" OpenURI Error: \" + ex.to_s + \"\\n\")\n\t\tend\n\t\tabort\n\tend\n\t# abort if page size is less than 10KB\n\tif (openURLpage.size * 0.001) < 10\n\t\tFile.open(\"log.txt\",\"a\") do |f|\n\t \t\tf.write(Time.new.utc.to_s + \" Page Size Error: Page size is \" + (openURLpage.size * 0.001).to_s + \"KB\\n\")\n\t\tend\n\t\tabort\n\tend\n\treturn Nokogiri::HTML(openURLpage)\nend", "def get_page_html(url)\n begin\n Nokogiri::HTML(open(url))\n rescue\n puts \"Can't reach the server.\"\n exit 1\n end\n end", "def get_page(url)\n @doc = Nokogiri::HTML(open(url))\n end", "def page_status url\n url = URI.parse(url)\n http = Net::HTTP.new(url.host, url.port)\n if url.scheme.downcase == \"https\"\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n http.use_ssl = true\n end\n http.start do\n http.request_get(url.path.empty? ? \"/\" : url.path) do |res|\n return {:name => res.class, :code => res.code}\n end\n end\n end", "def get_page\n begin\n puts \"@@@@@@@@@@@@@ Visiting: #{@url} from #{@parent_page.address if @parent_page.present?}\"\n require 'nokogiri'\n require 'open-uri'\n @page = Nokogiri::HTML(open(@url))\n @page_title = (title_container = @page.css('title').first) ? title_container.content : \"Title unknown\"\n @links = @page.css(\"a\")\n\n return true\n rescue => exc\n puts \"==Problem with URL #{@url} == #{ exc.message}\"\n return false\n end\n end", "def get_page(url)\n\t\tbegin\n\t\t if not defined? agent\n\t\t \tagent = Mechanize.new\n\t\t end\n\n\t\t return agent.get(url)\n\n\t\trescue Mechanize::ResponseCodeError => e\n\n\t\t # if page couldn't be found, throw an error\n\t\t if e.response_code == \"404\"\n\t\t \traise ArgumentError.new(\n\t\t \t\t\"#{@url} #{NOT_FOUND_ERROR}\"\n\t\t \t\t)\n\t\t else\n\t\t \tthrow\n\t\t end \n\n\t\tend\n\tend", "def url_info(url)\n response = handle_response(self.class.get(\"/urlinfo.json\", :query => {:url => url}))\n Topsy::UrlInfo.new(response)\n end", "def get_webpage(url)\n uri = URI.parse(url)\n Net::HTTP.get_response(uri)\nend", "def get_page(url)\n @log.info(\"Loading page: #{url}\")\n try_three_times do\n page = @agent.get(url)\n page.encoding = 'utf-8' if page.is_a?(Mechanize::Page)\n return page\n end\n end", "def is_available(page)\n\n # Todo: Return true if the page is available for scraping Development Applications. Return false otherwise\n\n return !page.nil? \n\nend", "def is_available(page)\n\n # Todo: Return true if the page is available for scraping Development Applications. Return false otherwise\n\n return !page.nil? \n\nend", "def retrieve_response(url)\n response = response(url)\n response = response(url) unless response[:code].present?\n response\n end", "def reachable?(url)\n page = MetaInspector.new(url)\n\n if page.response.status < 400\n true\n else\n false\n end\n rescue\n false\n end", "def extract_description(info_url)\n agent = Mechanize.new\n agent.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n page = agent.get(info_url)\n\n # The horrible thing about this page is they use tables for layout. Well done!\n # Also I think the \"Intended use\" bit looks like the most useful. So, we'll use that for the description\n table = page.at('div#bodypadding table')\n # For some reason occasionaly this page can be entirely blank. If it is just do our best and continue\n if table\n table.search('table')[1].search('tr').find do |row|\n # <th> tag contains the name of the field, <td> tag contains its value\n row.at('th') && row.at('th').inner_text.strip == \"Intended use\"\n end.at('td').inner_text.strip\n end\nend", "def get_page(url, prog_name = self.class)\n begin\n retries ||= 0\n page = Nokogiri::HTML(URI.open(url))\n rescue OpenURI::HTTPError => e\n retry if (retries += 1) < MAX_RETRIES\n logger.error(prog_name) { \"Could not load page '#{url}': #{e.message}\" }\n raise $!\n end\n page\n end", "def is_available(page)\n # Todo: Return true if the page is available for scraping Development Applications. Return false otherwise\n return !page.nil? \nend", "def is_available(page)\n # Todo: Return true if the page is available for scraping Development Applications. Return false otherwise\n return !page.nil? \nend", "def loadHTMLFromURL(url)\n begin\n @doc = Nokogiri::HTML(open(url))\n @url = url\n rescue\n Rails.logger.info \"RecipeParser.loadURL: unable to load URL #{url}\"\n return false\n end\n Rails.logger.info \"RecipeParser.loadURL: successfully loaded URL #{url}\"\n return true\n end", "def get_page(url)\n Hpricot.buffer_size = 262144\n Hpricot(open(url, {\"User-Agent\" => \"Mozilla/5.0 Firefox/3.5\"}))\n end", "def check_url_status(url)\n begin\n conn = Faraday.new(:url => url)\n response = conn.get\n rescue Faraday::ConnectionFailed => e\n return \"Unknown. Requires attention.\"\n else\n statusNum = response.status\n puts case statusNum\n when 200\n return \"200: Online\"\n when 201\n return \"201: Created\"\n when 204\n return \"204: No Content\"\n when 301\n return \"301: Moved Permanantly\"\n when 302\n return \"302: Redirecting\"\n when 304\n return \"304: Not Modified\"\n when 400\n return \"400: Bad Request\"\n when 401\n return \"401: Unauthorized\"\n when 403\n return \"403: Access Forbidden\"\n when 404\n return \"404: Not Found\"\n when 409\n return \"409: Conflict\"\n when 500\n return \"500: Internal Server Error\"\n else\n return \"Status code: #{statusNum}\"\n end\n\n end\n end", "def parse_dailydev_page\n start = Time.now\n items = @page.search('.ddinfo')\n if items.any?\n items.each do |item|\n desc = item.search('.foot').empty\n desc = item.inner_text.strip\n link_el = item.search('a').select { |item| /\\/deviation\\// === item.attributes['href'] }.first\n link = link_el.attributes['href']\n title = link_el.inner_text\n @daily_data << { :title => title, :desc => desc, :link => link }\n end\n end\n Time.now - start\n end", "def parse(url)\n retailer = url.split('/')[2]\n agent = Mechanize.new\n agent.user_agent_alias = 'Windows Mozilla'\n begin\n agent.get(url) do |page|\n images = []\n # try Open Graph first\n images << page.search(\"//meta[@property='#{OPEN_GRAPH[:image]}']/@content\").map(&:value)\n name = page.search(\"//meta[@property='#{OPEN_GRAPH[:name]}']/@content\")\n description = page.search(\"//meta[@property='#{OPEN_GRAPH[:description]}']/@content\")\n\n images += page.search(\"link[@rel='image_src']/@href\").map(&:value)\n images = page.image_urls if images.flatten!.empty? rescue nil # can't get images from Amazon for some reason\n\n price = get_price(page, retailer)\n name = get_name(page, retailer) if name.blank?\n name = page.search(\"//meta[@itemprop='name']/@content\") if name.blank?\n name = page.search(\"//meta[@name='title']/@content\") if name.blank?\n\n name = name.to_s.gsub(/Amazon.com:/, '') if name\n\n brand = get_brand(page, retailer)\n\n # strip brand off item name prefix and remove slash anything else\n name = name.to_s.gsub(brand.to_s, '').gsub(/^\\s*/,'').gsub(/\\|.*/,'')\n\n return { brand: brand.to_s, retailer: url.split('/')[2], name: name.to_s, price: price.to_s.to_d, images: images, description: description.to_s, url: url.to_s }\n end\n rescue => ex\n Rails.logger.error ex.message\n Rails.logger.error ex.backtrace\n \"Error: #{ex.message}\"\n return { brand: 'invalid URL', retailer: url.split('/')[2], name: 'invalid URL', price: '', images: nil, description: '', url: 'invalid URL' }\n end\n end", "def process_url(url)\n begin\n parsed = URI.parse(url)\n rescue => e\n return [FALSE,:url_parse,[e.to_s]]\n end\n\n robots = get_robots(parsed)\n meta = get_meta(parsed)\n\n if robots.nil?\n return [@options[:on_unknown],[make_error_str(:get_robots,url)]]\n end\n\n errors = []\n error = false\n result = []\n if @options[:mode] == :index\n if !meta.nil? && !meta_allows_indexing(meta,url)\n errors << make_error_str(:meta_disallows_indexing,url)\n error = true\n end\n\n unless robots_allow_indexing(robots,url)\n errors << make_error_str(:robots_disallow_indexing,url)\n error = true\n end\n elsif @options[:mode] == :noindex\n if !meta.nil? && meta_allows_indexing(meta,url)\n errors << make_error_str(:meta_allows_indexing,url)\n error = true\n end\n\n if robots_allow_indexing(robots,url)\n errors << make_error_str(:robots_allow_indexing,url)\n error = true\n end\n end\n\n result = error ? [:critical,errors] : [:ok]\n return result\n end", "def fetch_from_url(url)\n codes = extract_codes(url)\n\n return false if codes.none?\n fetch_from_code(codes.last)\n end", "def is_site?(url)\n\t\tputs \"Validate the website string format for: #{url}\" if @verbose\n\t\tbegin\n\t\t\turl=url.strip.downcase\n\t\t\tif is_url?(url)\n\t\t\t\tif url == url_2_site(url)\n\t\t\t\t\treturn true\n\t\t\t\telse\n\t\t\t\t\treturn false\n\t\t\t\tend\t\t\t\n\t\t\telse\n\t\t\t\tputs \"Unknown site format: #{url}\" if @verbose\n\t\t\t\treturn false\n\t\t\tend\n\t\trescue => ee\n\t\t\tputs \"Exception on method #{__method__}: #{ee}\" if @verbose\n\t\t\treturn nil\n\t\tend\n\tend", "def process_url(url)\n begin\n\n # the following scans\n url_kind_normalized = is_valid_url(url, nil)\n url_kind = url_kind_normalized[0]\n url = url_kind_normalized[1] ## normalized i.e. canonical format\n\n unless [:ref_static_content, :not_valid_url].include?(url_kind)\n if ::Crawl::Db::SiteMap.internal_links[url] || ::Crawl::Db::SiteMap.non_internal_links[url] || should_skip(url)\n # already scanned, we could bump the count if needed\n # if skip just skip!\n else\n # scan it and all its nested pages\n navigate_to_url_and_validate_that_url_was_found( url )\n page_content = browser.html\n @@page_scanner.scan_content(page_content, url)\n end\n end\n\n rescue StandardError => err\n puts \"Err: on url #{url} received: #{err}\"\n end\n\n end", "def get_page_from_url(url)\n site.pages.each do |page|\n if page.url == url then\n return page\n end\n end\n end", "def use(url)\n begin\n Nokogiri::HTML(open(url))\n return true\n rescue => exp\n return false\n end\n end", "def fetch_page\n Varnisher.log.info \"Looking for external resources on #{@url}...\"\n\n begin\n @html = Net::HTTP.get_response(@uri).body\n rescue\n Varnisher.log.info \"Hmm, I couldn't fetch that URL. Sure it's right?\\n\"\n return\n end\n end", "def url_accessibility(url)\n open(url).status.last == 'OK'\n rescue ::SocketError, Timeout::Error, Errno::ECONNREFUSED, OpenURI::HTTPError\n false\n end", "def get_doc(url)\n # open-uri options\n options = {}\n if $certs\n options = {http_basic_authentication: $certs}\n end\n options[:redirect] = false;\n\n # URI object\n uri = resolve_as_uri(url)\n\n # open-uri\n charset = nil\n begin\n html = open(uri, options) do |f|\n charset = f.charset\n f.read\n end\n rescue OpenURI::HTTPRedirect => redirect\n dir(\"Redirection to other host\") if uri.host != redirect.uri.host\n uri = redirect.uri\n retry\n end\n\n # parse\n return Nokogiri::HTML.parse(html, nil, charset)\nend", "def fetch_from_url url\n require \"net/http\"\n\n uri = URI.parse(url)\n\n http = Net::HTTP.new(uri.host, uri.port)\n request = Net::HTTP::Get.new(uri.request_uri)\n\n request['User-Agent'] = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36 OPR/36.0.2130.46'\n \n response = http.request(request)\n \n return response.body # => The body (HTML, XML, blob, whatever)\n end", "def scrub_fetch(url)\n begin\n Rails.logger.debug \"fetching raw html from #{url}\"\n Scrub.fetch_html(url)\n rescue SocketError\n Rails.logger.debug \"host unavailable\"\n self.errors.add(:base, \"couldn't resolve host name\")\n return false\n rescue\n Rails.logger.debug \"content unavailable\"\n self.errors.add(:base, \"error retrieving content\")\n return false\n end\n end", "def examine(klass, path, url)\n polish! url unless url.start_with? \"http://\"\n diff_page(Nokogiri::HTML(open(url)), parse_class(klass, path))\n declare_success\n end", "def check_package (url)\n Net::HTTP.start('dl.iuscommunity.org') do |http|\n http.open_timeout = 2\n http.read_timeout = 2\n http.head(url).code == '200'\n end\nend", "def document\n @document ||= open(@url).read\n\n rescue SocketError\n warn 'MetaInspector exception: The url provided does not exist or is temporarily unavailable (socket error)'\n @scraped = false\n rescue TimeoutError\n warn 'Timeout!!!'\n @scraped = false\n rescue Exception => e\n warn 'An exception occurred while trying to fetch the page!'\n warn e.message\n @scraped = false\n end", "def get_page(url)\n # If Nokogiri can't get the url stop the execution\n # and return a message to client\n begin\n Nokogiri::HTML(open(params[:url]))\n rescue => exception\n return render json: {errors: exception.message}, status: 422\n end\n end", "def cdn_url?(url)\n return false unless url =~ %r{^https?:\\/\\/}\n\n uri_options = {}\n\n netrc_info = Netrc.read\n uri = URI.parse(url)\n return false unless uri.userinfo.nil?\n\n netrc_host = uri.host\n credentials = netrc_info[netrc_host]\n uri_options[:http_basic_authentication] = credentials if credentials\n\n response = OpenURI.open_uri(url.chomp('/') + '/CocoaPods-version.yml', uri_options)\n response_hash = YAML.load(response.read) # rubocop:disable Security/YAMLLoad\n response_hash.is_a?(Hash) && !Source::Metadata.new(response_hash).latest_cocoapods_version.nil?\n rescue Psych::SyntaxError, ::OpenURI::HTTPError, SocketError\n return false\n rescue => e\n raise Informative, \"Couldn't determine repo type for URL: `#{url}`: #{e}\"\n end", "def get_xml(url, options = {})\n\t\t\tresponse = get_file(url, options)\n\t\t\tdoc = Hpricot.XML(response)\n\t\t\terrors = doc.search(\"*[@errCode]\")\n\t\t\tif errors.size > 0\n\t\t\t\terrors.each do |error|\n\t\t\t\t\traise Wowr::Exceptions::raise_me(error[:errCode], options)\n\t\t\t\tend\n\n elsif (doc%'achievements')\n\t\t\t return doc\n\t\t\telsif (doc%'dungeons')\n\t\t\t\treturn doc\n\t\t\telsif (doc%'page').nil?\n\t\t\t\traise Wowr::Exceptions::EmptyPage\n\t\t\telse\n\t\t\t\treturn (doc%'page')\n\t\t\tend\n\t\tend", "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 get_page()\n @page = Nokogiri::HTML(open(@url).read)\n end", "def get_single_url(url)\n\n useragent = \"NotubeMiniCrawler/0.1\"\n u = URI.parse url \n req = Net::HTTP::Get.new(u.request_uri,{'User-Agent' => useragent})\n begin \n res2 = Net::HTTP.new(u.host, u.port).start {|http|http.request(req) }\n end\n\n r = \"\"\n begin\n r = res2.body\n rescue OpenURI::HTTPError=>e\n case e.to_s \n when /^404/\n raise 'Not Found'\n when /^304/\n raise 'No Info'\n end\n end\n return r\n end", "def read_page(url)\n download(url, Downloader.cookie).read\n end", "def get_page(url_to_scrap)\n # Ouvre l'URL souhaitée \"url_to_scrap\" sous Nokogiri et la stocke dans l'objet \"page\" qui est retourné si l'URL a pu être trouvée\n # renvoie nil sinon\n page = nil\n if !url_to_scrap.nil? && url_to_scrap.instance_of?(String) && !url_to_scrap.strip.empty?\n puts \"L'URL qui vous intéresse est : \\\"#{url_to_scrap}\\\".\"\n begin\n page = Nokogiri::HTML(URI.open(url_to_scrap))\n rescue OpenURI::HTTPError => e\n if e.message == '404 Not Found'\n puts \"Malheureusement, la page \\\"#{url_to_scrap}\\\" n'a pas été trouvée.\" # handle 404 error\n else\n raise e\n end\n rescue Errno::ENOENT => e\n puts \"Malheureusement, le fichier \\\"#{url_to_scrap}\\\" n'a pas été trouvé.\" # handle \"No such file or directory @ rb_sysopen\" error\n rescue SocketError => e # handle \"Failed to open TCP connection to ... (getaddrinfo: Name or service not known)\" error\n puts \"Malheureusement, l'URL \\\"#{url_to_scrap}\\\" est incorrecte.\" # Le domaine peut ne pas exister (DNS error)\n rescue Errno::ECONNREFUSED => e\n puts \"Malheureusement, il n'y a aucun serveur en cours d'exécution sur l'adresse IP à laquelle vous voulez vous connecter.\"\n end\n end\n page\nend", "def open_website(url)\n page = Nokogiri::HTML(open(url)) \n # page.class # => Nokogiri::HTML::Document\n page\nend", "def response\n @response ||= Nokogiri::HTML(open(url))\n end", "def parse_page(response)\n\t\tNokogiri::HTML(response.body)\n\tend", "def check_for_hits(url)\n \n response = http_fetch(url).body\n\n response_html = Nokogiri::HTML(response)\n\n title = response_xml.at('title').inner_text\n # title is \"X documents\" (or 'Documents') if there are hits.\n # It's annoyingly \"Search Error\" if there are either 0 hits, or\n # if there was an actual error. So we can't easily log actual\n # errors, sorry.\n title.downcase =~ /^\\s*(\\d+)?\\s+document/\n if ( hits = $1)\n return hits.to_i\n else\n return 0\n end \n end", "def get_web_document(url)\n uri = URI.parse(url)\n response = Net::HTTP.get_response(uri)\n\n case response \n when Net::HTTPSuccess\n return response.body\n when Net::HTTPRedirection\n return get_web_document(response['Location'])\n else\n return nil\n end\nend", "def validate_url(url, user_agent = nil)\n resp = Pod::HTTP.validate_url(url, user_agent)\n\n if !resp\n warning('url', \"There was a problem validating the URL #{url}.\", true)\n elsif !resp.success?\n note('url', \"The URL (#{url}) is not reachable.\", true)\n end\n\n resp\n end", "def retrieve_page(url)\n begin \n page = Timeout::timeout(5) {$agent.get(url)}\n if page.is_a?(Mechanize::Page)\n return page\n else\n return nil\n end\n rescue\n return nil\n end\nend", "def parse_url\n tags = []\n # scrape data from page\n parser = Scrapping::Parser.new(url)\n unless parser.error\n # parse h1 from doc\n tags << parser.content_by_tag(parser.doc,'h1')\n\n # parse h2 from doc\n tags << parser.content_by_tag(parser.doc,'h2')\n\n # parse h3 from doc\n tags << parser.content_by_tag(parser.doc,'h3')\n\n # parase url of links from doc\n tags << parser.content_by_tag(parser.doc,'a')\n\n # make a single flatten array of tags\n tags = tags.flatten\n # create tags\n self.tags << Tag.create(tags)\n # return json response\n response = {error: false,message: \"Page content is parsed.\",status: 200}\n else\n response = {error: true,message: parser.message,status: 400}\n end\n end", "def find_page(url)\n found = Page.find_by_url(url)\n found if found #and (found.published?)\n end", "def get_page(target_url)\n response = @version.domain.request(\n 'GET',\n target_url\n )\n DomainPage.new(@version, response, @solution)\n end", "def noko_doc(url)\n begin\n Nokogiri::HTML(open(url).read)\n rescue OpenURI::HTTPError => msg\n raise PageNotFoundError.new(\"Page not found - #{url}\")\n end\n end", "def fetch(url)\n response = Curl::Easy.http_get(url)\n results = parse_seo(response.body_str)\n results.update({\n :url => url,\n :robots => extract_robots(url),\n :headers => response.headers,\n :cookies => response.cookies,\n :size => response.downloaded_bytes,\n :speed => response.download_speed })\n end", "def url_2_site (url)\n\t\tputs \"Retrieve the web site base for url: #{url}\" if @verbose\n\t\tbegin\n\t\t\turl = url.downcase\n\t\t\turl = url.sub(/^(.*?)http/i,'http')\n\t\t\tentry = url.split(%r{\\/\\/})\n\t\t\tprot=entry[0]\n\t\t\t# step 1, extract the host:port pair from the url\n\t\t\thost_port=entry[1].split(%r{\\/})[0]\n\t\t\tif host_port =~ /\\:/\n\t\t\t\thost=host_port.split(%r{\\:})[0]\n\t\t\t\tport=host_port.split(%r{\\:})[1].to_i\n\t\t\telsif prot =~ /https/i\n\t\t\t\thost=host_port\n\t\t\t\tport=443\n\t\t\telsif prot =~ /http/i\n\t\t\t\thost=host_port\n\t\t\t\tport=80\n\t\t\telse\n\t\t\t\thost=host_port\n\t\t\t\t#raise \"Unknown url format: #{url}\"\n\t\t\tend\n\t\t\t# additional logic to handle uncommon url base structures\n\t\t\tunless is_fqdn?(host)\n\t\t\t\tcase host\n\t\t\t\t\t# \"https://letmechoose.barclays.co.uk?source=btorganic/\" => \"https://letmechoose.barclays.co.uk\"\n\t\t\t\t\twhen /\\?|\\#/\t\n\t\t\t\t\t\thost=host.split(%r{\\?|\\#})[0]\n\t\t\t\t\telse\n\t\t\t\t\t\t#do nothing\n\t\t\t\tend\n\t\t\tend\n\t\t\t# step 2, put the host:port pair back to the normal site format \n\t\t\tprot=\"https:\" if port==443\n\t\t\tif port==80 || port==443\n\t\t\t\tsite=prot+\"//\"+host+\"/\"\n\t\t\telse\n\t\t\t\tsite=prot+\"//\"+host+\":\"+port.to_s+\"/\"\n\t\t\tend\n\t\t\tif site=~ /http/i\n\t\t\t\t#puts \"Base found: #{site}\" if @verbose\n\t\t\t\treturn site\n\t\t\telse\t\n\t\t\t\traise \"Problem encountered on method url_2_site: Unable to convert #{url}\"\n\t\t\t\treturn nil\n\t\t\tend\n\t\trescue => ee\n\t\t\tputs \"Exception on method #{__method__}: #{ee}\" if @verbose\n\t\t\treturn nil\n\t\tend\n\tend", "def load_page(url)\n retries_count = 0\n # For use URLs with TH symbols.\n url = URI.encode(url)\n begin\n retries_count += 1\n @browser.visit url\n rescue Exception => error\n display_error \"\\e[34;1m#{error.class} < #{error.class.superclass.name}\\e[0m \\e[31;1m#{error.message}\\e[0m\"\n Rollbar.error(error, 'Parser#load_page', {url: url})\n\n if retries_count < 3\n display_error \"##{__method__} failed for \\e[34;1m#{url}\\e[0m\"\n display_info \"Retry request \\e[33;1m#{retries_count}\\e[0m time...\"\n retry\n else\n display_error \"All attempts are exhausted! Failed to load \\e[34;1m#{url}\\e[0m\"\n @browser = nil\n end\n end\n end", "def get_info\n doc = Hpricot(open(noaa_url))\n puts noaa_url\n if !self.description\n doc.search(\"h1\").each do |elem| \n desc = elem.inner_html\n # remove imbeded links in the middle of the description\n desc.gsub!(/\\<a.href.*?\\<\\/a\\>/,' ')\n self.description = desc\n puts self.description\n self.save\n end\n end\n if !self.geo_location\n begin\n elems = doc.search(\"p/b\").to_a.map{|elm| elm.inner_html}\n if elems[1] == \"Owned and maintained by National Data Buoy Center\"\n puts elems[4]\n self.geo_location = elems[4]\n self.save\n end\n rescue\n end \n end\n end", "def get_meta(url)\n\n unless url.is_a? URI\n error \"{url} (instance of #{url.class}) is not an URI instance!\"\n return nil\n end\n\n begin\n body = Net::HTTP.get(url.host,url.request_uri)\n return nil unless body\n rescue => e\n error \"Failed to request url: #{url} : #{e}\"\n return nil\n end\n\n robots_arr = nil\n\n begin\n doc = Nokogiri::HTML(body)\n tags = doc.xpath(META_ROBOTS_TAG_SELECTOR)\n\n return nil if tags.nil? || tags.length == 0\n\n tag = tags.pop\n robots = tag[\"content\"]\n\n return nil unless robots\n\n robots_arr = robots.gsub(/\\s/,'').split(',')\n rescue => e\n error \"Failed to get meta for #{url} : #{e}\"\n return nil\n end\n\n # return lowercase values\n return robots_arr.map {|val| val.downcase}\n end", "def url_info(url,\r\n fetch_content = false,\r\n ignore_certificate_errors = false,\r\n timeout = 20)\r\n # Prepare query url.\r\n _path_url = '/url-info'\r\n _query_builder = Configuration.get_base_uri\r\n _query_builder << _path_url\r\n _query_url = APIHelper.clean_url _query_builder\r\n # Prepare headers.\r\n _headers = {\r\n 'accept' => 'application/json'\r\n }\r\n\r\n # Prepare form parameters.\r\n _parameters = {\r\n 'output-case' => 'camel',\r\n 'url' => url,\r\n 'fetch-content' => fetch_content,\r\n 'ignore-certificate-errors' => ignore_certificate_errors,\r\n 'timeout' => timeout\r\n }\r\n _parameters = APIHelper.form_encode_parameters(_parameters)\r\n # Prepare and execute HttpRequest.\r\n _request = @http_client.post(\r\n _query_url,\r\n headers: _headers,\r\n parameters: _parameters\r\n )\r\n CustomQueryAuth.apply(_request)\r\n _context = execute_request(_request)\r\n validate_response(_context)\r\n # Return appropriate response type.\r\n decoded = APIHelper.json_deserialize(_context.response.raw_body)\r\n URLInfoResponse.from_hash(decoded)\r\n end", "def parse(url, proxies: nil, debug: false)\n p = fetch(url, proxies: proxies, debug: debug)\n p.status.to_i==200 ? Nokogiri::HTML(p.body_str.force_encoding('windows-1251').encode('utf-8')) : raise(NotFound)\n end", "def online?\n Browser.get(url).code != 0\n end", "def get_doc(url)\n page = MetaInspector.new(url)\n doc = page.document\n\n raise page.errors[0] if !page.ok?\n\n doc\n end", "def stat_by_url(url, userdics: nil)\n stat_by_web(url, userdics: userdics)\n end", "def ping_url(url)\n begin\n Net::HTTP.get(URI.parse(url))\n return true\n rescue\n return false\n end\n end", "def get_page(target_url)\n response = @version.domain.request(\n 'GET',\n target_url\n )\n SimPage.new(@version, response, @solution)\n end", "def retrieve_page\n return nil unless url\n spurl = url.gsub(/^http:/, \"https:\")\n spurl << (spurl.include?(\"?\") ? \"&\" : \"?\")\n spurl << \"pagewanted=all\"\n p = super(spurl)\n\n # If it fails, reset the session and try one more time\n unless retreive_successful?(p)\n self.class.retrieve_session ||= WebPageParser::HTTP::Session.new\n p = super(spurl)\n end\n if retreive_successful?(p)\n p\n else\n raise RetrieveError, \"Blocked by NYT paywall\"\n end\n end", "def get_url_data(url)\n Nokogiri::HTML(open(url))\n end", "def get_page(target_url)\n response = @version.domain.request(\n 'GET',\n target_url\n )\n ServicePage.new(@version, response, @solution)\n end", "def get_page(target_url)\n response = @version.domain.request(\n 'GET',\n target_url\n )\n ServicePage.new(@version, response, @solution)\n end", "def retrieve_url(url)\n uri = URI::parse(url)\n http = Net::HTTP.new(uri.host, uri.port).start\n res = http.get(url,HEADERS)\n http.finish\n return res\n rescue Timeout::Error\n return false\n end", "def get_metadata(url, timeout = 5)\n stripped_url = url.strip\n\n # If there is an error, we just return nil\n begin\n if doc = Nokogiri::HTML(open(stripped_url, {\"User-Agent\" => DEFAULT_USER_AGENT, :read_timeout => 10}))\n metadata = {}\n metadata[:url] = stripped_url\n metadata[:title] = title(doc)\n metadata[:description] = description(doc)\n metadata[:canonical_url] = canonical_url(doc)\n metadata[:language] = language(doc)\n metadata\n end\n rescue\n nil\n end\n end", "def get_response(url)\n logger.debug \"GET (response) #{url}\"\n uri = normalize_url(url)\n\n req = Net::HTTP::Get.new(uri.request_uri)\n http = authenticate_request(uri, req)\n response = nil\n http.request(req) do |res|\n logger.debug \"GOT (#{res.code}) #{url}\"\n response = res\n end\n response\n end", "def get_url_data(url)\n Nokogiri::HTML(open(url))\n end", "def get_site_status(site_url)\n req_start = Time.now\n get_response = HttpHelper.get(site_url)\n if get_response != '-1'\n req_duration = Time.now - req_start\n Rails.logger.info \"STATUS: #{get_response.code} :: response time - #{req_duration}\"\n if req_duration > 4.0\n payload = { \"text\": \"Thredup.com load time exceeded threshold - #{req_duration} sec\" }\n request_hash = {:url => Tokenz.get_channel_url('testing'), :payload => payload}\n HttpHelper.post(request_hash)\n end\n return get_response.code.to_s\n end\n return '-1'\n end", "def is_site_compatible?(site_link, display)\n site = get_site(site_link)\n if site == nil\n puts 'Data error '.red + '(invalid website) :' + ' the website ' + site_link.yellow + ' is unmanaged' if display\n end\n site\n end", "def get_xml(url, options = {})\n\t\t\t\n\t\t\t# better way of doing this?\n\t\t\t# Map custom keys to the HTTP request values\n\t\t\treqs = {\n\t\t\t\t:character_name => 'n',\n\t\t\t\t:realm => 'r',\n\t\t\t\t:search => 'searchQuery',\n\t\t\t\t:type => 'searchType',\n\t\t\t\t:guild_name => 'n',\n\t\t\t\t:item_id => 'i',\n\t\t\t\t:team_size => 'ts',\n\t\t\t\t:team_name => 't',\n\t\t\t\t:group => 'group'\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\tparams = []\n\t\t\toptions.each do |key, value|\n\t\t\t\tparams << \"#{reqs[key]}=#{u(value)}\" if reqs[key]\n\t\t\tend\n\t\t\t\n\t\t\tquery = '?' + params.join('&') if params.size > 0\n\t\t\t\n\t\t\tbase = self.base_url(options[:locale], options)\n\t\t\tfull_query = base + url + query\n\t\t\t\n\t\t\tputs full_query if options[:debug]\n\t\t\t\n\t\t\tif options[:caching]\n\t\t\t\tresponse = get_cache(full_query, options)\n\t\t\telse\n\t\t\t\tresponse = http_request(full_query, options)\n\t\t\tend\n\t\t\t\t\t\t\n\t\t\tdoc = Hpricot.XML(response)\n\t\t\terrors = doc.search(\"*[@errCode]\")\n\t\t\tif errors.size > 0\nbegin\n\t\t\t\terrors.each do |error|\n\t\t\t\t\traise Wowr::Exceptions::raise_me(error[:errCode], options)\n\t\t\t\tend\nrescue\nend\n\t\t\telsif (doc%'page').nil?\n\t\t\t\traise Wowr::Exceptions::EmptyPage\n\t\t\telse\n\t\t\t\treturn (doc%'page')\n\t\t\tend\n\t\tend", "def processRoster url\n\tunparse_page = HTTParty.get(url)\n\tparse_page = Nokogiri::HTML(unparse_page)\n\n\th = height parse_page\n\t#puts h.length\n\tn = names parse_page\n\t#puts n.length\n\theightInInches = feetToInches(h)\n\tif heightInInches.inject(0){|sum,x| sum +x} != 0 \n\t\t\n\t\t\n\n\t\tdisplayNameHeight h,heightInInches,n\n\t\n\t\taverageHeight = average(heightInInches)\n\t\tputs \"\\nAverage height in inches is: #{averageHeight}\"\n\n\t\tfeet = averageHeight/12\n\t\tnum = averageHeight - feet.to_i * 12\n\t\tputs \"Average height in feet is: #{feet.to_i}\\' #{num}\\\"\"\n\telse\n\t\tputs \"No available height data for this sport.\"\n\tend\nend", "def probe(url)\n # @todo Create args options Hash to dynamically configure settings.\n raise ArgumentError.new, \"Incorrect number of arguments: expected 1.\" if url.nil? \n\n # Associate argument with @uri element tag for future logging purposes.\n # Will also serve for faster clash checking (aka w/o DBMS)\n url = URI.parse(url)\n @uri = url\n\n #Create NET::HTTP request to the specified IP\n http = Net::HTTP.new(url.host, url.port)\n http.read_timeout, http.open_timeout = 3\n \n request = Net::HTTP::Get.new(url)\n request['User-Agent'] = \"Gerridae Gem\"\n request['Accept'] = \"*/*\"\n \n # Gather response, switch code to string, add it to content hash.\n response = http.request(request)\n code = response.code.to_s \n @content[:return_code] = code\n\n\n # todo Abstract to own method within Helpers module.\n if Helpers::is_good_http_response? code.to_i \n @content = { :http_version => response.http_version, :message => response.message }\n\n # @todo Use JSON parsing method here\n response.each do |key, value|\n @content[key.to_sym] = value unless key.nil? && value.nil? \n end\n #todo Return HTTP code to indicate success.\n end\n #todo Return nil or other failure indicator for failure.\n\n end", "def parse_html\n scraped_content = Nokogiri::HTML(open(@url).read)\n raise WrongIDforURL if scraped_content.text == 'No such item.'\n return scraped_content\n end", "def url_exist?\n\t\tbegin\n\t\t\turi = URI.parse(valid_url?)\n\t\t\tresponse = Net::HTTP.get_response(uri)\n\t\trescue \n\t\t\terrors.add(:long_url,\"is invalid url\")\n\t\t\t# in AR, error is a class by itself already \n\t\t\t# go to static.rb to check the errors\n\t\tend\n\tend", "def fetch_url(url = '',sleep_time = 0)\n state = \"total\";\n\n if (url == '') then url=@url; end\n\n b = Watir::Browser.new :chrome\n \n # b.goto('worldometers.info')\n # b.cookies.add 'foo', 'bar', path: '/', expires: (Time.now + 10000), secure: true\n \n b.goto(url)\n\n if (sleep_time > 0) then sleep sleep_time end\n \n doc = Nokogiri::HTML.parse(b.html())\n b.close();\n\n ts = DateTime.now();\n\n server = url.split('/')[2];\n if (server == \"web.archive.org\") then\n #------------------------------------------------------------------------------\n # redefine output file name based on the time, encoded in the snapshot name\n #------------------------------------------------------------------------------\n time = url.split('/')[4];\n year = time[ 0,4].to_i\n mon = time[ 4,2].to_i\n day = time[ 6,2].to_i\n hour = time[ 8,2].to_i\n min = time[10,2].to_i\n sec = time[12,2].to_i\n ts = DateTime.new(year,mon,day,hour,min,sec,'+00:00');\n end\n\n output_fn = @output_dir+'/html/'+ts.strftime()+'_'+@country+'_'+state+'.html';\n f = File.open(output_fn,\"w\");\n\n f.puts(doc);\n f.close();\n \n return ;\n end", "def _get_html_page url:\n HTTParty.get(url).body\n rescue => e\n add_error __method__.to_sym, :failed, e.message\n raise ServiceError, e\n end", "def goto_url(url)\n response = Net::HTTP.get_response(URI.parse(url))\n status = response.code.to_i\n \n if status >= 300 and status < 400\n url = response['Location']\n # TODO - put general url beggining instead\n url = \"http://magiccards.info\" + url unless url.start_with?('http://')\n goto_url(url)\n else\n return url, response.body\n end\n end", "def getCompanyInfo(url)\n\tdoc = Nokogiri::HTML(open(url))\n\tarticle = doc.css('article.company_detail')\n\n\t# top details\n\n\ttopDiv = article.css('div.top_company_detail')\n\n\tnameDiv = topDiv.css('div.com_name')\n\tname = nameDiv.css('h2').text\n\tsubName = nameDiv.css('p').text\n\tlogo = nameDiv.css('a img').first['src']\n\taddress = topDiv.css('div.row.com_address p span').text\n\tputs name, subName, logo, address\n\n\ta = topDiv.css('div.com_social a').first\n\tif a != nil\n\t\tfacebook = a['href']\n\t\tputs facebook\n\tend\n\n\tinfoDiv = topDiv.css('div.row.com_info div').first\n\telements = infoDiv.elements\n\ti = 0\n\twhile i < elements.length do\n\t\tlbl = elements[i].css('label').text.strip\n\t\tcase lbl\n\t\twhen \"Telephone :\", \"Fax :\"\n\t\t\tdata = elements[i=i+1]\n\t\t\tdata = data.css('> text()').text.strip + data['data-last'].strip\n\t\twhen \"Email :\"\n\t\t\tdataCfEmail = elements[i].css('span.__cf_email__').first['data-cfemail']\n\t\t\tdata = getEmail(dataCfEmail)\n\t\twhen \"Website:\"\n\t\t\tdata = elements[i].css('a').text\n\t\twhen \"Catalogue Link :\"\n\t\t\tdata = elements[i].css('a.com_catelogue').first['href']\n\t\telse\n\t\t\tSTDERR.puts \"label: \" + lbl\n\t\tend\n\t\ti += 1\n\t\t\n\t\tputs lbl\n\t\tputs data\n\tend\n\n\tcategories = []\n\telements = topDiv.css('div div.line_share_social p.row.com_cat a')\n\telements.each do |element|\n\t\tcategories.push(element.text)\n\tend\n\tputs 'Categories: ', categories\n\n\ttextNodes = topDiv.css('div div.left.com_description text()')\n\tdescription = textNodes.map {|textNode| textNode.text.strip }.join(\"\\n\")\n\tputs description\n\n\tparagraphs = topDiv.css('div div.com_person_contact p')\n\tparagraphs.each do |paragraph|\n\t\tlbl = paragraph.css('label').text.strip\n\t\tcase lbl\n\t\twhen \"Main Contact :\", \"Designation :\", \"Websites :\", \"Tel :\", \"Payment Method :\", \"Market Coverage :\", \"Opening hours :\", \"Staff Strength :\", \"Year Established :\"\n\t\t\ttextNodes = paragraph.css('span text()')\n\t\t\tdata = textNodes.map {|textNode| textNode.text.strip }.join(\"\\n\")\n\t\twhen \"Email :\"\n\t\t\tdataCfEmail = paragraph.css('a.__cf_email__').first['data-cfemail']\n\t\t\tdata = getEmail(dataCfEmail)\n\t\telse\n\t\t\tSTDERR.puts \"label: \" + lbl\n\t\tend\n\t\tputs lbl, data\n\tend\n\n\t# middle details\n\n\tmiddleDiv = article.css('div.company_detail_middle')\n\n\tproducts = middleDiv.css('#product div a').map {|a| a['title']}\n\tputs 'Products: ', products\n\n\tdisplayAd = middleDiv.css('#iframeDisplayAd').first['src']\n\tputs displayAd\n\n\tiframe = middleDiv.css('#catalogue div.company_tab_content iframe').first\n\tif iframe != nil\n\t\tcatalogue = iframe['src']\n\t\tputs catalogue\n\tend\n\n\t# listingName = middleDiv.css('#comp_detail_all_listing p').text\n\t# middleDiv.css('#comp_detail_all_listing div').each do|listingDiv| {\n\t# \tdivs = listingDiv.css('div div')\n\t# }\nend", "def http_get_direct(url)\n log(\"http get : #{url}\") if $opt[\"debug\"]\n begin\n html = Net::HTTP.get_response(URI.parse(url)).body\n # XXX must fix the rescue its not working\n rescue => err\n log(\"Error: #{err}\")\n exit 2\n end\n html\nend", "def url_obj (url)\n url_1 = HTTParty.get(url)\n return Nokogiri::HTML(url_1)\nend", "def retrieve(url)\n Hpricot(Net::HTTP.get(URI.parse(url)))\n end", "def retrieve_content(url)\n begin\n m = Mechanize.new { |agent|\n agent.user_agent_alias = 'Mac Safari'\n }\n page = m.get(url) \n rescue => e \n puts \"[Error] retrieving #{url} \"\n puts e.message\n puts e.backtrace\n # $ACCUMULATED_DELAY += 1\n #puts \"[WARNING] Compulsory put programme into sleep due to page retrieval error. Back to work in #{$ACCUMULATED_DELAY} minute(s)\"\n # sleep $ACCUMULATED_DELAY\n \n # just return an empty Mechanize::Page\n page = nil\n ensure\n #$TOTAL_PAGE_REQUEST += 1\n #puts page.inspect\n #puts page.content\n return page\n end\nend", "def get_response url, format\r\n begin\r\n response = Net::HTTP.get_response(URI.parse(url))\r\n if format.to_sym == :json\r\n res = JSON.parse response.body\r\n else\r\n res = response.body\r\n end\r\n rescue Exception => e\r\n res = \"ERROR: There is a problem while fetching data, please check whether OpenTSDB is running or not.\"\r\n end\r\n res\r\n end", "def get_web_info_from_link(data, display)\n unless data[:link].start_with?('http://', 'https://')\n data[:link] = 'http://' + data[:link]\n end\n unless data[:link].end_with?('/')\n data[:link] += '/'\n end\n buff = data[:link].split('/')\n tmp_site = buff[2]\n data[:website] = is_site_compatible?(tmp_site, display)\n if data[:website] == nil\n return false\n end\n if data[:website][:to_complete] == ''\n data[:name] = buff[3]\n else\n data[:name] = buff[4]\n end\n data[:link] = data[:website][:link] + data[:website][:to_complete] + data[:name] + ((data[:website][:index_link_ends_with_slash]) ? '/' : '')\n true\n end", "def execute\n @result = MdnQuery::SearchResult.from_url(url)\n end", "def html_get(url)\n resp = Net::HTTP.get_response(url)\n if ['301', '302', '307'].include? resp.code\n url = URI.parse resp['location']\n elsif resp.code.to_i >= 400\n $stderr.puts \"[#{resp.code}] #{url}\"\n return\n end\n Net::HTTP.get url\n end", "def get_ver(url,tag)\n puts \"Search and return tag version within the url payload: #{url}, #{tag}\" if @verbose\n tag_ver=\"\"\n doc = open_page(url)\n case tag\n when \"utag.js\" # sample: ...,\"code_release_version\":\"cb20190312032612\",...\n doc.text.each_line do |line|\n my_line = line.downcase\n if my_line.include?(\"code_release_version\")\n puts \"Extract tag version from line: #{my_line}\" if @verbose\n m = my_line.match(/\\\"code\\_release\\_version\\\"\\:\\\"(?<ver>[a-z]+\\d+)\\\"/)\n tag_ver = m[:ver]\n break\n end\n end\n when \"analytics.js\" # sample #1: ga('create', 'UA-19175804-2', 'knopfdoubleday.com');\n doc.text.each_line do |line|\n my_line = line.downcase\n if my_line.include?(\"ga\") && my_line.include?(\"create\") #sample #2: __gaTracker('create', 'UA-121313929-1', 'auto');\n puts \"Extract tag version from line: #{my_line}\" if @verbose\n m = my_line.match(/[\\'|\\\"]create[\\'|\\\"]\\s*\\,\\s*[\\'|\\\"](?<ver>\\w+\\-\\d+\\-\\d+)[\\'|\\\"]\\s*\\,/)\n tag_ver = m[:ver]\n break\n end\n end\n when \"ga.js\"\n doc.text.each_line do |line|\n my_line = line.downcase\n puts my_line if @verbose\n if my_line.include?(\"push\") && my_line.include?(\"_setaccount\") # # sample #1: _gaq.push(['_setAccount', 'UA-13205363-65']);\n m = my_line.match(/[\\'|\\\"]\\_setaccount[\\'|\\\"]\\s*\\,\\s*[\\'|\\\"](?<ver>\\w+\\-\\d+\\-\\d+)[\\'|\\\"]/)\n tag_ver = m[:ver]\n break\n end\n if my_line.include?(\"_gettracker\") # sample #2: var pageTracker = _gat._getTracker(\"UA-12487327-1\");\n puts \"Extract tag version from line: #{my_line}\" if @verbose\n m = my_line.match(/\\_gettracker\\s*\\(\\s*[\\'|\\\"](?<ver>\\w+\\-\\d+\\-\\d+)[\\'|\\\"]/)\n tag_ver = m[:ver]\n break\n end\n\n end\n when \"all.js\" # sample: appId : '749936668352954',\n doc.text.each_line do |line|\n my_line = line.downcase\n if my_line.include?(\"appid\") && my_line.include?(\":\")\n puts \"Extract tag version from line: #{my_line}\" if @verbose\n m = my_line.match(/appid\\s+\\:\\s+[\\'|\\\"](?<ver>\\d+)[\\'|\\\"]\\s*\\,/)\n tag_ver = m[:ver]\n break\n end\n end\n\n else\n puts \"Don't know how to locate Adware Tag version: #{tag}\"\n # do nothing\n end\n doc = nil\n return tag_ver.upcase\n rescue => ee\n puts \"Exception on method #{__method__}: #{ee}: #{url} : #{tag}\" if @verbose\n return tag_ver\n end", "def get_page_from_url(url)\n\t(site.pages + site.posts).each do |page|\n\t\treturn page if page.url == url\n\tend\n\n\treturn nil\nend", "def get_results(url) #pass url in as argument\n scraper = make_scraper\n url=\"https://www.dice.com/jobs?q=rails&l=Washington%2C+DC&searchid=7137101740189\"\n page = scraper.get(url)\n end", "def info(url)\n\t\t\treturn nil unless url\n uri = URI.parse(url)\n bitlink = \"#{uri.host}#{uri.path}\"\n\n command = \"bitlinks/#{bitlink}\"\n\t\t\treturn execute_get(command, :long_url)\n\t\tend" ]
[ "0.58358526", "0.5818859", "0.5473012", "0.52615213", "0.5257803", "0.524651", "0.5232744", "0.52214617", "0.5165066", "0.51450235", "0.5086591", "0.50853395", "0.50853395", "0.50771624", "0.5074556", "0.5057889", "0.5052093", "0.50478536", "0.50478536", "0.504465", "0.50109714", "0.5009388", "0.5000193", "0.49814096", "0.49813434", "0.4981122", "0.497614", "0.49521703", "0.49493945", "0.4933367", "0.49262512", "0.4920727", "0.49087277", "0.49084404", "0.49040976", "0.48896953", "0.4886274", "0.48715985", "0.48667443", "0.485417", "0.48495734", "0.48449755", "0.48294246", "0.4828526", "0.48269266", "0.48143616", "0.48139474", "0.48132044", "0.48022673", "0.4789369", "0.47890928", "0.47884756", "0.4783561", "0.4764488", "0.4761659", "0.47612798", "0.47274694", "0.47223198", "0.47197622", "0.47111198", "0.4704134", "0.47024125", "0.469613", "0.4678546", "0.46657184", "0.46608594", "0.4655123", "0.46529713", "0.46489933", "0.46423656", "0.46409073", "0.46337235", "0.46337235", "0.46305373", "0.4630447", "0.46226805", "0.46196142", "0.4619372", "0.4618823", "0.46180096", "0.4616797", "0.46011156", "0.45999858", "0.45991975", "0.4596216", "0.45880735", "0.45822918", "0.4565937", "0.4563044", "0.45619643", "0.45556518", "0.4554407", "0.4531725", "0.45277452", "0.45224366", "0.4521851", "0.45212305", "0.451367", "0.4513609", "0.45111787" ]
0.78208727
0
Execute a specific command to acquire the exit code stderr, and raw data
def execute(cmd) captured_stdout = '' captured_stderr = '' exit_status = Open3.popen3(ENV, cmd) do |stdin, stdout, stderr, wait_thr| stdin.close captured_stdout = stdout.read captured_stderr = stderr.read wait_thr.value end [exit_status, captured_stdout, captured_stderr] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def call(command)\n $log.debug(\"exec #{command}\")\n\n stdout, stderr, exit_status = Open3::capture3(ENV, command)\n $log.debug(\"stderr = #{stderr}\") if stderr\n $log.debug(\"stdout = #{stdout}\")\n $log.debug(\"exit status = #{exit_status}\")\n\n status = Status.from_plowshare(exit_status.exitstatus)\n $log.debug(\"status = #{status}\")\n\n return nil, status unless exit_status.success?\n return stdout, status\n end", "def execute(cmd)\n puts \"TRACE: executing '#{cmd}'\" if verbose\n require 'open3'\n out_err, st = Open3.capture2e(*cmd.split(' '))\n if st.exitstatus != 0\n puts \"ERROR: #{cmd} exited with #{st.exitstatus}\\n\\n#{out_err}\"\n exit st.exitstatus\n end\n out_err\nend", "def run_with_stderr(*cmd)\n result = IO.popen(cmd, err: [:child, :out]) do |io|\n block_given? ? yield(io) : io.read\n end\n String === result && result.empty? ? nil : result\n end", "def execute_with_exit_code(command)\n if elevated\n session = elevated_session\n command = \"$env:temp='#{unelevated_temp_dir}';#{command}\"\n else\n session = unelevated_session\n end\n\n begin\n response = session.run(command) do |stdout, _|\n logger << stdout if stdout\n end\n [response.exitcode, response.stderr]\n ensure\n close\n end\n end", "def execute_with_exit_code(command)\n exit_code = nil\n session.open_channel do |channel|\n channel.request_pty\n\n channel.exec(command) do |_ch, _success|\n channel.on_data do |_ch, data|\n logger << data\n end\n\n channel.on_extended_data do |_ch, _type, data|\n logger << data\n end\n\n channel.on_request(\"exit-status\") do |_ch, data|\n exit_code = data.read_long\n end\n end\n end\n session.loop\n exit_code\n end", "def run_and_examine(command)\n response = IO.popen(command).readlines\n response.each { |response_line| @errors << response_line if response_line =~ /Error/i }\n puts \">#{command}\\n#{response.join}\" if $verbose || (@errors.size > 0)\n @errors.size == 0\n end", "def run_wrapped_cmd(cmd)\n separator = '-' * (TW - 4)\n\n puts \"Command output follows, on STDERR:\\n#{separator}\"\n ret = nil\n\n Open3.popen2e(cmd) do |_in, out, thr|\n # rubocop:disable Lint/AssignmentInCondition\n while l = out.gets do warn l end\n # rubocop:enable Lint/AssignmentInCondition\n ret = thr.value.exitstatus\n end\n\n puts separator\n ret\n end", "def get_response_from_command(command)\n output = nil\n status = popen4(command) do |pid, stdin, stdout, stderr|\n begin\n output = stdout.read\n rescue Exception => e\n raise Chef::Exceptions::Package, \"Could not read from STDOUT on command: #{command}\\nException: #{e.inspect}\"\n end\n end\n unless (0..1).include? status.exitstatus\n raise Chef::Exceptions::Package, \"#{command} failed - #{status.inspect}\"\n end\n output\n end", "def get_response_from_command(command)\n output = nil\n status = popen4(command) do |pid, stdin, stdout, stderr|\n begin\n output = stdout.read\n rescue Exception => e\n raise Chef::Exceptions::Package, \"Could not read from STDOUT on command: #{command}\\nException: #{e.inspect}\"\n end\n end\n unless (0..1).include? status.exitstatus\n raise Chef::Exceptions::Package, \"#{command} failed - #{status.inspect}\"\n end\n output\n end", "def _run_command(command)\n require \"posix-spawn\"\n\n pid, stdin, stdout, stderr = POSIX::Spawn.popen4(command)\n Process.waitpid(pid)\n\n # $?.exitstatus contains exit status do something with it if non zero raise error maybe\n end", "def execute(cmd)\n error_message=\"\"\n exception = false\n # execute\n begin\n #output = ` #{cmd} `\n output = %x( #{cmd})\n #output = system(call \"#{cmd}\")\n retcode = $?.exitstatus\n rescue Exception => e\n error_message= e.message.red\n exception = true\n end\n #retcode = $?.exitstatus\n return { \"output\" => output, \"error\" => error_message,\n \"retcode\" => retcode, \"exception\" => exception }\nend", "def run_with_err_output(command)\n %x{ #{command} 2>&1 }\n end", "def run_with_err_output(command)\n %x{ #{command} 2>&1 }\n end", "def run_with_err_output(command)\n %x{ #{command} 2>&1 }\n end", "def run_with_err_output(command)\n %x{ #{command} 2>&1 }\n end", "def run(cmd, opts = {}, &_block) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength\n env, cmd = prepare_cmd(cmd)\n # Store last command. env and cmd flipped, because usualy we more\n # interested in command instead of environment\n Grably.last_command = [cmd, env]\n lines = ''\n status = Open3.popen2e(env, *cmd, opts) do |_stdin, stdout_and_stderr, thr|\n stdout_and_stderr.sync = true\n stdout_and_stderr.each do |l|\n lines += l\n yield(l) if block_given?\n end\n lines.chomp!\n thr.value\n end\n\n return lines if status.exitstatus.zero?\n # Store error and exitstatus for later use. It useful when building\n # CI piplines and one can use error message.\n Grably.last_command = [cmd, status.exitstatus, lines]\n raise 'error: '.red.bright + Shellwords.shelljoin(cmd).red + \"\\nfail log: #{lines}\".green\n end", "def execute(*cmd)\n yield \"$ #{cmd.join(' ')}\" if block_given?\n output = ''\n\n Open3.popen2e(*cmd) do |_stdin, stdout_err, wait_thread|\n loop do\n line = stdout_err.gets\n break unless line\n\n output << line\n yield line if block_given?\n end\n\n exit_status = wait_thread.value\n raise ExecutionError, \"#{cmd.join(' ')} failed\" unless exit_status.success?\n end\n output\n end", "def execute\n { 'output' => `#{@cmd}`, 'process_status' => $? }\n end", "def execute(node, command)\n params = {}\n params[:exceptiononfailure] = false\n params[:exitcode] = true\n (exitcode, output) = node.execute(command, params)\n return [exitcode.to_i, output]\n end", "def run_command(cmd)\n IO.popen(cmd) do |f|\n while ! f.eof\n puts f.gets\n end\n end\n $?\n end", "def run(command,exit_on_error_with)\n info \"Running '#{command}'\"\n stdout_str, stderr_str, status = Open3.capture3(command)\n\n info stdout_str\n unless status.success?\n error stderr_str\n exit_now!(exit_on_error_with, \"There was a problem running '#{command}'\")\n end\nend", "def stderr(command, data)\n # called when the process writes to STDERR\n end", "def command(cmd)\n Open3.popen3(cmd) do |stdin, stdout, stderr|\n errors = stderr.readlines\n abort \"%s\\n%s\" % [cmd, errors.join] if errors.any?\n\n yield stdin, stdout if block_given?\n end\n end", "def exec_sys_cmd(cmd)\n log.debug(\">> #{cmd}\")\n output = %x{#{cmd} 2>&1}\n raise CommandError, \"#{cmd} failed, #{$?.describe}, #{output.strip}\" unless $?.success?\n end", "def run\n system(command)\n $?\n end", "def run\n system(command)\n $?\n end", "def exec!(command, status: T.unsafe(nil), &block); end", "def shell_execute(command)\n require 'open3'\n stdout, stderr, status = Open3.capture3(command.chomp)\n if status.success? && status.exitstatus.zero?\n stdout\n else\n msg = \"Shell command failed: [#{command}] caused by <STDERR = #{stderr}>\"\n msg << \" STDOUT = #{stdout}\" if stdout && stdout.length.positive?\n raise(StandardError, msg)\n end\n rescue SystemCallError => e\n msg = \"Shell command failed: [#{command}] caused by #{e.inspect}\"\n raise(StandardError, msg)\n end", "def exec_command(command)\n log = ''\n puts \"\\n=> Executing \\\"#{command}\\\"\"\n log += \"\\n\\n=> Executing \\\"#{command}\\\"\\n\"\n Open3.popen2e(command) { |stdin, stdout_and_stderr, wait_thr|\n stdout_and_stderr.each {|line|\n puts line\n log += line\n }\n }\n return log\nend", "def run_command(command)\n command = \"true\" if command.to_s.strip.empty?\n with_shell_instance do\n stdin.puts wrapped_command(command)\n stdin.close\n out, err = stdout.read, stderr.read\n out, status, _ = raw_stdout_to_parts(out)\n return status, out, err\n end\n end", "def stderr\n @cmd_result.stderr\n end", "def run_command(*command)\n\t\t\t#stdout, stderr, status\n\t\t\treturn Open3.capture3(*command)\n\t\tend", "def shell_command(command)\n system(command)\n\n result = $?\n\n reporter.info\n if result.exitstatus == 0\n reporter.exclaim(\"Command exited with status code: 0\")\n else\n reporter.error(\"Command exited with status code: #{result.exitstatus}\")\n end\n end", "def exec(command, &on_output)\n status = nil\n shell.execute(command) do |process|\n process.on_output(&on_output)\n process.on_error_output(&on_output)\n process.on_finish { |p| status = p.exit_status }\n end\n shell.session.loop(1) { status.nil? }\n status\n end", "def system_exec(cmd)\n Open3.popen3(RSpec::Support::Env.env, cmd) do |stdin, stdout, stderr, wait_thr|\n yield stdin, stdout, wait_thr if block_given?\n stdin.close\n\n @exitstatus = wait_thr && wait_thr.value.exitstatus\n @out = Thread.new { stdout.read }.value.strip\n @err = Thread.new { stderr.read }.value.strip\n end\n\n (@all_output ||= \"\") << [\n \"$ #{cmd.to_s.strip}\",\n out,\n err,\n @exitstatus ? \"# $? => #{@exitstatus}\" : \"\",\n \"\\n\"\n ].reject(&:empty?).join(\"\\n\")\n\n @out\n end", "def run(cmd)\n ENV['LANG'] = 'C'\n log \"Run: #{cmd}\"\n if dry_run\n return ['', 0]\n end\n stdout = `#{cmd} 2>&1`\n return_code = $?.exitstatus\n puts stdout\n puts \"Return: #{return_code}\"\n [stdout, return_code]\n end", "def get_from_shell_cmd(cmd, proc_id)\n stdout, stderr, status = Open3.capture3(cmd)\n if not status.success?\n cancel_job(\"error executing command '#{cmd}' - #{stderr}\", proc_id)\n end\n return stdout.strip!\nend", "def execute_with_exit(command) # rubocop:disable Lint/UnusedMethodArgument\n end", "def exec_command(command_string)\n io = IO.popen(command_string)\n raise Indy::Source::Invalid, \"No data returned from command string execution\" if io.eof?\n io\n end", "def run(cmd, capture_stderr=true)\n notice \"Running: \" + cmd.color(:white)\n cmd += \" 2>&1\" if capture_stderr\n\n out = \"\"\n IO.popen(cmd) do |f|\n while l = f.gets\n out += l\n msg \" \" + l\n end\n end\n\n raise CmdFailedError.new(\"Command '#{cmd}' had exit status #{$?.to_i}\") if $? != 0\n out\n end", "def exec!(cmd, options={})\n exit_status, stdout, stderr, cmd = exec(cmd, options)\n error_msg = options[:error_msg] || \"The following command exited with an error\"\n raise Appd::RemoteError.new(stdout, stderr, exit_status, cmd), error_msg if exit_status != 0\n return stdout\n end", "def assert_exec_output(node, command, expected_exitcode, expected_outputs)\n params = {}\n params[:exceptiononfailure] = false\n params[:exitcode] = true\n (exitcode, output) = node.execute(command, params)\n assert_equal(expected_exitcode.to_s, exitcode, \"Wrong exitcode returned\")\n assert_correct_output(expected_outputs, output)\n end", "def execute(cmd)\n res = eval(cmd, @pure_binding)\n $last_res = res\n eval(\"_ = $last_res\", @pure_binding)\n print_result res\n rescue Rush::Exception => e\n puts \"Exception #{e.class} -> #{e.message}\"\n rescue ::Exception => e\n puts \"Exception #{e.class} -> #{e.message}\"\n e.backtrace.each do |t|\n puts \" #{::File.expand_path(t)}\"\n end\n end", "def exec_with_exit(cmd)\n exit_code = nil\n session.open_channel do |channel|\n\n channel.request_pty\n\n channel.exec(cmd) do |ch, success|\n\n channel.on_data do |ch, data|\n logger << data\n end\n\n channel.on_extended_data do |ch, type, data|\n logger << data\n end\n\n channel.on_request(\"exit-status\") do |ch, data|\n exit_code = data.read_long\n end\n end\n end\n session.loop { !exit_code } # THERE IS A CHANGE ON THIS LINE, PAY ATTENTION!!!!!!\n exit_code\n end", "def erroneous_result(cmd, exception)\n stdout = nil\n stderr = ([exception.message] + exception.backtrace).join(\"\\n\")\n status = 1\n rspec_example_metadata(cmd, stdout, stderr)\n CommandResult.new(stdout: stdout, stderr: stderr, exit_status: status)\n end", "def execute command, ignore_error=false\n @logger.debug command\n \n Open3.popen2e(command) do |stdin, stdout_err, wait_thr|\n while line = stdout_err.gets\n @logger.debug line\n end\n \n exit_status = wait_thr.value\n unless exit_status.success? || ignore_error == true\n raise \"Error executing command: #{command}\"\n end\n end\n end", "def commandResult\n\t\t\t%x(#{@cmd} 2> /dev/null)\n\t\tend", "def run_and_output(cmd)\n run(cmd).output\n end", "def run_command(*command)\n print_command command\n result = system *command\n if result.nil?\n puts \"Failed to run command.\"\n exit 255\n elsif !result\n exit $?.exitstatus\n end\nend", "def run_i(cmd_string, &block)\n\texit_status = nil\n\tOpen3.popen2e(cmd_string) do |stdin, stdout_and_stderr, wait_thr|\n\t\toutput = nil\n\t\tbegin\n\t\t\toutput = stdout_and_stderr.gets\n\t\t\tputs output\n\t\tend while output\n\t\t\n\t\t\n\t\texit_status = wait_thr.value\n\tend\n\t\n\tif block\n\t\t# call the block if there is an error\n\t\traise block.call if exit_status != 0\n\tend\n\t\n\treturn exit_status\nend", "def plain_command cmd, options={}\n system(cmd)\n exitstatus = $?.exitstatus == 0 || $?.exitstatus == 1\n show_output(exitstatus, options)\n exitstatus\n end", "def check_exit_code!(executable, command, output)\n if $?.exitstatus != 0\n raise DownloaderError, \"Error on `#{executable} #{command}`.\\n#{output}\"\n end\n end", "def run()\n stdout_file = Tempfile::new(\"rbatch_tmpout\",RBatch::tmp_dir)\n stderr_file = Tempfile::new(\"rbatch_tmperr\",RBatch::tmp_dir)\n pid = spawn(@cmd_str,:out => [stdout_file,\"w\"],:err => [stderr_file,\"w\"])\n if @opt[:timeout] != 0\n timeout(@opt[:timeout]) do\n begin\n status = Process.waitpid2(pid)[1] >> 8\n rescue Timeout::Error => e\n raise(CmdException,\"Command timeout (over \" + @opt[:timeout] + \" sec)\" )\n end\n end\n else\n status = Process.waitpid2(pid)[1] >> 8\n end\n result = RBatch::CmdResult.new(stdout_file,stderr_file,status,@cmd_str)\n if @opt[:raise] && status != 0\n raise(CmdException,\"Command exit status is not 0. result: \" + result.to_s)\n end\n return result\n end", "def exec(command)\n #logger.debug { \"Github: Executing command: '#{command}'\" }\n #p \"Github: Executing command: '#{command}'\"\n \n # Get a path to a temp file\n #logfile = Tempfile.new('github__exec')\n #logfile.close\n \n #success = system(\"#{command} > #{logfile.path} 2>&1\")\n #output_from_command = File.readlines(logfile.path)\n #output_from_command = %x[command]\n shell = Shell.new(command)\n shell.run\n success = (shell.exitstatus == 0)\n output_from_command = shell.output\n if success\n #logger.debug { \"Github: Command output: #{output_from_command.inspect}\"}\n #p \"Github: Command output: #{output_from_command.inspect}\"\n return output_from_command\n else\n #logger.error { \"Github: Command '#{command}' didn't exit properly. Full output: #{output_from_command.inspect}\"}\n p \"Github: Command failed '#{command}' didn't exit properly. Full output: #{output_from_command.inspect}\"\n end\n \n #ensure\n #logfile.unlink\n end", "def cmd(cmd)\n @log.info cmd unless @log == nil\n res = `#{cmd} 2>&1`\n @log.info res unless @log == nil\n $?\n end", "def run_or_fail(cmd, redact: nil)\n put_command(cmd, redact: redact)\n Open3.popen3(*cmd) do |i, o, e, t|\n i.close\n if not t.value.success?\n STDERR.write red_term_text(e.read)\n exit t.value.exitstatus\n end\n end\n end", "def runOpen3CaptureOutput(*cmd_and_args)\n output = ''\n\n onError 'Empty runOpen3 command' if cmd_and_args.empty?\n\n if !File.exist?(cmd_and_args[0]) || !Pathname.new(cmd_and_args[0]).absolute?\n # check that the command exists if it is not a full path to a file\n requireCMD cmd_and_args[0]\n end\n\n Open3.popen3(*cmd_and_args) do |_stdin, stdout, stderr, wait_thr|\n # These need to be threads to work nicely on windows\n out_thread = Thread.new do\n stdout.each do |line|\n output.concat(line)\n end\n end\n\n err_thread = Thread.new do\n stderr.each do |line|\n output.concat(line)\n end\n end\n\n exit_status = wait_thr.value\n out_thread.join\n err_thread.join\n return exit_status, output\n end\n\n onError \"Execution shouldn't reach here\"\nend", "def test_outputonfailure\n provider = newprovider\n\n dir = tstdir\n file = File.join(dir, \"mycmd\")\n sh = Puppet::Util.which(\"sh\")\n File.open(file, \"w\") { |f|\n f.puts %{#!#{sh}\n echo A Failure >&2\n exit 2\n }\n }\n File.chmod(0755, file)\n\n provider.commands :cmd => file\n\n inst = provider.new(nil)\n\n assert_raise(Puppet::ExecutionFailure) do\n inst.cmd \"some\", \"arguments\"\n end\n\n out = nil\n begin\n inst.cmd \"some\", \"arguments\"\n rescue Puppet::ExecutionFailure => detail\n out = detail.to_s\n end\n\n\n assert(\n out =~ /A Failure/,\n\n \"Did not receive command output on failure\")\n\n\n assert(\n out =~ /Execution of/,\n\n \"Did not receive info wrapper on failure\")\n end", "def run_capture(command, *args)\n if !args.empty?\n args = args.flatten.map { |i| shell_escape(i) }.join(\" \")\n command = \"#{command} #{args}\"\n end\n result = `#{command}`\n if $? != 0\n if $?.termsig == Signal.list[\"INT\"]\n raise \"#{command} interrupted\"\n end\n raise RunError, \"#{command} failed : #{$?.to_i / 256} #{result.inspect}\"\n end\n result\n end", "def sh(cmd)\n output = `#{cmd}`\n if !$?.success?\n puts \"Command exited with failure code: #{cmd}\"\n puts \"Aborting.\"\n exit(1)\n end\n output\nend", "def runOpen3CaptureOutput(*cmdAndArgs)\n\n output = \"\"\n\n if cmdAndArgs.length < 1\n onError \"Empty runOpen3 command\"\n end\n\n if !File.exists? cmdAndArgs[0] or !Pathname.new(cmdAndArgs[0]).absolute?\n # check that the command exists if it is not a full path to a file\n requireCMD cmdAndArgs[0]\n end\n\n Open3.popen3(*cmdAndArgs) {|stdin, stdout, stderr, wait_thr|\n\n # These need to be threads to work nicely on windows\n outThread = Thread.new{\n stdout.each {|line|\n output.concat(line)\n }\n }\n\n errThread = Thread.new{\n stderr.each {|line|\n output.concat(line)\n }\n } \n\n exit_status = wait_thr.value\n outThread.join\n errThread.join\n return exit_status, output\n }\n\n onError \"Execution shouldn't reach here\"\nend", "def run_for_output(cmd)\n LOG.debug \"RUNNING (for output): #{cmd}\"\n out, _status = Open3.capture2e(cmd)\n out.strip\n end", "def run(cmd)\n rtn = nil\n\n Open3.popen3(cmd) do |_, o, e, t|\n out_reader = Thread.new { o.read }\n err_reader = Thread.new { e.read }\n\n rtn = [out_reader.value, err_reader.value, t.value]\n end\n\n rtn\nend", "def execute(command, testcase, params={})\n if params[:exceptiononfailure].nil?\n if params[:exitcode]\n exceptiononfailure = false\n else\n exceptiononfailure = true\n end\n else\n exceptiononfailure = params[:exceptiononfailure]\n end\n\n testcase_output(\"#{@short_hostname}$ #{command}\", testcase) if not params[:noecho]\n # wrap command in order to see stderr when command is not found\n if params[:nostderr]\n command = \"( #{command} ) 2>/dev/null\"\n else\n command = \"( #{command} ) 2>&1\"\n end\n\n stdout = IO.popen(command)\n data = \"\"\n batch_lines = \"\"\n interval_start = Time.now.to_i\n while line = stdout.gets\n duration = Time.now.to_i - interval_start\n batch_lines = batch_lines + line\n\n # only send back output through DRb once every 2 seconds to avoid using up all resources\n if duration > 2\n testcase_output(batch_lines, testcase, false) if not params[:noecho]\n batch_lines = \"\"\n interval_start = Time.now.to_i\n end\n data = data + line;\n end\n testcase_output(batch_lines, testcase, false) if not params[:noecho]\n stdout.close\n\n maxsize = 200*1024\n if (data.length < maxsize)\n output = data\n else\n output = data[-maxsize..-1] + \"\\n\\nStdout buffer for command '#{command}' was too large, last #{maxsize/1024}KB returned\\n\"\n end\n\n if exceptiononfailure && $?.exitstatus != 0\n ex = ExecuteError.new(\"non-zero exit status (#{$?.exitstatus.to_i}) from #{command}\")\n ex.output = output\n raise ex\n end\n\n # check that the output won't be too large for passing\n # through DRb, setting 100kb as a hard limit\n if params[:exitcode]\n return [$?.exitstatus.to_s, output]\n else\n return output\n end\n end", "def runCmd\n puts \" Deployed and running #{@request.data['command']} #{@request.data['arguments']}\".light_green\n print ' STDOUT'.light_cyan + ' and' + ' STDERR'.light_magenta + \":\\n\"\n\n # offset (place saving) variables\n @stdoutOffset = 0\n @stderrOffset = 0\n begin\n # get most recent task state\n # need to wait for \"task_running\" before we can ask for STDOUT/STDERR\n @taskState = JSON.parse(RestClient.get \"#{@uri}/api/history/task/#{@thisTask['taskId']['id']}\")\n @taskState[\"taskUpdates\"].each do |update|\n @taskState = update['taskState']\n end\n if @taskState == \"TASK_FAILED\"\n return 1 # failure\n end\n if @taskState == \"TASK_RUNNING\"\n sleep 1\n # print stdout\n @stdout = JSON.parse(RestClient.get \"#{@uri}/api/sandbox/#{@thisTask['taskId']['id']}/read\", {params: {path: \"stdout\", length: 30000, offset: @stdoutOffset}})['data']\n outLength = @stdout.bytes.to_a.size\n if @stdout.length > 0\n print @stdout.light_cyan\n @stdoutOffset += outLength\n end\n # print stderr\n @stderr = JSON.parse(RestClient.get \"#{@uri}/api/sandbox/#{@thisTask['taskId']['id']}/read\", {params: {path: \"stderr\", length: 30000, offset: @stderrOffset}})['data']\n errLength = @stderr.bytes.to_a.size\n if @stderr.length > 0\n print @stderr.light_magenta\n @stderrOffset += errLength\n end\n end\n end until @taskState == \"TASK_FINISHED\"\n\n return 0 # success\n end", "def pexec(cmd)\n `#{cmd} 2>&1`\n $?\nend", "def execute(cmd)\n res = eval(@multiline_cmd << \"\\n\" << cmd, @pure_binding)\n $last_res = res\n eval(\"_ = $last_res\", @pure_binding)\n @multiline_cmd = ''\n print_result res\n rescue SyntaxError => e\n unless e.message.include? 'unexpected end-of-input'\n @multiline_cmd = ''\n puts \"Exception #{e.class} -> #{e.message}\"\n end\n # Else it should be multiline command.\n rescue Rush::Exception => e\n puts \"Exception #{e.class} -> #{e.message}\"\n @multiline_cmd = ''\n rescue ::Exception => e\n puts \"Exception #{e.class} -> #{e.message}\"\n e.backtrace.each { |t| puts \"\\t#{::File.expand_path(t)}\" }\n @multiline_cmd = ''\n end", "def exec_cmd(var)\n # In bash, the exit value of the last command is the exit value of the\n # entire pipeline\n out = execute(\"echo \\\"#{var[:input]}\\\" | #{var[:cmd]}\", failonfail: false, combine: true)\n st = $CHILD_STATUS.exitstatus\n { out: out, exit: st }\n end", "def run_command(cmd, *args)\n r,w = IO.pipe\n\n pid = fork do\n r.close\n STDIN.close\n STDOUT.reopen(w)\n STDERR.reopen(w)\n\n exec(cmd, *args)\n end\n\n w.close\n output = r.read.force_encoding('binary')\n pid, status = Process::wait2(pid)\n\n [output, status]\n end", "def execute_and_handle(command, outpipe, errpipe)\n Open3.popen3(command) do |_, stdout, stderr|\n if (outpipe)\n outpipe.call(stdout)\n end\n if (errpipe)\n errpipe.call(stderr)\n end\n end\nend", "def gp( cmd )\n stdout = stderr = wt = nil\n Open3.popen3( \"bundle exec bin/gp #{cmd}\" ) do |i, o, e, w|\n i.close\n stdout = o.readlines.map!(&:chomp!)\n stderr = e.readlines.map!(&:chomp!)\n wt = w\n end\n [stdout, stderr, wt.value.exitstatus]\nend", "def run_i(cmd_string)\n\tstdin, stdout_and_stderr, wait_thr = Open3.popen2e cmd_string\n\t\n\toutput = nil\n\tbegin\n\t\toutput = stdout_and_stderr.gets\n\t\tputs output\n\tend while output\n\t\n\tstdin.close\n\tstdout_and_stderr.close\nend", "def process_result(result, exit_status); end", "def _external(cmd, opts={})\n #log :info, \"cmd is ||#{cmd.inspect}||\"\n log :info, \"starting [#{cmd.join(' ')}]\" if !opts.has_key?(:silent)\n\n start = Time.now\n outfile = Tempfile.new\n pid = Process.spawn(*cmd, out: outfile.fileno, err: :out)\n SUBPROCS << pid # add to halt list\n\n begin\n _, status = Process.wait2(pid)\n rescue Errno::ECHILD\n # our subproc was killed, usually by our shutdown routine\n exit_code = 1\n else\n exit_code = status.exitstatus\n end\n\n SUBPROCS.delete(pid) # remove from halt list\n diff = format_time_diff(start)\n\n outfile.rewind\n result = outfile.read\n outfile.close!\n\n log :info, \"ran [#{cmd.join(' ')}] in #{diff}\" if !opts.has_key?(:silent)\n \n if exit_code > 0 && !$shutdown\n log :error, \"command [#{cmd.join(' ')}] returned an error (code #{exit_code}), with the following output\"\n log :error, result\n end\n\n if opts.has_key?(:timing)\n return exit_code, result, diff\n else\n return exit_code, result\n end\nend", "def run_command(cmd)\n IO.popen(cmd) do |stdout|\n stdout.reject(&:empty?)\n end.unshift($?.exitstatus.zero?)\nend", "def run_command(cmd)\n IO.popen(cmd) do |stdout|\n stdout.reject(&:empty?)\n end.unshift($?.exitstatus.zero?)\nend", "def run_open3_capture_output_separate(*cmd_and_args)\n output = ''\n stderr_text = ''\n\n onError 'Empty runOpen3 command' if cmd_and_args.empty?\n\n if !File.exist?(cmd_and_args[0]) || !Pathname.new(cmd_and_args[0]).absolute?\n # check that the command exists if it is not a full path to a file\n requireCMD cmd_and_args[0]\n end\n\n Open3.popen3(*cmd_and_args) do |_stdin, stdout, stderr, wait_thr|\n # These need to be threads to work nicely on windows\n out_thread = Thread.new do\n stdout.each do |line|\n output.concat(line)\n end\n end\n\n err_thread = Thread.new do\n stderr.each do |line|\n stderr_text.concat(line)\n end\n end\n\n exit_status = wait_thr.value\n out_thread.join\n err_thread.join\n return exit_status, output, stderr_text\n end\n\n onError \"Execution shouldn't reach here\"\nend", "def capture_with_status(*args)\n _print_command(*args)\n args.last.delete :errexit if args.last.is_a? Hash\n args.last.delete :xtrace if args.last.is_a? Hash\n stdout, status = Open3.capture2(*args)\n return stdout.chomp, status\nend", "def run(command_builder)\n command = command_builder.command\n\n sub = Subexec.run(command, timeout: options[:timeout])\n\n if sub.exitstatus != 0\n\n # Raise the appropriate error\n if sub.output =~ /no decode delegate/i || sub.output =~ /did not return an image/i\n raise MiniMagick::Invalid, sub.output\n else\n # TODO: should we do something different if the command times out ...?\n # its definitely better for logging.. otherwise we dont really know\n raise MiniMagick::Error, \"Command (#{command.inspect.gsub(\"\\\\\", \"\")}) failed: #{{:status_code => sub.exitstatus, :output => sub.output}.inspect}\"\n end\n else\n sub.output\n end\n end", "def syscall(*cmd)\n begin\n stdout, stderr, status = Open3.capture3(*cmd)\n # strip trailing eol\n status.success? && stdout.slice!(0..-(1 + $/.size)) \n\n stderr = stderr\n rescue\n end\n end", "def exec_shell(command, error_message, options = {})\n puts \"Running command: #{command}\" unless options[:silent] == true\n result = `#{command}`\n if options[:dont_fail_on_error] == true\n puts error_message unless $?.success?\n else\n fail_script_unless($?.success?, \"#{error_message}\\nShell failed: #{command}\\n#{result}\")\n end\n\n return result\n end", "def exec!(command, opts = {}, &block)\n # Options\n stdout = ''\n stderr = ''\n defaults = {\n :check_exit_status => true\n }\n \n opts = defaults.merge opts\n\n # First, set up the environment...\n if @env.size > 0\n command = (\n @env.map { |k,v| k.to_s.upcase + '=' + v } << command\n ).join(' ')\n end\n\n # Before execution, cd to cwd\n command = \"cd #{escape(@cwd)}; \" + command\n\n # Input redirection\n if opts[:from]\n command += \" <#{escape(opts[:from])}\"\n end\n\n # Output redirection\n if opts[:to]\n command += \" >#{escape(opts[:to])}\"\n end\n\n # After command, add a semicolon...\n unless command =~ /;\\s*\\z/\n command += ';'\n end\n\n # Then echo the exit status.\n command += ' echo $?; '\n\n\n # If applicable, wrap the command in a sudo subshell...\n if @sudo\n command = \"sudo -S -u #{@sudo} bash -c #{escape(command)}\"\n if @password\n opts[:stdin] = @password + \"\\n\" + opts[:stdin].to_s\n end\n end\n\n buffer = ''\n echoed = 0\n stderr_echoed = 0\n status = nil\n written = false\n\n # Run ze command with callbacks.\n # Return status.\n channel = ssh.open_channel do |ch|\n ch.exec command do |ch, success|\n raise \"could not execute command\" unless success\n\n # Handle STDOUT\n ch.on_data do |c, data|\n # Could this data be the status code?\n if pos = (data =~ /(\\d{1,3})\\n\\z/)\n # Set status\n status = $1\n\n # Flush old buffer\n opts[:stdout].call(buffer) if opts[:stdout]\n stdout << buffer\n\n # Save candidate status code\n buffer = data[pos .. -1]\n\n # Write the other part of the string to the callback\n opts[:stdout].call(data[0...pos]) if opts[:stdout]\n stdout << data[0...pos]\n else\n # Write buffer + data to callback\n opts[:stdout].call(buffer + data) if opts[:stdout]\n stdout << buffer + data\n buffer = ''\n end\n \n if opts[:echo] and echoed < stdout.length\n stdout[echoed..-1].split(\"\\n\")[0..-2].each do |fragment|\n echoed += fragment.length + 1\n log fragment\n end\n end\n end\n\n # Handle STDERR\n ch.on_extended_data do |c, type, data|\n # STDERR\n if type == 1\n # Callback\n opts[:stderr].call(data) if opts[:stderr]\n\n # Accrue in stderr string\n stderr << data\n\n # Play forward any unwritten lines\n if opts[:echo] and stderr_echoed < stderr.length\n stderr[stderr_echoed..-1].split(\"\\n\")[0..-2].each do |fragment|\n stderr_echoed += fragment.length + 1\n log :stderr, fragment\n end\n end\n end\n end\n \n # Write stdin\n if opts[:stdin]\n ch.on_process do\n unless written\n ch.send_data opts[:stdin]\n written = true\n else\n # Okay, we wrote stdin\n unless block or ch.eof?\n ch.eof!\n end\n end\n end\n end\n\n # Handle close\n ch.on_close do\n if opts[:echo]\n # Echo last of input data\n stdout[echoed..-1].split(\"\\n\").each do |fragment|\n echoed += fragment.length + 1\n log fragment\n end\n\n # Last of stderr\n stderr[stderr_echoed..-1].split(\"\\n\").each do |fragment|\n echoed += fragment.length + 1\n log :stderr, fragment\n end\n end\n end\n end\n end\n \n if block\n # Run the callback\n callback_thread = Thread.new do\n if opts[:stdin]\n # Wait for stdin to be written before calling...\n until written\n sleep 0.1\n end\n end\n\n block.call(channel)\n end\n end\n\n # Wait for the command to complete.\n channel.wait\n\n # Let the callback thread finish as well\n callback_thread.join if callback_thread\n\n if opts[:check_exit_status]\n # Make sure we have our status.\n if status.nil? or status.empty?\n raise \"empty status in host#exec() for #{command}, hmmm\"\n end\n\n # Check status.\n status = status.to_i\n if status != 0\n raise \"#{command} exited with non-zero status #{status}!\\nSTDERR:\\n#{stderr}\\nSTDOUT:\\n#{stdout}\"\n end\n end\n\n stdout.chomp\n end", "def system_exitcode(t, stderr, name)\t\n\t\tif t.value.success?\n\t\t\t$logfile.puts \"#{Time.new.strftime(\"%c\")}: Running #{name} finished.\"\n\t\t\tif stderr.any?\n\t\t\t\t$logfile.puts \"#{name} output:\"\n\t\t\t\tstderr.readlines.each {|line| $logfile.puts line}\n\t\t\tend\n\t\telse\n\t\t\t$logfile.puts \"#{Time.new.strftime(\"%c\")}: Error in #{name}:\"\n\t\t\tstderr.readlines.each {|line| $logfile.puts line}\n\t\t\texit\n\t\tend\n\tend", "def system_run(cmd, o={})\n opts = {:quiet => false, :sysread => 1024}.merge(o)\n buf = \"\"\n ddputs(\"Running command: #{cmd}\")\n Open3.popen3(cmd) do |stdout, stdin, stderr|\n begin\n while (chunk = stdin.readpartial(opts[:sysread]))\n buf << chunk\n unless chunk.nil? || chunk.empty?\n $stdout.write(chunk) #if debugging? || verbose?\n end\n end\n err = stderr.readlines\n $stderr.write_nonblock(err)\n rescue SystemCallError => error\n err = stderr.readlines\n $stderr.write_nonblock(err)\n rescue EOFError => error\n err = stderr.readlines\n $stderr.write_nonblock(err)\n # used to do nothing\n end\n end\n buf\n end", "def `(cmd)\n old_execute(cmd + \" 2>&1\")\nend", "def rc\n @cmd_result.rc\n end", "def execute cmd, identifier = ''\n success = true\n\n Open3.popen3(cmd) do |stdin, stdout, stderr, wait_thr|\n err = to_safe_string(stderr.read)\n if err != ''\n write(err, identifier, 'error')\n success = false\n end \n out = to_safe_string(stdout.read)\n if out != ''\n write(out, identifier, 'default')\n end\n end\n return success\n end", "def system_exitcode(t, stderr, name)\t\n\t\tif t.value.success?\n\t\t\t$logfile.puts \"#{Time.new.strftime(\"%c\")}: #{name} succeded.\"\n\t\t\tif stderr.any?\n\t\t\t\t$logfile.puts \"#{name} output:\"\n\t\t\t\tstderr.readlines.each {|line| $logfile.puts line}\n\t\t\tend\n\t\telse\n\t\t\t$logfile.puts \"#{Time.new.strftime(\"%c\")}: Error in #{name}:\"\n\t\t\tstderr.readlines.each {|line| $logfile.puts line}\n\t\t\texit\n\t\tend\n\tend", "def run_with_status(*args)\n _print_command(*args)\n args.last.delete :errexit if args.last.is_a? Hash\n args.last.delete :xtrace if args.last.is_a? Hash\n pid = Process.spawn(*args)\n return Process.wait2(pid).last\nend", "def run_cmd(cmd, timing_metric=nil, log_errors=true)\n ret = \"\"\n exit_code = 0\n start = Time.now.to_i\n timestamp = Time.now.to_s\n plugin_state = {\n :cmd => cmd,\n :timing_metric => timing_metric,\n :start_time => start,\n :log_errors => log_errors\n }\n raise_event(:run_command_start, plugin_state)\n log_and_stream \"<div class='command'><h4>#{timestamp}: Running #{cmd}</h4>\\n<p class='output'>\"\n time = Benchmark.measure do\n Open3.popen3(cmd) do |inn, out, err, wait_thr|\n output = \"\"\n until out.eof?\n # raise \"Timeout\" if output.empty? && Time.now.to_i - start > 300\n chr = out.read(1)\n output << chr\n ret << chr\n if chr == \"\\n\" || chr == \"\\r\"\n log_and_stream output + \"<br>\"\n output = \"\"\n end\n end\n error_message = nil\n log_and_stream(output) unless output.empty?\n\n error_message = err.read unless err.eof?\n if (log_errors) then\n log_and_stream(\"<span class='stderr'>STDERR: #{error_message}</span><br>\") unless error_message.nil?\n else\n log_and_stream(\"STDERR:\" + error_message + \"<br>\") unless error_message.nil?\n end\n\n unless error_message.nil? then\n plugin_state[:error_message] = error_message\n raise_event(:run_command_error, plugin_state)\n end\n\n # Log non-zero exits\n if wait_thr.value.exitstatus != 0 then\n log_and_stream(\"<span class='stderr'>DANGER! #{cmd} had an exit value of: #{wait_thr.value.exitstatus}</span><br>\")\n exit_code = wait_thr.value.exitstatus\n end\n end\n end\n log_and_stream \"</p>\"\n log_and_stream \"<h5>Time: #{time}</h5></div>\"\n plugin_state[:exit_code] = exit_code\n plugin_state[:stdout] = ret\n plugin_state[:time] = time.real\n raise_event(:run_command_end, plugin_state)\n return { :stdout => ret, :exit_code => exit_code }\n end", "def execute(filename, command, error)\n # Execute Command\n @result[:_task] = filename\n @result[:_timestamp]= Time.now.to_i\n # @result[:_date]\n unless @params[\"_target\"][\"remote\"].nil?\n begin \n stdout, stderr, status = Open3.capture3(*command)\n rescue Exception => e\n default_error = { \n msg: e.message,\n kind: \"test::#{filename}\",\n details: { class: e.class.to_s,\n backtrace: e.backtrace }, \n }\n @result[:_error] = default_error.merge(error)\n\n end\n @result[:_stdout] = stdout\n @result[:_sterr] = stderr\n @result[:_status] = status\n @result\n else\n @result[:_timestamp]= Time.now\n @result[:_command_start_time] = Time.now\n begin \n $results = command.call()\n @result[:_command_end_time] = Time.now\n rescue Exception => e\n @result[:_command_end_time] = Time.now\n default_error = { \n msg: e.message,\n kind: \"test::#{filename}\",\n details: { class: e.class.to_s,\n backtrace: e.backtrace }, \n }\n @result[:_error] = default_error.merge(error)\n #puts @result\n end\n # makes sure the results are at the top level of the return object\n unless $results.nil?\n $results.each do |key, value|\n @result[key] = value\n end\n end\n end\n @result\n end", "def popen(cmd, path = nil, vars = {}, &block)\n result = popen_with_detail(cmd, path, vars, &block)\n\n [\"#{result.stdout}#{result.stderr}\", result.status&.exitstatus]\n end", "def run\n COMMANDS.each do |cmd_group|\n cmd_group.each do |cmd|\n ret_code = self.send(\"operate_#{cmd_group[0]}\", @argv) if @argv[0] == cmd\n return ret_code if (ret_code == ARG_ERROR or ret_code == SUCCESS)\n end\n end\n\n print_unrecognizable_error\n return CMD_ERROR\n end", "def read_command_output( cmd, *args )\n\t\t\t# output = IO.read( '|-' ) or exec cmd, *args # No popen on some platforms. :(\n\t\t\targstr = Shellwords.join( args )\n\t\t\toutput = `#{cmd} #{argstr}`.chomp\n\t\t\treturn output\n\t\tend", "def stream_output(command)\n puts command\n exit_status = nil\n Open3.popen3(command) do |stdin, stdout, stderr, wait_thread|\n stdout.each { |line| puts line }\n stderr.each { |line| puts line }\n exit_status = wait_thread.value.to_i\n end\n raise %Q(The command \"#{command}\" failed.) unless exit_status == 0\nend", "def sh_exec(*args)\n unless args.last.kind_of? Hash\n args << {}\n end\n\n opts = args.last\n opts[:err] = [:child, :out] # write stdout and stderr to pipe, so we can read it later\n\n out = IO.popen(args, 'r') {|io| io.read}\n success = $? == 0\n\n return success, out\n end", "def exitstatus\n subexec.try(:exitstatus)\n end", "def execute\n final_command = \"#{@command} 2>&1\"\n puts \":: #{final_command}\"\n duration = 0\n Transcoder.logger.info(\"\\nExecuting Command: #{final_command}\\n\")\n if block_given?\n @raw_result = ''\n IO.popen(final_command) do |pipe|\n pipe.each(\"\\r\") do |line| \n new_progress, duration = parse_progress(line, duration)\n if new_progress != @progress\n @progress = new_progress\n yield @progress\n $defout.flush\n end\n @raw_result += line + \"\\r\" \n end\n end\n else\n @raw_result = `#{final_command}`\n end\n Transcoder.logger.info(\"Result: \\n#{@raw_result}\")\n parse_result(@raw_result)\n end", "def run_cmd cmd\n info cmd\n status = system(cmd)\n if status\n info(\"Woot! Woot! - command succeeded #{cmd}\")\n else\n error(\"Gahhhh! Bad status from #{cmd}\")\n end\n status\n end", "def run_cmd(cmd, *args)\n output, = Open3.capture2e(cmd, *args)\n\n output\n end" ]
[ "0.70583147", "0.69758534", "0.69353664", "0.680935", "0.6742753", "0.67330915", "0.6726129", "0.66874856", "0.66874856", "0.66532004", "0.66139555", "0.65990394", "0.65990394", "0.65990394", "0.65990394", "0.6590954", "0.6590257", "0.6580369", "0.6576773", "0.6569997", "0.65537876", "0.6504397", "0.64462596", "0.64338475", "0.6405966", "0.6405966", "0.6400577", "0.6364073", "0.63301384", "0.629332", "0.62895423", "0.62749964", "0.6269682", "0.62667394", "0.6260293", "0.6243124", "0.6229424", "0.6228443", "0.62116885", "0.62060237", "0.61921257", "0.6180022", "0.6173128", "0.61675775", "0.61505145", "0.6142037", "0.6119423", "0.6117084", "0.6111491", "0.6103229", "0.6101514", "0.6093375", "0.6092661", "0.6092429", "0.6080368", "0.6078104", "0.6076996", "0.60743725", "0.60742486", "0.60689527", "0.6064412", "0.60527533", "0.6049081", "0.6036152", "0.6034813", "0.60297745", "0.60280126", "0.6025668", "0.60226905", "0.60208917", "0.6012297", "0.5988945", "0.5985604", "0.59848213", "0.59694767", "0.59694767", "0.5960707", "0.59581536", "0.595696", "0.59543496", "0.5948392", "0.59435207", "0.59372336", "0.5935249", "0.5932824", "0.5927966", "0.5925625", "0.59225446", "0.592161", "0.592142", "0.59213454", "0.59208375", "0.591807", "0.59047496", "0.5904661", "0.5900051", "0.58970046", "0.5891241", "0.5884396", "0.5880545" ]
0.6723059
7
Use callbacks to share common setup or constraints between actions.
def set_order_item @order_item = OrderItem.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
take a number: gives "name" a "number" in line
def take_a_number(the_deli, name) the_deli << "#{name}" #names to be added into the_deli array puts "Welcome, #{name}. You are number #{the_deli.length} in line." end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def num\n name\n end", "def take_a_number(katz_deli, name)\n # add person to end of line\n katz_deli << name\n # call out (`puts`) the person's name along with their position in line\n puts \"Welcome, #{name}. You are number #{katz_deli.size} in line.\"\nend", "def take_a_number(deli, name)\n deli << name\n puts \"Welcome, #{name}. You are number #{deli.length} in line.\"\nend", "def line(number); end", "def numbername\n self.number + \" - \" + self.name\n end", "def take_a_number(deli, name)\n deli.push(name)\n puts \"Welcome, #{name}. You are number #{deli.count} in line.\"\nend", "def number\n @number ||= (num = name.match(/([0-9]{4})$/) and num[1].to_i)\n end", "def line(number)\n end", "def take_a_number(deli,name)\n deli << name\n puts \"Welcome, #{name}. You are number #{deli.length} in line.\"\n\nend", "def process_line(ln)\n ln.strip!\n if ln =~ /(.*)\\s+\\(\\d+\\)\\z/\n $1\n else\n ln\n end\n end", "def take_a_number(katz_deli, name)\n katz_deli.push(name)\n# return the person's name along with their position in line by using the hashtag, swingly brackets to call every arguement's iteration\n puts \"Welcome, #{name}. You are number #{katz_deli.length} in line.\"\nend", "def line_number\n number[6..-1]\n end", "def take_a_number(katz_deli, name)\n katz_deli << name\n puts \"Welcome, #{name}. You are number #{katz_deli.length} in line.\"\nend", "def take_a_number(katz_deli, name)\n katz_deli << name\n puts \"Welcome, #{name}. You are number #{katz_deli.length} in line.\"\nend", "def take_a_number (deli, name)\n deli << name\n puts \"Welcome, #{name}. You are number #{deli.length} in line.\"\n return deli\nend", "def number(name, number)\n push(name, number)\n end", "def take_a_number(katz_deli, person)\n katz_deli.push(person)\n new_person_in_line = \" \"\n katz_deli.each_with_index do |item,index|\n new_person_in_line = \"Welcome, #{item}. You are number #{index + 1} in line.\"\n end\n puts new_person_in_line\n end", "def take_a_number(deli,customer)\n deli << customer\n line_number = deli.length\n puts \"Welcome, #{customer}. You are number #{line_number} in line.\"\nend", "def identifier\n num\n end", "def take_a_number(the_line, customer)\n the_line << customer\n puts \"Welcome, #{customer}. You are number #{the_line.size} in line.\"\nend", "def take_a_number(katz_deli, name)\n #the take_a_number method should puts the person's name along with their postion in line --use .push(element) to add a person's name to the line\n katz_deli.push(name)\n\n puts \"Welcome, #{name}. You are number #{katz_deli.length} in line.\"\nend", "def take_a_number(katz_deli, name)\n katz_deli.push(name)\n puts \"Welcome, #{name}. You are number #{katz_deli.length} in line.\"\nend", "def take_a_number(katz_deli, name)\n katz_deli.push(name)\n puts \"Welcome, #{name}. You are number #{katz_deli.length} in line.\"\nend", "def take_a_number(katz_deli, name) # Takes deli line and a new customer name as input.\n katz_deli.push(name) # Add new customer to deli line.\n puts \"Welcome, #{name}. You are number #{katz_deli.size} in line.\" # Returns the required string.\nend", "def take_a_number(katz_deli, name)\n katz_deli << name\n\n# katz_deli.each_with_index do |name, index|\n puts \"Welcome, #{name}. You are number #{katz_deli.length} in line.\"\n# end\nend", "def line(num) lines(num, 1) end", "def number_from_name(name)\r\n return nil unless name\r\n match = name.scan(/^(\\d+)/).first\r\n match ? match.first.to_i : nil\r\n end", "def number_as_text(name, i)\n \n # puts \"number_as_text\" + [name, i].inspect\n return if i.nil? or i == 0\n \n # reverse the number\n value = i.to_s.reverse\n \n hundreds = \"#{UNITS[value[2].chr.to_i]}-hundred\" if i > 99\n tens = \"#{TENS[value[1].chr.to_i * 10]}\" if i > 9\n units = \"#{UNITS[value[0].chr.to_i]}\" unless value[0].chr == \"0\"\n teens = \"#{TEENS[(i%100)]}\" if TEENS.key?(i % 100)\n concat_parts(hundreds, tens, units, teens, i)\n end", "def line(number)\n lines[number - 1]\n end", "def line(line_no)\n @line[line_no]\n end", "def line(line_no)\n @line[line_no]\n end", "def line(line_no)\n @line[line_no]\n end", "def line(line_no)\n @line[line_no]\n end", "def line(line_no)\n @line[line_no]\n end", "def take_a_number(katz_deli, name)\n katz_deli << name\n puts \"Welcome, #{name}. You are number #{katz_deli.size} in line.\"\n return katz_deli\nend", "def line\n\t\tl = @name\n\t\t(1..25).each do |i|\n\t\t\tl += \" &\"\n\t\t\tif i <= @number then\n\t\t\t\tl += \" \\\\!$\\\\times$\"\n\t\t\tend\n\t\tend\n\t\tl += \" \\\\\\\\\\n\"\n\t\treturn l\n\tend", "def format_line_num(*line_numbers)\n width = line_numbers.collect{|i| i.to_s.length }.max\n line_numbers.collect{|i| sprintf(\"%#{width}d\", i) }\nend", "def number lines\n lines.each_with_index.map { |x,i| \"#{i + 1}: #{x}\" }\nend", "def name(integer)\n places = integer.to_i.to_s.split(//).collect{|s| s.to_i}.reverse\n name = []\n ((places.length + 2) / 3).times do |p|\n strings = Numerals.trio(places[p * 3, 3])\n name.push(Mega[p]) if strings.length > 0 and p > 0\n name += strings\n end\n name.push(Ones[0]) unless name.length > 0\n name.reverse.join(\" \")\n end", "def read_numbers n\n if(n == 0)\n return \"\"\n end\n \n hash = number_to_words_hash\n num_str = n.to_s\n len = num_str.length\n placeholder = \" \" \n \n if (len == 4)\n placeholder = \" thousand \" \n end\n\n if (len == 3)\n placeholder = \" hundred \"\n if (n % 100 != 0)\n placeholder = placeholder + \"and \"\n end\n end\n\n if (len == 2)\n if hash.has_key?(n)\n return hash[n] \n end\n return hash[(num_str[0].to_s+\"0\").to_i] + \"-\" + hash[num_str[1].to_i]\n\n end\n \n return (hash[num_str[0].to_i] + placeholder + read_numbers(num_str[1, len].to_i)).rstrip \nend", "def take_a_number(katz_deli, person)\n katz_deli << person\n puts \"Welcome, #{person}. You are number #{katz_deli.length} in line.\"\nend", "def show_id(input)\n index = /\\d/.match(input)\n index = index.to_s.to_i + 1 - 1\n pp find(index)\nend", "def take_a_number(katz_deli, name)\n puts \"Welcome, #{name}. You are number #{katz_deli.length + 1} in line.\";\n katz_deli.push(name);\nend", "def take_a_number(katz_deli, name)\n \n \n people_waiting = katz_deli.count\n\n katz_deli << name\n \n \n while people_waiting > 0\n \n \n puts \"#{name} your place in line is #{people_waiting+1}\"\n \n \n break\n \n \n\n end\n \n end", "def line(line_no)\n @line[line_no]\n end", "def line(line_no)\n @line[line_no]\n end", "def line(line_no)\n @line[line_no]\n end", "def take_a_number(katz_deli, customer_name)\n if katz_deli == []\n katz_deli << customer_name\n katz_deli.map.with_index do |name, place|\n puts \"Welcome, #{name}. You are number #{place + 1} in line.\"\n end\n else\n katz_deli << customer_name\n katz_deli.map.with_index do |name, place|\n end\n last_customer = katz_deli.last\n last_place = katz_deli.index(last_customer)\n puts \"Welcome, #{last_customer}. You are number #{last_place + 1} in line.\"\n end\n #line(katz_deli)\nend", "def initialize name, number\n @name = name\n @number = number\n end", "def parse_debug_line_number(number_as_string)\n # Deduct 1 because kakoune always maintains an extra empty line at the end of the debug buffer.\n number_as_string.to_i - 1\nend", "def line_n\n [\"Times Square\", \"34th\", \"28th\", \"23rd\", \"Union Square\", \"8th\"]\nend", "def number_or_name\n number ? \"Chapter #{number_as_word}\" : name\n end", "def get_number(lines)\n lines.shift.to_i\n end", "def take_a_number(katz_deli, name)\n puts \"Welcome, #{name}. You are number #{katz_deli.size + 1} in line.\"\n katz_deli.push(name)\nend", "def section_number(snum)\n \"#{snum.to_s}\"\nend", "def read_specific_line(file_name, line_number)\n line = `sed '#{line_number + 1}!d' #{file_name}`\n line.chop! if line.last == \"\\n\"\n LoggerHelper.print_to_log(\"Lines in '#{file_name}' by number is '#{line}'\")\n line\n end", "def pnum cel\n number = cel.gsub(' ', '').gsub('(', '').gsub(')', '')\n end", "def create_line(num)\n '-' * num\nend", "def take_a_number(array, name)\n array.push(name)\n\n place = array.index(name)\n place = place.to_i\n place += 1\n\n puts \"Welcome, #{name}. You are number #{place} in line.\"\nend", "def take_a_number(katz_deli, name) #defines the take_a_number method using an array's (katz_deli) coorindnates with an assosicated sequence of names.\n katz_deli.push(name) # .push takes the names and adds them to end of the array (katz_deli), pushing forward the next person in line.\n position = katz_deli.index(name) # .index takes the names' positions within the array to to create a queue of people waiting in line. Ascribing the names to position within the array katz_deli.\n puts \"Welcome, #{name}. You are number #{katz_deli.index(name)+1} in line.\" #\"puts\" sends a message with the name of the ticket taker and their ticket number, which is their place within the array and adds 1 (Ruby array indexing starts at 0.) Also, an index of -1 indicates the last element of the array, -2 is the next to last element in the array, and so on.\n return name, position #returns the name and position of the following person to move the line.\nend", "def player_by_number(number)\n players.each do |name, stats|\n if stats[:number] == number\n return name\n end\n end\nend", "def name\n \"#{number}: #{short_name}\"\n end", "def read_line_number(filename, number)\n return nil if number < 1\n line = File.readlines(filename)[number-1]\n line ? line.chomp : nil\n end", "def name_or_number\n if !name.empty?\n name\n elsif number\n \"Chapter #{number_as_word}\"\n else\n \"\"\n end\n end", "def name_bill\n \"#{name}:#{endNumber}\"\n end", "def fixed_line_number\n FFaker.numerify('6### ####')\n end", "def print_numbers\n @file.each do |line|\n number = clean_numbers(line[:homephone])\n puts number\n end\n\n end", "def number\n\t\tname.gsub(/^rfc/i, '').to_i\n\tend", "def value(line)\r\n line.split(\" \")[1].to_i\r\nend", "def add(name)\n\tp result = name.join.to_i + 1\n\tar = result.to_s.split('')\n\tp ar.map! { |x| x.to_i }\nend", "def write_with_number(index, s, n)\n write_text(index, s)\n write_text(index, n, 2)\n end", "def draw_item_number(item, rect)\n return if item.result_n == 1\n num = sprintf('x%d', item.result_n)\n draw_text(rect, num, 2)\n end", "def satellitenumber\n @line1[02...07].to_i\n end", "def take_a_number (katz_deli, name)\n katz_deli << name\n if katz_deli == 0\n puts \"The line is currently empty.\"\n else\n# .length returns number of names in katz_deli array.\n puts \"Welcome, #{name}. You are number #{katz_deli.length} in line.\"\n end\nend", "def get_trace_id(line)\n return line.split(\"\\t\")[1].to_i\nend", "def get_numerology (your_number)\r\n\tcase your_number\r\n\t\twhen 1\r\n\t\t\tputs \"You are a ONE! One is the leader. The number one indicates the ability to stand alone, and is a strong vibration. Ruled by the Sun.\"\r\n\t\twhen 2\r\n\t\t\tputs \"You are a TWO! This is the mediator and peace-lover. The number two indicates the desire for harmony. It is a gentle, considerate, and sensitive vibration. Ruled by the Moon.\"\r\n\t\twhen 3\r\n\t\t\tputs \"You are a THREE! Number Three is a sociable, friendly, and outgoing vibration. Kind, positive, and optimistic, Three’s enjoy life and have a good sense of humor. Ruled by Jupiter.\"\r\n\t\twhen 4\r\n\t\t\tputs \"You are a FOUR! This is the worker. Practical, with a love of detail, Fours are trustworthy, hard-working, and helpful. Ruled by Uranus.\"\r\n\t\twhen 5\r\n\t\t\tputs \"You are a FIVE! This is the freedom lover. The number five is an intellectual vibration. These are ‘idea’ people with a love of variety and the ability to adapt to most situations. Ruled by Mercury.\"\r\n\t\twhen 6 \r\n\t\t\tputs \"You are a SIX! This is the peace lover. The number six is a loving, stable, and harmonious vibration. Ruled by Venus.\"\r\n\t\twhen 7 \r\n\t\t\tputs \"You are a SEVEN! This is the deep thinker. The number seven is a spiritual vibration. These people are not very attached to material things, are introspective, and generally quiet. Ruled by Neptune.\"\r\n\t\twhen 8 \r\n\t\t\tputs \"You are an EIGHT! This is the manager. Number Eight is a strong, successful, and material vibration. Ruled by Saturn.\"\r\n\t\twhen 9\r\n\t\t\tputs \"You are a NINE! This is the teacher. Number Nine is a tolerant, somewhat impractical, and sympathetic vibration. Ruled by Mars.\"\r\n\t\telse \r\n\t\t\tputs \"Sorry, but your number doesn't exist.\"\r\n\tend\r\nend", "def name\n lines[0]\n end", "def get_number(identifier)\n print \"==> Enter the #{identifier} number: \"\n gets.chomp.to_i\nend", "def get2number(afirstname, asecondname)\n \"Hello #{afirstname} #{asecondname}\"\nend", "def print_number(number)\n number.nil? ? \"_\" : (number + 1).to_s\n end", "def take_a_number(array, name)\n length = array.length \n case length\n when 0 \n array.push(name)\n puts \"Welcome, #{array[0]}. You are number 1 in line.\"\n else \n array.push(name)\n puts \"Welcome, #{name}. You are number #{array.length} in line.\"\n end\n end", "def housenumber\n \"[#{@housenumber}]\"\n end", "def generate_name_with_digit (digit)\n char_array = ('a'..'z').to_a + ('0'..'9').to_a + ['_'] # char_array.length is 37\n\n quotient = digit\n queue = []\n while true do\n queue.push quotient % N_CHAR\n quotient = (quotient / N_CHAR).round - 1\n if quotient <= -1\n break\n end\n end\n\n name = ''\n while queue.any? do\n name = name + char_array[queue.pop]\n end\n name\n end", "def take_a_number(katz_deli, customer)\n katz_deli.push(customer)\n puts \"Welcome, #{customer}. You are number #{katz_deli.length} in line.\"\n end", "def draw_item_number(rect, item)\n draw_text(rect, sprintf(\":%2d\", $game_party.item_number(item)), 2)\n end", "def line_index(num)\n\t\tif num == 0\n\t\t\treturn -1\n\t\telsif num <= @line_indices.length\n\t\t\treturn @line_indices[num - 1]\n\t\telsif num == @line_indices.length + 1\n\t\t\treturn @text.length\n\t\telse\n\t\t\treturn -999 # todo\n\t\tend \n\tend", "def coordinator(num)\n if num < 10\n [0, num]\n else\n num.to_s.split('').map(&:to_i)\n end\n end", "def interesting_number(number)\n number.each_char.map {|c| c.to_i}\n puts number\nend", "def full_info number \n\t\tshort_text = description.split(\"<br>\")[0][0..59]\n\t\tshort_text = short_text + \"...\" if short_text.length == 60\n\t\t\"#{number}. #{short_text}\"\n\tend", "def ordinal(number)\n Geode::FastInflector.ordinal(number.to_i)\n end", "def number_to_name\n proto_table.invert[@number] || @number.to_s\n end", "def code_by_ordinal(num)\n chunks.find { |ch| ch.ordinal == num }\n end", "def name\n \"#{gtc_number}-#{name_str(order_number)}-#{name_str(mod_number)}\"\n end", "def callnumbers_from_945(record)\n callnumbers = []\n # Get the and b values to use as alternates\n # TODO: do we need to consider other fields (e.g. 099)?\n values_090ab = []\n x090ab = extract_marc(\"090ab\", :trim_punctuation => false)\n x090ab.call(record, values_090ab, nil)\n alternate_stem = values_090ab.join(\" \")\n # Process the callnumbers in the 945\n f945 = record.select {|f| f.tag == \"945\"}\n f945.each do |f|\n a = subfield_value(f, \"a\")\n b = subfield_value(f, \"b\")\n c = subfield_value(f, \"c\")\n g = subfield_value(f, \"g\")\n callnumber = build_callnumber(a, b, c, g, alternate_stem)\n if callnumber != \"\"\n callnumbers << callnumber\n end\n end\n callnumbers\nend", "def elementnumber\n @line1[64...68].to_i\n end", "def draw_item_number(rect, item)\n draw_text(rect, sprintf(\":%2d\", @event.tb_unit.item_number(item)), 2)\n end", "def human_readable(number, type)\n\t# Do some math then return the number in a commified form:\n\treturn (number/type).to_s.gsub(/(\\d)(?=\\d{3}+(?:\\.|$))(\\d{3}\\..*)?/,'\\1,\\2')\nend", "def format_num(num); number_with_delimiter(num) end", "def number!(theDot = '.')\n theDot = '.' if theDot.length == 0\n theDot = theDot.delete(\"\\n\")\n l = @theLines.length\n nums = Array.new\n 1.upto(l) { |i| nums << sprintf('%d%s ', i, theDot) }\n w = nums[l-1].length\n nums.each_index { |i| nums[i] = nums[i].rjust(w) + @theLines[i] }\n @theLines = nums\n return self\n end", "def getNumber _args\n \"getNumber _args;\" \n end" ]
[ "0.65389943", "0.64754903", "0.6464459", "0.64454347", "0.6438557", "0.63748974", "0.63555187", "0.6334456", "0.6275784", "0.6238477", "0.6220943", "0.61808383", "0.61358494", "0.61358494", "0.6130072", "0.6125467", "0.6120338", "0.6069747", "0.6038459", "0.6002342", "0.5935922", "0.59218985", "0.59218985", "0.5917619", "0.58976144", "0.58778256", "0.5853958", "0.5846091", "0.58215356", "0.5821248", "0.5821248", "0.5821248", "0.5821248", "0.5821248", "0.5819491", "0.5801479", "0.5800087", "0.57875735", "0.5762515", "0.57559794", "0.57448995", "0.57180303", "0.57162786", "0.5695672", "0.56787133", "0.56787133", "0.56787133", "0.5668412", "0.56558645", "0.5649485", "0.56392044", "0.5637994", "0.56297505", "0.561709", "0.56149507", "0.56092584", "0.5600269", "0.55891556", "0.5587144", "0.5585443", "0.554975", "0.55332196", "0.5528773", "0.5508398", "0.54936033", "0.5476493", "0.54608613", "0.5460229", "0.5454421", "0.54407775", "0.5416994", "0.53986835", "0.5395672", "0.53941566", "0.53859305", "0.5380313", "0.537651", "0.53630966", "0.5361224", "0.5328061", "0.5311101", "0.53075755", "0.5305868", "0.53057694", "0.53040916", "0.5300098", "0.52999187", "0.52973497", "0.5293285", "0.52926296", "0.5287648", "0.52851397", "0.5269697", "0.52692044", "0.52610594", "0.52593404", "0.52547836", "0.5254253", "0.52524227", "0.5240794" ]
0.5986978
20
TODO: filter by resource type if system uses different resource types later
def index if params[:fromDate] == '' || params[:toDate] == '' flash[:alert] = 'Please choose the date range' return redirect_to upcoming_bookings_url end build_date_params @bookings = Booking.all( coworker_id: nil, resource_ids: [], options: { from_time: @from_time, to_time: @to_time } ).sort_by(&:from_time) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def resource_type_filter\n return filter_for(:resource_type_id, \n objects_to_names_and_ids(current_user.company.resource_types),\n session[:resource_filters], _(\"Resource Type\"))\n end", "def resource_type_filter\n return filter_for(:resource_type_id,\n objects_to_names_and_ids(current_user.company.resource_types),\n session[:resource_filters], ResourceType.model_name.human)\n end", "def find_resources(type)\n resource_collection.all_resources.select do |resource|\n resource_name(resource) == type.to_sym\n end\n end", "def get_resource_types\n Occi::Log.debug(\"Getting resource types ...\")\n collection = @model.get Occi::Core::Resource.kind\n collection.kinds.collect { |kind| kind.term }\n end", "def getResourceType() \n @obj.getResourceType() \n end", "def resource_type\n\t\t\t\t\t\traise \"Not implemented.\"\n\t\t\t\t\tend", "def filter_resources(resources, opts)\n if opts[:type] && opts[:name]\n resources.select { |r| r.type == opts[:type] && r.name == opts[:name] }\n elsif opts[:type]\n resources.select { |r| r.type == opts[:type] }\n elsif opts[:name]\n resources.select { |r| r.name == opts[:name] }\n else\n resources\n end\n end", "def get_resource_types\n get_types(Occi::Core::Resource.kind)\n end", "def resource_type\n return @resource_type\n end", "def resource_type\n return @resource_type\n end", "def resource_type\n return @resource_type\n end", "def resource_type\n return @resource_type\n end", "def resource_type\n \"b\"\n end", "def get_resource_type()\n return RedXmlResource::TYPE\n end", "def all_of_type\n Resource::AllOfType.new(type)\n end", "def resources_by_type(ast)\n result = Hash.new{|hash, key| hash[key] = Array.new}\n find_resources(ast).each{|resource| result[resource_type(resource)] << resource}\n result\n end", "def resources_by_type(ast)\n result = Hash.new{|hash, key| hash[key] = Array.new}\n find_resources(ast).each{|resource| result[resource_type(resource)] << resource}\n result\n end", "def find_resource(obj)\n\n\n\n resources.detect do |r|\n\n\n\n r.resource_name.to_s == obj.to_s || r.resource_class.to_s == obj.to_s\n\n\n\n end ||\n\n\n\n if obj.respond_to? :base_class\n\n\n\n resources.detect{ |r| r.resource_class.to_s == obj.base_class.to_s }\n\n\n\n end\n\n\n\n end", "def get_resource(resource_type, filter = {})\n fail \"resource_type must be specified\" if resource_type.nil?\n\n # Ensure the hash key is correct when searching\n hash_key = resource_type.to_s.upcase\n hash_key = 'VMTEMPLATE' if hash_key == 'TPL' || hash_key == 'TEMPLATE'\n\n if filter.empty?\n Chef::Log.warn(\"get_resource: 'name' or 'id' must be provided\")\n return nil\n end\n pool = get_pool(resource_type)\n\n if resource_type.to_s != 'user' && filter[:id] && !filter[:id].nil?\n pool.info!(-2, filter[:id].to_i, filter[:id].to_i)\n return pool.first\n end\n\n if resource_type.to_s == 'user'\n pool.info\n else\n pool.info!(-2, -1, -1)\n end\n resources = []\n pool.each do |res|\n next unless res.name == filter[:name]\n next if filter[:uname] && res.to_hash[hash_key]['UNAME'] != filter[:uname]\n resources << res\n end\n return nil if resources.empty?\n return resources[0] if resources.size == 1\n resources\n end", "def subclass_resource_equivalents\n @subclass_resource_names ||= [resource_name.to_sym]\n end", "def lookup(type)\n @resource_types[type] || []\n end", "def resource\n return Object unless resource_type\n return resource_type.constantize unless resource_id\n return _resource\n end", "def type\n Resource::ALL\n end", "def is_resource\n return self.resource_type == Resource::RESOURCE;\n end", "def get_resource_class\n \tresource_name.classify.constantize\n end", "def find_resource(type, name)\n begin\n return resource_collection.lookup(\"#{type}[#{name}]\")\n rescue Chef::Exceptions::ResourceNotFound; end\n\n resource_collection.all_resources.find do |resource|\n resource_name(resource) == type && (name === resource.identity || name === resource.name)\n end\n end", "def map_resource_type(resource_types, node)\n if resource_types.empty?\n if node.is_a?(IFile)\n return {\n 'string' => 'File',\n 'icon' => 'file'\n }\n else\n return {\n 'string' => 'Unknown',\n 'icon' => 'cog'\n }\n end\n end\n\n types = {\n '{http://calendarserver.org/ns/}calendar-proxy-write' => {\n 'string' => 'Proxy-Write',\n 'icon' => 'people'\n },\n '{http://calendarserver.org/ns/}calendar-proxy-read' => {\n 'string' => 'Proxy-Read',\n 'icon' => 'people'\n },\n '{urn:ietf:params:xml:ns:caldav}schedule-outbox' => {\n 'string' => 'Outbox',\n 'icon' => 'inbox'\n },\n '{urn:ietf:params:xml:ns:caldav}schedule-inbox' => {\n 'string' => 'Inbox',\n 'icon' => 'inbox'\n },\n '{urn:ietf:params:xml:ns:caldav}calendar' => {\n 'string' => 'Calendar',\n 'icon' => 'calendar'\n },\n '{http://calendarserver.org/ns/}shared-owner' => {\n 'string' => 'Shared',\n 'icon' => 'calendar'\n },\n '{http://calendarserver.org/ns/}subscribed' => {\n 'string' => 'Subscription',\n 'icon' => 'calendar'\n },\n '{urn:ietf:params:xml:ns:carddav}directory' => {\n 'string' => 'Directory',\n 'icon' => 'globe'\n },\n '{urn:ietf:params:xml:ns:carddav}addressbook' => {\n 'string' => 'Address book',\n 'icon' => 'book'\n },\n '{DAV:}principal' => {\n 'string' => 'Principal',\n 'icon' => 'person'\n },\n '{DAV:}collection' => {\n 'string' => 'Collection',\n 'icon' => 'folder'\n }\n }\n\n info = {\n 'string' => [],\n 'icon' => 'cog'\n }\n\n resource_types.each do |resource_type|\n if types.key?(resource_type)\n info['string'] << types[resource_type]['string']\n else\n info['string'] << resource_type\n end\n end\n\n types.each do |key, resource_info|\n if resource_types.include?(key)\n info['icon'] = resource_info['icon']\n break\n end\n end\n\n info['string'] = info['string'].join(', ')\n\n info\n end", "def get_resource_type_identifiers\n get_kind_type_identifiers_related_to Occi::Core::Resource.kind.type_identifier\n end", "def transform_Resource(o, scope)\n Types::TypeFactory.resource(o.type, o.title)\n end", "def resources_by_type(ast)\n raise_unless_xpath!(ast)\n result = Hash.new{|hash, key| hash[key] = Array.new}\n find_resources(ast).each do |resource|\n result[resource_type(resource)] << resource\n end\n result\n end", "def resource_type\n document_type\n end", "def resource_type\n document_type\n end", "def resource_class\n\t\t\t\t@resource_class ||= resource_name.classify.constantize\n\t\t\tend", "def lookup_resource(type, name, run_context)\n begin\n run_context.resource_collection.find(\"#{ type }[#{ name }]\")\n rescue ArgumentError => e\n puts \"You provided invalid arugments to resource_collection.find: #{ e }\"\n rescue RuntimeError => e\n puts \"The resources you searched for were not found: #{ e }\"\n end\n end", "def resource_class\n # TODO does this need to have draft?\n @resource_class ||= resource_name.classify.constantize\n end", "def controlled_resources\n @controlled_resources ||= if params[:media_name]\n super.where(type: singular_linked_media_type)\n else\n super\n end\n end", "def resource_type\n case\n when controller_name.starts_with?('search')\n params[:record_type]\n when is_variable_controller?\n 'variables'\n when is_services_controller?\n 'services'\n when is_tools_controller?\n 'tools'\n else\n # default\n 'collections'\n end\n end", "def resource_class\n resource_finder.is_a?(Class) ? resource_finder : resource_finder.name.classify.constantize\n end", "def resource_type_from_document(document)\n resource_type = \"\"\n\n #type_ssi\n #resource_type = document[\"format_ssi\"] unless document[\"format_ssi\"].nil?\n resource_type = document[\"format_ssi\"] || document[\"type_ssi\"]\n resource_type = resource_type.is_a?(Array) ? resource_type.first : resource_type\n end", "def resource_type_from_document(document)\n resource_type = \"\"\n\n #type_ssi\n #resource_type = document[\"format_ssi\"] unless document[\"format_ssi\"].nil?\n resource_type = document[\"format_ssi\"] || document[\"type_ssi\"]\n resource_type = resource_type.is_a?(Array) ? resource_type.first : resource_type\n end", "def resource_singular() self.class.read_inheritable_attribute(:resource_singular) end", "def storage_only\n select {|d| d.resource_type == 17}\n end", "def get_resource_type(type, resource_path)\n changed_path = resource_path.split('/').last\n if type.eql?('singular')\n changed_path.singularize.to_sym\n else\n changed_path.to_sym\n end\n end", "def dor_resource_content_type\n public_xml_doc.xpath('//contentMetadata/resource/@type').map(&:text)\n end", "def resource_class\n resource_specification.klass\n end", "def get_resource_type_identifiers\n get_entity_types_related_to Occi::Core::Resource.kind.type_identifier\n\n end", "def resource_type=(value)\n @resource_type = value\n end", "def resource_type=(value)\n @resource_type = value\n end", "def resource_type=(value)\n @resource_type = value\n end", "def resource_type=(value)\n @resource_type = value\n end", "def show\n @resource_type = @resource.resource_type\n @values = ResourceValue.where(\"resource_id = ?\", params[:id])\n @field_types = []\n @values.each do |value|\n if value.field.resource_type_reference_id\n @field_types << Resource.find(value.resource_reference_id).resource_type\n else\n @field_types << value.field.field_type\n end\n end \n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @resource }\n end\n end", "def resource_param\n \"#{params[:resource]}\".classify\n end", "def get_resource(resource_type)\n\n Occi::Log.debug(\"Instantiating #{resource_type} ...\")\n\n if @model.get_by_id resource_type\n # we got a resource type identifier\n Occi::Core::Resource.new resource_type\n elsif @model.kinds.select { |kind| kind.term == resource_type }.any?\n # we got a resource type name\n Occi::Core::Resource.new @model.kinds.select {\n |kind| kind.term == resource_type\n }.first.type_identifier\n else\n raise \"Unknown resource type! [#{resource_type}]\"\n end\n\n end", "def resource_name\n resource_class.slice(0,1).downcase + resource_class.slice(1,resource_class.length)\n end", "def resource_list\n self.resources\n end", "def resource_attributes_by_type(ast)\n result = {}\n resources_by_type(ast).each do |type,resources|\n result[type] = resources.map{|resource| resource_attributes(resource)}\n end\n result\n end", "def resource_attributes_by_type(ast)\n result = {}\n resources_by_type(ast).each do |type,resources|\n result[type] = resources.map{|resource| resource_attributes(resource)}\n end\n result\n end", "def resource_attributes_by_type(ast)\n result = {}\n resources_by_type(ast).each do |type,resources|\n result[type] = resources.map{|resource| resource_attributes(resource)}\n end\n result\n end", "def resource_class\n @resource_class ||= resource_name.classify.constantize\n end", "def resource_class\n @resource_class ||= resource_name.classify.constantize\n end", "def resource_class\n @resource_class ||= resource_name.classify.constantize\n end", "def map_to_orcid_type( resource_type )\n\n case resource_type\n when 'Article'\n return 'journal-article'\n when 'Book'\n return 'book'\n when 'Conference Paper'\n return 'conference-paper'\n when 'Part of Book'\n return 'book-chapter'\n when 'Report'\n return 'report'\n when 'Journal'\n return 'journal-issue'\n when 'Poster'\n return 'conference-poster'\n else\n return 'other'\n end\n\n end", "def resource_class\n @resource_class ||= resource_name.classify.constantize\n end", "def resource_class\n @resource_class ||= self.class.to_s.split(\":\").last\n end", "def remap_resource_type\n return unless is_a?(Bulkrax::CsvFileSetEntry)\n\n parsed_metadata.delete('resourceType_attributes')\n parsed_metadata['resource_type'] = raw_metadata['resourcetype']&.split(/\\s*[|]\\s*/)\n end", "def catalog_resources\n # This method exists to supply a common interface to the puppet catalog\n # for different versions of puppet.\n @catalog.resources.map do |r|\n if r.is_a?(String)\n # puppet 0.25 and older\n resource(r)\n elsif r.is_a?(Puppet::Resource)\n # puppet 2.6 and newer\n r\n else\n raise \"Unknown resource object #{r.class}\"\n end\n end\n end", "def set_resourcetype\n @resourcetype = Resourcetype.find(params[:id])\n end", "def resource_type\n /(\\/api\\/(?<type>\\w+)\\/?)/ =~ full_url\n type.capitalize\n end", "def set_resource_type\n @resource_type = ResourceType.find(resource_type_params[:id])\n end", "def find_all_resources(resource_descr, resource_type, authorizer)\n debug \"find_resources: descr: '#{resource_descr.inspect}'\"\n if resource_descr.kind_of? Hash\n can_handle = eval(\"OMF::SFA::Model::#{resource_type.classify}\").respond_to? :handle_rest_get_resource\n if can_handle\n cls = eval(\"OMF::SFA::Model::#{resource_type.classify}\")\n resources = cls.handle_rest_get_resource(resource_descr)\n else\n resources = eval(\"OMF::SFA::Model::#{resource_type.classify}\").where(resource_descr)\n end\n else\n raise FormatException.new \"Unknown resource description type '#{resource_descr.class}' (#{resource_descr})\"\n end\n\n # raise UnknownResourceException.new \"Resource '#{resource_descr.inspect}' is not available or doesn't exist\" if resources.nil? || resources.empty?\n raise UnknownResourceException.new \"Resource '#{resource_descr.inspect}' is not available or doesn't exist\" if resources.nil?\n\n resources.map do |r|\n begin\n raise InsufficientPrivilegesException unless authorizer.can_view_resource?(r)\n r\n rescue InsufficientPrivilegesException\n nil\n end\n end.compact\n end", "def type_as_class(resource_name)\n\t resource_name.singularize.capitalize.constantize\n\tend", "def published_resource_class\n @published_resource_class ||= resource_name.classify.pluralize.constantize\n end", "def resource_id\n return \"%s:%s\" % [self.resource_type, self.id]\n end", "def get_resource_type_identifier(type)\n get_type_identifier(type, Occi::Core::Resource.kind)\n end", "def to_resource_declaration(type)\n if type.respond_to?(:type_name) && type.respond_to?(:title)\n title = type.title\n type_name = type.type_name\n elsif type_result = /(\\w+)\\['?(\\w+)'?\\]/.match(type.to_s)\n # not all types have a type_name and title so we\n # output to a string and parse the results\n title = type_result[2]\n type_name = type_result[1]\n else\n return type\n end\n res = scope.catalog.resource(type_name, title)\n return res.to_ral if res\n # don't return anything or returns nil if item is not in the catalog\n end", "def resource_class\n \t@resource_class ||= get_resource_class\n end", "def resource_for(klass)\n resources[klass]\n end", "def show\n @resource_fields = Field.where(\"resource_type_id = ?\", params[:id])\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @resource_type }\n end\n end", "def ar_resource\n return unless type && id\n return unless self.class.union_models.include?(type.to_sym)\n\n klass = type.classify.constantize rescue nil\n return unless klass\n klass.find_by_id(id)\n end", "def type(resource_type)\n Cocina::Models::FileSetType.properties[resource_type.to_sym]\n end", "def resourceType\n 'DomainResource'\n end", "def class_of_resource\n @class_of_resource ||= resource_name.classify.constantize\n end", "def as_resource()\n # Titles might have NULL, 0 (not assigned), or 7 (multiple) as \n # the language. Return nil for all of these\n resource = {\n :title => title,\n :language => [nil, 0, 7].include?(languageid) ? nil : \n languages.codes.language_code,\n :type => titletypes.titletype,\n :order => displayorder,\n :prepend => nil,\n :append => nil\n }\n\n # These titletypes are use to indicate the phrasing of a series \n # title\n #\n # 7 = from the series X\n # 15 = from the X series \n # 16 = from X\n #\n # We'll break that up into a phrase to prepend and/or append to the \n # title when it is displayed\n if [7, 15, 16].include?(titletypeid)\n resource[:type] = \"Series\"\n phrase = titletypes.titletype.match(/\\((.+)\\)/)\n if phrase == nil\n raise UnknownSeriesFormatError, \"Cannot parse series title format \\\"#{collection_tms_titletypes.titletype}\\\"\"\n end\n\n affixes = phrase[1].match(/^(.+)?(X)(.+)?$/)\n if affixes[1] != nil\n resource[:prepend] = affixes[1].strip\n end\n\n if affixes[3] != nil\n resource[:append] = affixes[3].strip\n end\n end\n \n resource\n end", "def find_resource str\n resources.find{|rsc_klass| rsc_klass.to_s == str }\n end", "def show\n @resource = Resource.find(params[:id])\n @resource_type = ResourceType.find(@resource.resource_type_id)\n @values = ResourceValue.where(resource_id: params[:id])\n @field_types=[]\n @values.each do |value|\n @field_types << value.Field\n end\n \n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @resource }\n end\n end", "def get_resource resource_uuid\n return resource_uuid if resource_uuid.is_a?(Resource)\n \n tmp = @resources.find{|res|res.uuid == resource_uuid}\n \n raise \"unknown resource with uuid #{resource_uuid}\" unless tmp\n \n tmp\n end", "def resource_class\n @resource_class ||= resource_class_name.constantize\n end", "def resource_item_name\n resource_name.to_s.singularize.to_sym\n end", "def list_resource\n resource_class.all_but_other\n end", "def resource_class\n @resource_class ||= resource_name.classify.constantize\n end", "def resource_class\n @resource_class ||= resource_name.classify.constantize\n end", "def resource_class\n @resource_class ||= resource_name.classify.constantize\n end", "def resource_query\n resource_class\n end", "def resource_type\n return 'Data'\n end", "def as_resource\n {\n :primary => @primary.as_resource,\n :other => @other.count > 0 ? @other.map {|t| t.as_resource} : nil\n }\n end", "def resource_type(resource)\n resource.xpath('string(command/ident/@value)')\n end", "def resource_type(resource)\n resource.xpath('string(command/ident/@value)')\n end", "def resource_model\n Object.const_get options[:resource].classify\n end", "def get_resource_templates\n @model.get.mixins.select { |mixin| mixin.related.select { |rel| rel.end_with? 'resource_tpl' }.any? }\n end", "def resource?\n product_type == :resource\n end", "def check_resource! resource \n resources.include?(resource.to_s) ? resource_parsed(resource) : raise(\"resource should be in [tags, posts, bundles]\") \n end" ]
[ "0.75654453", "0.74132526", "0.7187222", "0.6966026", "0.685138", "0.68013346", "0.67923766", "0.67795813", "0.6766436", "0.6766436", "0.6766436", "0.6766436", "0.6668854", "0.6653556", "0.663171", "0.6625173", "0.6625173", "0.6618369", "0.6604739", "0.6571398", "0.6552887", "0.6549308", "0.6514374", "0.6497889", "0.6422962", "0.6420405", "0.6391593", "0.6371205", "0.634648", "0.6316327", "0.62610173", "0.62610173", "0.62458956", "0.6240646", "0.6229627", "0.6225697", "0.62209433", "0.6215016", "0.62073123", "0.62073123", "0.6196359", "0.6196162", "0.6189921", "0.6174538", "0.6166484", "0.6161517", "0.6140609", "0.6140609", "0.6140609", "0.6140609", "0.6137315", "0.61341745", "0.61321884", "0.61291105", "0.6128004", "0.61239314", "0.61239314", "0.61239314", "0.6122697", "0.6122697", "0.6122697", "0.61133355", "0.61002094", "0.60947514", "0.60901845", "0.60875124", "0.6084219", "0.6084033", "0.60800743", "0.6072274", "0.60498875", "0.6049727", "0.6040064", "0.6038865", "0.60370344", "0.6035678", "0.6022765", "0.6021045", "0.6020698", "0.6018728", "0.60181457", "0.60172766", "0.6016669", "0.60148704", "0.60140073", "0.6012077", "0.6011465", "0.60070205", "0.60053164", "0.59968704", "0.59968704", "0.59968704", "0.59955907", "0.59945136", "0.5988286", "0.5987007", "0.5987007", "0.5983784", "0.5979069", "0.5958747", "0.5957947" ]
0.0
-1
constantly alternates between these two loops
def buy_in_loop @entry_time = Time.now set_amount_and_check_balance loop do log_time_and_price set_and_log_indicator_ivars if lagging_indicators_green && leading_indicators_green set_buy_in break else @dc.prepend 'position_logs', "NOT BUYING IN YET ------------------------------------ <br /><br />" set_sleep_time #varies depending on state of indicators. end end manage_position_loop end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def performs_sequential!()\n\n @m.times do |y|\n @n.times do |x|\n\n turn!(x, y)\n end\n end\n\n self\n end", "def loop!\n f, l = first, last\n first.prv = l\n last.nxt = f\n end", "def check_for_implication_loops\n # actually this is tricky\n end", "def alternate!\n return self if size.zero?\n first = self[0]\n return self.clear << [first] if size == 1\n ary1, ary2 = populate_alternate_arrays\n self.clear << ary1 << ary2\n end", "def two(a, b)\n for i in a..b\n puts i if a.even?\n a += 1\n end\nend", "def interleave(array_1, array_2)\n new_array = []\n total_elements = array_1.length + array_2.length\n array_1_current_idx, array_2_current_idx = 0 , 0\n\n total_elements.times do |current_iteration|\n if current_iteration.odd?\n new_array.push(array_2[array_2_current_idx])\n array_2_current_idx += 1\n else\n new_array.push(array_1[array_1_current_idx])\n array_1_current_idx += 1\n end\n end\n\n new_array\nend", "def light_switcher(array, inc)\n counter = 0\n\n while counter < array.length\n array[counter] = !array[counter] if (counter + 1) % inc == 0\n counter += 1\n end\n\n array\nend", "def run_block_with_next\n numbers = []\n\n (1..20).each do |number|\n next if number.odd?\n numbers << number\n end\n\n numbers\nend", "def cycle()\n Enumerator.new do |out|\n values = self.touch{|x| out.yield x}.to_a\n unless values.empty?\n loop do\n values.each{|x| out.yield x}\n end\n end\n end\n end", "def pre_loop; end", "def cycle arr\n while true\n arr.each do |elem|\n yield elem\n end\n end\nend", "def double_repeat\n 2.times { yield }\nend", "def climb_stairs_2(n)\n a = b = 1\n n.times { a, b = b, a + b }\n a\nend", "def stripe_cycle\n cycle('odd', 'even')\n end", "def generateLoop2\n for i in 1...10 do #do optional\n puts i\n end\n end", "def my_times\n\t\tfor i in 1..self\n\t\t\tyield\n\t\tend\n\tend", "def compute\n\t\twhile @current != 1\n\t\t \tif (@current % 2) == 0\n\t\t\t\t@current = @current / 2\n\t\t\telse\n\t\t\t\t@current = (3 * @current) + 1\n\t\t\tend\n\t\t\t@seq[@count] = @current\n\t\t\t@count += 1\n\t\tend\n\t\t@count += 1\n\tend", "def aliquot_sequence(a,b)\n arr = [a]\n j = 0\n (b-1).times do\n sum = 0\n i = 1\n while i < arr[j]\n if arr[j] % i == 0\n sum += i\n end\n i += 1\n end\n j += 1\n arr << sum\n end\n print arr\nend", "def loop; end", "def recycle\n recycling = true\n while recycling \n while @total_caps >= 4 \n recycle_caps\n end\n while @empty_bottles >= 2 \n recycle_bottles\n end\n if @empty_bottles < 2 && @total_caps < 4 \n recycling = false\n end\n end\nend", "def iter_hegemon_auto_loop(i=0)\n do_state_tasks(i)\n update_state(:only_auto)\n end", "def every_other\n i = 1\n numbers = []\n 50.times do\n numbers << i\n i+= 2\n end\n return numbers\nend", "def iter\n f1,f2,k = 1,1,2\n f1,f2,k = f2,f1+f2,k+1 while f2.to_s.size < 1000\n puts k\nend", "def ex2\n for i in (0..5)\n for j in (1..(4 - (4 - i).abs))\n print '#'\n end\n print \"\\n\"\n end\nend", "def light_switcher(lights)\n 1.upto(lights.size) do |light_num|\n 1.upto(lights.size) do |num|\n if num % light_num == 0\n lights[num] == \"off\" ? lights[num]=\"on\" : lights[num]=\"off\"\n end\n end\n end\n lights\nend", "def step_one_to_n_to_one(n)\n e = Enumerator.new do |y|\n (1..n).step(2).each { |i| y << i}\n (n - 2).downto(1).each { |i| y << i if i.odd?}\n end\nend", "def each\n while true do\n yield\n break if ! advance\n end\n end", "def flip_switches(num)\n i = num\n until i >= $switches.length\n $switches[i] = !$switches[i]\n i += num\n end\nend", "def cycle\n if has_size?\n super\n else\n i = 0\n loop do\n yield at(i)\n i += 1\n end\n end\n end", "def move_to_next_generation\n @x.times{ |r|\n @y.times{|c| \n @mat[r][c].step_generation\n }\n } \n end", "def loop_with_next\n numbers = []\n counter = 0\n\n while counter < 20\n counter += 1\n next if counter.even?\n numbers << counter\n end\n\n numbers\nend", "def update_loop_animation_index\r\n if @_loop_animation != nil and (Graphics.frame_count % 2 == 0)\r\n update_loop_animation\r\n @_loop_animation_index += 1\r\n @_loop_animation_index %= @_loop_animation.frame_max\r\n end\r\n end", "def two_times\n yield\n yield\nend", "def yo_dawg(num)\n n.times do\n n.times do\n puts \"I put a loop in your loop so you can loop while you loop.\"\n end\n end\nend", "def part1\n 2.times do\n \n 6.times do\n play :G4\n play :E4\n play :E2\n sleep 0.5\n end\n \n 2.times do\n play :A4\n play :E4\n play :E2\n sleep 0.5\n end\n end\nend", "def interleave(arr1, arr2)\n return_array = []\n counter = 1\n until arr2.empty?\n if counter.odd?\n return_array << arr1.shift\n counter += 1\n else\n return_array << arr2.shift\n counter += 1\n end\n end\n return_array\nend", "def repeater(n = 1)\n\tn.times do\n\t\tyield\n\tend\nend", "def while(&block)\n\t\t\t\t\trepeat &block\n\t\t\t\tend", "def cycle(n)\n RGL::ImplicitGraph.new { |g|\n g.vertex_iterator { |b| 0.upto(n - 1, &b) }\n g.adjacent_iterator { |x, b| b.call((x + 1) % n) }\n g.directed = true\n }\nend", "def go\n @i += 1\n puts \"====================\"\n puts \"Tour n°#{@i}\"\n puts \"====================\"\n\n#creation d'une boucle pour alterner les joueurs\n loop do @i < 9\n \n if @i.odd?\n turn(@joueur1)\n\n else @i.even?\n turn(@joueur2)\n end\n break if @i == 9\n end\n end", "def with_transitional_values\n a = b = 1\n 3.upto(@n) do\n c = a + b\n a = b\n b = c\n end\n\n #puts \"answer is %d\" % b\n end", "def carry_over\n while clock.any? { |val| val < 0 }\n indx = clock.rindex(-1)\n clock[indx - 1] -= 1\n clock[indx] = n\n end\n end", "def interleave(arr1, arr2)\r\n combined_arr = []\r\n counter = 0\r\n arr1.size.times do\r\n combined_arr << arr1[counter]\r\n combined_arr << arr2[counter]\r\n counter += 1\r\n end\r\n combined_arr\r\nend", "def moveZeroes(nums)\n slow = fast = 0\n while fast<nums.size do\n if not nums[slow]==0 then\n slow += 1\n elsif nums[fast]!=0 then\n nums[slow] ^= nums[fast]\n nums[fast] ^= nums[slow]\n nums[slow] ^= nums[fast]\n slow += 1\n end\n fast += 1\n end\n nums\nend", "def turn_loop\n # @tet = TET_2ROW#.sample\n @tet = TETS.sample\n @logger.info(\"turn #{@turn}\")\n STDIN.iflush\n @turn_state = @grid.mcopy # save state at start of turn(each block is turn)\n @pos = @start_pos.mcopy\n @subturn = 0\n subturn_loop\n # check for full row\n increase_score(process_completed_lines)\n end", "def step_two\n zeros = find_starrable_zeros\n return unless zeros.any?\n\n zeros.each do |zero|\n row = zero.first\n col = zero.last\n starred_zeros.set_cell(row, col, true) if zero_starrable?(row, col)\n end\n end", "def diamond(i) # I hope I didn't name my variables\n spaces_toggle = -1 # the same as the instruction\n spaces = i/2 # This is MY algorithm !\n bling_toggle = 1\n bling = 1\n (i).times do\n spaces.times {print \" \"} \n bling.times {print \"*\"}\n spaces.times {print \" \"} \n print \"\\n\"\n spaces += 1 * spaces_toggle\n bling += 2 * bling_toggle\n if bling == i # Center of function\n bling.times {print \"*\"}\n print \"\\n\"\n spaces += 1\n bling -= 2\n spaces_toggle = 1\n bling_toggle = -1\n end\n end\nend", "def sequence(integer1, integer2)\n sequence_array = []\n current_value = integer2\n integer1.times do\n sequence_array << current_value\n current_value += integer2\n end\n sequence_array\nend", "def each_block\n 0.upto(3) do |x|\n 0.upto(3) do |y|\n # TODO: Move the bitwise and into #rotation.\n # Not sure now there's a rotate method for each direction.\n c = Tetrominos[@shape][@rotation & 3][y][x]\n yield x, y, c if c == 1\n end\n end\n end", "def toggle_lights(n)\n multipled_substring = []\n\n (1..n).each do |count|\n multiplier = 1\n\n loop do\n product = count * multiplier\n break if product > n\n multipled_substring << product\n multiplier += 1\n end\n end\n #multipled_substring\n\n final_result = []\n (1..n).each do |number|\n times_of_toggle = multipled_substring.count(number)\n \n final_result << number if times_of_toggle.odd?\n end\n p final_result\nend", "def ex1\n for i in (0..5)\n for j in (1..(6 - i))\n print '#'\n end\n print \"\\n\"\n end\nend", "def damepares(n1, n2)\n (n1..n2).each do |i|\n puts i if i.even?\n end\nend", "def alternating_sequence\n max = amount_of_rails - 1\n direction = 1\n current = 0\n\n result = [current]\n\n (message_length - 1).times do\n current += direction\n direction *= -1 if current.zero? || current == max\n result << current\n end\n\n result\n end", "def animate_once(indices, interval)\n if @animate_once_control == 2\n return if indices == @animate_once_indices && interval == @animate_once_interval\n @animate_once_control = 0\n end\n\n unless @animate_once_control == 1\n @anim_counter = 0\n @img_index = indices[0]\n @index_index = 0\n @animate_once_indices = indices\n @animate_once_interval = interval\n @animate_once_control = 1\n return\n end\n\n @anim_counter += 1\n return unless @anim_counter >= interval\n\n if @index_index == indices.length - 1\n @animate_once_control = 2\n yield if block_given?\n else\n @index_index += 1\n @img_index = indices[@index_index]\n @anim_counter = 0\n end\n end", "def switch_lights(n)\n switches = Array.new(n, 'off')\n divisor = 1\n until divisor > switches.size\n switches.each_with_index do |light, indx|\n light_number = indx + 1\n if (light_number % divisor).zero?\n switches[indx] = 'on' if light == 'off'\n switches[indx] = 'off' if light == 'on'\n end\n end\n divisor += 1\n end\n switches\nend", "def caterpillar_method\n result=[]\n i=0\n while(i<self.size/2)\n j=i+1\n while (self[j] && (yield self[i],self[j]))\n result<<[self[i],self[j]]\n j+=1\n end\n i+=1\n end\n return result\n end", "def L\n 3.times { R() }\n end", "def each \r\n @x1.upto(@x2) { |x|\r\n @y1.upto(@y2) { |y|\r\n yield x,y\r\n }\r\n }\r\n end", "def cyclic2?(first_link)\n slow_runner = first_link\n fast_runner = first_link\n\n while true\n 2.times do\n fast_runner = fast_runner.next\n return false if fast_runner.nil?\n return true if fast_runner == slow_runner\n end\n\n slow_runner = slow_runner.next\n end\nend", "def sequence(n1, n2)\n\n arr = []\n counter = 1\n \n while n1 >0\n loop do \n arr << n2 * counter\n counter +=1\n break if counter > n1\n end\n break\n end\narr\nend", "def running_total_2 arr\n arr.each_with_index { |elm, idx| idx == 0 ? next : arr[idx] += arr [idx-1] }\nend", "def get_cycle x\r\n count = 0\r\n while (x > 1)\r\n case\r\n when x[0] == 0 #even\r\n count += 1\r\n x = x/2\r\n when x[0] == 1 #odd\r\n count += 2\r\n x = ((3*x + 1)/2)\r\n end\r\n end\r\n count += 1\r\nend", "def number_loop_three(i)\n (0..i).each do |num|\n puts \"The number now is #{num}\" \n end \nend", "def iterate\n self.update\n @time += 1\n end", "def run( current, positions, iterations, num_values )\n iterations.times do \n slice_start = current.next\n current.next = current.next.next.next.next\n destination = nil\n backoff = 1\n \n while ! destination \n search_for_label = current.value - backoff\n if search_for_label < 1\n search_for_label += num_values\n end \n destination = positions[search_for_label]\n if destination.value == slice_start.value ||\n destination.value == slice_start.next.value ||\n destination.value == slice_start.next.next.value \n destination = nil\n backoff += 1\n end\n end\n \n after_slice = destination.next\n destination.next = slice_start\n slice_start.next.next.next = after_slice\n current = current.next\n end\nend", "def get_loop_even(num)\n (0..num).each { |x| x if (x%2==0)}\nend", "def loop\n measurement = yield @position\n\n while true do\n position = control measurement\n\n measurement = yield position\n end\n end", "def balance\n @anchors.length.times { |i| balance_at i } \n end", "def test_consistency_ruby_test\r\n rubyArr = [1,1]\r\n seed = 10\r\n r = Random.new(seed)\r\n firstIteration = mine(rubyArr, r)\r\n secondIteration = mine(rubyArr, r)\r\n if firstIteration = secondIteration\r\n assert true\r\n end\r\n end", "def double_numbers!(numbers)\n counter = 0\n\n loop do\n break if counter == numbers.size\n\n current_number = numbers[counter]\n numbers[counter] = current_number * 2\n\n counter += 1\n end\n\n numbers\nend", "def increment_iteration\n @iteration += 1\n end", "def lights(n)\n arr = Array.new(n, false)\n n.times do |count|\n arr.each_with_index { |element, idx| arr[idx] = !element if (idx + 1) % (count + 1) == 0}\n end\n result =[]\n arr.each_with_index { |element, idx| result << idx+1 if element }\n result\nend", "def diagonal_win\n 6.times do\n end\n end", "def alternating_mapper(arr, p1, p2)\n (0...arr.length).map {|i| i.even? ? p1.call(arr[i]) : p2.call(arr[i])}\nend", "def interleave(arr1, arr2)\n index = 0\n results = []\n arr1.size.times do\n results << arr1[index] << arr2[index]\n index += 1\n end\n results\nend", "def looping_by_multi_2( num )\n\n result = 1\n\n while( result < num )\n result *= 2\n puts( result )\n end\n\nend", "def restart_loop\n new_last_word_index = @words.keys.sort.last\n if new_last_word_index.nil?\n @i_last_real_word = 0 \n @i = 0\n else\n @i_last_real_word = new_last_word_index\n @i = @i_last_real_word\n end\n end", "def restart_loop\n new_last_word_index = @words.keys.sort.last\n if new_last_word_index.nil?\n @i_last_real_word = 0 \n @i = 0\n else\n @i_last_real_word = new_last_word_index\n @i = @i_last_real_word\n end\n end", "def cycle\n (@isodd = !@isodd) ? 'even' : 'odd'\n end", "def repeatm\n $inside_multiplier_action = true\n _multiplier = ( ($multiplier.nil? || $multiplier == 0) ? 1 : $multiplier )\n _multiplier.times { yield }\n $multiplier = 0\n $inside_multiplier_action = false\n end", "def interleave(array1, array2)\n combo_size = array1.size + array2.size\n combo_array = []\n index = 0\n \n until combo_array.size == combo_size\n combo_array << array1[index] << array2[index]\n index += 1\n end\n \n combo_array\nend", "def test_next_statement\n i = 0\n result = []\n while i < 10\n i += 1\n next if (i % 2) == 0\n result << i\n end\n assert_equal (1..10).step(2).to_a, result\n end", "def loops\n return @loops if @loops\n @loops = (data['loops']||[]).map { |l| function.blocks.by_name(l).loop }\n end", "def slow_dance(direction, tiles_array)\n i = 0\n loop do\n return i if direction == tiles_array[i]\n i += 1\n end\nend", "def light1000(num)\n lights = []\n counter = 1\n\n num.times { |i| lights << false} # initalize lights\n\n while counter <= num\n light_switcher(lights, counter)\n counter += 1\n end\n\n lights\nend", "def interleave(array1, array2)\n results_array = []\n counter = 0 \n loop do \n results_array << array1[counter]\n results_array << array2[counter]\n counter += 1 \n break if counter >= array1.size\n end \n \n results_array\nend", "def toggle(switches)\n 1.upto(1000) do |step|\n switches.map do |switch_num, on_or_off|\n if switch_num % step == 0\n switches[switch_num] = !on_or_off\n end\n end\n end\nend", "def toggle_lights(number_of_lights)\n lights = initialize_lights(number_of_lights)\n 1.upto(lights.size) do |iteration_number|\n toggle_every_nth_light(lights, iteration_number)\n end\n \n p \"Lights #{joinor(on_lights(lights))} are on\"\n p \"Lights #{joinor(off_lights(lights))} are off\"\nend", "def cycle\n allOn(0.1)\n allOff(0.1)\n \n \"hello\".chars.each do |letter|\n writeLetter(letter.to_sym)\n sleep(0.5)\n allOff()\n sleep(0.25)\n end\n end", "def multiple()\n\tresult = 0\n\t\tfor i in 1...1000\n\t\t\tif i%3 == 0 || i%5 == 0\n\tresult += i\n\t\t\tend\n\t\tend\n\treturn result\nend", "def interleave(arr1, arr2)\n output_arr = []\n arr1.size.times do |idx|\n output_arr << arr1[idx]\n output_arr << arr2[idx]\n end\n output_arr\nend", "def do_it_twice(array)\n yield(array[0])\n yield(array[1])\nend", "def alternatingSums(a)\n team_one, team_two = 0, 0\n teams = []\n\n a.each_with_index do |num, index|\n if index.even? # Par\n team_one += num\n else # odd - impar\n team_two += num\n end\n end\n teams.push(team_one)\n teams.push(team_two)\n \n puts \"#{teams}\"\nend", "def a_few_more_steps\n loop do\n puts \"Right foot back\"\n sleep(0.5)\n puts \"Left foot back\"\n sleep(0.5)\n puts \"Right foot back\"\n sleep(0.5)\n puts \"Stop\"\n sleep(1)\n puts \"Right foot steps right and back\"\n sleep(0.5)\n puts \"Left foot crosses over right\"\n sleep(0.5)\n puts \"Right foot steps right\"\n sleep(0.5)\n puts \"Turn\"\n sleep(1)\nend\nend", "def interleave(ary1, ary2)\n ary = []\n ary1.size == ary2.size ? ary.push(ary1.shift) : ary.push(ary2.shift) until ary2.empty?\n ary\nend", "def each(&block)\n @succ.each(&block)\n end", "def code\n d = a + (7 * 362)\n b = c = 0\n loop do\n a = d\n while a != 0\n b = a\n a = 0\n loop do\n c = 2\n while c != 0\n break if b == 0\n\n b -= 1\n c -= 1\n end\n break if b == 0\n\n a += 1\n end\n b = 2 - c\n c = 0\n puts b\n end\n end\n end", "def lights(num)\n switches = Array.new(num, false)\n num.times do |n|\n switches = switches.each_with_index.map do |el, i|\n if ((i + 1) % (n + 1)).zero?\n !el\n else\n el\n end\n end\n end\n switches.each_with_index.map { |el, i| i + 1 if el }.select { |el| el }\nend", "def fibonacci_iterative(num)\n a = 1\n b = 1\n\n while num > 1\n a, b = b, a + b # parallel assignment (x, y = x, y)\n num -= 1\n end\n a\nend", "def evenLoop(n)\n total = n * 2\n for x in 1..total\n if x % 2 == 0\n x\n end\n end\nend", "def endless_loop\n loop { yield }\n end" ]
[ "0.6231678", "0.59329766", "0.5930323", "0.58379114", "0.5811057", "0.5698566", "0.5648129", "0.5646934", "0.56390053", "0.5620709", "0.5593258", "0.55929995", "0.55867755", "0.5558013", "0.55525696", "0.55356276", "0.5533881", "0.55211794", "0.5496905", "0.5481098", "0.5475729", "0.5467853", "0.5466763", "0.54635274", "0.5446867", "0.543745", "0.5428787", "0.5410327", "0.54032755", "0.5401919", "0.5398806", "0.5375417", "0.537275", "0.53681254", "0.5367979", "0.53662795", "0.53469294", "0.53373504", "0.5336596", "0.53265995", "0.53172356", "0.5316461", "0.53038824", "0.5300875", "0.52966213", "0.52964526", "0.527197", "0.52717084", "0.5270541", "0.52670246", "0.52647865", "0.5256467", "0.5250313", "0.52485204", "0.5248111", "0.5232183", "0.5231902", "0.52238464", "0.52196884", "0.52159494", "0.52083254", "0.52071774", "0.5206862", "0.5205836", "0.5203021", "0.5202664", "0.51879615", "0.5185411", "0.51838046", "0.5182461", "0.51813656", "0.51766557", "0.51750576", "0.5167735", "0.51652515", "0.51597315", "0.5159635", "0.5159635", "0.5157981", "0.5157683", "0.51510924", "0.5150838", "0.51501715", "0.5147442", "0.5140591", "0.51365787", "0.51335233", "0.5132399", "0.5131603", "0.5130221", "0.51285833", "0.5128388", "0.5123978", "0.51201797", "0.5119033", "0.5115378", "0.5111902", "0.51088476", "0.5105241", "0.51020306", "0.5101471" ]
0.0
-1
widths 25, 50, 100 formats webp, original
def test_picture_files tested('auto rms.jpg') files = Dir.glob(temp_dir('generated' + '/*')) assert_equal(6, files.length) assert_includes stdout, 'Generating' end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def uml(picture_name, contents, width_slide, width_plain)\n new_width = calculate_width(width_plain)\n formats = %w(pdf eps)\n img_path = super(picture_name, contents, width_slide, width_plain, 'pdf')\n image(img_path, formats, '', '', new_width, new_width)\n end", "def uml(picture_name, contents, width_slide, width_plain)\n new_width = calculate_width(width_slide)\n formats = %w[pdf eps]\n img_path = super(picture_name, contents, width_slide, width_plain, 'pdf')\n image(img_path, formats, '', '', new_width, new_width)\n end", "def header_posicao_047_a_076\n\t\t\t\t\t\t\"#{conta.razao_social}\".adjust_size_to(30)\n\t\t\t\t\tend", "def fw; self.fixed_width = true; self; end", "def set_wiki_format_for_preview\n @text.wiki_format = params[:pwfmt_format] if @text && params[:pwfmt_format]\n end", "def set_wiki_format_for_preview\n @text.wiki_format = params[:pwfmt_format] if @text && params[:pwfmt_format]\n end", "def header_posicao_047_a_076\n\t\t\t\t\t''.adjust_size_to(30)\n\t\t\t\tend", "def make_responsive(img,type,width)\n [\n [\"-resize 'x#{width}>'\", \".webp\"],\n [\"-resize 'x#{width * 2}>'\", \"@2x.webp\"],\n ].each do |i|\n convert(type, img, i.first, i.last)\n end\nend", "def make_responsive(img,width)\n [\n [\"-resize 'x#{width}>'\", \"-#{width}.webp\"],\n [\"-resize 'x#{width * 2}>'\", \"-#{width}@2x.webp\"],\n ].each do |i|\n convert(img, i.first, i.last)\n end\nend", "def pdf_to_html(url)\n\tend", "def embed_width\n width_ok? ? width : 1000\n end", "def set_character_width_narrow\n set_print_mode 1\n set_linefeed_rate 40\n end", "def show\n \n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @card }\n format.pdf {\n @page_size=params[\"page_size\"]\n @page_layout = params[\"page_layout\"]\n prawnto :prawn => { :left_margin=>0,:right_margin=>0,:bottom_margin=>0,:top_margin=>0,:page_size=>params[\"page_size\"],:page_layout=>params[\"layout\"].to_sym }\n # @iconv = Iconv.new('acsii', 'utf-8') \n # @desc [email protected](@card.desc)\n @desc = @card.desc\n @font_size = params[\"font_size\"].to_i\n render :layout => false\n }\n end\n end", "def prepare_display(width)\n r = @result.reverse\n factor = width.to_f / (r.transpose[1].max)\n r.map { |l, c, r| [ l, (c * factor).round, r ] }\n end", "def contents_width\n width - standard_padding * 2\n end", "def width; end", "def width; end", "def width; end", "def width; end", "def width; end", "def width; end", "def width; end", "def width; end", "def width; end", "def fit_width; end", "def format_link(url_pair)\n # image display output\n if url_pair[:format] == :image\n return \"<div class='image'>\\n <div class='image-inner'>\\n <a href='\" + \n url_pair[:post_url] + \n \"' target='_blank'>\\n <img src='\" +\n url_pair[:image_url] +\n \"'>\\n </a>\\n </div>\\n</div>\"\n end\n\n # imgur gifv output\n if url_pair[:format] == :gifv\n return \"<div class='video-container'>\\n <div class='video-inner'>\\n <a href='\" +\n url_pair[:post_url] +\n \"' target='_blank'>\\n <video autoplay='autoplay' type='video/mp4' id='video' loop='loop' muted='muted' preload='auto' src='\" +\n url_pair[:image_url] +\n \"'></video>\\n </a>\\n </div>\\n</div>\"\n end\n end", "def urlwidth(value)\n merge(siiurlwidth: value.to_s)\n end", "def wrap(width, width2 = nil)\n lines = []\n line = \"\"\n line_len = 0\n fragments.each do |frag|\n frag_len = frag.gsub(/\\e\\[\\d+(;\\d+)*m/, \"\").size\n if line_len.zero?\n line = frag\n line_len = frag_len\n elsif width && line_len + 1 + frag_len > width\n lines << line\n line = frag\n line_len = frag_len\n width = width2 if width2\n else\n line_len += frag_len + 1\n line = \"#{line} #{frag}\"\n end\n end\n lines << line if line_len.positive?\n lines\n end", "def style_conversion; end", "def preformatting\n\n end", "def adjust_width\n self.width = [[text_size('O' * @max_characters).width + padding * 2,\n @title ? text_size(@title).width + padding * 2 : 0].max, Graphics.width].min\n end", "def convert_html(text)\n auto_html text do\n html_escape :map => {\n '&' => '&amp;',\n '>' => '&gt;',\n '<' => '&lt;',\n '\"' => '\"'\n }\n image\n youtube :width => 510, :height => 332\n vimeo :width => 510, :height => 332\n link :target => :_blank\n redcarpet :target => :_blank\n end\n end", "def test_aliases_w_and_width\n expected = \"https://demo.imgix.net/image.png?w=720\"\n actual_w = unsigned_client.path(\"image.png\").w(720)\n actual_width = unsigned_client.path(\"image.png\").width(720)\n assert_equal expected, actual_w.to_url, actual_width.to_url\n end", "def formats; end", "def formats; end", "def image_hwstring(width, height)\n out = ''\n if width\n out += 'width=\"' + width.to_i.to_s + '\" '\n end\n if height\n out += 'height=\"' + height.to_i.to_s + '\" '\n end\n out\n end", "def fix_wikimedia_characters(res)\n res.media.where(w: nil).find_each do |img|\n next if img.source_url =~ /(svg|ogg|ogv)$/\n string = img.source_page_url.sub(/^.*File:/, '').sub(/\\..{3,4}$/, '')\n good_name = URI.decode(string)\n bad_name = img.source_url.sub(/^.*\\//, '').sub(/\\..{3,4}$/, '')\n %i[source_url name_verbatim name description description_verbatim].each do |f|\n img[f].sub!(bad_name, good_name) unless img[f].nil?\n end\n img.save\n img.download_and_resize\n end\n end", "def width(string, font_size)\n string_base_width = string.bytes.inject(0){|result, byte|\n byte_width = WIDTHS[byte] || 1000\n result + byte_width\n }\n string_base_width * font_size / 1000\n end", "def epl width = 197, height=124\n epl = encoded_polyline_cache ? encoded_polyline_cache : set_epl\n epl.gsub(\"?size=197x124\", \"?size=#{width}x#{height}\")\n end", "def epl width = 197, height=124\n epl = encoded_polyline_cache ? encoded_polyline_cache : set_epl\n epl.gsub(\"?size=197x124\", \"?size=#{width}x#{height}\")\n end", "def pps(pp)\n [\n pp[:tl][:x], pp[:tl][:y], 0, 0,\n pp[:tr][:x], pp[:tr][:y], width, 0,\n pp[:br][:x], pp[:br][:y], width, height,\n pp[:bl][:x], pp[:bl][:y], 0, height\n ].join ' '\n end", "def format_print(print_values)\n widths = Array.new(print_values[0].size, 0)\n print_values.each do |print_value|\n widths = widths.zip(print_value).map! {|width, value| value.length > width ? value.length : width }\n end\n\n print_values.each do |print_value|\n widths.zip(print_value) do |width, value|\n printf(\"%-#{width + 5}s\", value)\n end\n puts \"\"\n end\n end", "def pack_format\n \"a#{width}\"\n end", "def for_web_urls\n self.fixed_length\n end", "def url_to_font(source, options = T.unsafe(nil)); end", "def max_width_by_string(string)\n if string.length > 17\n return \"width:#{string.length * 0.6}em;\"\n end\n return \"\"\n end", "def sized(width, height)\n\t\t\t@sized_thumb = @template\n\t\t\t@sized_thumb.sub! \"{width}\", width.to_s\n\t\t\t@sized_thumb.sub! \"{height}\", height.to_s\n\t\tend", "def epl width = 197, height=124\n epl = encoded_polyline_cache\n epl.gsub(\"?size=197x124\", \"?size=#{width}x#{height}\")\n end", "def my_width \n 0.75\n end", "def mapf_format_paragraph(text, max_width = contents_width)\n text = text.clone\n # Create a Dummy Contents - I wanted to boost compatibility by using the \n # default process method for escape codes. It may have the opposite effect, \n # for some :( \n real_contents = contents # Preserve Real Contents\n self.contents = Bitmap.new(contents_width, 24)\n reset_font_settings\n paragraph = \"\"\n while !text.empty?\n text.lstrip!\n oline, nline, tw = mapf_format_by_line(text.clone, max_width)\n # Replace old line with the new one\n text.sub!(/#{Regexp.escape(oline)}/m, nline)\n paragraph += text.slice!(/.*?(\\n|$)/)\n end\n contents.dispose # Dispose dummy contents\n self.contents = real_contents # Restore real contents\n return paragraph\n end", "def write_url_web(row1, col1, row2, col2, url, str = nil, format = nil)\n record = 0x01B8 # Record identifier\n length = 0x00000 # Bytes to follow\n\n xf = format || @url_format # The cell format\n\n # Write the visible label but protect against url recursion in write().\n str = url if str.nil?\n @writing_url = 1\n error = write(row1, col1, str, xf)\n @writing_url = 0\n return error if error == -2\n\n # Pack the undocumented parts of the hyperlink stream\n unknown1 = [\"D0C9EA79F9BACE118C8200AA004BA90B02000000\"].pack(\"H*\")\n unknown2 = [\"E0C9EA79F9BACE118C8200AA004BA90B\"].pack(\"H*\")\n\n # Pack the option flags\n options = [0x03].pack(\"V\")\n\n # Convert URL to a null terminated wchar string\n url = url.split('').join(\"\\0\")\n url = url + \"\\0\\0\\0\"\n\n # Pack the length of the URL\n url_len = [url.length].pack(\"V\")\n\n # Calculate the data length\n length = 0x34 + url.length\n\n # Pack the header data\n header = [record, length].pack(\"vv\")\n data = [row1, row2, col1, col2].pack(\"vvvv\")\n\n # Write the packed data\n append( header, data,unknown1,options,unknown2,url_len,url)\n\n return error\n end", "def safe_width(width)\n\n\n\n width.to_s.gsub(/\\A(\\d+)\\z/, '\\1px')\n\n\n\n end", "def calculate_width(width)\n\n new_width = width\n\n if /%/ === new_width\n new_width.gsub!(/%/, '')\n width_num = new_width.to_i / 100.0\n new_width = \"#{width_num.to_s}\\\\textwidth\"\n end\n\n new_width\n end", "def frame(text, char)\n width = text.max { |a,b| a.length <=> b.length }.size + 4\n output = \"\" << \"#{char}\" * width << \"\\n\"\n text.each { |line| output << \"#{char} #{line}\" << \"%0#{width - line.size - 2}s\" % char << \"\\n\" }\n output << \"#{char}\" * width\nend", "def generate_layout(width, text)\n layout = ::Swt::TextLayout.new Shoes.display\n layout.setText text\n layout.setSpacing(@opts[:leading] || DEFAULT_SPACING)\n font = ::Swt::Font.new Shoes.display, @dsl.font, @dsl.font_size,\n ::Swt::SWT::NORMAL\n style = ::Swt::TextStyle.new font, nil, nil\n layout.setStyle style, 0, text.length - 1\n shrink_layout_to(layout, width) unless layout_fits_in?(layout, width)\n\n font.dispose\n\n layout\n end", "def screenshot_as(format, full_page: T.unsafe(nil)); end", "def mapf_format_paragraph(text, max_width = contents_width)\n text = text.clone\n # Create a Dummy Contents - I wanted to boost compatibility by using the\n # default process method for escape codes. It may have the opposite effect,\n # for some :(\n real_contents = contents # Preserve Real Contents\n self.contents = Bitmap.new(24, 24)\n reset_font_settings\n paragraph = \"\"\n while !text.empty?\n text.lstrip!\n oline, nline, tw = mapf_format_by_line(text.clone, max_width)\n # Replace old line with the new one\n text.sub!(/#{Regexp.escape(oline)}/m, nline)\n paragraph += text.slice!(/.*?(\\n|$)/)\n end\n contents.dispose # Dispose dummy contents\n self.contents = real_contents # Restore real contents\n return paragraph\n end", "def width\n end", "def width\n end", "def get_width; end", "def render_length_limit; end", "def format_text(title, url, url_title_time_ary)\n s = \"Title: #{title}¥nURL: #{url}¥n¥n\"\n url_title_time_ary.each do |aurl, atitle, atime|\n s << \"* (#{atime})#{atitle}¥n\"\n s << \" #{aurl}¥n\"\n end\n s\nend", "def _wrapper_formats; end", "def do_window_adjust(bytes); end", "def render_length; end", "def responsive_embed_code_css\n <<~END\n #fulcrum-embed-outer-#{id} {\n width:auto;\n page-break-inside:avoid;\n -webkit-column-break-inside:avoid;\n break-inside:avoid;\n max-width:#{embed_width}px;\n margin:auto;\n background-color:#000;\n }\n #fulcrum-embed-inner-#{id} {\n overflow:hidden;\n padding-bottom:#{padding_bottom}%;\n position:relative; height:0;\n }\n iframe#fulcrum-embed-iframe-#{id} {\n overflow:hidden;\n border-width:0;\n left:0; top:0;\n width:100%;\n height:100%;\n position:absolute;\n }\n END\n end", "def as_size2( s = nil )\n prefix = %W(ТиБ ГиБ МиБ КиБ Б)\n s = (s || self).to_f\n i = prefix.length - 1\n while s > 512 && i > 0\n s /= 1024\n i -= 1\n end\n ((s > 9 || s.modulo(1) < 0.1 ? '%d' : '%.1f') % s) + ' ' + prefix[i]\n end", "def watermark_formatted_text\n struct = export_as_mla_structure(parent_presenter)\n wrapped = wrap_text(struct[:author] + '___' + struct[:title], 150)\n parts = wrapped.split('___')\n [{ text: parts[0] },\n { text: parts[1], styles: [:italic] },\n { text: \"\\n\" + wrap_text(struct[:publisher], 150) },\n { text: \"\\nDownloaded on behalf of #{request_origin}\" }\n ]\n end", "def formatting(str)\n puts str * 80\nend", "def set_character_width_normal\r\n set_print_mode 0\r\n set_linefeed_rate 55\r\n end", "def designerPdfViewer(h, word)\n heights = Array.new\n hsh = Hash.new\n (\"a\"..\"z\").each_with_index { |letter, i| hsh[letter] = h[i] }\n word.each_char { |ch| heights << hsh[ch] }\n return heights.max * heights.count\nend", "def print_width\n raise \"Can't calculate print width for encoding: #{encoding}\" unless encoding == Encoding::UTF_8\n codepoints.reduce(0) do |result,code|\n result + ((code.is_chinese_character? || code.is_chinese_punctuation?) ? 2 : 1)\n end\n end", "def format_text(text)\n return text if text.blank?\n\n truncated_text = text.gsub(/\\b\\S{71,}\\b/) do |word|\n if word !~ /^https?:\\/\\//\n truncate(word, 70)\n else\n word\n end\n end\n\n simple_format(h(truncated_text).gsub(/\\bhttps?:\\/\\/\\S+/) do |word|\n if word =~ /\\.$/\n website_link(word.gsub(/\\.$/, ''), 70, false) + \".\" # Remove end of sentence dot from URL\n else\n website_link(word, 70, false)\n end\n end)\n end", "def preview_text(maxlength = 30)\n ::CGI.escapeHTML(source.to_s)[0..maxlength]\n end", "def width=(_); end", "def width=(_); end", "def render_style(text, mediatype=\"all\")\n [\"<style type='text/css' media='#{mediatype}' >\",\n text,\n \"</style>\\n\"].join(\"\\n\") \n end", "def urlify(str, length)\n new_str = ''\n\n str.each_char.each_with_index do |c, i|\n break if i == length\n new_str << (c == ' ' ? '%20' : c)\n end\n\n new_str\nend", "def preview(text, length=400)\n text.split(/\\s/).inject(\"\") do |out, chunk|\n if (out.size + 1 + chunk.size) <= length\n out + \" \" + chunk\n else\n return out + \" ...\"\n end\n end\n end", "def format_shortcodes(text)\n # preprocess to replace badly formatted shortcodes with syntactically correct shortcodes\n # [youtube id width height] -> [youtube id=\"id\" width=\"width\" height=\"height\"]\n Shortcode.process(text.gsub(/\\[youtube\\s+?(\\w*?)\\s+?(\\d+)\\s+?(\\d+)\\s*\\]/, '[youtube id=\"\\1\" width=\"\\2\" height=\"\\3\"]'))\n end", "def permalink_style; end", "def pango_render_text(width,font,text)\n pango = self.create_pango_layout\n pango.width = width*1000\n pango.wrap=Pango::WRAP_WORD\n pango.font_description = Pango::FontDescription.new(font)\n pango.markup=text\n self.show_pango_layout(pango)\n end", "def header_width_height(width,height)\r\n \"<style type=\\\"text/css\\\">\\n##{@container} { height: #{height}px;\\n width: #{width}px;\\n}\\n</style>\"\r\n end", "def wrap_width(width)\n gsub(/([^\\n\\r]{1,#{width}})/,\"\\\\1\\n\")\n end", "def preview\n self.content.split(' ')[0...5].join(' ') + '...'\n end", "def refresh\n self.contents=pbDoEnsureBitmap(self.contents,self.width-self.borderX,\n self.height-self.borderY)\n bitmap=self.contents\n bitmap.clear\n x=0\n y=0\n if @heading\n textwidth = bitmap.text_size(@heading).width\n pbDrawShadowText(bitmap,x,y,textwidth+4,32,@heading,@window.textColor,nil)\n y+=32\n end\n x+=4\n width=self.width-self.borderX\n height=self.height-self.borderY\n textscan=self.text.scan(/./m)\n scanlength=textscan.length\n @helper.cursor=scanlength if @helper.cursor>scanlength\n @helper.cursor=0 if @helper.cursor<0\n [email protected]\n fromcursor=0\n while (startpos>0)\n c=(@helper.passwordChar!=\"\") ? @helper.passwordChar : textscan[startpos-1]\n fromcursor+=bitmap.text_size(c).width\n break if fromcursor>width-4\n startpos-=1\n end\n for i in startpos...scanlength\n c=(@helper.passwordChar!=\"\") ? @helper.passwordChar : textscan[i]\n textwidth=bitmap.text_size(c).width\n next if c==\"\\n\"\n # Draw text\n pbDrawShadowText(bitmap,x,y, textwidth+4, 32, c,@window.textColor,nil)\n # Draw cursor if necessary\n if ((@frame/10)&1) == 0 && [email protected]\n bitmap.fill_rect(x,y+4,2,24,@window.textColor)\n end\n # Add x to drawn text width\n x += textwidth\n end\n if ((@frame/10)&1) == 0 && [email protected]\n bitmap.fill_rect(x,y+4,2,24,@window.textColor)\n end\n end", "def mime_type_and_size\n#(<%=media_item.content_type%>, <%=bytes_to_size(media_item.size)%>)\n result = \"\"\n if !content_type.blank?\n result << content_type\n end\n \n if !size.blank?\n result << ', ' if !result.blank?\n result << bytes_to_size(size)\n end\n \n result = '(' << result << ')' if !result.blank?\nend", "def set_character_width_normal\n set_print_mode 0\n set_linefeed_rate 55\n end", "def format_post(post)\n # Look at \"post-info.png\" for details on what's in the post array\n title = post['title']\n score = post['score']\n author = post['author']\n url = post['url']\n preview = post['thumbnail']\n \"`#{CGI.unescapeHTML(title)}`, Score: `#{score}`, By `u/#{author}`, @ #{url}\"\nend", "def pshr_srcset(upload, versions: [])\n if upload.has_versions? && versions.any?\n return versions.map { |v| \"#{upload.file[v].url} #{upload.file[v].metadata['width']}w\" }.join(', ')\n else\n return nil\n end\n end", "def calc_width; padding * 2 + base_width; end", "def calc_width; padding * 2 + base_width; end", "def wicked_pdf_url_base64(url); end", "def url(size_name) \n if @youtube_id\n \"http://img.youtube.com/vi/#{@youtube_id}/0.jpg\"\n else\n \"http://img.youtube.com/vi/0.jpg\"\n end\n end", "def styles; end", "def styles; end", "def styles; end", "def test_picture_markup\n output = tested('auto rms.jpg')\n\n assert errors_ok? output\n\n sources = output.css('source')\n ss1 = '/generated/rms-25-c87b11253.webp 25w,' \\\n ' /generated/rms-50-c87b11253.webp 50w,' \\\n ' /generated/rms-100-c87b11253.webp 100w'\n\n assert_equal ss1, sources[0]['srcset']\n assert_equal std_rms_ss, sources[1]['srcset']\n\n assert_equal 'image/webp', sources[0]['type']\n assert_equal 'image/jpeg', sources[1]['type']\n\n assert_equal rms_url, output.at_css('img')['src']\n end", "def base_width; 26 + @width; end", "def blank_profile_pic_size(format)\n if format == 'display'\n '200x200'\n elsif format == 'tiny'\n '100x100'\n elsif format == 'xtiny'\n '50x50'\n else\n nil\n end\n end", "def output_tranformed_pixels\n\t\tstring_of_pixels = @pixels.join(\"\")\n\t\tresult = string_of_pixels.scan(/.{1,9}/).join(\"\\n\")\n\t\t#puts result\n\t\tputs result\n\t\tresult\n\tend" ]
[ "0.56965244", "0.56241006", "0.56122464", "0.54735243", "0.5460694", "0.5460694", "0.5447592", "0.53227234", "0.5310752", "0.5271013", "0.52313244", "0.52006453", "0.519558", "0.4993038", "0.4976429", "0.4974337", "0.4974337", "0.4974337", "0.4974337", "0.4974337", "0.4974337", "0.4974337", "0.4974337", "0.4974337", "0.4961797", "0.4952806", "0.49469557", "0.49388224", "0.4894983", "0.48881617", "0.4873991", "0.48540586", "0.48466694", "0.4842087", "0.4842087", "0.48413453", "0.48365244", "0.48083532", "0.48040208", "0.48040208", "0.48012173", "0.48002213", "0.47814196", "0.47754902", "0.4759492", "0.47501552", "0.4747893", "0.4723408", "0.47209403", "0.47204474", "0.47113356", "0.4710687", "0.47048795", "0.47004414", "0.46981835", "0.468927", "0.46881908", "0.46811092", "0.46811092", "0.4653828", "0.46510744", "0.46501613", "0.46495825", "0.4649037", "0.46484876", "0.46302477", "0.4617537", "0.46139246", "0.46120027", "0.46115705", "0.46064708", "0.46025375", "0.46020788", "0.46013898", "0.4599151", "0.4599151", "0.4598696", "0.4590407", "0.45903835", "0.45889977", "0.45879364", "0.45833427", "0.4577082", "0.45716035", "0.4561108", "0.45607808", "0.4560153", "0.45569357", "0.45531973", "0.4551595", "0.45487505", "0.45487505", "0.45478383", "0.4544712", "0.45405996", "0.45405996", "0.45405996", "0.45383027", "0.45361486", "0.45320064", "0.45307985" ]
0.0
-1
widths 25, 50, 100 formats webp, original
def test_picture_markup output = tested('auto rms.jpg') assert errors_ok? output sources = output.css('source') ss1 = '/generated/rms-25-c87b11253.webp 25w,' \ ' /generated/rms-50-c87b11253.webp 50w,' \ ' /generated/rms-100-c87b11253.webp 100w' assert_equal ss1, sources[0]['srcset'] assert_equal std_rms_ss, sources[1]['srcset'] assert_equal 'image/webp', sources[0]['type'] assert_equal 'image/jpeg', sources[1]['type'] assert_equal rms_url, output.at_css('img')['src'] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def uml(picture_name, contents, width_slide, width_plain)\n new_width = calculate_width(width_plain)\n formats = %w(pdf eps)\n img_path = super(picture_name, contents, width_slide, width_plain, 'pdf')\n image(img_path, formats, '', '', new_width, new_width)\n end", "def uml(picture_name, contents, width_slide, width_plain)\n new_width = calculate_width(width_slide)\n formats = %w[pdf eps]\n img_path = super(picture_name, contents, width_slide, width_plain, 'pdf')\n image(img_path, formats, '', '', new_width, new_width)\n end", "def header_posicao_047_a_076\n\t\t\t\t\t\t\"#{conta.razao_social}\".adjust_size_to(30)\n\t\t\t\t\tend", "def fw; self.fixed_width = true; self; end", "def set_wiki_format_for_preview\n @text.wiki_format = params[:pwfmt_format] if @text && params[:pwfmt_format]\n end", "def set_wiki_format_for_preview\n @text.wiki_format = params[:pwfmt_format] if @text && params[:pwfmt_format]\n end", "def header_posicao_047_a_076\n\t\t\t\t\t''.adjust_size_to(30)\n\t\t\t\tend", "def make_responsive(img,type,width)\n [\n [\"-resize 'x#{width}>'\", \".webp\"],\n [\"-resize 'x#{width * 2}>'\", \"@2x.webp\"],\n ].each do |i|\n convert(type, img, i.first, i.last)\n end\nend", "def make_responsive(img,width)\n [\n [\"-resize 'x#{width}>'\", \"-#{width}.webp\"],\n [\"-resize 'x#{width * 2}>'\", \"-#{width}@2x.webp\"],\n ].each do |i|\n convert(img, i.first, i.last)\n end\nend", "def pdf_to_html(url)\n\tend", "def embed_width\n width_ok? ? width : 1000\n end", "def set_character_width_narrow\n set_print_mode 1\n set_linefeed_rate 40\n end", "def show\n \n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @card }\n format.pdf {\n @page_size=params[\"page_size\"]\n @page_layout = params[\"page_layout\"]\n prawnto :prawn => { :left_margin=>0,:right_margin=>0,:bottom_margin=>0,:top_margin=>0,:page_size=>params[\"page_size\"],:page_layout=>params[\"layout\"].to_sym }\n # @iconv = Iconv.new('acsii', 'utf-8') \n # @desc [email protected](@card.desc)\n @desc = @card.desc\n @font_size = params[\"font_size\"].to_i\n render :layout => false\n }\n end\n end", "def prepare_display(width)\n r = @result.reverse\n factor = width.to_f / (r.transpose[1].max)\n r.map { |l, c, r| [ l, (c * factor).round, r ] }\n end", "def contents_width\n width - standard_padding * 2\n end", "def width; end", "def width; end", "def width; end", "def width; end", "def width; end", "def width; end", "def width; end", "def width; end", "def width; end", "def fit_width; end", "def format_link(url_pair)\n # image display output\n if url_pair[:format] == :image\n return \"<div class='image'>\\n <div class='image-inner'>\\n <a href='\" + \n url_pair[:post_url] + \n \"' target='_blank'>\\n <img src='\" +\n url_pair[:image_url] +\n \"'>\\n </a>\\n </div>\\n</div>\"\n end\n\n # imgur gifv output\n if url_pair[:format] == :gifv\n return \"<div class='video-container'>\\n <div class='video-inner'>\\n <a href='\" +\n url_pair[:post_url] +\n \"' target='_blank'>\\n <video autoplay='autoplay' type='video/mp4' id='video' loop='loop' muted='muted' preload='auto' src='\" +\n url_pair[:image_url] +\n \"'></video>\\n </a>\\n </div>\\n</div>\"\n end\n end", "def urlwidth(value)\n merge(siiurlwidth: value.to_s)\n end", "def wrap(width, width2 = nil)\n lines = []\n line = \"\"\n line_len = 0\n fragments.each do |frag|\n frag_len = frag.gsub(/\\e\\[\\d+(;\\d+)*m/, \"\").size\n if line_len.zero?\n line = frag\n line_len = frag_len\n elsif width && line_len + 1 + frag_len > width\n lines << line\n line = frag\n line_len = frag_len\n width = width2 if width2\n else\n line_len += frag_len + 1\n line = \"#{line} #{frag}\"\n end\n end\n lines << line if line_len.positive?\n lines\n end", "def style_conversion; end", "def preformatting\n\n end", "def adjust_width\n self.width = [[text_size('O' * @max_characters).width + padding * 2,\n @title ? text_size(@title).width + padding * 2 : 0].max, Graphics.width].min\n end", "def convert_html(text)\n auto_html text do\n html_escape :map => {\n '&' => '&amp;',\n '>' => '&gt;',\n '<' => '&lt;',\n '\"' => '\"'\n }\n image\n youtube :width => 510, :height => 332\n vimeo :width => 510, :height => 332\n link :target => :_blank\n redcarpet :target => :_blank\n end\n end", "def test_aliases_w_and_width\n expected = \"https://demo.imgix.net/image.png?w=720\"\n actual_w = unsigned_client.path(\"image.png\").w(720)\n actual_width = unsigned_client.path(\"image.png\").width(720)\n assert_equal expected, actual_w.to_url, actual_width.to_url\n end", "def formats; end", "def formats; end", "def image_hwstring(width, height)\n out = ''\n if width\n out += 'width=\"' + width.to_i.to_s + '\" '\n end\n if height\n out += 'height=\"' + height.to_i.to_s + '\" '\n end\n out\n end", "def fix_wikimedia_characters(res)\n res.media.where(w: nil).find_each do |img|\n next if img.source_url =~ /(svg|ogg|ogv)$/\n string = img.source_page_url.sub(/^.*File:/, '').sub(/\\..{3,4}$/, '')\n good_name = URI.decode(string)\n bad_name = img.source_url.sub(/^.*\\//, '').sub(/\\..{3,4}$/, '')\n %i[source_url name_verbatim name description description_verbatim].each do |f|\n img[f].sub!(bad_name, good_name) unless img[f].nil?\n end\n img.save\n img.download_and_resize\n end\n end", "def width(string, font_size)\n string_base_width = string.bytes.inject(0){|result, byte|\n byte_width = WIDTHS[byte] || 1000\n result + byte_width\n }\n string_base_width * font_size / 1000\n end", "def epl width = 197, height=124\n epl = encoded_polyline_cache ? encoded_polyline_cache : set_epl\n epl.gsub(\"?size=197x124\", \"?size=#{width}x#{height}\")\n end", "def epl width = 197, height=124\n epl = encoded_polyline_cache ? encoded_polyline_cache : set_epl\n epl.gsub(\"?size=197x124\", \"?size=#{width}x#{height}\")\n end", "def pps(pp)\n [\n pp[:tl][:x], pp[:tl][:y], 0, 0,\n pp[:tr][:x], pp[:tr][:y], width, 0,\n pp[:br][:x], pp[:br][:y], width, height,\n pp[:bl][:x], pp[:bl][:y], 0, height\n ].join ' '\n end", "def format_print(print_values)\n widths = Array.new(print_values[0].size, 0)\n print_values.each do |print_value|\n widths = widths.zip(print_value).map! {|width, value| value.length > width ? value.length : width }\n end\n\n print_values.each do |print_value|\n widths.zip(print_value) do |width, value|\n printf(\"%-#{width + 5}s\", value)\n end\n puts \"\"\n end\n end", "def pack_format\n \"a#{width}\"\n end", "def for_web_urls\n self.fixed_length\n end", "def url_to_font(source, options = T.unsafe(nil)); end", "def max_width_by_string(string)\n if string.length > 17\n return \"width:#{string.length * 0.6}em;\"\n end\n return \"\"\n end", "def sized(width, height)\n\t\t\t@sized_thumb = @template\n\t\t\t@sized_thumb.sub! \"{width}\", width.to_s\n\t\t\t@sized_thumb.sub! \"{height}\", height.to_s\n\t\tend", "def epl width = 197, height=124\n epl = encoded_polyline_cache\n epl.gsub(\"?size=197x124\", \"?size=#{width}x#{height}\")\n end", "def my_width \n 0.75\n end", "def mapf_format_paragraph(text, max_width = contents_width)\n text = text.clone\n # Create a Dummy Contents - I wanted to boost compatibility by using the \n # default process method for escape codes. It may have the opposite effect, \n # for some :( \n real_contents = contents # Preserve Real Contents\n self.contents = Bitmap.new(contents_width, 24)\n reset_font_settings\n paragraph = \"\"\n while !text.empty?\n text.lstrip!\n oline, nline, tw = mapf_format_by_line(text.clone, max_width)\n # Replace old line with the new one\n text.sub!(/#{Regexp.escape(oline)}/m, nline)\n paragraph += text.slice!(/.*?(\\n|$)/)\n end\n contents.dispose # Dispose dummy contents\n self.contents = real_contents # Restore real contents\n return paragraph\n end", "def write_url_web(row1, col1, row2, col2, url, str = nil, format = nil)\n record = 0x01B8 # Record identifier\n length = 0x00000 # Bytes to follow\n\n xf = format || @url_format # The cell format\n\n # Write the visible label but protect against url recursion in write().\n str = url if str.nil?\n @writing_url = 1\n error = write(row1, col1, str, xf)\n @writing_url = 0\n return error if error == -2\n\n # Pack the undocumented parts of the hyperlink stream\n unknown1 = [\"D0C9EA79F9BACE118C8200AA004BA90B02000000\"].pack(\"H*\")\n unknown2 = [\"E0C9EA79F9BACE118C8200AA004BA90B\"].pack(\"H*\")\n\n # Pack the option flags\n options = [0x03].pack(\"V\")\n\n # Convert URL to a null terminated wchar string\n url = url.split('').join(\"\\0\")\n url = url + \"\\0\\0\\0\"\n\n # Pack the length of the URL\n url_len = [url.length].pack(\"V\")\n\n # Calculate the data length\n length = 0x34 + url.length\n\n # Pack the header data\n header = [record, length].pack(\"vv\")\n data = [row1, row2, col1, col2].pack(\"vvvv\")\n\n # Write the packed data\n append( header, data,unknown1,options,unknown2,url_len,url)\n\n return error\n end", "def safe_width(width)\n\n\n\n width.to_s.gsub(/\\A(\\d+)\\z/, '\\1px')\n\n\n\n end", "def calculate_width(width)\n\n new_width = width\n\n if /%/ === new_width\n new_width.gsub!(/%/, '')\n width_num = new_width.to_i / 100.0\n new_width = \"#{width_num.to_s}\\\\textwidth\"\n end\n\n new_width\n end", "def frame(text, char)\n width = text.max { |a,b| a.length <=> b.length }.size + 4\n output = \"\" << \"#{char}\" * width << \"\\n\"\n text.each { |line| output << \"#{char} #{line}\" << \"%0#{width - line.size - 2}s\" % char << \"\\n\" }\n output << \"#{char}\" * width\nend", "def generate_layout(width, text)\n layout = ::Swt::TextLayout.new Shoes.display\n layout.setText text\n layout.setSpacing(@opts[:leading] || DEFAULT_SPACING)\n font = ::Swt::Font.new Shoes.display, @dsl.font, @dsl.font_size,\n ::Swt::SWT::NORMAL\n style = ::Swt::TextStyle.new font, nil, nil\n layout.setStyle style, 0, text.length - 1\n shrink_layout_to(layout, width) unless layout_fits_in?(layout, width)\n\n font.dispose\n\n layout\n end", "def screenshot_as(format, full_page: T.unsafe(nil)); end", "def mapf_format_paragraph(text, max_width = contents_width)\n text = text.clone\n # Create a Dummy Contents - I wanted to boost compatibility by using the\n # default process method for escape codes. It may have the opposite effect,\n # for some :(\n real_contents = contents # Preserve Real Contents\n self.contents = Bitmap.new(24, 24)\n reset_font_settings\n paragraph = \"\"\n while !text.empty?\n text.lstrip!\n oline, nline, tw = mapf_format_by_line(text.clone, max_width)\n # Replace old line with the new one\n text.sub!(/#{Regexp.escape(oline)}/m, nline)\n paragraph += text.slice!(/.*?(\\n|$)/)\n end\n contents.dispose # Dispose dummy contents\n self.contents = real_contents # Restore real contents\n return paragraph\n end", "def width\n end", "def width\n end", "def get_width; end", "def render_length_limit; end", "def format_text(title, url, url_title_time_ary)\n s = \"Title: #{title}¥nURL: #{url}¥n¥n\"\n url_title_time_ary.each do |aurl, atitle, atime|\n s << \"* (#{atime})#{atitle}¥n\"\n s << \" #{aurl}¥n\"\n end\n s\nend", "def _wrapper_formats; end", "def do_window_adjust(bytes); end", "def render_length; end", "def responsive_embed_code_css\n <<~END\n #fulcrum-embed-outer-#{id} {\n width:auto;\n page-break-inside:avoid;\n -webkit-column-break-inside:avoid;\n break-inside:avoid;\n max-width:#{embed_width}px;\n margin:auto;\n background-color:#000;\n }\n #fulcrum-embed-inner-#{id} {\n overflow:hidden;\n padding-bottom:#{padding_bottom}%;\n position:relative; height:0;\n }\n iframe#fulcrum-embed-iframe-#{id} {\n overflow:hidden;\n border-width:0;\n left:0; top:0;\n width:100%;\n height:100%;\n position:absolute;\n }\n END\n end", "def as_size2( s = nil )\n prefix = %W(ТиБ ГиБ МиБ КиБ Б)\n s = (s || self).to_f\n i = prefix.length - 1\n while s > 512 && i > 0\n s /= 1024\n i -= 1\n end\n ((s > 9 || s.modulo(1) < 0.1 ? '%d' : '%.1f') % s) + ' ' + prefix[i]\n end", "def watermark_formatted_text\n struct = export_as_mla_structure(parent_presenter)\n wrapped = wrap_text(struct[:author] + '___' + struct[:title], 150)\n parts = wrapped.split('___')\n [{ text: parts[0] },\n { text: parts[1], styles: [:italic] },\n { text: \"\\n\" + wrap_text(struct[:publisher], 150) },\n { text: \"\\nDownloaded on behalf of #{request_origin}\" }\n ]\n end", "def formatting(str)\n puts str * 80\nend", "def set_character_width_normal\r\n set_print_mode 0\r\n set_linefeed_rate 55\r\n end", "def designerPdfViewer(h, word)\n heights = Array.new\n hsh = Hash.new\n (\"a\"..\"z\").each_with_index { |letter, i| hsh[letter] = h[i] }\n word.each_char { |ch| heights << hsh[ch] }\n return heights.max * heights.count\nend", "def print_width\n raise \"Can't calculate print width for encoding: #{encoding}\" unless encoding == Encoding::UTF_8\n codepoints.reduce(0) do |result,code|\n result + ((code.is_chinese_character? || code.is_chinese_punctuation?) ? 2 : 1)\n end\n end", "def format_text(text)\n return text if text.blank?\n\n truncated_text = text.gsub(/\\b\\S{71,}\\b/) do |word|\n if word !~ /^https?:\\/\\//\n truncate(word, 70)\n else\n word\n end\n end\n\n simple_format(h(truncated_text).gsub(/\\bhttps?:\\/\\/\\S+/) do |word|\n if word =~ /\\.$/\n website_link(word.gsub(/\\.$/, ''), 70, false) + \".\" # Remove end of sentence dot from URL\n else\n website_link(word, 70, false)\n end\n end)\n end", "def preview_text(maxlength = 30)\n ::CGI.escapeHTML(source.to_s)[0..maxlength]\n end", "def width=(_); end", "def width=(_); end", "def render_style(text, mediatype=\"all\")\n [\"<style type='text/css' media='#{mediatype}' >\",\n text,\n \"</style>\\n\"].join(\"\\n\") \n end", "def urlify(str, length)\n new_str = ''\n\n str.each_char.each_with_index do |c, i|\n break if i == length\n new_str << (c == ' ' ? '%20' : c)\n end\n\n new_str\nend", "def preview(text, length=400)\n text.split(/\\s/).inject(\"\") do |out, chunk|\n if (out.size + 1 + chunk.size) <= length\n out + \" \" + chunk\n else\n return out + \" ...\"\n end\n end\n end", "def format_shortcodes(text)\n # preprocess to replace badly formatted shortcodes with syntactically correct shortcodes\n # [youtube id width height] -> [youtube id=\"id\" width=\"width\" height=\"height\"]\n Shortcode.process(text.gsub(/\\[youtube\\s+?(\\w*?)\\s+?(\\d+)\\s+?(\\d+)\\s*\\]/, '[youtube id=\"\\1\" width=\"\\2\" height=\"\\3\"]'))\n end", "def permalink_style; end", "def pango_render_text(width,font,text)\n pango = self.create_pango_layout\n pango.width = width*1000\n pango.wrap=Pango::WRAP_WORD\n pango.font_description = Pango::FontDescription.new(font)\n pango.markup=text\n self.show_pango_layout(pango)\n end", "def header_width_height(width,height)\r\n \"<style type=\\\"text/css\\\">\\n##{@container} { height: #{height}px;\\n width: #{width}px;\\n}\\n</style>\"\r\n end", "def wrap_width(width)\n gsub(/([^\\n\\r]{1,#{width}})/,\"\\\\1\\n\")\n end", "def preview\n self.content.split(' ')[0...5].join(' ') + '...'\n end", "def refresh\n self.contents=pbDoEnsureBitmap(self.contents,self.width-self.borderX,\n self.height-self.borderY)\n bitmap=self.contents\n bitmap.clear\n x=0\n y=0\n if @heading\n textwidth = bitmap.text_size(@heading).width\n pbDrawShadowText(bitmap,x,y,textwidth+4,32,@heading,@window.textColor,nil)\n y+=32\n end\n x+=4\n width=self.width-self.borderX\n height=self.height-self.borderY\n textscan=self.text.scan(/./m)\n scanlength=textscan.length\n @helper.cursor=scanlength if @helper.cursor>scanlength\n @helper.cursor=0 if @helper.cursor<0\n [email protected]\n fromcursor=0\n while (startpos>0)\n c=(@helper.passwordChar!=\"\") ? @helper.passwordChar : textscan[startpos-1]\n fromcursor+=bitmap.text_size(c).width\n break if fromcursor>width-4\n startpos-=1\n end\n for i in startpos...scanlength\n c=(@helper.passwordChar!=\"\") ? @helper.passwordChar : textscan[i]\n textwidth=bitmap.text_size(c).width\n next if c==\"\\n\"\n # Draw text\n pbDrawShadowText(bitmap,x,y, textwidth+4, 32, c,@window.textColor,nil)\n # Draw cursor if necessary\n if ((@frame/10)&1) == 0 && [email protected]\n bitmap.fill_rect(x,y+4,2,24,@window.textColor)\n end\n # Add x to drawn text width\n x += textwidth\n end\n if ((@frame/10)&1) == 0 && [email protected]\n bitmap.fill_rect(x,y+4,2,24,@window.textColor)\n end\n end", "def mime_type_and_size\n#(<%=media_item.content_type%>, <%=bytes_to_size(media_item.size)%>)\n result = \"\"\n if !content_type.blank?\n result << content_type\n end\n \n if !size.blank?\n result << ', ' if !result.blank?\n result << bytes_to_size(size)\n end\n \n result = '(' << result << ')' if !result.blank?\nend", "def set_character_width_normal\n set_print_mode 0\n set_linefeed_rate 55\n end", "def format_post(post)\n # Look at \"post-info.png\" for details on what's in the post array\n title = post['title']\n score = post['score']\n author = post['author']\n url = post['url']\n preview = post['thumbnail']\n \"`#{CGI.unescapeHTML(title)}`, Score: `#{score}`, By `u/#{author}`, @ #{url}\"\nend", "def pshr_srcset(upload, versions: [])\n if upload.has_versions? && versions.any?\n return versions.map { |v| \"#{upload.file[v].url} #{upload.file[v].metadata['width']}w\" }.join(', ')\n else\n return nil\n end\n end", "def calc_width; padding * 2 + base_width; end", "def calc_width; padding * 2 + base_width; end", "def wicked_pdf_url_base64(url); end", "def url(size_name) \n if @youtube_id\n \"http://img.youtube.com/vi/#{@youtube_id}/0.jpg\"\n else\n \"http://img.youtube.com/vi/0.jpg\"\n end\n end", "def styles; end", "def styles; end", "def styles; end", "def base_width; 26 + @width; end", "def blank_profile_pic_size(format)\n if format == 'display'\n '200x200'\n elsif format == 'tiny'\n '100x100'\n elsif format == 'xtiny'\n '50x50'\n else\n nil\n end\n end", "def output_tranformed_pixels\n\t\tstring_of_pixels = @pixels.join(\"\")\n\t\tresult = string_of_pixels.scan(/.{1,9}/).join(\"\\n\")\n\t\t#puts result\n\t\tputs result\n\t\tresult\n\tend" ]
[ "0.56964666", "0.56240404", "0.56118727", "0.54733765", "0.5460478", "0.5460478", "0.54472125", "0.53225136", "0.53105706", "0.5270903", "0.5231124", "0.52005523", "0.51955914", "0.49930593", "0.49762097", "0.49741358", "0.49741358", "0.49741358", "0.49741358", "0.49741358", "0.49741358", "0.49741358", "0.49741358", "0.49741358", "0.49616534", "0.49528378", "0.49468064", "0.4938855", "0.48948067", "0.48880193", "0.48738796", "0.48539096", "0.4846546", "0.4841813", "0.4841813", "0.48412332", "0.48363596", "0.48082936", "0.48039028", "0.48039028", "0.4801027", "0.48000124", "0.47813177", "0.47753555", "0.47593746", "0.47501203", "0.4747953", "0.4723279", "0.4720817", "0.47202086", "0.47111621", "0.47104898", "0.47048506", "0.4700269", "0.46981397", "0.46890044", "0.4687946", "0.46809447", "0.46809447", "0.46536255", "0.46509534", "0.46500942", "0.4649378", "0.46489996", "0.46483952", "0.46300194", "0.4617378", "0.46136996", "0.46119347", "0.46114573", "0.46064186", "0.4602323", "0.46018848", "0.46013793", "0.45989582", "0.45989582", "0.4598562", "0.4590391", "0.45903736", "0.4588834", "0.45877907", "0.45833313", "0.4577044", "0.4571622", "0.45610148", "0.45606774", "0.4560071", "0.4556819", "0.45530716", "0.4551406", "0.4548631", "0.4548631", "0.4547777", "0.45446563", "0.45404354", "0.45404354", "0.45404354", "0.45359826", "0.45318076", "0.4530602" ]
0.45380226
97
img with sizes attribute
def test_sizes output = tested('sizes rms.jpg') assert errors_ok? output assert_equal '(max-width: 600px) 80vw, 50%', output.at_css('img')['sizes'] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def image_size(style = default_style)\n return nil if instance_read(:meta).nil? || instance_read(:meta).empty?\n \"#{width(style)}x#{height(style)}\"\n end", "def image_sizes\n { :small => 'x110',\n :medium => 'x208',\n :large => 'x413',\n :big => 'x654',\n :storage => 'x867'\n }\n end", "def image_sizes=(sizes)\n @image_sizes = sizes\n end", "def image_size\n end", "def thumbnail(size); end", "def sizes\n @sizes ||= self.class.image_sizes.dup\n end", "def test_data_img_yes_size\n output = tested('data_img_yes_size rms.jpg')\n\n assert errors_ok? output\n\n assert_equal '(max-width: 600px) 80vw, 50%',\n output.at_css('img')['data-sizes']\n end", "def get_photo_size(sizes, label)\n size = sizes.find { |s| s.label == label }\n { url: size.source, width: size.width, height: size.height }\n end", "def small(input) # Method that returns the image\n self.images[input].variant(resize: \"300x300\").processed # Resizing the image and return it\n end", "def display_image \r\n self.image.variant(resize_to_limit: [1000, 1000]) \r\n end", "def update_image_attributes\n if imageable.present?\n self.width, self.height = `identify -format \"%wx%h\" #{url.file.path}`.split(/x/)\n end\n end", "def small_image_url\n self.small_image.convert('-resize 50%').url\n end", "def display_image\n image.variant resize_to_limit: Settings.validation.post.img_resize\n end", "def intrinsic_image_dimensions path\n if path.end_with? '.svg'\n img_obj = ::Prawn::Svg::Interface.new ::IO.read(path), self, {}\n img_size = img_obj.document.sizing\n { width: img_size.output_width, height: img_size.output_height }\n else\n # NOTE build_image_object caches image data previously loaded\n _, img_size = ::File.open(path, 'rb') {|fd| build_image_object fd }\n { width: img_size.width, height: img_size.height }\n end\n end", "def image_size\n {\n width: image_file_width,\n height: image_file_height,\n }\n end", "def compute_image_size src\n $stderr.puts \"c_i_s #{src.class} #{src.to_s.size} #{src.inspect}\" if src.to_s.size < 1024\n case src\n when Pathname\n # @verbose = true\n result = cmd_out(\"#{BIN_PREFIX}imgsize -r #{src.to_s.inspect}\")\n result = /(\\d+) (\\d+)/.match(result)\n result = result ? { :width => result[1].to_i, :height => result[2].to_i } : nil\n result\n when String\n compute_image_size(force_to_file)\n else\n raise TypeError, \"#{src.class}\"\n end\n end", "def old_resize_image(img, size)\n size = size.first if size.is_a?(Array) && size.length == 1 && !size.first.is_a?(Fixnum)\n if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))\n size = [size, size] if size.is_a?(Fixnum)\n img.thumbnail!(*size)\n elsif size.is_a?(String) && size =~ /^c.*$/ # Image cropping - example geometry string: c75x75\n dimensions = size[1..size.size].split(\"x\")\n img.crop_resized!(dimensions[0].to_i, dimensions[1].to_i)\n else\n img.change_geometry(size.to_s) { |cols, rows, image| image.resize!(cols<1 ? 1 : cols, rows<1 ? 1 : rows) }\n end\n self.width = img.columns if respond_to?(:width)\n self.height = img.rows if respond_to?(:height)\n img.strip! unless attachment_options[:keep_profile]\n quality = img.format.to_s[/JPEG/] && get_jpeg_quality\n out_file = write_to_temp_file(img.to_blob { self.quality = quality if quality })\n temp_paths.unshift out_file\n self.size = File.size(self.temp_path)\n end", "def size\n width * height\n end", "def display_image\n image.variant(resize_to_limit: [500,500])\n end", "def image_for(id, size=:source)\n image_tag \"https://spoonacular.com/recipeImages/#{id}-#{IMAGE_SIZES[size]}\"\n end", "def sized(width, height)\n\t\t\t@sized_thumb = @template\n\t\t\t@sized_thumb.sub! \"{width}\", width.to_s\n\t\t\t@sized_thumb.sub! \"{height}\", height.to_s\n\t\tend", "def size\n {width: @iplimage_struct.width, height: @iplimage_struct.height}\n end", "def display_image\n image.variant(resize_to_limit: [500, 500])\n end", "def display_image\n image.variant(resize_to_limit: [500, 500])\n end", "def display_image\n image.variant(resize_to_limit: [500, 500])\n end", "def display_image\n image.variant(resize_to_limit: [500, 500])\n end", "def display_image\n image.variant(resize_to_limit: [500, 500])\n end", "def display_image\n image.variant(resize_to_limit: [500, 500])\n end", "def dynamic_resize_to_fit(size)\n resize_to_fit *(model.class::IMAGE_CONFIG[size])\n end", "def image_width\n end", "def format\n open{ |f| ImageSize.new(f) }.format\n end", "def format\n open{ |f| ImageSize.new(f) }.format\n end", "def image_size(path)\n magick = MiniMagick::Image.open path\n \"#{magick.width}x#{magick.height}\"\nend", "def test_method_size\n width, height = (1..100).to_a.sample( 2 )\n base_image = Magick::Image.new( width, height )\n image_adapter = Image::AdapterMagickImage.new( base_image )\n \n # maps width/height to size( :x ) / size ( :y )\n assert_equal width, image_adapter.size( :x )\n assert_equal height, image_adapter.size( :y )\n end", "def set_dimensions\n\t\timg = Magick::Image::read(\"#{Rails.root}/public\"+image_url(:image).to_s).first\n\t\tself.width = img.columns\n\t\tself.height = img.rows\n\t\tself.size \t= img.filesize\n\t\tif self.v.nil? then self.v = 0 end\n\t\tself.url \t= img.filename\n\tend", "def describe_image(image)\n puts \"#{image[:name]} is #{image[:width]}px * #{image[:height]}px\"\nend", "def test_data_img_no_size\n output = tested('data_img_no_size rms.jpg')\n\n assert errors_ok? output\n\n assert_equal '(max-width: 600px) 80vw, 50%',\n output.at_css('img')['sizes']\n end", "def save_image_dimensions\n if data.content_type == \"image/jpeg\" || \"image/png\" || \"image/jpg\" || \"image/gif\"\n geo = Paperclip::Geometry.from_file(data.queued_for_write[:original])\n self.width = geo.width\n self.height = geo.height\n end\n end", "def thumbnail input\n return self.images[input].variant(resize: '300x300').processed\n end", "def extract_dimensions\n return unless is_image?\n {original: 'image_dimensions', resized: 'resized_dimensions'}.each_pair do |style, method|\n tempfile = media.queued_for_write[style]\n unless tempfile.nil?\n geometry = Paperclip::Geometry.from_file(tempfile)\n self.send(\"#{method}=\", [geometry.width.to_i, geometry.height.to_i])\n end\n end\n end", "def img(src = \"\", alt = \"\", width = nil, height = nil)\n attributes = if src.kind_of?(String)\n { \"SRC\" => src, \"ALT\" => alt }\n else\n src\n end\n attributes[\"WIDTH\"] = width.to_s if width\n attributes[\"HEIGHT\"] = height.to_s if height\n super(attributes)\n end", "def get_size\n img_sizes = flickr.photos.getSizes(photo_id: @info['id']).to_a\n img = img_sizes.last\n\n # Loop down through images until appropriate sized one is found\n (img_sizes.length-2).downto(0) do |i|\n if img_sizes[i]['height'].to_i < 1000 || img_sizes[i]['width'].to_i < 1600\n img = img_sizes[i+1]\n break\n end\n end\n\n @source = img['source']\n @page = img['url']\n @height = img['height']\n @width = img['width']\n end", "def resize(size='512x512')\n if self.url.present?\n image = MiniMagick::Image.open(self.url)\n image.resize(size)\n image\n end\n end", "def image_dimensions\n {\n thumbnail: 'square/100,100/0/default.jpg',\n default: 'full/80,80/0/default.jpg',\n medium: 'full/125,125/0/default.jpg',\n large: 'full/!400,400/0/default.jpg'\n }\n end", "def product_image(size)\n images.presence && images[0].url(size)\n end", "def resize_image(img, size)\n size = size.first if size.is_a?(Array) && size.length == 1 && !size.first.is_a?(Fixnum)\n if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))\n size = [size, size] if size.is_a?(Fixnum)\n img.thumbnail!(*size)\n elsif size.is_a?(String) && size =~ /^c.*$/ # Image cropping - example geometry string: c75x75\n dimensions = size[1..size.size].split(\"x\")\n img.crop_resized!(dimensions[0].to_i, dimensions[1].to_i)\n elsif size.is_a?(String) && size =~ /^b.*$/ # Resize w/border - example geometry string: b75x75\n dimensions = size[1..size.size].split(\"x\")\n img.change_geometry(dimensions.join(\"x\")) do |cols, rows, image|\n image.resize!(cols<1 ? 1 : cols, rows<1 ? 1 : rows )\n end\n img.background_color = \"black\"\n x_offset = (img.columns - dimensions[0].to_i) / 2\n y_offset = (img.rows - dimensions[1].to_i) / 2\n img = img.extent(dimensions[0].to_i, dimensions[1].to_i, x_offset, y_offset)\n else\n img.change_geometry(size.to_s) { |cols, rows, image| image.resize!(cols<1 ? 1 : cols, rows<1 ? 1 : rows) }\n end\n img.strip! unless attachment_options[:keep_profile]\n temp_paths.unshift write_to_temp_file(img.to_blob)\n end", "def large_image\n self.image.large\n end", "def size\n \"#{width}x#{height}\"\n end", "def size\n \"#{width}x#{height}\"\n end", "def resize_image(img, size)\n size = size.first if size.is_a?(Array) && size.length == 1\n if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))\n if size.is_a?(Fixnum)\n # Borrowed from image science's #thumbnail method and adapted \n # for this.\n scale = size.to_f / (img.width > img.height ? img.width.to_f : img.height.to_f)\n img.resize!((img.width * scale).round(1), (img.height * scale).round(1), false)\n else\n img.resize!(size.first, size.last, false) \n end\n else\n w, h = [img.width, img.height] / size.to_s\n img.resize!(w, h, false)\n end\n temp_paths.unshift random_tempfile_filename\n self.size = img.export(self.temp_path)\n end", "def image(size:)\n return nil unless (types = SIZE_TO_TYPE[size.to_i])\n\n data = nil\n types.each do |type|\n break if (data = self.data(type: type))\n end\n\n data\n end", "def resize_image(img, size)\n size = size.first if size.is_a?(Array) && size.length == 1 && !size.first.is_a?(Fixnum)\n if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))\n size = [size, size] if size.is_a?(Fixnum)\n img.thumbnail!(*size)\n elsif size.is_a?(String) && size =~ /^c.*$/ # Image cropping - example geometry string: c75x75\n dimensions = size[1..size.size].split(\"x\")\n img.crop_resized!(dimensions[0].to_i, dimensions[1].to_i)\n elsif size.is_a?(String) && size =~ /^b.*$/ # Resize w/border - example geometry string: b75x75\n dimensions = size[1..size.size].split(\"x\")\n img.change_geometry(dimensions.join(\"x\")) do |cols, rows, image| \n image.resize!(cols<1 ? 1 : cols, rows<1 ? 1 : rows ) \n end\n img.background_color = \"black\"\n x_offset = (img.columns - dimensions[0].to_i) / 2\n y_offset = (img.rows - dimensions[1].to_i) / 2\n img = img.extent(dimensions[0].to_i, dimensions[1].to_i, x_offset, y_offset)\n else\n img.change_geometry(size.to_s) { |cols, rows, image| image.resize!(cols<1 ? 1 : cols, rows<1 ? 1 : rows) }\n end\n img.strip! unless attachment_options[:keep_profile]\n temp_paths.unshift write_to_temp_file(img.to_blob)\n end", "def size(size)\n w = width\n h = height\n if width && height\n d = [w, h].max\n max = case size.to_s\n when \"thumbnail\" then 160\n when \"small\" then 320\n when \"medium\" then 640\n when \"large\" then 960\n when \"huge\" then 1280\n else; 1e10\n end\n if max < d\n w = w * max / d\n h = h * max / d\n end\n end\n [w, h]\n end", "def set_original\n if keep_original\n if size_o.blank?\n image = MiniMagick::Image.open(name)\n self.size_o = \"#{image.width}x#{image.height}\"\n end\n else\n self.size_o = ''\n end\nend", "def pixel_size; size.x * size.y; end", "def normalized_sizes(width, height)\n if width.to_i > @image.width\n width = @image.width\n end\n if height.to_i > @image.height\n height = @image.height\n end\n \"#{width}x#{height}\"\n end", "def weave_image_size_to_xml(xmlstr, xpath_prefix='')\n doc = REXML::Document.new(xmlstr)\n doc.elements.each(xpath_prefix + 'IMAGE') do |img_e|\n img_file_path = nil\n img_e.each_element('SOURCE') do |src_e|\n img_file_path = src_e.get_text.to_s\n end # img_file_path must not be nil\n size_e = REXML::Element.new('SIZE')\n if FileTest.exist?(img_file_path)\n text = File.size(img_file_path).to_s\n else\n text = '-'\n end\n size_e.add(REXML::Text.new(text))\n img_e.add(size_e)\n end\n doc\n end", "def image_width(image_width)\n end", "def images (size_requested = 'all')\n returned_images = []\n images = @record.fetch('ImageInfo', {})\n if images.count > 0\n images.each do |image|\n if size_requested == image['Size'] || size_requested == 'all'\n returned_images.push({size: image['Size'], src: image['Target']})\n end\n end\n end\n returned_images\n end", "def image_as_medium_thumbnail\n image.variant(resize_to_fill: [350, 350]).processed\n end", "def size\n \n return case \n when pixels <= (16*16)\n :tiny\n when pixels <= (32*32)\n :small\n when pixels <= (64*64)\n :icon\n when pixels <= (4200..6200)\n :default\n when pixels <= (128*128)\n :medium\n when pixels <= (256*256)\n :large\n when pixels <= (512*512)\n :huge\n else\n :silly\n end\n \n end", "def size=(size='300x200')\n @width, @height = size.split(\"x\").map { |dimension| dimension.to_i }\n end", "def process_small_image\n small_image.encode!(:png).convert!('-resize 50x50 -gravity center -background none -extent 50x50')\n end", "def xf_image_tag (src, attrs = {})\n attrs = attrs.symbolize_keys()\n content = \"\"\n caption = attrs.delete(:caption)\n unless caption.nil?\n content += typeWithAttrs(\"caption\", caption, nil, xhtml2prefix)\n end\n width = attrs.delete(:width)\n unless width.nil?\n content += typeWithAttrs(\"param\", nil, {:name => \"mcs-aspect-ratio-width\", :value => width}, xhtml2prefix)\n end\n height = attrs.delete(:height)\n unless height.nil?\n content += typeWithAttrs(\"param\", nil, {:name => \"mcs-aspect-ratio-height\", :value => height}, xhtml2prefix)\n end\n attrs[:src] = src\n typeWithAttrs(\"object\", content, attrs, xhtml2prefix)\n end", "def set_dimensions!\n if RMAGICK_SUPPORTED\n #MES- Turn the blob into an ImageMagick object\n img = Magick::Image.from_blob(data).first\n if img.nil?\n raise \"Error: could not get imagemagick image from picture #{self.id}'s data\"\n end\n \n #KS- grab width & height and save them\n self.height = img.rows\n self.width = img.columns\n end\n end", "def test_srcset_and_sizes\n stub_sizes_srcset\n\n correct = <<~HEREDOC\n <img src=\"good_url\" srcset=\"width srcset\" sizes=\"correct sizes\">\n HEREDOC\n\n assert_equal correct, @tested.to_s\n end", "def my_resize(width, height)\n manipulate! do |img|\n img.resize \"#{width}x#{height}!\"\n img\n end\n end", "def size=(width, height)\n end", "def image_height\n end", "def img_name_size(file, size)\n return file.sub(\"_300\", \"_#{size}\")\n end", "def choose_dimensions(img_elem, default_width, default_height)\n width = default_width\n height = default_height # Until we determine otherwise\n\n # CSS styling takes precedence over explicit +width+ and +height+ attributes, so\n # look for the explicit attributes first and then override them below if the CSS\n # styling yields values.\n width = img_elem['width'] if img_elem.has_attribute?('width')\n height = img_elem['height'] if img_elem.has_attribute?('height')\n\n # Attempt to override the explicit attribute values with CSS style values.\n if img_elem.has_attribute?('style')\n css_width = extract_css_dimension(img_elem['style'], :width)\n css_height = extract_css_dimension(img_elem['style'], :height)\n\n width = css_width if css_width\n height = css_height if css_height\n end\n\n [width, height]\n end", "def variants\n VARIANTS.keys.map do |size|\n CreateImage.new(attributes.merge(size: size, disabled: size != 'large'))\n end\n end", "def resize\n image = ManagedImage.from_path(params[:image])\n width = params[:width].to_i\n height = params[:height].to_i\n render json: image.resize(width, height)\n end", "def large_image_width\n 850\n end", "def resize_to_fit\n image = ManagedImage.from_path(params[:image])\n width = params[:width].to_i\n height = params[:height].to_i\n render json: image.resize_to_fit(width, height)\n end", "def thumbnail_definitions\n thumbnail_sizes\n end", "def small_image_url\n \"#{image_url}?type=small\"\n end", "def thumb_for(document, size)\n image_tag document.thumb(size, self)\n end", "def test_png_size_determined_correctly\n assert_equal [120, 175], @page.get_png_size(@test_png)\n end", "def size=(size)\n self.width = self.height = @size = size\n end", "def create_size src,dest,params\n return nil if !File.exists?(src)\n i = Image.new(src)\n params[:to] = dest\n FileUtils.mkdir_p File.dirname(dest)\n i.out params\n @hooks.create(:original => src,\n :sized => dest,\n :not_found => params[:not_found],\n :autogenerated => params[:autogenerated],\n :width => params[:width],\n :height => params[:height]) if @hooks && !params[:skiphook]\n end", "def resize\n @image.resize \"#{@placement[:a]}x#{OUTER}\\!\"\n end", "def set_image_size(file = local_file_name(:full_size))\n w, h = FastImage.size(file)\n return unless /^\\d+$/.match?(w.to_s)\n\n self.width = w.to_i\n self.height = h.to_i\n save_without_our_callbacks\n end", "def large\n if image.on_storage?\n variant(1200)\n else\n relevant_assets_cache.select { |item| item.width <= 1200 }.sort_by(&:width).last.url\n end\n end", "def create_resized_image\n create_image do |xfrm|\n if size\n MiniMagick::Tool::Convert.new do |cmd|\n cmd << xfrm.path # input\n cmd.flatten\n cmd.resize(size)\n cmd << xfrm.path # output\n end\n end\n end\n end", "def getImg(width=64, height=64)\n if self.image\n self.image+\"?width=#{width}&height=#{height}\"\n else\n \"no_image.png\"\n end\n end", "def set_offer_image_dimensions\n if offer_image.queued_for_write[:full_size]\n geometry = Paperclip::Geometry.from_file(offer_image.queued_for_write[:full_size])\n self.offer_image_width = geometry.width\n self.offer_image_height = geometry.height\n end\n end", "def setup_available_sizes(file)\n# ::Rails.logger.debug \"setup_available_sizes: #{file.path}\"\n# if model.original_image_width.nil? || model.original_image_height.nil?\n# \n# img = ::Magick::Image::read(@file.file).first\n# model.original_image_width = img.columns\n# model.original_image_height = img.rows\n# ::Rails.logger.debug \"setup w/h for validtaion #{img.columns}x#{img.rows}\"\n# end\n\n model.class::IMAGE_CONFIG.keys.each do |key|\n self.class_eval do\n define_method(\"has_#{key}_config?\".to_sym) { |file| true }\n end\n end\n end", "def portfolio_img img, type\n if img.is_a?(String)\n img\n elsif type == 'thumb'\n image_generator(height: '350', width: '200')\n else\n image_generator(height: '600', width: '400')\n end\n end", "def size_with_meta_data(style = nil)\n style ? meta_for_style(style)[:size] : size_without_meta_data\n end", "def edit_picture_dialog_size(content)\n if content.settings[:caption_as_textarea]\n content.settings[:sizes] ? \"380x320\" : \"380x300\"\n else\n content.settings[:sizes] ? \"380x290\" : \"380x255\"\n end\n end", "def size\n @sizes ||= strip(:size)\n end", "def is_small_imageable?\n return true\n end", "def size\n @images.size\n end", "def image(options = {}, html_options = {})\n html_options[:src] = if options.is_a?(String) then options else self.url_for(options) end\n html_options[:alt] ||= File.basename(html_options[:src], '.*').split('.').first.capitalize\n\n if html_options[:size]\n html_options[:width], html_options[:height] = html_options[:size].split(\"x\")\n html_options.delete :size\n end\n\n tag(\"img\", html_options)\n end", "def imgur_large(url)\n\t\turl.match(@@picsize_regex) do |match|\n\t\t\t\"http://i.imgur.com/\"+match[1]+\"l\"+\".\"+match[3]\n\t\tend\n\tend", "def resizeImage(file, size)\n img_orig = Magick::Image.read(\"public/#{file}\").first\n \n width = img_orig.columns\n height = img_orig.rows\n \n if(width > size || height > size)\n if(width > height)\n height = size * height / width\n width = size\n else\n width = size * height / width\n height = size\n end\n \n img = img_orig.resize_to_fit(width, height)\n \n img.write(\"public/#{file}\")\n end\n end", "def image_url(max_size=1600)\r\n\r\n src_width = self.DELIV_OPS.svg_image.svg_width.first.to_f\r\n src_height = self.DELIV_OPS.svg_image.svg_height.first.to_f\r\n\r\n ratio = [ max_size / src_width , max_size / src_height ].min\r\n\r\n dest_width = (src_width * ratio).to_i\r\n dest_height = (src_height * ratio).to_i\r\n\r\n \"#{DIL_CONFIG['aware_region_url']}#{self.DELIV_OPS.svg_image.svg_image_path.first}&destwidth=#{dest_width}&destheight=#{dest_height}&padh=center&padv=center\"\r\n end", "def imgur_small_square(url)\n\t\turl.match(@@picsize_regex) do |match|\n\t\t\t\"http://i.imgur.com/\"+match[1]+\"s\"+\".\"+match[3]\n\t\tend\n\tend", "def image_of(movie, msize)\n if(self.checkURI(movie))\n image_tag(movie.img, alt: movie.title, class: \"movie_image\", width: msize)\n else\n image_tag(\"/images/missing.jpg\", alt: movie.title, class: \"movie_image\", width: msize)\n end\n end" ]
[ "0.7520836", "0.7360362", "0.724988", "0.7172528", "0.70751977", "0.7008975", "0.6905201", "0.6890874", "0.6789753", "0.6772769", "0.67674047", "0.67609435", "0.6746429", "0.67457914", "0.67315453", "0.67028576", "0.66869587", "0.6682386", "0.663354", "0.66269255", "0.66169643", "0.6611281", "0.66089183", "0.66089183", "0.66089183", "0.66089183", "0.66089183", "0.66089183", "0.6603301", "0.6579931", "0.6576122", "0.6576122", "0.6573789", "0.6570071", "0.6569317", "0.6568488", "0.653809", "0.6533808", "0.65255433", "0.6503455", "0.6492323", "0.64888734", "0.64762235", "0.64740807", "0.64700097", "0.64691854", "0.6468037", "0.64677423", "0.64677423", "0.64492005", "0.6432672", "0.64136726", "0.6412501", "0.63985354", "0.6363806", "0.636188", "0.63473547", "0.63435256", "0.6330855", "0.6321466", "0.6321401", "0.6318775", "0.6309941", "0.62907714", "0.62888426", "0.6286453", "0.6274502", "0.62623334", "0.62555736", "0.62479156", "0.6243633", "0.62205887", "0.62174886", "0.62016076", "0.6201437", "0.6198386", "0.6197247", "0.61924005", "0.6191997", "0.6168299", "0.6166314", "0.6154423", "0.61500406", "0.61477476", "0.61425364", "0.61393887", "0.61340874", "0.61296314", "0.6123446", "0.61210716", "0.61180305", "0.6113864", "0.61122733", "0.61003375", "0.60993123", "0.6094813", "0.60860175", "0.6084251", "0.6083549", "0.60832566" ]
0.7231818
3
data_ output with sizes attr, yes datasizes
def test_data_img_yes_size output = tested('data_img_yes_size rms.jpg') assert errors_ok? output assert_equal '(max-width: 600px) 80vw, 50%', output.at_css('img')['data-sizes'] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def size ; data['size'] ; end", "def get_size(data)\n @horizontal_length = data[0].length\n @vertical_length = data.length\n end", "def size\n stats[:dataSize]\n end", "def size\n stats[:dataSize]\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\n @data.size\n end", "def size\n @data.size\n end", "def size\n @info[:size]\n end", "def size\n data.values.inject(0){|m,v| m+=v.size}\n end", "def d_size\n @desc[:size].to_i\n end", "def data_length\n super\n end", "def size\n return @data.size\n end", "def sizes(data)\n s = {}\n data.each { |line| \n line.each_pair { |key, value|\n s[key] = [column_name(key).length, value.length, (s[key] || 0)].max\n }\n }\n s\n end", "def size\r\n self.data.length\r\n end", "def current_size\n @data.size\n end", "def byte_size(); @data.byte_size + 4; end", "def data_size\n @iplimage_struct.image_size\n end", "def size\n info[\"size\"]\n end", "def size\n return @args[:data].length\n end", "def ndata; end", "def size\n self.data.length + 4\n end", "def get_size\n\t\tend", "def size\n @size \n end", "def size\n @size \n end", "def size\n\t\t7500\n\tend", "def data\n @data ||= \"O\" * size\n end", "def size\n @data.bytesize\n end", "def size\n @bindata.size\n end", "def size\n return @data.size\n end", "def data_size\n size = 0\n @avi.process_movi do |indices, movi|\n size = movi.size\n [indices, movi]\n end\n size\n end", "def size\n @data_items.size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def interpret_size(size); 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 return @args[\"data\"].length\n end", "def size\n\n end", "def size\n\n\n end", "def trait\n @raw_data.size\n end", "def size\n end", "def size\n end", "def size\n end", "def size\n end", "def size\n end", "def size\n end", "def size\n end", "def size\n @data ? @data.size : header.sh_size\n end", "def size_with_meta_data(style = nil)\n style ? read_meta(style, :size) : size_without_meta_data\n end", "def get_size\n\t\treturn @size\n\tend", "def size\n\tend", "def size\n \t@size\n end", "def size\n end", "def size\n end", "def size\n end", "def size; @size end", "def size\r\n\t\t@size\r\n\t\t#el tamaño\r\n\tend", "def size_with_meta_data(style = nil)\n style ? meta_for_style(style)[:size] : size_without_meta_data\n end", "def size\n Integer(metadata[\"size\"]) if metadata[\"size\"]\n end", "def memsize\n end", "def size\n @size\n end", "def size\n self[:size]\n end", "def size\nend", "def dimensions\n data[:dimensions]\n end", "def log_data_size(el, value, indent)\n indentation = ' ' * indent\n val_size = if value.kind_of?(Hash) || value.kind_of?(Array) || value.kind_of?(ActiveRecord::Base) || !value.respond_to?(\"size\")\n Marshal.dump(value).size\n else\n value.size\n end\n\n line = \"#{indentation}#{el} <#{value.class.name}> Size #{val_size}\"\n line << \" Elements #{value.size}\" if value.kind_of?(Hash) || value.kind_of?(Array)\n line << \" ActiveRecord Object!!\" if value.kind_of?(ActiveRecord::Base)\n $log.warn(format_log_message(line))\n\n return if value.kind_of?(Hash) || value.kind_of?(Array) || value.kind_of?(ActiveRecord::Base)\n\n $log.debug { \"Value #{value.inspect[0...2000]}\" }\n end", "def size\n @sizes ||= strip(:size)\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def bytes\n case hydra_model\n when \"Collection\"\n super\n else\n fetch(Solrizer.solr_name(\"file_size\", :stored_sortable, type: :long))\n end \n end", "def memory_footprint\n BULK_APIS.keys.map do |key| \n size = nil\n if redis.exists(redis_key(key))\n size = redis.debug(\"object\", redis_key(key)).match(/serializedlength:(\\d+)/)[1].to_i / 1024.0\n end\n [key, size]\n end.to_h.compact\n end", "def size\n end", "def size\n @size.size\n end", "def size\n attribute_prop(3)\n end", "def size; end", "def size; end" ]
[ "0.76078606", "0.7328655", "0.7306415", "0.7306415", "0.71286786", "0.71286786", "0.6887701", "0.6887701", "0.6887701", "0.6842166", "0.6828724", "0.68108106", "0.6805772", "0.6795957", "0.67811364", "0.673414", "0.6719803", "0.6694658", "0.6692248", "0.6686813", "0.66781837", "0.66472536", "0.66354805", "0.6631877", "0.6616896", "0.6616896", "0.65619206", "0.6535247", "0.6528589", "0.6518224", "0.65102553", "0.6496457", "0.64791024", "0.6475502", "0.6475502", "0.6475502", "0.6475502", "0.6475502", "0.6475502", "0.6475502", "0.6475502", "0.6475502", "0.6475502", "0.6475502", "0.6475502", "0.6475502", "0.6475502", "0.6475502", "0.6475502", "0.6475502", "0.6475502", "0.6475502", "0.6475502", "0.6475502", "0.6475502", "0.6475502", "0.6475502", "0.6452999", "0.644925", "0.644925", "0.644925", "0.6432801", "0.6412862", "0.639429", "0.6394285", "0.6390827", "0.6390827", "0.6390827", "0.6390827", "0.6390827", "0.6390827", "0.6390827", "0.63835734", "0.6378723", "0.6378462", "0.63779", "0.6368503", "0.6364996", "0.6364996", "0.6364996", "0.63496745", "0.6346325", "0.63454896", "0.63385695", "0.6320949", "0.63158125", "0.6301735", "0.6285786", "0.62572473", "0.6252862", "0.62517804", "0.62336016", "0.62336016", "0.62336016", "0.622639", "0.62212527", "0.6206028", "0.62047225", "0.62037504", "0.6202819", "0.6202819" ]
0.0
-1
data_ output with sizes attr, no datasizes
def test_data_img_no_size output = tested('data_img_no_size rms.jpg') assert errors_ok? output assert_equal '(max-width: 600px) 80vw, 50%', output.at_css('img')['sizes'] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def size ; data['size'] ; end", "def get_size(data)\n @horizontal_length = data[0].length\n @vertical_length = data.length\n end", "def size\n stats[:dataSize]\n end", "def size\n stats[:dataSize]\n end", "def size\n @data.size\n end", "def size\n @data.size\n end", "def data_length\n super\n end", "def data\n @data ||= \"O\" * size\n end", "def ndata; end", "def size\n @data.size\n end", "def size\n @data.size\n end", "def size\n @data.size\n end", "def size\n data.values.inject(0){|m,v| m+=v.size}\n end", "def size\n return @data.size\n end", "def sizes(data)\n s = {}\n data.each { |line| \n line.each_pair { |key, value|\n s[key] = [column_name(key).length, value.length, (s[key] || 0)].max\n }\n }\n s\n end", "def size\r\n self.data.length\r\n end", "def current_size\n @data.size\n end", "def byte_size(); @data.byte_size + 4; end", "def size\n return @args[:data].length\n end", "def size\n @info[:size]\n end", "def data_size\n @iplimage_struct.image_size\n end", "def size\n self.data.length + 4\n end", "def d_size\n @desc[:size].to_i\n end", "def size\n info[\"size\"]\n end", "def size\n @bindata.size\n end", "def size\n @data.bytesize\n end", "def get_size\n\t\tend", "def data_size\n size = 0\n @avi.process_movi do |indices, movi|\n size = movi.size\n [indices, movi]\n end\n size\n end", "def size\n return @data.size\n end", "def size\n @size \n end", "def size\n @size \n end", "def trait\n @raw_data.size\n end", "def size\n @data_items.size\n end", "def size\n return @args[\"data\"].length\n end", "def size\n\t\t7500\n\tend", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def size\n @size\n end", "def interpret_size(size); end", "def size_with_meta_data(style = nil)\n style ? read_meta(style, :size) : size_without_meta_data\n end", "def size\n @data ? @data.size : header.sh_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 bytes\n case hydra_model\n when \"Collection\"\n super\n else\n fetch(Solrizer.solr_name(\"file_size\", :stored_sortable, type: :long))\n end \n end", "def size_with_meta_data(style = nil)\n style ? meta_for_style(style)[:size] : size_without_meta_data\n end", "def to_s\n pad_field :data, :options\n recalc_block_len\n super\n end", "def save_size_data \n if (!(bb1.nil?||bb1.blank?) || !(ss1.nil?||ss1.blank?) || !(bb2.nil?||bb2.blank?) || !(pp1.nil?||pp1.blank?) || !(bb3.nil?||bb3.blank?) || !(ss2.nil?||ss2.blank?) || !(kk1.nil?||kk1.blank?) || !(jj1.nil?||jj1.blank?)) \n unless bb1.nil? || bb1.blank?\n baju=bb1.upcase\n else\n baju=''\n end\n unless jj1.nil? || jj1.blank?\n jbiru=jj1.upcase\n else\n jbiru=''\n end\n self.size_data = {baju: baju,seluar: ss1.to_s,beret: bb2.to_s, pcap: pp1.to_s, bhat: bb3.to_s, scap: ss2.to_s, kasut: kk1.to_s, jbiru: jbiru}\n end\n end", "def size\n end", "def size\n end", "def size\n end", "def size\n end", "def size\n end", "def size\n end", "def size\n end", "def size\n\n end", "def size\n \t@size\n end", "def size\n @sizes ||= strip(:size)\n end", "def size\n self[:size]\n end", "def log_data_size(el, value, indent)\n indentation = ' ' * indent\n val_size = if value.kind_of?(Hash) || value.kind_of?(Array) || value.kind_of?(ActiveRecord::Base) || !value.respond_to?(\"size\")\n Marshal.dump(value).size\n else\n value.size\n end\n\n line = \"#{indentation}#{el} <#{value.class.name}> Size #{val_size}\"\n line << \" Elements #{value.size}\" if value.kind_of?(Hash) || value.kind_of?(Array)\n line << \" ActiveRecord Object!!\" if value.kind_of?(ActiveRecord::Base)\n $log.warn(format_log_message(line))\n\n return if value.kind_of?(Hash) || value.kind_of?(Array) || value.kind_of?(ActiveRecord::Base)\n\n $log.debug { \"Value #{value.inspect[0...2000]}\" }\n end", "def memory_footprint\n BULK_APIS.keys.map do |key| \n size = nil\n if redis.exists(redis_key(key))\n size = redis.debug(\"object\", redis_key(key)).match(/serializedlength:(\\d+)/)[1].to_i / 1024.0\n end\n [key, size]\n end.to_h.compact\n end", "def size\n end", "def size\n end", "def size\n end", "def size\r\n\t\t@size\r\n\t\t#el tamaño\r\n\tend", "def dimensions\n data[:dimensions]\n end", "def normalize_output(data)\n output = {}\n\n until data.empty?\n row = data.shift\n normalized_row = row.size == 1 ? row + data.shift : row\n device, size, used, available, used_percent, mount = normalized_row\n output[mount] = DiskUsageItem.new(mount, device: device, size: to_filesize(size), used: to_filesize(used), available: to_filesize(available), used_percent: used_percent.to_i, mount: mount)\n end\n\n output\n end", "def size\n\tend", "def size; @size end", "def get_size\n\t\treturn @size\n\tend", "def size\n @size\n end", "def size\n\n\n end", "def add_file_datastream(file, opts={})\n super\n if file.respond_to?(:size)\n size = bits_to_human_readable(file.size)\n elsif file.kind_of?(File)\n size = bits_to_human_readable(File.size(file))\n else\n size = \"\"\n end\n datastreams[\"descMetadata\"].extent = size\n end", "def size\n Integer(metadata[\"size\"]) if metadata[\"size\"]\n end", "def size\n self.data.keys.size\n end", "def size\n self.datastreams.values.map(&:size).compact.sum\n end", "def inspect\n tmp = @data\n begin\n @data = nil\n @data_summary = (\"#{tmp.size},#{tmp[0,256]}\" if tmp)\n return super\n ensure\n @data = tmp\n @data_summary = nil\n end\n end", "def size\n {width: @iplimage_struct.width, height: @iplimage_struct.height}\n end", "def size\nend", "def size\n @size\n end" ]
[ "0.73123187", "0.7034131", "0.69246083", "0.69246083", "0.68477607", "0.68477607", "0.6803036", "0.6740246", "0.66061413", "0.66039586", "0.66039586", "0.66039586", "0.6559971", "0.65096176", "0.6483793", "0.6466329", "0.6456414", "0.64278555", "0.641152", "0.639167", "0.63830847", "0.63652563", "0.63180286", "0.6270595", "0.6254402", "0.62418574", "0.62329316", "0.6223484", "0.62206846", "0.618611", "0.618611", "0.61824805", "0.6176397", "0.6160399", "0.6118918", "0.6104091", "0.6104091", "0.6104091", "0.6104091", "0.6104091", "0.6104091", "0.6104091", "0.6104091", "0.6104091", "0.6104091", "0.6104091", "0.6104091", "0.6104091", "0.6104091", "0.6104091", "0.6104091", "0.6104091", "0.6104091", "0.6104091", "0.6104091", "0.6104091", "0.6104091", "0.6104091", "0.6104091", "0.6094246", "0.60929", "0.607234", "0.6034486", "0.6034486", "0.6034486", "0.6031487", "0.602404", "0.6014306", "0.60084075", "0.59926665", "0.59926665", "0.59926665", "0.59926665", "0.59926665", "0.59926665", "0.59926665", "0.5990675", "0.5988299", "0.59878933", "0.5987239", "0.5986213", "0.5985168", "0.5967677", "0.5967677", "0.5967677", "0.59667474", "0.59667355", "0.59646034", "0.5962653", "0.59611094", "0.59590304", "0.5955941", "0.5951833", "0.595139", "0.59234536", "0.5917892", "0.5902374", "0.58931476", "0.5889577", "0.5871907", "0.586747" ]
0.0
-1
Ensure that attributes passed into the tag do not persist to other tags.
def test_attribute_persistence tested 'attributes rms.jpg --img class="goaway"' test_attributes end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def clean_attributes\n @attribute_changes = {}\n end", "def sanitized_allowed_attributes=(attributes); end", "def sanitized_allowed_attributes=(attributes); end", "def safe_attributes=(attrs, user=User.current)\n return unless attrs.is_a?(Hash)\n\n attrs = attrs.dup\n attrs = delete_unsafe_attributes(attrs, user)\n \n return if attrs.empty?\n\n # mass-assignment security bypass\n assign_attributes attrs, :without_protection => true\n end", "def allowed_attributes=(_arg0); end", "def allowed_attributes=(_arg0); end", "def clean_dirty_attributes!\n @dirty_attribute_keys = []\n end", "def ignored_merge_attributes\n IGNORED_ATTRIBUTES\n end", "def remove_attributes_protected_from_mass_assignment_with_exception_on_unsafe_attributes(attributes)\n safe_attributes = remove_attributes_protected_from_mass_assignment_without_exception_on_unsafe_attributes(attributes)\n if attributes != safe_attributes\n raise RuntimeError, \"Cannot mass assign the following attributes: #{(attributes.keys - safe_attributes.keys).to_sentence}\"\n end\n safe_attributes\n end", "def sanitize_attributes!\n remove_invalid_subjects!\n remove_invalid_audiences!\n remove_invalid_levels!\n set_prices!\n nil\n end", "def sanitize_attributes\n # Summary, content are sanitized with an HTML sanitizer, we want imgs etc to be present.\n # Other attributes are sanitized by stripping tags, they should be plain text.\n self.content = Sanitizer.sanitize_html self.content\n self.summary = Sanitizer.sanitize_html self.summary\n\n self.title = Sanitizer.sanitize_plaintext self.title\n self.author = Sanitizer.sanitize_plaintext self.author\n self.guid = Sanitizer.sanitize_plaintext self.guid\n self.url = Sanitizer.sanitize_plaintext self.url\n end", "def scrub_attributes(node)\n node.attribute_nodes.each do |attr_node|\n attr_name = if attr_node.namespace\n \"#{attr_node.namespace.prefix}:#{attr_node.node_name}\"\n else\n attr_node.node_name\n end\n\n if DATA_ATTRIBUTE_NAME.match?(attr_name)\n next\n end\n\n unless SafeList::ALLOWED_ATTRIBUTES.include?(attr_name)\n attr_node.remove\n next\n end\n\n if SafeList::ATTR_VAL_IS_URI.include?(attr_name)\n next if scrub_uri_attribute(attr_node)\n end\n\n if SafeList::SVG_ATTR_VAL_ALLOWS_REF.include?(attr_name)\n scrub_attribute_that_allows_local_ref(attr_node)\n end\n\n next unless SafeList::SVG_ALLOW_LOCAL_HREF.include?(node.name) &&\n attr_name == \"xlink:href\" &&\n attr_node.value =~ /^\\s*[^#\\s].*/m\n\n attr_node.remove\n next\n end\n\n scrub_css_attribute(node)\n\n node.attribute_nodes.each do |attr_node|\n if attr_node.value !~ /[^[:space:]]/ && attr_node.name !~ DATA_ATTRIBUTE_NAME\n node.remove_attribute(attr_node.name)\n end\n end\n\n force_correct_attribute_escaping!(node)\n end", "def update_attributes!(attributes)\n super(mark_for_destruction(attributes))\n end", "def ignore_attributes\n read_inheritable_attribute(:attr_ignore) || []\n end", "def untouchable_params_attributes #:nodoc:\n { :outfile_id => true }\n end", "def attributes_for_create(attribute_names)\n tag_lists = tag_types.map { |tags_type| \"#{tags_type.to_s.singularize}_list\" }\n super.delete_if { |attr| tag_lists.include? attr }\n end", "def ignore_non_read_or_write_attributes\n ['title', 'email', 'expertise_list', 'tool_list', 'mbox_sha1sum']\n end", "def ignoring(*attributes)\n attributes.each do |attr_name|\n @_attributes.delete(attr_name.to_sym)\n end\n end", "def clean_attributes\n attributes.delete(:bare_metal)\n attributes.delete(:flavor_id)\n attributes.delete(:ephemeral_storage)\n end", "def set_attributes(attrs)\n @attributes = attrs.dup\n true\n end", "def on_stag(name)\n @attrs = {}\n end", "def ignore_attributes(*attributes)\r\n @@ignored_attributes[name] = attributes.flatten.map(&:to_s)\r\n end", "def attr_clean!(key)\n @dirty_attribute_keys ||= []\n @dirty_attribute_keys.delete_if {|k| k == key.to_sym }\n end", "def sanitize_for_mass_assignment(attrs)\n return attrs\n end", "def validate_exclusion_of(attr); end", "def attributes_for_update(attribute_names)\n tag_lists = tag_types.map { |tags_type| \"#{tags_type.to_s.singularize}_list\" }\n super.delete_if { |attr| tag_lists.include? attr }\n end", "def fix_attributes\n fix_encoding\n strip_attributes\n content_manipulation\n sanitize_attributes\n default_attribute_values\n fix_url\n calculate_unique_hash\n end", "def strip_tags\n %w(name description allowed_values).each do |a|\n next if send(a).blank?\n self.send \"#{a}=\", send(a).gsub(/\\<.*?\\>/, '')\n end\n true\n end", "def strip_tags\n %w(name description allowed_values).each do |a|\n next if send(a).blank?\n self.send \"#{a}=\", send(a).gsub(/\\<.*?\\>/, '')\n end\n true\n end", "def strip_tags\n %w(name description allowed_values).each do |a|\n next if send(a).blank?\n self.send \"#{a}=\", send(a).gsub(/\\<.*?\\>/, '')\n end\n true\n end", "def update_attributes(attrs)\n difference = attrs.keys - ASSIGNABLE\n if difference.empty?\n attributes.merge!(attrs)\n else\n raise \"unexpected attributes #{difference} for #{@node.path}\"\n end\n end", "def sync_tags(attributes)\n return unless attributes.key?(TAG_IDS_ATTR)\n\n recipe.tags = Tag.where(id: attributes[TAG_IDS_ATTR])\n attributes.delete(TAG_IDS_ATTR)\n end", "def sanitize_attributes\n %w(author title description keyword).each do |field|\n self.send(\"#{field}=\",HTMLEntities.new.decode(self.send(field)))\n end\n end", "def update_attributes(attributes)\n super(mark_for_destruction(attributes))\n end", "def clean_refill dirty_atts\n # TODO\n end", "def on_stag( name )\n @attrs = {}\n end", "def protected_attributes=(attributes = nil)\n attributes = attributes.is_a?(Hash) ? attributes.symbolize_keys : {}\n send :attributes=, attributes.only(:author, :email, :summary, :content, :attachment), false\n end", "def ignore_if_not_exists\n attributes.fetch(:ignoreIfNotExists)\n end", "def check_attribute!(attribute)\n raise \"Unexpected attribute #{attribute} used\" unless self.class.attributes && self.class.attributes.include?(attribute)\n end", "def check_attribute!(attribute)\n raise \"Unexpected attribute #{attribute} used\" unless self.class.attributes && self.class.attributes.include?(attribute)\n end", "def remove_attr(name); end", "def remove_attr(name); end", "def clear_attributes\n @attributes = nil\n end", "def prepare_attribute!(_element, options)\n if options[:attribute].is_a?(FalseClass)\n options.except!(:attribute)\n elsif !options.key?(:attribute)\n options[:attribute] = true\n end\n end", "def preinitialize(attrs = nil)\n @attributes = {}\n end", "def should_be_partially_valid_except(*attrs)\n invalid_attributes = []\n all_attrs = self.instance_variables.map {|iv| iv.gsub('@','')}\n # use the key names from @attributes for ActiveRecord objects\n all_attrs = self.attributes.keys if self.instance_variables.include?('attributes')\n attrs.each do |attr_name|\n invalid_attributes << attr_name.to_s\n end\n should_be_valid_on = all_attrs - invalid_attributes\n should_be_partially_valid_on(should_be_valid_on)\n end", "def clean_attributes(attributes)\n attributes[:license] = Array(attributes[:license]) if attributes.key? :license\n attributes[:rights_statement] = Array(attributes[:rights_statement]) if attributes.key? :rights_statement\n remove_blank_attributes!(attributes)\n end", "def assign_to_or_mark_for_destruction(record, attributes, allow_destroy)\n record.attributes = attributes.except(*UNASSIGNABLE_KEYS)\n record.mark_for_destruction if has_destroy_flag?(attributes) && allow_destroy\n end", "def sanitized_allowed_tags=(tags); end", "def sanitized_allowed_tags=(tags); end", "def sanitize_for_mass_assignment(attributes)\n return attributes\n end", "def allow_unknown_attributes!\n define_method :handle_unknown_attribute do |*|\n end\n end", "def assign_tag_attrs(attributes)\n # support default data, class, and aria attribute names\n data_attr(attributes.delete(:data)) if attributes[:data]\n aria_attr(attributes.delete(:aria)) if attributes[:aria]\n add_class(*attributes.delete(:class)) if attributes[:class]\n root_attr(attributes.delete(:splat)) if attributes[:splat]\n end", "def attributes_no_helpers(attrs)\n\t\t\[email protected]! attrs\n\t\t\tyield self if block_given?\n\t\t\treturn self\n\t\tend", "def tag_attrs(opts = T.unsafe(nil)); end", "def copy_audit_attributes\n node.run_state['audit_attributes'] = node['audit']['attributes']\n node.rm('audit', 'attributes') unless node['audit']['attributes_save']\n end", "def remove_unique_attrs( char )\n ResourcePool.unique_attrs.each do |attr|\n if (self.is_storing_picked?(attr[0]))\n atr = attr[0]\n attr.slice(1, (attr.length - 1)).each do |attr|\n if (attr.is_a?(Array))\n self.add_to_picked(atr, char.send(attr[1]))\n self.delete_from_pool(attr[0], char.send(attr[1]))\n else\n self.add_to_picked(atr, char.send(attr))\n self.delete_from_pool(atr, char.send(attr))\n end\n end\n end\n end\n end", "def clean_attributes(attributes)\n # attributes[:rights_license] = Array(attributes[:rights_license]) if attributes.key? :rights_license\n super( attributes )\n end", "def replicate_omit_attributes(*attribute_names)\n self.replicate_omit_attributes = attribute_names if attribute_names.any?\n @replicate_omit_attributes || superclass.replicate_omit_attributes\n end", "def partially_valid_clear\n @partially_valid_attributes = []\n end", "def writable_attributes resource = nil\n attrs = accessible_attributes(resource).delete_if { |attribute| attribute =~ /(_attributes)$/ }\n attrs -= get_associations(resource)\n end", "def assign_to_or_mark_for_destruction(record, attributes, allow_destroy)\n if has_destroy_flag?(attributes) && allow_destroy\n record.mark_for_destruction\n else\n record.attributes = attributes.except(*UNASSIGNABLE_KEYS)\n end\n end", "def update_attrs(node, attrs, merge = false)\n return false unless attrs\n # keep the current tags\n attrs['tags'] = node.normal.tags || []\n original = Marshal.load(Marshal.dump(node.normal))\n node.normal = if merge\n Chef::Mixin::DeepMerge.merge(node.normal, attrs)\n else\n attrs\n end\n original != node.normal\n end", "def protect_attributes(*args)\n self.protected_attributes ||= []\n self.protected_attributes << args.collect(&:to_s)\n end", "def sanitize_inputs\n attributes.each do |attr_name, attr_value|\n next unless attr_value.is_a? String\n self[attr_name] = strip_markup attr_value\n end\n end", "def mark_for_destruction(attributes)\n self.class.embeddings.each do |embed|\n if attributes[embed]\n updates = attributes[embed].map { |model| model[:id] }.compact\n destroy = updates.empty? ? send(\"_super_#{embed}\".to_sym).select(:id) : send(\"_super_#{embed}\".to_sym).select(:id).where('id NOT IN (?)', updates)\n destroy.each { |model| attributes[embed] << { :id => model.id, :_destroy => '1' } }\n end\n end\n\n attributes\n end", "def decorated_attributes(attrs = {})\n attrs.dup\n end", "def other_attrs\n @other_attrs ||= {}\n end", "def strip_attributes(attrs_to_check)\n attrs_to_check = model.attribute_names if @attrs_to_manage[:strip] == :all\n\n attrs_to_check.each do |attribute|\n value = strip_attribute(attribute)\n model[attribute] = value if value\n end\n end", "def remove_attribute(name); end", "def remove_attribute(name); end", "def remove_attribute(name); end", "def remove_attribute(name); end", "def assert_attribute_is_validated(model, attribute)\n # This line sets the specified attribute to nil \n model.assign_attributes(attribute => nil)\n assert !model.valid?, \"#{attribute.to_s} is not being validated\"\n end", "def set_attributes(attrs)\n @attributes = attrs.to_smash\n true\n end", "def sanitize(attributes, authorizer)\n sanitized_attributes = attributes.reject { |key, value| authorizer.deny?(key) }\n debug_protected_attribute_removal(attributes, sanitized_attributes)\n sanitized_attributes\n end", "def assert_attribute_is_validated(model, attribute)\n # This line sets the specified attribute to nil\n model.assign_attributes(attribute => nil)\n assert !model.valid?, \"#{attribute.to_s} is not being validated\"\n end", "def assert_attribute_is_validated(model, attribute)\n # This line sets the specified attribute to nil\n model.assign_attributes(attribute => nil)\n assert !model.valid?, \"#{attribute.to_s} is not being validated\"\n end", "def sanitize_attributes\n if self.sanitize_level\n self.description = Sanitize.clean(self.description, self.sanitize_level)\n self.name = Sanitize.clean(self.name, self.sanitize_level)\n end\n end", "def unknown_attributes\n @unknown_attributes ||= {}\n end", "def unknown_attributes\n @unknown_attributes ||= {}\n end", "def unknown_attributes\n @unknown_attributes ||= {}\n end", "def clear_audit_attributes\n all_audit_attributes.each do |attribute_name|\n if respond_to?(attribute_name) && respond_to?(\"#{ attribute_name }=\")\n write_attribute(attribute_name, nil)\n end\n end\n\n @changed_attributes = changed_attributes.reduce(ActiveSupport::HashWithIndifferentAccess.new) do |result, (key, value)|\n unless all_audit_attributes.include?(key.to_sym)\n result[key] = value\n end\n\n result\n end\n end", "def validate_attributes!(attributes)\n invalid_properties = attributes.keys.map(&:to_s) - self.attributes.keys\n raise UndefinedPropertyError, \"Undefined properties: #{invalid_properties.join(',')}\" if invalid_properties.size > 0\n end", "def safe_attributes=(attrs, user=User.current)\n return unless attrs.is_a?(Hash)\n\n attrs = attrs.deep_dup\n\n # Project and Tracker must be set before since new_statuses_allowed_to depends on it.\n if (p = attrs.delete('project_id')) && safe_attribute?('project_id')\n if allowed_target_projects(user).where(:id => p.to_i).exists?\n self.project_id = p\n end\n end\n\n if (t = attrs.delete('tracker_id')) && safe_attribute?('tracker_id')\n self.tracker_id = t\n end\n if project\n # Set the default tracker to accept custom field values\n # even if tracker is not specified\n self.tracker ||= project.trackers.first\n end\n\n if (s = attrs.delete('status_id')) && safe_attribute?('status_id')\n if new_statuses_allowed_to(user).collect(&:id).include?(s.to_i)\n self.status_id = s\n end\n end\n\n attrs = delete_unsafe_attributes(attrs, user)\n return if attrs.empty?\n\n if attrs['parent_issue_id'].present?\n s = attrs['parent_issue_id'].to_s\n unless (m = s.match(%r{\\A#?(\\d+)\\z})) && (m[1] == parent_id.to_s || Issue.visible(user).exists?(m[1]))\n @invalid_parent_issue_id = attrs.delete('parent_issue_id')\n end\n end\n\n if attrs['custom_field_values'].present?\n editable_custom_field_ids = editable_custom_field_values(user).map {|v| v.custom_field_id.to_s}\n\n ###############\n ## Custom START\n editable_custom_field_ids |= editable_custom_field_values(user).map {|v| v.custom_field_id.to_s + '-comment'}\n ## Custom END\n ###############\n\n attrs['custom_field_values'].select! {|k, v| editable_custom_field_ids.include?(k.to_s)}\n end\n\n if attrs['custom_fields'].present?\n editable_custom_field_ids = editable_custom_field_values(user).map {|v| v.custom_field_id.to_s}\n attrs['custom_fields'].select! {|c| editable_custom_field_ids.include?(c['id'].to_s)}\n end\n\n # mass-assignment security bypass\n assign_attributes attrs, :without_protection => true\n end", "def clean_attributes\n return attributes if group.nil? || !group.empty?\n\n filtered_attributes = attributes.dup\n filtered_attributes.delete(:group)\n end", "def touch_once *attrs\n touch *attrs.select {|attribute| attributes[attribute.to_s].nil? }\n end", "def validate_attributes!(attributes)\n return attributes if attributes.blank?\n invalid_properties = attributes.keys.map(&:to_s) - self.attributes.keys\n invalid_properties.reject! { |name| self.respond_to?(\"#{name}=\") }\n fail UndefinedPropertyError, \"Undefined properties: #{invalid_properties.join(',')}\" if !invalid_properties.empty?\n end", "def omitted_attributes\n (self.class.replicate_omit_attributes + @replicate_opts[:omit]).uniq\n end", "def sanitize!\n begin\n\n # Sanitize newly read Tags\n @@settings[:tag_fields].each do |tag_field|\n field = tag_field.to_s\n field_value = send(\"#{field}\")\n send(\"#{field}=\", ModelUtils::id3_sanitize(field_value))\n end\n\n # Rescue any exceptions\n rescue Exception => e\n log.error e\n end\n end", "def expensive_validate_presence_of_proper_attributes(attrs)\n attributes_list.each do |attr|\n unless attrs.delete(attr) || optional_attributes_list.include?(attr)\n raise BadAttributesError, \"Missing attribute '#{attr}'\"\n end\n end\n\n raise BadAttributesError, \"Unknown attributes #{attrs.inspect}\" unless attrs.empty?\n end", "def clean_attrs\n data = node.to_hash\n %w(run_list recipes roles).each { |k| data.delete(k) }\n data\n end", "def attr_unsearchable(*args)\n if table_exists?\n opts = args.extract_options!\n args.flatten.each do |attr|\n attr = attr.to_s\n raise(ArgumentError, \"No persisted attribute (column) named #{attr} in #{self}\") unless self.columns_hash.has_key?(attr)\n self._metasearch_exclude_attributes = self._metasearch_exclude_attributes.merge(\n attr => {\n :if => opts[:if]\n }\n )\n end\n end\n end", "def clear_attributes\n self.attribute_names.clear\n self.public_attribute_names.clear\n self.protected_attribute_names.clear\n\n true\n end", "def replicate_omit_attributes=(attribute_names)\n @replicate_omit_attributes = attribute_names\n end", "def sanitize_attributes\n self.name = \"#{self.name}\".strip\n end", "def copy_attributes_from(el)\n self.attributes = el.attributes.reject { |attr| !%w(slug block hint priority fixed disabled locales from_parent widget_type widget_index).include?(attr) }\n self.from_parent = true\n end", "def reset_attributes_buffer\n @attributes = []\n end", "def strip_attributes(doc)\n attrs = %w[data-tralics-id data-label data-number data-chapter\n role aria-readonly target]\n doc.tap do\n attrs.each do |attr|\n doc.xpath(\"//@#{attr}\").remove\n end\n end\n end", "def safe_attributes=(attrs, user = User.current)\n if attrs.is_a?(Hash)\n if attrs['watcher_user_ids'].present?\n groups = Group.active.visible.where(id: attrs['watcher_user_ids'].compact.uniq)\n\n attrs['group_ids'] = groups.map(&:id).map(&:to_s)\n attrs['watcher_user_ids'] -= groups.map(&:id).map(&:to_s)\n\n groups.each do |group|\n group.users.each do |groups_user|\n attrs['watcher_user_ids'] << groups_user.id\n end\n end\n end\n end\n\n super\n end", "def attributes; @attributes ||= []; end" ]
[ "0.6329165", "0.6232465", "0.6232465", "0.62250835", "0.6173405", "0.6173405", "0.6170182", "0.61473346", "0.6085685", "0.6062724", "0.60559154", "0.60468197", "0.6035718", "0.6017482", "0.6011926", "0.5983391", "0.598302", "0.59792477", "0.59545505", "0.5952442", "0.5934745", "0.5932468", "0.59227824", "0.59192663", "0.59150773", "0.5913253", "0.5904271", "0.5870377", "0.5870377", "0.5870377", "0.586001", "0.58328015", "0.583218", "0.581799", "0.58143103", "0.579497", "0.5782065", "0.5746824", "0.5725953", "0.5725953", "0.5722653", "0.5722653", "0.5717566", "0.5695148", "0.56923175", "0.5684062", "0.5683286", "0.5667604", "0.56601584", "0.56601584", "0.5654319", "0.5647911", "0.5647652", "0.5637078", "0.5636584", "0.5635453", "0.56121784", "0.56110597", "0.56035924", "0.55960464", "0.5592713", "0.5590888", "0.55899376", "0.55776376", "0.557051", "0.5543757", "0.55378807", "0.5534575", "0.55334365", "0.55328363", "0.55328363", "0.55328363", "0.55328363", "0.5531358", "0.55260503", "0.5521871", "0.55174655", "0.55174655", "0.5498391", "0.5490723", "0.5490723", "0.5490723", "0.54897547", "0.5487861", "0.54873973", "0.5486903", "0.5483748", "0.54778224", "0.54776865", "0.5468122", "0.5468024", "0.54679996", "0.5460866", "0.54419", "0.5441305", "0.5438873", "0.5438165", "0.5432122", "0.54316556", "0.5428335", "0.542363" ]
0.0
-1
Ensure that when attributes are passed from both the argument and the preset, they all make it into the final output.
def test_combined_attributes output = tested 'attributes rms.jpg --img class="arg classes"' attrs = output.at_css('img')['class'].split assert_includes attrs, 'arg' assert_includes attrs, 'classes' assert_includes attrs, 'img' end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def make_attributes_definitions_or_croak(attrArgs, &attrBlok)\n eye = :'m_attrs_defs'\n\n # Work with attribute as strings\n \n $DEBUG && logger_me(eye, logger_fmt_kls(:attrArgs => attrArgs, :attrBlok => attrBlok))\n\n mustbe_attributes_specification_or_croak(attrArgs, eye, \"attrArgs not attributes_specification\")\n \n #STOPATTRARGSINSUPER\n \n #attrAll = mustbe_not_empty_or_croak(mustbe_array_key_or_nil_or_croak(attrArgs, :all, eye, \"all attributes not array\"), eye, \"all attributes is empty\").map(&:to_s)\n attrAll = mustbe_not_empty_or_croak(mustbe_attributes_specification_all_key_or_croak(attrArgs, :all, eye), eye, \"all attributes is empty\").map(&:to_s)\n \n\n #puts(\"\\n\\n\\nATTR ALL >#{attrAll}<\")\n\n #STOPMAKEATTRSPECSENTRY\n\n attrInc = mustbe_attributes_specification_include_key_or_nil_or_croak(attrArgs, :include, eye) # mustbe all strings\n #puts(\"ATTR INC >#{attrInc.class}< >#{attrInc}< >#{is_value_not_empty?(attrInc)}<\")\n attrInc && mustbe_not_empty_or_croak(attrInc, eye, \"include attributes is empty\")\n\n attrExc = mustbe_attributes_specification_exclude_key_or_nil_or_croak(attrArgs, :exclude, eye) || []\n \n attrMapNom = mustbe_attributes_definitions_key_or_nil_or_croak(attrArgs, :definitions, eye) || {}\n attrMap = attrMapNom && potrubi_util_map_hash_kv(attrMapNom) {|k,v| [k.to_s, v]} # keys all strings\n\n # Ensure all consistent\n \n attrInc && mustbe_subset_or_croak(attrInc, attrAll, eye, \"include attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrExc, attrAll, eye, \"exclude attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrMap.keys, attrAll, eye, \"attribute map contains unknown attributes\")\n \n attrUse = ((attrInc || attrAll) - attrExc).uniq # list of unique attributes to report on\n\n # consolidate \"faked up\" attr specs with ones provided to get the composite attrSpecs\n \n attrDefsNom = potrubi_util_array_to_hash(attrUse).merge(attrMap.select {|k,v| attrUse.include?(k)}) # consolidated \"faked up\" attr specs with ones provided\n\n attrDefs = potrubi_util_map_hash_v(attrDefsNom) do | attrName, attrSpecNom|\n\n attrSpec =\n case attrSpecNom\n when NilClass then {}\n when Hash then\n attrSpecNom.each_with_object({}) do | (verbName, verbSpec), h1 |\n case verbName\n when :pass_thru then h1[:pass_thru] = verbSpec # dont touch; just pass through\n when :event_defaults then # add these to pass_thru\n h1[:pass_thru] = (h1[:pass_thru] || {}).merge(verbName => verbSpec)\n when :map, :select, :metric then\n h1[verbName] = {\n :method_name => \"#{verbName}_#{attrName}_#{rand(1000000)}\", # make a unqiue name\n :method_spec => verbSpec # spec must be valid to dynamic_define_methods\n }\n else\n logic_exception(verbName, eye, \"attrName >#{attrName}< verbName >#{verbName}< value should be impossible\")\n end\n end\n \n else\n logic_exception(attrrSpecNom, eye, \"attrSpecNom value should be impossible\")\n end\n\n attrSpec\n \n end\n \n $DEBUG && logger_mx(eye, logger_fmt_kls(:attrDefs => attrDefs))\n\n mustbe_attributes_definitions_or_croak(attrDefs, eye, \"attrDefs failed contract\")\n\n #STOPMAKEATTRSPECS\n \n end", "def check_input_entry\n %i{assembly mut_bulk bg_bulk mut_bulk_vcf bg_bulk_vcf mut_parent bg_parent repeats_file}.each do | symbol |\n if @options.key?(symbol)\n if @options[symbol] == 'None'\n param = (symbol.to_s + '_given').to_sym\n @options[symbol] = ''\n @options.delete(param)\n end\n end\n end\n end", "def prepare_attribute!(_element, options)\n if options[:attribute].is_a?(FalseClass)\n options.except!(:attribute)\n elsif !options.key?(:attribute)\n options[:attribute] = true\n end\n end", "def tributes *attrs\n if attrs.empty? \n @tributes ||= []\n else \n @tributes = attrs\n super *attrs\n end \n end", "def prepare_attribute!(_element, _options)\n end", "def attribute_assignment?\n arguments.one? && attribute_assignment_selector?\n end", "def copy_attrs(other)\n (ActsAsArtifact::ARTIFACT_ATTRIBUTES + [:name, :requirement]).each do |attr|\n value = other.instance_variable_get(\"@#{attr}\")\n value = value.dup if value && !value.kind_of?(Numeric) && !value.kind_of?(Symbol)\n instance_variable_set(\"@#{attr}\", value)\n end\n end", "def process_attrasgn exp\n exp = exp.dup\n exp.target = process exp.target\n exp.arglist = process exp.arglist\n exp\n end", "def pre_execute\n\n @node['atts'] = []\n end", "def attributes=(_arg0); end", "def test_argument_can_be_overwritten_through_assignment\n Crd::Flex::Command.new 'mxmlc' do |s|\n s.output = 'Main.swf'\n assert_equal( 'Main.swf', s.output )\n s.output = 'App.swf'\n assert_equal( 'App.swf', s.output )\n end\n end", "def finalize\n super\n\n @short = Config.get_if_unset(@short, nil)\n @type = Config.get_if_unset(@type, ANY_ARGUMENT_TYPE)\n @operator = Util.ensure_instance(\n Config.get_if_unset(@operator, Cliqr::Command::ArgumentOperator.for_type(@type))\n )\n @default = Config.get_if_unset(@default, ARGUMENT_DEFAULTS[@type])\n @multi_valued = Config.get_if_unset(@multi_valued, false)\n\n self\n end", "def prepare_attributes(data_set, meta_data, options)\n # create meta data and data set for the scaled output\n sc = DatasetScaling.new(meta_data, data_set)\n @meta_data = sc.scaled_meta\n @scaled_dataset = sc.scaled_data_set\n set_attributes(@scaled_dataset, options[:extreme_values])\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 allowed_attributes=(_arg0); end", "def allowed_attributes=(_arg0); end", "def finalize()\n if @ready_to_go\n return\n end\n if @needs_help\n add_help \n end\n @attributes.sort!\n dups = []\n previous = nil\n @attributes.each do |an_attr|\n if an_attr == previous\n dups.push(an_attr)\n else\n previous = an_attr\n end\n end\n if dups.length > 0\n raise \"Duplicate attribute names, #{dups}, for command line options.\"\n end\n @positionals.push(@parms_list.length)\n @attributes.freeze\n @defaults.freeze\n @parms_list.freeze\n @parms_hash.freeze\n @positionals.freeze\n @ready_to_go = true\n end", "def update!(**args)\n @scrub_argument_value = args[:scrub_argument_value] if args.key?(:scrub_argument_value)\n @scrub_context = args[:scrub_context] if args.key?(:scrub_context)\n end", "def test_attribute_persistence\n tested 'attributes rms.jpg --img class=\"goaway\"'\n\n test_attributes\n end", "def normalize_options\n copy_options_to_attributes(ATTRIBUTE_OPTIONS)\n copy_boolean_options_to_attributes(ATTRIBUTE_BOOLEAN_OPTIONS)\n handle_key_option\n handle_errors_option\n\n Forme.attr_classes(@attr, @opts[:class]) if @opts.has_key?(:class)\n\n if @opts[:error]\n Forme.attr_classes(@attr, 'error')\n @attr[\"aria-invalid\"] = \"true\"\n if @opts.fetch(:error_handler, true)\n if @opts[:error_id]\n @attr['aria-describedby'] ||= @opts[:error_id]\n else\n if id = @attr[:id] || @attr['id']\n error_id = @attr['aria-describedby'] ||= \"#{id}_error_message\"\n @opts[:error_id] = error_id\n end\n end\n end\n end\n\n if data = opts[:data]\n data.each do |k, v|\n k = k.to_s.tr(\"_\", \"-\") if k.is_a?(Symbol) && input.opts[:dasherize_data]\n sym = :\"data-#{k}\"\n @attr[sym] = v unless @attr.has_key?(sym)\n end\n end\n end", "def preset?\n custom_attribute_choices.any?\n end", "def assign_attributes( args = {} )\n args.each do |attr, value|\n send(\"#{attr}=\", value)\n end unless args.blank?\n end", "def arguments\n self.class.dry_initializer.attributes(self)\n end", "def prepare_attribute!(name, _element, options)\n options[:attribute] = true if %w[href rel].include?(name.to_s)\n options[:render_nil] = render_nil?\n end", "def cap_attribute(*args)\n if args.length == 2\n cap_attribute(args.first => args.last)\n elsif args.length == 1 && args.first.kind_of?(Hash)\n @cap_attributes.update(args.first)\n else\n raise ArgumentError('Must be (key, value) or (hash).')\n end\n end", "def parse_attributes! #:nodoc:\n self.attributes = (attributes || []).map do |attr|\n Barbecue::Generators::GeneratedAttribute.parse(attr)\n end\n end", "def clean dirty_atts\n clean_atts = cartridge_cleaning_code(dirty_atts, 'Ink Grabber', false)\n clean_atts['mpn'] = clean_atts['item_number'] if clean_atts['real'] == false \n clean_atts['yield'] = parse_yield(clean_atts['title']) if clean_atts['yield'].nil?\n clean_atts['toolow'] = false\n clean_atts['retailer_id'] = 18 \n clean_atts['instock'] = clean_atts['stock'] = case dirty_atts['availability'] \n when \"/stock.gif\"\n true\n when \"/oostock.gif\" \n false\n end\n clean_atts['availability'] = nil\n \n return clean_atts\n end", "def update!(**args)\n @enable_feature_attributes = args[:enable_feature_attributes] if args.key?(:enable_feature_attributes)\n @explanation_baseline = args[:explanation_baseline] if args.key?(:explanation_baseline)\n end", "def update!(**args)\n @asset = args[:asset] if args.key?(:asset)\n @interaction_on_this_asset = args[:interaction_on_this_asset] if args.key?(:interaction_on_this_asset)\n end", "def update!(**args)\n @attributes = args[:attributes] if args.key?(:attributes)\n @usage_info = args[:usage_info] if args.key?(:usage_info)\n end", "def update!(**args)\n @baseline = args[:baseline] if args.key?(:baseline)\n @box = args[:box] if args.key?(:box)\n @capline = args[:capline] if args.key?(:capline)\n @compact_symbol_boxes = args[:compact_symbol_boxes] if args.key?(:compact_symbol_boxes)\n @confidence = args[:confidence] if args.key?(:confidence)\n @is_from_dictionary = args[:is_from_dictionary] if args.key?(:is_from_dictionary)\n @is_identifier = args[:is_identifier] if args.key?(:is_identifier)\n @is_last_in_sentence = args[:is_last_in_sentence] if args.key?(:is_last_in_sentence)\n @is_numeric = args[:is_numeric] if args.key?(:is_numeric)\n @label = args[:label] if args.key?(:label)\n @penalty = args[:penalty] if args.key?(:penalty)\n @rotated_box = args[:rotated_box] if args.key?(:rotated_box)\n @symbol = args[:symbol] if args.key?(:symbol)\n @alternates = args[:alternates] if args.key?(:alternates)\n @text = args[:text] if args.key?(:text)\n @writing_direction = args[:writing_direction] if args.key?(:writing_direction)\n end", "def update!(**args)\n @approximation_error = args[:approximation_error] if args.key?(:approximation_error)\n @baseline_output_value = args[:baseline_output_value] if args.key?(:baseline_output_value)\n @feature_attributions = args[:feature_attributions] if args.key?(:feature_attributions)\n @instance_output_value = args[:instance_output_value] if args.key?(:instance_output_value)\n @output_display_name = args[:output_display_name] if args.key?(:output_display_name)\n @output_index = args[:output_index] if args.key?(:output_index)\n @output_name = args[:output_name] if args.key?(:output_name)\n end", "def expects_argument?\n config[:argument] && config[:argument] != :optional\n end", "def update!(**args)\n @attribute = args[:attribute] if args.key?(:attribute)\n @pivot_entity_slot = args[:pivot_entity_slot] if args.key?(:pivot_entity_slot)\n @remodelings = args[:remodelings] if args.key?(:remodelings)\n end", "def _match_arguments_optionals_before\n @optionals_before = {}\n tracker = {}\n\n @options.each do |option, _key|\n next unless option.is_argument\n\n if option.is_optional\n # setup tracker for optional group\n tracker[option.is_optional] = [] if tracker[option.is_optional].nil?\n\n # mark all optionals as not-included\n tracker[option.is_optional].push(\n included: false,\n name: option.name,\n )\n else\n @optionals_before[option.name] = tracker\n tracker = {}\n end\n end\n\n # make sure all optionals are accounted for in the map\n if tracker != {}\n # use a special key so we can handle it differently in the filling process\n @optionals_before[:REMAINING] = tracker\n @optionals_before_has_remaining = true\n end\n\n _match_arguments_options_before_matcher\n\n self\n end", "def update!(**args)\n @attribute = args[:attribute] if args.key?(:attribute)\n @description = args[:description] if args.key?(:description)\n @destination = args[:destination] if args.key?(:destination)\n @resolution = args[:resolution] if args.key?(:resolution)\n @severity = args[:severity] if args.key?(:severity)\n @timestamp = args[:timestamp] if args.key?(:timestamp)\n @title = args[:title] if args.key?(:title)\n @type = args[:type] if args.key?(:type)\n end", "def specify(attrs)\n attrs[:sources] ||= attrs[:language].to_s\n attrs[:source_ext] ||= attrs[:language].to_s\n attrs.each { |name, value| instance_variable_set(\"@#{name}\", value) }\n end", "def update!(**args)\n @argument = args[:argument] if args.key?(:argument)\n @catalog_version = args[:catalog_version] if args.key?(:catalog_version)\n @contextual_sensitivity = args[:contextual_sensitivity] if args.key?(:contextual_sensitivity)\n @enabled_remodelings = args[:enabled_remodelings] if args.key?(:enabled_remodelings)\n @ignored_tokens = args[:ignored_tokens] if args.key?(:ignored_tokens)\n @key = args[:key] if args.key?(:key)\n @marker = args[:marker] if args.key?(:marker)\n @modifiers = args[:modifiers] if args.key?(:modifiers)\n @name = args[:name] if args.key?(:name)\n @sensitivity = args[:sensitivity] if args.key?(:sensitivity)\n @signals = args[:signals] if args.key?(:signals)\n @unexplained_tokens = args[:unexplained_tokens] if args.key?(:unexplained_tokens)\n end", "def argument?; end", "def attribute=(_arg0); end", "def attribute=(_arg0); end", "def extra=(_arg0); end", "def attributes(*args, &block)\n if current_object.nil?\n raise(ArgumentError, \"You cannot use #attributes when inferred object is not present.\")\n end\n\n args.each do |arg|\n if arg.is_a?(Hash)\n merge_result!(arg.keys.first, current_object.send(arg.values.first))\n else\n merge_result!(arg, current_object.send(arg))\n end\n end\n nil\n end", "def arguments(model)\n\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n\t\t# argument for string\n\t\tstring = OpenStudio::Ruleset::OSArgument::makeStringArgument(\"string\", true)\n\t\tstring.setDisplayName(\"Set inputs for equipment containing the string (case sensitive, enter *.* for all):\")\n string.setDefaultValue(\"*.*\")\n\t\targs << string\n\n # PTAC inputs\n'\nZoneHVAC:PackagedTerminalAirConditioner,\n , !- Name\n , !- Availability Schedule Name\n , !- Air Inlet Node Name\n , !- Air Outlet Node Name\n , !- Outdoor Air Mixer Object Type\n , !- Outdoor Air Mixer Name\n , !- Supply Air Flow Rate During Cooling Operation {m3/s}\n , !- Supply Air Flow Rate During Heating Operation {m3/s}\n , !- Supply Air Flow Rate When No Cooling or Heating is Needed {m3/s}\n , !- Outdoor Air Flow Rate During Cooling Operation {m3/s}\n , !- Outdoor Air Flow Rate During Heating Operation {m3/s}\n , !- Outdoor Air Flow Rate When No Cooling or Heating is Needed {m3/s}\n , !- Supply Air Fan Object Type\n , !- Supply Air Fan Name\n , !- Heating Coil Object Type\n , !- Heating Coil Name\n , !- Cooling Coil Object Type\n , !- Cooling Coil Name\n DrawThrough, !- Fan Placement\n , !- Supply Air Fan Operating Mode Schedule Name\n , !- Availability Manager List Name\n 1; !- Design Specification ZoneHVAC Sizing Object Name\n'\n ptac_flow_clg = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('ptac_flow_clg', true)\n ptac_flow_clg.setDisplayName(\"PTAC: Supply Air Flow Rate During Cooling Operation {ft3/min}\")\n ptac_flow_clg.setDefaultValue(-1)\n args << ptac_flow_clg\n\n ptac_flow_htg = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('ptac_flow_htg', true)\n ptac_flow_htg.setDisplayName(\"PTAC: Supply Air Flow Rate During Heating Operation {ft3/min}\")\n ptac_flow_htg.setDefaultValue(-1)\n args << ptac_flow_htg\n\n ptac_flow_no_clg_or_htg = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('ptac_flow_no_clg_or_htg', true)\n ptac_flow_no_clg_or_htg.setDisplayName(\"PTAC: Supply Air Flow Rate When No Cooling or Heating is Needed {ft3/min}\")\n ptac_flow_no_clg_or_htg.setDefaultValue(-1)\n args << ptac_flow_no_clg_or_htg\n\n ptac_oa_clg = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"ptac_oa_clg\",false)\n ptac_oa_clg.setDisplayName(\"PTAC: Outdoor Air Flow Rate During Cooling Operation {ft3/min}\")\n ptac_oa_clg.setDefaultValue(-1)\n args << ptac_oa_clg\n\n ptac_oa_htg = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"ptac_oa_htg\",false)\n ptac_oa_htg.setDisplayName(\"PTAC: Outdoor Air Flow Rate During Heating Operation {ft3/min}\")\n ptac_oa_htg.setDefaultValue(-1)\n args << ptac_oa_htg\n\n ptac_oa_no_clg_or_htg = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"ptac_oa_no_clg_or_htg\",false)\n ptac_oa_no_clg_or_htg.setDisplayName(\"PTAC: Outdoor Air Flow Rate When No Cooling or Heating is Needed {ft3/min}\")\n ptac_oa_no_clg_or_htg.setDefaultValue(-1)\n args << ptac_oa_no_clg_or_htg\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 not sch.scheduleTypeLimits.empty?\n unitType = sch.scheduleTypeLimits.get.unitType\n #puts \"#{sch.name}, #{unitType}\"\n if unitType == \"Availability\"\n sch_handles << sch.handle.to_s\n sch_display_names << sch_name\n end\n end\n end\n\n\t\t#argument for schedules\n sched = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"sched\", sch_handles, sch_display_names, false)\n sched.setDisplayName(\"PTAC: Supply Air Fan Operating Mode Schedule Name\")\n args << sched\n'\n # Fan Inputs TODO add additional types when available: OnOff\n'\nFan:ConstantVolume,\n , !- Name\n , !- Availability Schedule Name\n 0.7, !- Fan Total Efficiency\n , !- Pressure Rise {Pa}\n , !- Maximum Flow Rate {m3/s}\n 0.9, !- Motor Efficiency\n 1, !- Motor In Airstream Fraction\n , !- Air Inlet Node Name\n , !- Air Outlet Node Name\n General; !- End-Use Subcategory\n'\n fan_eff_tot = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('fan_eff_tot', true)\n fan_eff_tot.setDisplayName(\"Fan: Fan Total Efficiency\")\n fan_eff_tot.setDefaultValue(-1)\n args << fan_eff_tot\n\n fan_rise = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('fan_rise', true)\n fan_rise.setDisplayName(\"Fan: Pressure Rise {inH2O}\")\n fan_rise.setDefaultValue(-1)\n args << fan_rise\n\n fan_flow = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('fan_flow', true)\n fan_flow.setDisplayName(\"Fan: Maximum Flow Rate {ft3/min}\")\n fan_flow.setDefaultValue(-1)\n args << fan_flow\n\n fan_eff_mot = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('fan_eff_mot', true)\n fan_eff_mot.setDisplayName(\"Fan: Motor Efficiency\")\n fan_eff_mot.setDefaultValue(-1)\n args << fan_eff_mot\n\n # Htg Coil Inputs TODO add additional when available after 1.6.0\n\n hc_ewt = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"hc_ewt\", false)\n hc_ewt.setDisplayName(\"Htg Coil: Rated Inlet Water Temperature {F}\")\n hc_ewt.setDefaultValue(-1)\n args << hc_ewt\n\n hc_eat = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"hc_eat\", false)\n hc_eat.setDisplayName(\"Htg Coil: Rated Inlet Air Temperature {F}\")\n hc_eat.setDefaultValue(-1)\n args << hc_eat\n\n hc_lwt = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"hc_lwt\", false)\n hc_lwt.setDisplayName(\"Htg Coil: Rated Outlet Water Temperature {F}\")\n hc_lwt.setDefaultValue(-1)\n args << hc_lwt\n\n hc_lat = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"hc_lat\", false)\n hc_lat.setDisplayName(\"Htg Coil: Rated Outlet Air Temperature {F}\")\n hc_lat.setDefaultValue(-1)\n args << hc_lat\n\n # Clg Coil Inputs\n'\nCoil:Cooling:DX:SingleSpeed,\n , !- Name\n , !- Availability Schedule Name\n , !- Gross Rated Total Cooling Capacity {W}\n , !- Gross Rated Sensible Heat Ratio\n 3, !- Gross Rated Cooling COP {W/W}\n , !- Rated Air Flow Rate {m3/s}\n 773.3, !- Rated Evaporator Fan Power Per Volume Flow Rate {W/(m3/s)}\n , !- Air Inlet Node Name\n , !- Air Outlet Node Name\n , !- Total Cooling Capacity Function of Temperature Curve Name\n , !- Total Cooling Capacity Function of Flow Fraction Curve Name\n , !- Energy Input Ratio Function of Temperature Curve Name\n , !- Energy Input Ratio Function of Flow Fraction Curve Name\n , !- Part Load Fraction Correlation Curve Name\n , !- Nominal Time for Condensate Removal to Begin {s}\n , !- Ratio of Initial Moisture Evaporation Rate and Steady State Latent Capacity {dimensionless}\n , !- Maximum Cycling Rate {cycles/hr}\n , !- Latent Capacity Time Constant {s}\n , !- Condenser Air Inlet Node Name\n AirCooled, !- Condenser Type\n 0.9, !- Evaporative Condenser Effectiveness {dimensionless}\n , !- Evaporative Condenser Air Flow Rate {m3/s}\n , !- Evaporative Condenser Pump Rated Power Consumption {W}\n , !- Crankcase Heater Capacity {W}\n 10, !- Maximum Outdoor Dry-Bulb Temperature for Crankcase Heater Operation {C}\n , !- Supply Water Storage Tank Name\n , !- Condensate Collection Water Storage Tank Name\n , !- Basin Heater Capacity {W/K}\n 2, !- Basin Heater Setpoint Temperature {C}\n , !- Basin Heater Operating Schedule Name\n , !- Sensible Heat Ratio Function of Temperature Curve Name\n 1; !- Sensible Heat Ratio Function of Flow Fraction Curve Name\n'\n cc_cap = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"cc_cap\", false)\n cc_cap.setDisplayName(\"Clg Coil: Gross Rated Total Cooling Capacity {Btu/h}\")\n cc_cap.setDefaultValue(-1)\n args << cc_cap\n\n cc_shr = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"cc_shr\", false)\n cc_shr.setDisplayName(\"Clg Coil: Gross Rated Sensible Heat Ratio\")\n cc_shr.setDefaultValue(-1)\n args << cc_shr\n\n cc_cop = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"cc_cop\", false)\n cc_cop.setDisplayName(\"Clg Coil: Gross Rated Cooling COP {Btuh/Btuh}\")\n cc_cop.setDefaultValue(-1)\n args << cc_cop\n\n cc_flow = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"cc_flow\", false)\n cc_flow.setDisplayName(\"Clg Coil: Rated Air Flow Rate {ft3/min}\")\n cc_flow.setDefaultValue(-1)\n args << cc_flow\n\n return args\n\n end", "def tool_attrs=(tool_attributes={})\n tool_attributes.each_pair do |k,v|\n tool.send(\"#{k}=\", v)\n end\n end", "def AMT02=(arg)", "def flush\n if @attribute_json\n @updated_json = @attribute_json.dup\n else\n @updated_json = default_attribute\n end\n \n # Update the attribute's JSON values based on any new params. Sadly due to the\n # structure of the JSON vs the flat nature of the puppet properties, this\n # is a bit of a manual task.\n if not @property_hash[:secured1].to_s.empty?\n @updated_json[\"secured1\"] = @property_hash[:secured1]\n end\n if not @property_hash[:secured2].to_s.empty?\n @updated_json[\"secured2\"] = @property_hash[:secured2]\n end\n if not @property_hash[:secured3].to_s.empty?\n @updated_json[\"secured3\"] = @property_hash[:secured3]\n end\n if not @property_hash[:secured4].to_s.empty?\n @updated_json[\"secured4\"] = @property_hash[:secured4]\n end\n\n #Either arg1 or encrypted_arg1 is returned by Opsview, so we need to make sure to do the right thing\n #when transitioning to and from encrypted arguments\n\n if not @resource[:arg1].nil?\n @updated_json[\"secured1\"] = \"0\"\n @updated_json[\"arg1\"] = @property_hash[:arg1]\n if defined?@updated_json[\"encrypted_arg1\"]\n \t@updated_json.delete(\"encrypted_arg1\")\n end\n elsif not @property_hash[:encrypted_arg1].to_s.empty?\n @updated_json[\"encrypted_arg1\"] = @property_hash[:encrypted_arg1]\n @updated_json[\"secured1\"] = \"1\"\n if defined?@updated_json[\"arg1\"]\n \t@updated_json.delete(\"arg1\")\n end\n end\n\n if not @resource[:arg2].nil?\n @updated_json[\"secured2\"] = \"0\"\n @updated_json[\"arg2\"] = @property_hash[:arg2]\n if defined?@updated_json[\"encrypted_arg2\"]\n \t@updated_json.delete(\"encrypted_arg2\")\n end\n elsif not @property_hash[:encrypted_arg2].to_s.empty?\n @updated_json[\"encrypted_arg2\"] = @property_hash[:encrypted_arg2]\n @updated_json[\"secured2\"] = \"1\"\n if defined?@updated_json[\"arg2\"]\n \t@updated_json.delete(\"arg2\")\n end\n end\n\n if not @resource[:arg3].nil?\n @updated_json[\"secured3\"] = \"0\"\n @updated_json[\"arg3\"] = @property_hash[:arg3]\n if defined?@updated_json[\"encrypted_arg3\"]\n \t@updated_json.delete(\"encrypted_arg3\")\n end\n elsif not @property_hash[:encrypted_arg3].to_s.empty?\n @updated_json[\"encrypted_arg3\"] = @property_hash[:encrypted_arg3]\n @updated_json[\"secured3\"] = \"1\"\n if defined?@updated_json[\"arg3\"]\n \t@updated_json.delete(\"arg3\")\n end\n end\n\n if not @resource[:arg4].nil?\n @updated_json[\"secured4\"] = \"0\"\n @updated_json[\"arg4\"] = @property_hash[:arg4]\n if defined?@updated_json[\"encrypted_arg4\"]\n \t@updated_json.delete(\"encrypted_arg4\")\n end\n elsif not @property_hash[:encrypted_arg4].to_s.empty?\n @updated_json[\"encrypted_arg4\"] = @property_hash[:encrypted_arg4]\n @updated_json[\"secured4\"] = \"1\"\n if defined?@updated_json[\"arg4\"]\n \t@updated_json.delete(\"arg4\")\n end\n end\n\n if not @property_hash[:value].to_s.empty?\n @updated_json[\"value\"] = @property_hash[:value]\n end\n\n if not @property_hash[:label1].nil?\n @updated_json[\"label1\"] = @property_hash[:label1]\n end\n if not @property_hash[:label2].nil?\n @updated_json[\"label2\"] = @property_hash[:label2]\n end\n if not @property_hash[:label3].nil?\n @updated_json[\"label3\"] = @property_hash[:label3]\n end\n if not @property_hash[:label4].nil?\n @updated_json[\"label4\"] = @property_hash[:label4]\n end\n\n\n @updated_json[\"name\"] = @resource[:attribute]\n \n # Flush changes:\n put @updated_json.to_json\n\n if defined? @resource[:reload_opsview]\n if @resource[:reload_opsview].to_s == \"true\"\n Puppet.notice \"Configured to reload opsview\"\n do_reload_opsview\n else\n Puppet.notice \"Configured NOT to reload opsview\"\n end\n end\n\n @property_hash.clear\n @attribute_properties.clear\n\n false\n end", "def update!(**args)\n @asset_set = args[:asset_set] if args.key?(:asset_set)\n @campaign = args[:campaign] if args.key?(:campaign)\n @resource_name = args[:resource_name] if args.key?(:resource_name)\n @status = args[:status] if args.key?(:status)\n end", "def attr_reader(*args)\n super\n comparison_attrs.concat(args)\n end", "def arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n \n # Make an argument to apply/not apply this measure\n chs = OpenStudio::StringVector.new\n chs << \"TRUE\"\n chs << \"FALSE\"\n apply_measure = OpenStudio::Ruleset::OSArgument::makeChoiceArgument('apply_measure', chs, true)\n apply_measure.setDisplayName(\"Apply Measure?\")\n apply_measure.setDefaultValue(\"TRUE\")\n args << apply_measure\n \n #Argument 1 Type of Chilled Beam System, required, choice, default Active\n beam_options = [\"Active\", \"Passive\"]\n cooled_beam_type = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"cooled_beam_type\", beam_options,true)\n cooled_beam_type.setDisplayName('Select the Type of Chilled Beam to be added and indicate the Thermal Zones that Chilled Beams will be added to. NOTE: Users should confirm subsequent chilled beam model parameters. Defaulted coefficient values may not be representative of actual chilled beam performance')\n cooled_beam_type.setDefaultValue(\"Active\")\n args << cooled_beam_type\n \n #Argument 3 Chilled Water Loop selection or creation \n existing_plant_loops = model.getPlantLoops\n existing_chilled_loops = existing_plant_loops.select{ |pl| pl.sizingPlant.loopType() == \"Cooling\"}\n existing_plant_names = existing_chilled_loops.select{ |pl| not pl.name.empty?}.collect{ |pl| pl.name.get }\n existing_plant_names << \"Create New\"\n existing_plant_loop_name = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"existing_plant_loop_name\", existing_plant_names, true)\n existing_plant_loop_name.setDisplayName('Chilled Water loop serving chilled beams. If \"Create New\" is selected a loop containing an air cooled chiller (COP=3.5) generating chilled water at 57 Deg F will be created. A constant speed pump (with user defined pressure rise) will be created.')\n existing_plant_loop_name.setDefaultValue (\"Create New\")\n args << existing_plant_loop_name\n \n #argument 4, new loop rated pump head type double, required, double, default 60 feet\n new_loop_rated_pump_head = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('new_loop_pump_head', true)\n new_loop_rated_pump_head.setDisplayName('The pump head (in feet of water) that will be assigned to the primary chilled water loop circulation pump. This argument will only be used if a new chilled water plant loop is created.')\n new_loop_rated_pump_head.setDefaultValue (60)\n args<< new_loop_rated_pump_head\n #must check interpretation of the 60 default value for pump head. meant to be 60 feet.\n \n #argument 5. air_loop_name, required, double, default Create New\n air_loops_list = model.getAirLoopHVACs.collect { |l| l.name.get }\n air_loops_list << \"Create New\"\n air_loop_name = OpenStudio::Ruleset::OSArgument::makeChoiceArgument('air_loop_name', air_loops_list, true)\n air_loop_name.setDisplayName('Air loop to serve selected zones by chilled beam units. This should be an air loop configured as a DOAS. If \"Create New\" is selected, an air loop containing a Dual Wheel DOAS system with a chilled water coil served by the user selected chiller plant loop will be created. The DOAS will be configured to deliver a constant temperature of 65 Deg F to connected zones.')\n air_loop_name.setDefaultValue (\"Create New\")\n args << air_loop_name\n \n #argument 5.5 (mislabeled in spec) new airloop fan pressure rise, required, double, default none\n new_airloop_fan_pressure_rise = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('new_airloop_fan_pressure_rise',true)\n new_airloop_fan_pressure_rise.setDisplayName('The pressure rise (inches of water) that will be assigned to the constant speed fans of a new air loop. This pressure rise, which includes the pressure across an energy wheel, will be split evenly between the new supply and exhaust fans.')\n new_airloop_fan_pressure_rise.setDefaultValue(\"5.00\")\n args << new_airloop_fan_pressure_rise\n \n #argument 6 supply air vol flow rate, double, default to -1\n supply_air_vol_flow_rate = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('supply_air_vol_flow_rate',true)\n supply_air_vol_flow_rate.setDisplayName('The combined air flow rate (cfm) of the supply air serving all chilled beams in a zone. Enter -1 to autosize (based on the zone ventilation requirement). If a value is entered, and multiple thermal zones are selected, this value will be hard coded to all selected zones.')\n supply_air_vol_flow_rate.setDefaultValue(\"-1\")\n args << supply_air_vol_flow_rate\n \n #argument 7 max tot chw vol flow rate, required, double, default -1\n max_tot_chw_vol_flow_rate = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('max_tot_chw_vol_flow_rate',true)\n max_tot_chw_vol_flow_rate.setDisplayName('Combined maximum chilled water flow rate (gpm) of all chilled beam units serving a zone. Enter -1 to autosize based on the zone design load. If a value is entered, and multiple thermal zones are selected, this value will be hard coded to all selected zones.')\n max_tot_chw_vol_flow_rate.setDefaultValue(\"-1\")\n args << max_tot_chw_vol_flow_rate\n \n #arg 8 number of beams, required, double, default -1\n number_of_beams = OpenStudio::Ruleset::OSArgument::makeIntegerArgument('number_of_beams',true)\n number_of_beams.setDisplayName('The number of individual chilled beam units serving each zone. Enter -1 to autosize based on a value of 1.11 GPM per chilled beam unit.')\n number_of_beams.setDefaultValue(\"-1\")\n args << number_of_beams\n \n #arg9 beam_length, required, double, defailt -1\n beam_length = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('beam_length',true)\n beam_length.setDisplayName('The length (ft) of an individual beam. Enter -1 to autosize based upon the # of beam units and the zone design sensible cooling load.')\n beam_length.setDefaultValue(\"-1\")\n args << beam_length\n \n #arg10 design_inlet_water_temperature, requried, double, default 59\n design_inlet_water_temperature = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('design_inlet_water_temperature',true)\n design_inlet_water_temperature.setDisplayName('The design inlet water temperature (Deg F) of a beam unit.')\n design_inlet_water_temperature.setDefaultValue(\"59\")\n args << design_inlet_water_temperature\n \n #arg11 design_outlet_water_temperature, required, double, default 62.6\n design_outlet_water_temperature = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('design_outlet_water_temperature',true)\n design_outlet_water_temperature.setDisplayName('The design outlet water temperature )Deg F) of the beam units.')\n design_outlet_water_temperature.setDefaultValue(\"62.6\")\n args << design_outlet_water_temperature\n \n #arg12 coil_surface_area_per_coil_length, required, double, default 17.78\n coil_surface_area_per_coil_length = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('coil_surface_area_per_coil_length',true)\n coil_surface_area_per_coil_length.setDisplayName('Surface area on the air side of the beam per unit beam length (ft^2/ft). This parameter is a unique value representing specific chilled beam products. See E+ Engineering Reference for equation details')\n coil_surface_area_per_coil_length.setDefaultValue(\"17.78\")\n args << coil_surface_area_per_coil_length\n \n #arg13 coefficient_alpha required, double, default 15.3\n coefficient_alpha = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('coefficient_alpha',true)\n coefficient_alpha.setDisplayName('Model parameter alpha (unitless). This parameter is a unique value representing specific chilled beam products. See E+ Engineering Reference for equation details')\n coefficient_alpha.setDefaultValue(\"15.3\")\n args << coefficient_alpha\n \n #arg14 coefficient_n1, required, double, default 0\n coefficient_n1 = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('coefficient_n1',true)\n coefficient_n1.setDisplayName('Model parameter n1 (unitless). This parameter is a unique value representing specific chilled beam products. See E+ Engineering Reference for equation details')\n coefficient_n1.setDefaultValue(\"0\")\n args << coefficient_n1\n \n #arg15 coefficient_n2,required, double, default .84)\n coefficient_n2 = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('coefficient_n2',true)\n coefficient_n2.setDisplayName('Model parameter n2 (unitless). This parameter is a unique value representing specific chilled beam products. See E+ Engineering Reference for equation details')\n coefficient_n2.setDefaultValue(\"0.84\")\n args << coefficient_n2\n\n #arg16 coefficient_n3,required, double, default .84)\n coefficient_n3 = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('coefficient_n3',true)\n coefficient_n3.setDisplayName('Model parameter n3 (unitless). This parameter is a unique value representing specific chilled beam products. See E+ Engineering Reference for equation details')\n coefficient_n3.setDefaultValue(\".12\")\n args << coefficient_n3\n \n #arg17 coefficient_a0,required, double, default .5610)\n coefficient_a0 = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('coefficient_a0',true)\n coefficient_a0.setDisplayName('Model parameter a0 (unitless). This parameter is a unique value representing specific chilled beam products. See E+ Engineering Reference for equation details')\n coefficient_a0.setDefaultValue(\".5610\")\n args << coefficient_a0\n \n #arg18 coefficient_k1,required, double, default .00571)\n coefficient_k1 = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('coefficient_k1',true)\n coefficient_k1.setDisplayName('Model parameter k1 (unitless). This parameter is a unique value representing specific chilled beam products. See E+ Engineering Reference for equation details')\n coefficient_k1.setDefaultValue(\".005710\")\n args << coefficient_k1\n \n #arg19 coefficient_n,required, double, default .40)\n coefficient_n = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('coefficient_n',true)\n coefficient_n.setDisplayName('Model parameter n (unitless). This parameter is a unique value representing specific chilled beam products. See E+ Engineering Reference for equation details')\n coefficient_n.setDefaultValue(\".400\")\n args << coefficient_n\n \n #arg20 coefficient_kin,required, double, default 2.0)\n coefficient_kin = OpenStudio::Ruleset::OSArgument::makeDoubleArgument('coefficient_kin',true)\n coefficient_kin.setDisplayName('Model parameter kin (unitless). This parameter is a unique value representing specific chilled beam products. See E+ Engineering Reference for equation details')\n coefficient_kin.setDefaultValue(\"2.0\")\n args << coefficient_kin\n \n #argument 21 leaving_pipe_inside_dia, required, choice, default \"1/2 type K\"\n pipe_inside_dia_options = [\"1/2 Type K\", \"1/2 Type L\", \"3/4 Type K\", \"3/4 Type L\"]\n leaving_pipe_inside_dia = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"leaving_pipe_inside_dia\", pipe_inside_dia_options,true)\n leaving_pipe_inside_dia.setDisplayName('Diameter (inches) of the chilled beam unit water inlet and outlet pipe connections.')\n leaving_pipe_inside_dia.setDefaultValue(\"1/2 Type K\")\n args << leaving_pipe_inside_dia\n #note: [1/2 TypeK = .527 ] [1/2 Type L = .545] [3/4 type k = .745] [3/4 type l=.785]\n \n return args\n end", "def test_check_allows_parameters\n file = Puppet::Type.type(:file)\n klass = file.attrclass(:check)\n\n resource = file.new(:path => tempfile)\n inst = klass.new(:resource => resource)\n\n {:property => [:owner, :group], :parameter => [:ignore, :recurse], :metaparam => [:require, :subscribe]}.each do |attrtype, attrs|\n assert_nothing_raised(\"Could not set check to a single #{attrtype} value\") do\n inst.value = attrs[0]\n end\n\n if attrtype == :property\n assert(resource.property(attrs[0]), \"Check did not create property instance during single check\")\n end\n assert_nothing_raised(\"Could not set check to multiple #{attrtype} values\") do\n inst.value = attrs\n end\n if attrtype == :property\n assert(resource.property(attrs[1]), \"Check did not create property instance during multiple check\")\n end\n end\n\n # But make sure actually invalid attributes fail\n assert_raise(Puppet::Error, \":check did not fail on invalid attribute\") do\n inst.value = :nosuchattr\n end\n end", "def setAperture _args\n \"setAperture _args;\" \n end", "def validate_attrs\n @target.present? && [email protected]? && @actor.present? && @action_key.present?\n end", "def parse(src)\n recAttrParse(src)\n # look if there are any duplicates, if there are it's an error:\n counterHash = Hash.new(0)\n args.each { |a| k=a.to_sym; counterHash[k] += 1 }\n dupes = []; counterHash.each { |k, v| dupes << k if v > 1 }\n raise \"Duplicate arguments for #{self} - [#{dupes.join(',')}]\" unless dupes.empty?\n @argSet = Set.new(args)\n updateKey\n self\n end", "def attributes!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 14 )\n\n type = ATTRIBUTES\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 147:4: 'attributes'\n match( \"attributes\" )\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__, 14 )\n\n end", "def new_attributes(args)\n stats = default_attributes\n update_stats(stats, args)\n end", "def update!(**args)\n @generic_metadata = args[:generic_metadata] if args.key?(:generic_metadata)\n @output_info = args[:output_info] if args.key?(:output_info)\n end", "def parse_user_arguments(runner, user_arguments)\n apply_measure = runner.getStringArgumentValue(\"apply_measure\",user_arguments)\n # This measure is not applicable if apply_measure is false\n if apply_measure == \"FALSE\"\n runner.registerAsNotApplicable(\"Not Applicable - User chose not to apply this measure via the apply_measure argument.\")\n return true\n end\n \n @cooled_beam_type = runner.getStringArgumentValue(\"cooled_beam_type\", user_arguments)\n @existing_plant_loop_name = runner.getStringArgumentValue(\"existing_plant_loop_name\", user_arguments)\n @new_loop_pump_head = runner.getDoubleArgumentValue(\"new_loop_pump_head\", user_arguments)\n @air_loop_name = runner.getStringArgumentValue(\"air_loop_name\", user_arguments)\n @new_airloop_fan_pressure_rise = runner.getDoubleArgumentValue(\"new_airloop_fan_pressure_rise\", user_arguments)\n @supply_air_vol_flow_rate = runner.getDoubleArgumentValue(\"supply_air_vol_flow_rate\", user_arguments)\n @max_tot_chw_vol_flow_rate = runner.getDoubleArgumentValue(\"max_tot_chw_vol_flow_rate\", user_arguments)\n @number_of_beams = runner.getIntegerArgumentValue(\"number_of_beams\", user_arguments)\n @beam_length = runner.getDoubleArgumentValue(\"beam_length\", user_arguments)\n @design_inlet_water_temperature = runner.getDoubleArgumentValue(\"design_inlet_water_temperature\", user_arguments)\n @design_outlet_water_temperature = runner.getDoubleArgumentValue(\"design_outlet_water_temperature\", user_arguments)\n @coil_surface_area_per_coil_length = runner.getDoubleArgumentValue(\"coil_surface_area_per_coil_length\", user_arguments)\n @coefficient_alpha = runner.getDoubleArgumentValue(\"coefficient_alpha\", user_arguments)\n @coefficient_n1 = runner.getDoubleArgumentValue(\"coefficient_n1\", user_arguments)\n @coefficient_n2 = runner.getDoubleArgumentValue(\"coefficient_n2\", user_arguments)\n @coefficient_n3 = runner.getDoubleArgumentValue(\"coefficient_n3\", user_arguments)\n @coefficient_a0 = runner.getDoubleArgumentValue(\"coefficient_a0\", user_arguments)\n @coefficient_k1 = runner.getDoubleArgumentValue(\"coefficient_k1\", user_arguments)\n @coefficient_n = runner.getDoubleArgumentValue(\"coefficient_n\", user_arguments)\n @coefficient_kin = runner.getDoubleArgumentValue(\"coefficient_kin\", user_arguments)\n @leaving_pipe_inside_dia = runner.getStringArgumentValue(\"leaving_pipe_inside_dia\", user_arguments)\n end", "def update!(**args)\n @normalized = args[:normalized] if args.key?(:normalized)\n @source = args[:source] if args.key?(:source)\n end", "def emit_manifest_assign(prop, seed, ctx, prop_field_name, opts = {})\n # Chef name field must use label_name\n if prop.name == 'name' && opts[:first_level]\n [@provider.label_name(prop.__resource),\n formatter(prop.class, @datagen.value(prop.class, prop, seed))]\n else\n super(prop, seed, ctx, prop_field_name)\n end\n end", "def test_should_require_some_assets_if_provided_by_number_using_attributes\n AssetRelation.destroy_all\n item = AssetType.new\n item.sized.options[:required] = 1\n\n begin\n item.update_attributes :sized_attributes => [two_asset_relation_attributes.first]\n assert item.valid?\n ensure\n # cleanup\n item.sized.options[:required] = false\n end\n end", "def update!(**args)\n @attribute_map = args[:attribute_map] if args.key?(:attribute_map)\n @dropped_attributes_count = args[:dropped_attributes_count] if args.key?(:dropped_attributes_count)\n end", "def defaulted_attrs\n given_attrs.reject {|attr| send(\"given_#{attr}?\")}\n end", "def update!(**args)\n @attributes = args[:attributes] if args.key?(:attributes)\n end", "def attributes=(*args)\n define_dynamic_answer_setters!\n super(*args)\n end", "def update!(**args)\n @attribute_name = args[:attribute_name] if args.key?(:attribute_name)\n @attribute_value = args[:attribute_value] if args.key?(:attribute_value)\n @section_name = args[:section_name] if args.key?(:section_name)\n end", "def setup_object_attributes; end", "def update!(**args)\n @enforcement_output = args[:enforcement_output] if args.key?(:enforcement_output)\n end", "def attrs_or_default(attrs)\n options = attrs.extract_options!\n attrs = yield if attrs.blank?\n attrs << options\n end", "def adopt_extractions extraction_params={}\n if extraction_params.present?\n build_gleaning unless gleaning\n # Declare the attributes needed w/o launching to glean\n # NB: we take ALL proffered attributes, not just those that are priorly needed\n # gleaning.attribs_needed! *extraction_params.keys\n gleaning.accept_attributes extraction_params\n\n # attribs_needed! *extraction_params.keys\n accept_attributes extraction_params\n end\n end", "def PRF03=(arg)", "def update!(**args)\n @pipeline_ready_condition = args[:pipeline_ready_condition] if args.key?(:pipeline_ready_condition)\n @targets_present_condition = args[:targets_present_condition] if args.key?(:targets_present_condition)\n @targets_type_condition = args[:targets_type_condition] if args.key?(:targets_type_condition)\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 arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n \n #file path to air loop assignment\n file_path = OpenStudio::Ruleset::OSArgument.makeStringArgument(\"file_path\", true)\n file_path.setDisplayName(\"Enter the path to the file:\")\n file_path.setDescription(\"Example: 'C:\\\\Projects\\\\AHU_assignment.csv'\")\n args << file_path\n\n #make a choice argument for type of AirTerminal\n chs_names = OpenStudio::StringVector.new\n chs_names << \"AirTerminal:SingleDuct:Uncontrolled\"\n chs_names << \"AirTerminal:SingleDuct:VAV:NoReheat\"\n #chs_names << \"AirTerminal:SingleDuct:VAV:Reheat(Elec)\"\n #chs_names << \"AirTerminal:SingleDuct:VAV:Reheat(Gas)\"\n chs_names << \"AirTerminal:SingleDuct:VAV:Reheat(HW)\"\n #chs_names << \"AirTerminal:SingleDuct:ConstantVolume:Reheat(Elec)\"\n #chs_names << \"AirTerminal:SingleDuct:ConstantVolume:Reheat(Gas)\"\n chs_names << \"AirTerminal:SingleDuct:ConstantVolume:Reheat(HW)\"\n\n default_air_terminal_type = OpenStudio::Ruleset::OSArgument::makeChoiceArgument('default_air_terminal_type', chs_names, true)\n default_air_terminal_type.setDisplayName(\"Select default type of AirTerminal:\")\n default_air_terminal_type.setDefaultValue(\"AirTerminal:SingleDuct:Uncontrolled\")\n args << default_air_terminal_type\n \n #select plant loops\n plantLoops = model.getPlantLoops\n plantLoops_handle = OpenStudio::StringVector.new\n plantLoops_displayName = OpenStudio::StringVector.new\n plantLoops.each do |plantLoop|\n plantLoops_handle << plantLoop.handle.to_s\n plantLoops_displayName << plantLoop.name.to_s\n end \n \n # make an argument for heating loop, if applicable\n heating_plant_loop = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"heating_plant_loop\", plantLoops_handle, plantLoops_displayName,false)\n heating_plant_loop.setDisplayName(\"Select the heating plant loop for use for air terminals, if applicable.\")\n args << heating_plant_loop\n \n # make an argument for cooling loop, if applicable\n # cooling_plant_loop = OpenStudio::Ruleset::OSArgument::makeChoiceArgument(\"cooling_plant_loop\", plantLoops_handle, plantLoops_displayName,false)\n # cooling_plant_loop.setDisplayName(\"Select the cooling plant loop for use with the air terminals, if applicable.\")\n # cooling_plant_loop.setDefaultValue(plantLoops_displayName[0])\n # args << cooling_plant_loop\n \n return args\n end", "def test_can_retrieve_argument_set_through_assignment\n Crd::Flex::Command.new 'mxmlc' do |s|\n s.output = 'Main.swf'\n assert_equal( 'Main.swf', s.output )\n end\n end", "def test_new\n\n # inputs.\n attr_in = @testee.param_attr( :in )\n assert_equal( [:param_in_real], attr_in )\n assert_equal( nil, @testee.param_in_real ) # check initial value.\n\n # options.\n attr_opt = @testee.param_attr( :opt )\n assert_equal( [:param_opt_in_fast_period,\n :param_opt_in_fast_ma_type,\n :param_opt_in_slow_period,\n :param_opt_in_slow_ma_type,\n :param_opt_in_signal_period,\n :param_opt_in_signal_ma_type], attr_opt )\n\n # outputs.\n attr_out = @testee.param_attr( :out )\n assert_equal( [:param_out_macd,\n :param_out_macd_signal,\n :param_out_macd_hist], attr_out )\n assert_equal( nil, @testee.param_out_macd )\n assert_equal( nil, @testee.param_out_macd_signal )\n assert_equal( nil, @testee.param_out_macd_hist )\n\n #\n tmp = [0.0, 1.0, 2.0]\n assert_raise(RuntimeError){ @testee.param_in_real( tmp ) }\n\n #\n #pp @testee.singleton_methods\n @testee.param_in_real = tmp\n assert_equal( tmp, @testee.param_in_real )\n\n ret = @testee.param_out_setting\n assert_equal( [nil,nil,nil], @testee.param_out_macd )\n assert_equal( { :param_out_macd => [nil,nil,nil],\n :param_out_macd_signal => [nil,nil,nil],\n :param_out_macd_hist => [nil,nil,nil],\n }, ret )\n\n\n end", "def extractable_options?; end", "def update!(**args)\n @additional_attributes = args[:additional_attributes] if args.key?(:additional_attributes)\n @asset_type = args[:asset_type] if args.key?(:asset_type)\n @description = args[:description] if args.key?(:description)\n @display_name = args[:display_name] if args.key?(:display_name)\n @labels = args[:labels] if args.key?(:labels)\n @location = args[:location] if args.key?(:location)\n @name = args[:name] if args.key?(:name)\n @network_tags = args[:network_tags] if args.key?(:network_tags)\n @project = args[:project] if args.key?(:project)\n end", "def update!(**args)\n @asset = args[:asset] if args.key?(:asset)\n @campaign = args[:campaign] if args.key?(:campaign)\n @resource_name = args[:resource_name] if args.key?(:resource_name)\n @status = args[:status] if args.key?(:status)\n end", "def update!(**args)\n @argument_composing_mid = args[:argument_composing_mid] if args.key?(:argument_composing_mid)\n @attribute_signals = args[:attribute_signals] if args.key?(:attribute_signals)\n @concept_entity_mid = args[:concept_entity_mid] if args.key?(:concept_entity_mid)\n @confidence_level = args[:confidence_level] if args.key?(:confidence_level)\n @deduped_funcalls = args[:deduped_funcalls] if args.key?(:deduped_funcalls)\n @expression_status = args[:expression_status] if args.key?(:expression_status)\n @freefolks_trigger = args[:freefolks_trigger] if args.key?(:freefolks_trigger)\n @grounding_signals = args[:grounding_signals] if args.key?(:grounding_signals)\n @high_confidence = args[:high_confidence] if args.key?(:high_confidence)\n @intent_annotation_sources = args[:intent_annotation_sources] if args.key?(:intent_annotation_sources)\n @intent_composing_mid = args[:intent_composing_mid] if args.key?(:intent_composing_mid)\n @intent_provenance = args[:intent_provenance] if args.key?(:intent_provenance)\n @intent_relevant_mid = args[:intent_relevant_mid] if args.key?(:intent_relevant_mid)\n @is_close_interpretation = args[:is_close_interpretation] if args.key?(:is_close_interpretation)\n @is_disambiguation_card_intent = args[:is_disambiguation_card_intent] if args.key?(:is_disambiguation_card_intent)\n @is_disambiguation_intent = args[:is_disambiguation_intent] if args.key?(:is_disambiguation_intent)\n @is_neural_categorical_interpretation = args[:is_neural_categorical_interpretation] if args.key?(:is_neural_categorical_interpretation)\n @is_ui_composition_intent = args[:is_ui_composition_intent] if args.key?(:is_ui_composition_intent)\n @local_signals = args[:local_signals] if args.key?(:local_signals)\n @osrp_journey_tag = args[:osrp_journey_tag] if args.key?(:osrp_journey_tag)\n @parsed_due_to_experiment = args[:parsed_due_to_experiment] if args.key?(:parsed_due_to_experiment)\n @parsing_signals = args[:parsing_signals] if args.key?(:parsing_signals)\n @prefulfillment_ranking_score = args[:prefulfillment_ranking_score] if args.key?(:prefulfillment_ranking_score)\n @prefulfillment_signals = args[:prefulfillment_signals] if args.key?(:prefulfillment_signals)\n @referential_resolution = args[:referential_resolution] if args.key?(:referential_resolution)\n @refx_summary_node_id = args[:refx_summary_node_id] if args.key?(:refx_summary_node_id)\n @response_meaning_signals = args[:response_meaning_signals] if args.key?(:response_meaning_signals)\n @result_support = args[:result_support] if args.key?(:result_support)\n @role = args[:role] if args.key?(:role)\n @selected_by_prefulfillment_ranking = args[:selected_by_prefulfillment_ranking] if args.key?(:selected_by_prefulfillment_ranking)\n @shopping_ids = args[:shopping_ids] if args.key?(:shopping_ids)\n @signals_fallback_intents = args[:signals_fallback_intents] if args.key?(:signals_fallback_intents)\n @uses_prefulfillment_ranker = args[:uses_prefulfillment_ranker] if args.key?(:uses_prefulfillment_ranker)\n end", "def update!(**args)\n @dash_length_meters = args[:dash_length_meters] if args.key?(:dash_length_meters)\n @gap_color = args[:gap_color] if args.key?(:gap_color)\n @gap_length_meters = args[:gap_length_meters] if args.key?(:gap_length_meters)\n @material = args[:material] if args.key?(:material)\n @paint_color = args[:paint_color] if args.key?(:paint_color)\n @pattern = args[:pattern] if args.key?(:pattern)\n @physical_line_token = args[:physical_line_token] if args.key?(:physical_line_token)\n end", "def test_can_pipe_output_to_another_fn\n result = interpret @lib + 'x=mkattr(foo:, 2); %x.foo | dup()'\n assert_eq result, 2\n end", "def update!(**args)\n @case_sensitive = args[:case_sensitive] if args.key?(:case_sensitive)\n @extract_a = args[:extract_a] if args.key?(:extract_a)\n @extract_b = args[:extract_b] if args.key?(:extract_b)\n @field_a = args[:field_a] if args.key?(:field_a)\n @field_a_index = args[:field_a_index] if args.key?(:field_a_index)\n @field_a_required = args[:field_a_required] if args.key?(:field_a_required)\n @field_b = args[:field_b] if args.key?(:field_b)\n @field_b_index = args[:field_b_index] if args.key?(:field_b_index)\n @field_b_required = args[:field_b_required] if args.key?(:field_b_required)\n @output_constructor = args[:output_constructor] if args.key?(:output_constructor)\n @output_to_field = args[:output_to_field] if args.key?(:output_to_field)\n @output_to_field_index = args[:output_to_field_index] if args.key?(:output_to_field_index)\n @override_output_field = args[:override_output_field] if args.key?(:override_output_field)\n end", "def attr_writer(*vars)\n # avoid tracking attributes that are added by the class_attribute\n # as these are class attributes and not instance attributes.\n tracked_vars = vars.reject {|var| respond_to? var }\n add_tracked_attrs(false, true, *tracked_vars)\n vars.extract_options!\n super\n end", "def update!(**args)\n @examples_override = args[:examples_override] if args.key?(:examples_override)\n @metadata = args[:metadata] if args.key?(:metadata)\n @parameters = args[:parameters] if args.key?(:parameters)\n end", "def attrs_provided?(attrs)\n !attrs.empty?\n end", "def correct_abbreviations_attributes; end", "def prepared_attributes_for_essence\n attributes = {\n ingredient: default_text(definition['default'])\n }\n attributes\n end", "def update!(**args)\n @attributes = args[:attributes] if args.key?(:attributes)\n @name = args[:name] if args.key?(:name)\n end", "def update!(**args)\n @attributes = args[:attributes] if args.key?(:attributes)\n @name = args[:name] if args.key?(:name)\n end", "def extractable_options?; true end", "def test_both_attrs\n PictureTag.stubs(:html_attributes)\n .returns('img' => 'class=\"img\"', 'parent' => 'class=\"parent\"')\n\n correct = <<~HEREDOC\n <img class=\"img parent\" src=\"good_url\" srcset=\"ss\">\n HEREDOC\n\n assert_equal correct, @tested.to_s\n end", "def probers=(_arg0); end", "def PRF02=(arg)", "def update!(**args)\n @asset_set = args[:asset_set] if args.key?(:asset_set)\n @customer = args[:customer] if args.key?(:customer)\n @resource_name = args[:resource_name] if args.key?(:resource_name)\n @status = args[:status] if args.key?(:status)\n end", "def required_args\n doodle.attributes.select{ |k, v| v.required?}.map{ |k,v| v}\n end", "def assign_text_param_if_used(attr_name, value)\n\t\tsend \"#{attr_name}=\", value.strip.presence if value\n\tend", "def update!(**args)\n @asset = args[:asset] if args.key?(:asset)\n @asset_set = args[:asset_set] if args.key?(:asset_set)\n @resource_name = args[:resource_name] if args.key?(:resource_name)\n @status = args[:status] if args.key?(:status)\n end", "def arguments(model)\n args = OpenStudio::Ruleset::OSArgumentVector.new\n\n #make an argument for heating setback amount\n htg_setback_f = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"htg_setback_f\",true)\n htg_setback_f.setDisplayName(\"Heating Setback (F) - Decrease in Heating Setpoint\")\n htg_setback_f.setDefaultValue(15.0)\n args << htg_setback_f\n\n #make an argument for cooling setback amount\n clg_setback_f = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"clg_setback_f\",true)\n clg_setback_f.setDisplayName(\"Cooling Setback (F) - Increase in Cooling Setpoint\")\n clg_setback_f.setDefaultValue(5.0)\n args << clg_setback_f \n \n #setback start time\n start_time = OpenStudio::Ruleset::OSArgument::makeStringArgument(\"start_time\",true)\n start_time.setDisplayName(\"Time to Start Setback (eg 18:00).\")\n start_time.setDefaultValue(\"20:00\")\n args << start_time\n\n #weekday end time\n end_time = OpenStudio::Ruleset::OSArgument::makeStringArgument(\"end_time\",true)\n end_time.setDisplayName(\"Time to End Setback (eg 07:00).\")\n end_time.setDefaultValue(\"07:00\")\n args << end_time\n\n #make an argument for material and installation cost\n material_cost = OpenStudio::Ruleset::OSArgument::makeDoubleArgument(\"material_cost\",true)\n material_cost.setDisplayName(\"Material and Installation Cost($).\")\n material_cost.setDefaultValue(0.0)\n args << material_cost\n\n return args\n end", "def test_multiple_attrs\n PictureTag.stubs(:html_attributes).returns(\n 'picture' => 'class=\"picture\"',\n 'parent' => 'class=\"parent\"',\n 'source' => 'class=\"source\"',\n 'img' => 'class=\"img\"',\n 'alt' => 'alt text'\n )\n\n correct = <<~HEREDOC\n <picture class=\"picture parent\">\n <source class=\"source\" srcset=\"ss\" type=\"original\">\n <img class=\"img\" src=\"good_url\" alt=\"alt text\">\n </picture>\n HEREDOC\n\n assert_equal correct, @tested.to_s\n end" ]
[ "0.58576226", "0.52793735", "0.52575773", "0.5203818", "0.51870185", "0.5125669", "0.5117332", "0.5110013", "0.5103362", "0.5088816", "0.50814444", "0.5061189", "0.5060868", "0.5054867", "0.5051679", "0.5051679", "0.5000203", "0.4977076", "0.49484178", "0.49476695", "0.49373114", "0.49362227", "0.49209014", "0.4917804", "0.49154267", "0.49063954", "0.48777103", "0.48639262", "0.48433176", "0.4832655", "0.48295766", "0.48023823", "0.47799367", "0.47790012", "0.47633255", "0.47595462", "0.47581315", "0.47441986", "0.47410238", "0.47348335", "0.47348335", "0.47290483", "0.47246316", "0.47188967", "0.47157273", "0.47145373", "0.47092232", "0.47091478", "0.4705749", "0.4701455", "0.46958214", "0.46945813", "0.4680898", "0.46722174", "0.46598557", "0.4658695", "0.465853", "0.4649755", "0.46460232", "0.46403927", "0.46380454", "0.46380404", "0.46227854", "0.4615172", "0.46139187", "0.4611932", "0.4610183", "0.4609432", "0.46050635", "0.45973703", "0.4597284", "0.45951158", "0.4592972", "0.45895293", "0.4586767", "0.4581438", "0.45724624", "0.45684576", "0.45680153", "0.4564925", "0.45612895", "0.4558144", "0.45516223", "0.45487952", "0.4544203", "0.45426628", "0.45408285", "0.45320782", "0.45312953", "0.45312953", "0.45312324", "0.4528416", "0.45257673", "0.4524191", "0.45239276", "0.45225382", "0.4522154", "0.45215005", "0.45193398", "0.45172215" ]
0.49564713
18
fallback width and format
def test_fallback output = tested 'fallback rms.jpg' assert_match url_matcher(format: 'webp', width: 35), output.at_css('img')['src'] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def width=(_); end", "def width=(_); end", "def fit_width; end", "def width=(_arg0); end", "def width; end", "def width; end", "def width; end", "def width; end", "def width; end", "def width; end", "def width; end", "def width; end", "def width; end", "def fw; self.fixed_width = true; self; end", "def safe_width(width)\n\n\n\n width.to_s.gsub(/\\A(\\d+)\\z/, '\\1px')\n\n\n\n end", "def width\n end", "def width\n end", "def default_widths\n @default_widths ||= []\n end", "def get_width; end", "def width_str\r\n has_width? ? parms[0] : \"\"\r\n end", "def my_width \n 0.75\n end", "def width\n raise NotImplementedError\n end", "def width=(width)\n end", "def width(val); @width = val; self; end", "def truncate_trait\n options[:style] = [options.try(:[], :style), 'min-width: 0;'].join(' ').squish\n end", "def default_style\n return 0\n end", "def prepare_display(width)\n r = @result.reverse\n factor = width.to_f / (r.transpose[1].max)\n r.map { |l, c, r| [ l, (c * factor).round, r ] }\n end", "def width=(width)\n @width = width || 0\n end", "def width=(width)\n @width = width || 0\n end", "def is_width?(); @type == GRT_WIDTH; end", "def width\n @width ||= [title, formatted_values].flatten.map(&:length).max\n end", "def want_format?(derived_name, derived_width, derived_height)\n true\n end", "def get_width\n width = self.unpadded_width\n\n if not width.nil? and width != 0\n return { :width => \"#{width}px\" }\n else\n return {}\n end\n end", "def width\r\n has_width? ? parms[0].to_i : 0\r\n end", "def adjust_width\n self.width = [[text_size('O' * @max_characters).width + padding * 2,\n @title ? text_size(@title).width + padding * 2 : 0].max, Graphics.width].min\n end", "def set_character_width_narrow\n set_print_mode 1\n set_linefeed_rate 40\n end", "def width(value)\n @ole.Width = value\n nil\n end", "def width(value)\n @ole.Width = value\n nil\n end", "def width\n @width\n end", "def width(style_name=nil)\n style_name ||= reflection.default_style\n if style_name.equal?(:original)\n from_examination :@original_width\n else\n dimensions(style_name).at(0)\n end\n end", "def width?\n !!width\n end", "def width_multiplier\n @width_multiplier || 1\n end", "def has_width?\r\n parms\r\n end", "def base_width; 26 + @width; end", "def width\n options[:width] || Config.width\n end", "def formats; end", "def formats; end", "def calculate_width(width)\n new_width = width\n\n if /%/ === new_width\n new_width.delete!('%')\n width_num = new_width.to_i / 100.0\n new_width = \"#{width_num}\\\\textwidth\"\n end\n\n new_width\n end", "def preformatting\n\n end", "def width\n self.class.width\n end", "def defined_style_conversions; end", "def width(str, cjk = false)\n raise NotImplementedError\n end", "def pack_format\n \"a#{width}\"\n end", "def _wrapper_formats; end", "def width\n metadata[:width] if valid?\n end", "def strokewidth(width)\n @style[:strokewidth] = width\n end", "def strokewidth(width)\n @style[:strokewidth] = width\n end", "def calculate_width(width)\n\n new_width = width\n\n if /%/ === new_width\n new_width.gsub!(/%/, '')\n width_num = new_width.to_i / 100.0\n new_width = \"#{width_num.to_s}\\\\textwidth\"\n end\n\n new_width\n end", "def column_widths\n []\n end", "def set_character_width_normal\r\n set_print_mode 0\r\n set_linefeed_rate 55\r\n end", "def autowidth(widtharray)\n return if value.nil?\n\n if styles.cellXfs[style].alignment && styles.cellXfs[style].alignment.wrap_text\n first = true\n value.to_s.split(/\\r?\\n/, -1).each do |line|\n if first\n first = false\n else\n widtharray << 0\n end\n widtharray[-1] += string_width(line, font_size)\n end\n else\n widtharray[-1] += string_width(value.to_s, font_size)\n end\n widtharray\n end", "def enforce\n assert_minimum_width\n padding = renderer.padding\n\n if natural_width <= renderer.width\n if renderer.resize\n expand_column_widths\n else\n renderer.column_widths.map do |width|\n padding.left + width + padding.right\n end\n end\n else\n if renderer.resize\n shrink\n else\n rotate\n end\n end\n end", "def calc_width; padding * 2 + base_width; end", "def calc_width; padding * 2 + base_width; end", "def inqfillstyle\n inquiry_int { |pt| super(pt) }\n end", "def inqfillstyle\n inquiry_int { |pt| super(pt) }\n end", "def set_character_width_normal\n set_print_mode 0\n set_linefeed_rate 55\n end", "def full_width\n options.fetch(:full_width, false)\n end", "def style_conversion; end", "def embed_width\n width_ok? ? width : 1000\n end", "def natural_width\n renderer.column_widths.inject(0, &:+) + border_size + padding_size\n end", "def wrap_width(width)\n gsub(/([^\\n\\r]{1,#{width}})/,\"\\\\1\\n\")\n end", "def setwidth(width)\n @width = width\n end", "def base_width; 24 + SKC_Settings::WIDTH; end", "def _prepare_format #:nodoc:\n fmstr = nil\n fmt = []\n each_column { |c, i|\n ## trying a zero for hidden columns\n ## worked but an extra space is added below and the sep\n w = c.width\n case c.align\n when :right\n #fmt << \"%.#{w}s \"\n fmt << \"%#{w}.#{w}s \"\n else\n fmt << \"%-#{w}.#{w}s \"\n end\n }\n ## the next line will put a separator after hidden columns also\n fmstr = fmt.join(@y)\n #puts \"format: #{fmstr} \" # 2011-12-09 23:09:57\n return fmstr\n end", "def contents_width\n width - standard_padding * 2\n end", "def width\n instance.options[:width]\n end", "def setfillintstyle(*)\n super\n end", "def width\n if present?(options[:width])\n options[:width]\n\n elsif present?(options[:name])\n geometry.bordered_width\n\n else\n value.size\n\n end\n end", "def width\n self.resolution.first unless self.resolution.nil? || many?\n end", "def widths_reset\n @width = GroupLayout::DEFAULT_SIZE\n @max = GroupLayout::DEFAULT_SIZE\n end", "def setWidth(width)\n # This exists to deal with an inconsistency in IE's implementation where\n # it won't accept negative numbers in length measurements\n # FIXME: assert extractLengthValue(width.trim().toLowerCase()) >= 0 : \"CSS widths should not be negative\";\n \n DOM.setStyleAttribute(@element, \"width\", width)\n end", "def width\n if present?(options[:width])\n options[:width]\n\n elsif present?(options[:name])\n if left_aligned?\n value.size\n\n else\n geometry.bordered_width\n\n end\n\n else\n value.size\n\n end\n end", "def formatted_size\n Helpers.rcompact(@formats)\n sz = size\n fs = @formats.size\n fs > sz ? fs : sz\n end", "def correct_style_detected; end", "def correct_style_detected; end", "def correct_style_detected; end", "def width!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 35 )\n\n type = WIDTH\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 365:8: 'width'\n match( \"width\" )\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__, 35 )\n\n end", "def inqfillintstyle\n inquiry_int { |pt| super(pt) }\n end", "def inqfillintstyle\n inquiry_int { |pt| super(pt) }\n end", "def width\n return options[:width] if present?(options[:width])\n return geometry.width if registered?\n\n raise Vedeu::Error::MissingRequired,\n 'The text provided cannot be wrapped or pruned because a ' \\\n ':width option was not given, or a :name option was either not ' \\\n 'given or there is no geometry registered with that name.'\n end", "def width\r\n assert_exists\r\n return @o.invoke(\"width\").to_s\r\n end", "def width=(value)\n\t\t\t@width = value\n\t\tend", "def width=(value)\n\t\t\t@width = value\n\t\tend", "def setwidth\n if @max != nil && !min !=nil then\n @vwidth = @max - @min\n if @min > 0.0 then \n @logmin = log10(@min)\n if @max > 0.0 then\n @logwidth = log10(@max) - log10(@min)\n end\n end\n end\n end", "def width=(width)\n if width.nil?\n fail ArgumentError, 'invalid value for \"width\", width cannot be nil.'\n end\n @width = width\n end", "def length_spec; @length && @length != 0 ? \"[#{@length}\" + (@scale ? '.' + @scale.to_s : '') + ']' : '' end", "def apply_wrap!(opt)\n super(opt, WRAP_FORMATS)\n end", "def apply_wrap!(opt)\n super(opt, WRAP_FORMATS)\n end", "def apply_wrap!(opt)\n super(opt, WRAP_FORMATS)\n end", "def use_autowidth() @use_autowidth; end" ]
[ "0.6885236", "0.6885236", "0.6850314", "0.6584504", "0.6580705", "0.6580705", "0.6580705", "0.6580705", "0.6580705", "0.6580705", "0.6580705", "0.6580705", "0.6580705", "0.6513701", "0.6423407", "0.6402112", "0.6402112", "0.6366919", "0.6365824", "0.63242286", "0.62605226", "0.6189384", "0.6183753", "0.61484295", "0.6144554", "0.61333525", "0.61235064", "0.61105156", "0.61105156", "0.60764635", "0.60405755", "0.6037465", "0.5981728", "0.59611994", "0.5942341", "0.5920635", "0.58910775", "0.58910775", "0.5881999", "0.58801633", "0.5852542", "0.5841667", "0.58343524", "0.5801089", "0.5788564", "0.573943", "0.573943", "0.5733276", "0.5731041", "0.57232904", "0.5722895", "0.57186544", "0.57176536", "0.5711387", "0.5709382", "0.5691764", "0.5691764", "0.5674822", "0.56630385", "0.5660375", "0.5648899", "0.56281394", "0.56274486", "0.56274486", "0.56001174", "0.56001174", "0.55981874", "0.5581606", "0.55732614", "0.55454165", "0.5543704", "0.55074096", "0.5506489", "0.5503384", "0.5498444", "0.5496982", "0.547587", "0.54540384", "0.54502535", "0.5448259", "0.54466665", "0.54277927", "0.5424131", "0.54117155", "0.5410851", "0.5410851", "0.5410851", "0.54017097", "0.5394322", "0.5394322", "0.53920287", "0.53917897", "0.53882784", "0.53882784", "0.53864783", "0.5386396", "0.53842926", "0.538268", "0.538268", "0.538268", "0.5375006" ]
0.0
-1
Fallback is actually generated
def test_fallback_exists File.unstub :exist? tested 'fallback rms.jpg' files = Dir.glob(temp_dir('generated') + '/rms-35-?????????.webp') assert_equal 1, files.length end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fallbacks; end", "def fallbacks; end", "def fallback_data; end", "def fallback_data; end", "def fallbacks=(_arg0); end", "def generate\n throw \"override me before innocent kittens are hurt!\"\n end", "def fallback\n @@fallback\n end", "def fallbacks=(fallbacks); end", "def fallback\n logger.info ap params\n head :ok\n end", "def fallback\n head :ok\n end", "def meth(fallback: nil)\nend", "def meth(fallback: nil)\nend", "def template() false end", "def generate\n super\n end", "def fallback(&block)\n @fallback = true\n result = block.call\n @fallback = false\n result\n end", "def generate\n raise NotImplementedError\n end", "def generate\n raise NotImplementedError\n end", "def ignores; end", "def missing; end", "def special\n override\n end", "def generate\n conflict? ? self.next : normalized\n end", "def fallbacks\n @fallbacks ||= {}\n end", "def generate; end", "def generate; end", "def default; end", "def default; end", "def dynamic?; end", "def miss_reason; end", "def try_fallback(append_mode)\n if ogr2ogr.invalid_dates?\n job.log 'Fallback: Autoguessing problem, trying to disable the problematic column'\n @job.fallback_executed = \"date\"\n ogr2ogr.overwrite = true\n ogr2ogr.csv_guessing = true\n ogr2ogr.quoted_fields_guessing = false\n disable_autoguessing_on_wrong_column(ogr2ogr.filepath, ogr2ogr.command_output)\n ogr2ogr.run(append_mode)\n elsif ogr2ogr.encoding_error?\n job.log \"Fallback: There is an encoding problem, trying with ISO-8859-1\"\n @job.fallback_executed = \"encoding\"\n ogr2ogr.overwrite = true\n ogr2ogr.encoding = \"ISO-8859-1\"\n ogr2ogr.run(append_mode)\n elsif ogr2ogr.missing_srs?\n job.log \"Fallback: Source dataset has no coordinate system, forcing -s_srs 4326\"\n @job.fallback_executed = \"srs 4326\"\n ogr2ogr.overwrite = true\n ogr2ogr.shape_coordinate_system = '4326'\n ogr2ogr.run(append_mode)\n end\n ogr2ogr.set_default_properties\n end", "def generate\n raise \"must implement\"\n end", "def generator\n config[\"default_generator\"] || select_generator\nend", "def custom; end", "def custom; end", "def default?; return !explicit?; end", "def specie; end", "def specie; end", "def specie; end", "def specie; end", "def ignore; end", "def fallback_data\n @fallback_data ||= {}\n end", "def safe_by_default; end", "def missing?; end", "def default_proc() end", "def explicit?; end", "def default_definition() {} end", "def generated\n end", "def create_record_for_not_found_response; end", "def create_Not_Found_Response(request_path)\n\tbody = ''\n\tinitial = generic_Generate_Initial(404)\n\theaders = generic_Generate_Headers(body)\n\tgeneric_Generate_Response(initial,headers,body)\nend", "def regenerator; end", "def skip_paths; end", "def overrides; end", "def explicit; end", "def test_defaults_via\n assert_nothing_raised(ActionController::RoutingError) do\n @rs_defaults_via.generate :controller => :bug\n end\n end", "def weber; end", "def default_for(target)\n case @data[:default]\n when Bolt::PlanFailure\n # Bolt::PlanFailure needs to be declared before Bolt::Error because\n # Bolt::PlanFailure is an instance of Bolt::Error, so it can match both\n # in this case we need to treat Bolt::PlanFailure's in a different way\n #\n # raise Bolt::PlanFailure errors so that the PAL can catch them and wrap\n # them into Bolt::PlanResult's for us.\n raise @data[:default]\n when Bolt::Error\n Bolt::Result.from_exception(target, @data[:default])\n when Hash\n result_for(target, **Bolt::Util.walk_keys(@data[:default], &:to_sym))\n else\n raise 'Default result must be a Hash'\n end\n end", "def fallback_url\n return @fallback_url\n end", "def source(override); end", "def optional_issue_property(fallback = '')\n yield\n rescue\n fallback\n end", "def default_wrapper; end", "def find_templates(name, prefix, partial, details)\n # checks if the format has a fallback chain\n if @fallback_formats.has_key?(details[:formats].first)\n details = details.dup\n details[:formats] = Array.wrap(@fallback_formats[details[:formats].first]) \n end\n super(name, prefix, partial, details)\n end", "def default\n end", "def private; end", "def miss_reason=(_arg0); end", "def do_fallback action\n do_redirect fallback_path\n end", "def default_content; end", "def generate\n end", "def dynamic; end", "def unknown?; false; end", "def unknown?; false; end", "def generate_comprehensive\n\n end", "def overwrite?; end", "def not_found; end", "def template; end", "def template; end", "def template; end", "def template; end", "def template; end", "def template; end", "def template; end", "def generic?; true; end", "def use_template_by_default\n @use_template_by_default || false\n end", "def without_default_proc\n self.default_proc = nil\n\n begin\n yield\n ensure\n self.default_proc = DEFAULT_PROC\n end\n end", "def languagefallback()\n merge(languagefallback: 'true')\n end", "def method_missing(sym, *args)\n\t\t\t\t\tputs \"method_missing: sym = #{sym}\"\n\t\t\t\t\tif sym.to_s =~ /to_ferret$/ then\n\t\t\t\t\t\tputs \"************************** REJECTED **************************\"\n\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telse\n\t\t\t\t\t\tsuper(sym, *args)\n\t\t\t\t\tend\n\t\t\t\tend", "def is_undefined()\n res = super(context,self)\n return res\n end", "def missing_option; end", "def missing_option; end", "def missing_option; end", "def missing_option; end", "def missing_option; end", "def missing_option; end", "def missing_option; end", "def missing_option; end", "def missing_option; end", "def generate\n end", "def update_code_gen_default_value_if_able!\n # we don't support default values for procs\n if @data_type == :string_callback\n @code_gen_default_value = nil\n return\n end\n\n if @code_gen_default_value.nil?\n unless @code_gen_sensitive\n\n @code_gen_default_value = @default_value\n end\n end\n end", "def default_url\n # # For Rails 3.1+ asset pipeline compatibility:\n ActionController::Base.helpers.asset_path(\"fallback/\" + [version_name, \"default.png\"].compact.join('_'))\n \"/assets/fallback/\" + [version_name, \"default.png\"].compact.join('_')\n end", "def original; end", "def render!; raise NotImplementedError end", "def apply; nil; end", "def default_render\n # if this api_method is blank, and error should already have been rendered\n return if @api_method.blank?\n if Rails.env.development? || Rails.env.test_dev?\n @json_response = @api_method.call(params)\n else\n begin\n @json_response = @api_method.call(params)\n rescue ActiveRecord::RecordNotFound => e\n return render_error(e.message, 404)\n rescue EOL::Exceptions::ApiException => e\n return render_error(e.message)\n rescue => e\n EOL.log(\"API error (#{@api_method})\")\n EOL.log_error(e)\n return render_error('Sorry, there was a problem')\n end\n end\n\n # return the JSON object generated above, OR\n # render the default (or custom) partial for this method: e.g. api/search_1_0.xml.builder\n respond_to do |format|\n if @api_method::TEMPLATE\n xml_template = @api_method::TEMPLATE\n else\n xml_template = \"api/#{params[:action]}_#{@api_method::VERSION.tr('.', '_')}\"\n end\n format.xml { render template: xml_template, layout: false }\n format.json { render json: @json_response, callback: params[:callback] }\n end\n end" ]
[ "0.74256533", "0.74256533", "0.6943717", "0.6943717", "0.6911517", "0.66755295", "0.6485262", "0.6407383", "0.6286948", "0.6112707", "0.606089", "0.606089", "0.5886607", "0.5824552", "0.57680345", "0.5754977", "0.57537025", "0.5742189", "0.5737953", "0.5714434", "0.56846344", "0.5676963", "0.56515765", "0.56515765", "0.56391793", "0.56391793", "0.56335145", "0.5581425", "0.55659187", "0.55402285", "0.55355793", "0.55267394", "0.55267394", "0.55188555", "0.5510674", "0.5510674", "0.5510674", "0.5510674", "0.54888964", "0.5434188", "0.5406237", "0.53967625", "0.53834397", "0.53732604", "0.53511643", "0.53327423", "0.53321797", "0.5331581", "0.5325253", "0.53207004", "0.53165466", "0.53165096", "0.5315363", "0.53120697", "0.530514", "0.53021914", "0.52950704", "0.5262779", "0.52610296", "0.52586925", "0.52456075", "0.5242995", "0.523176", "0.52309066", "0.5223534", "0.52158076", "0.521053", "0.51984596", "0.51984596", "0.5189076", "0.5182883", "0.5174707", "0.5172428", "0.5172428", "0.5172428", "0.5172428", "0.5172428", "0.5172428", "0.5172428", "0.51421714", "0.51419866", "0.5134177", "0.512599", "0.5125854", "0.5117239", "0.511624", "0.511624", "0.511624", "0.511624", "0.511624", "0.511624", "0.511624", "0.511624", "0.511624", "0.5115781", "0.5115099", "0.51114464", "0.5108702", "0.510194", "0.5098781", "0.50964195" ]
0.0
-1
Ensure fallback images aren't enlarged when cropped.
def test_cropped_fallback output = tested 'fallback rms.jpg 1:3' assert_includes stderr, 'rms.jpg' assert_match url_matcher(format: 'webp', width: 30), output.at_css('img')['src'] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_that_grids_do_not_work_for_small_imgs\n end", "def default_preset(img)\n img.crop_resized(128, 128, params[:gravity]).quality(75)\n end", "def square_image_crop\n if (self.crops)\n if !(self.crop_x.nil? || self.crop_y.nil? || self.crop_w.nil? || self.crop_h.nil?)\n @image = MiniMagick::Image.open(self.photo.url)\n # if image is larger than our max screen size, the cropped image will be incorrect (resizing)\n @image.sample(((700/@image[:width].to_f) * 100).to_s + \"%\") if @image[:width] > 700\n @image.crop(\"#{self.crop_w}x#{self.crop_h}+#{self.crop_x}+#{self.crop_y}\")\n @image.set(\"page\", \"#{self.crop_w}x#{self.crop_h}+#{self.crop_x}+#{self.crop_y}\") \n self.square_image = @image\n end\n end\n end", "def store_image_dimensions_for_cropping\n save_attached_files # make sure Paperclip stores the files before this callback is executed\n if file.exists?\n img = ThumbMagick::Image.new(file.path('tocrop'))\n w,h = img.dimensions\n self.resize = 1\n self.crop_w = w\n self.crop_h = h\n self.crop_x = self.crop_y = 0\n save_without_versioning\n latest_version.update_attributes(:resize => resize, :crop_w => crop_w, :crop_h => crop_h, :crop_x => 0, :crop_y => 0)\n end\n end", "def recreate_cropped_image\n if file.exists?\n img = ThumbMagick::Image.new(file.path('tocrop'))\n img.\n thumbnail(\"#{ (resize * 100).to_i }%\").\n crop(\"#{crop_w}x#{crop_h}\", crop_x, crop_y).\n write(file.path('cropped'))\n end \n end", "def scale_image_gap?\n true\n end", "def allow_image_cropping?\n content && content.settings[:crop] && picture &&\n picture.can_be_cropped_to?(\n content.settings[:size],\n content.settings[:upsample],\n ) && !!picture.image_file\n end", "def cropping?\n !crop_x.blank? && !crop_y.blank? && !crop_ratio.blank?\n end", "def crop\n return unless model.can_be_cropped?\n manipulate! do |image|\n image.combine_options do |command|\n command.crop(model.magick_thumbnail_coordinates)\n end\n image\n end\n end", "def check_for_resize; end", "def check_size_constraints!(other, offset_x, offset_y)\n if width < other.width + offset_x\n raise ChunkyPNG::OutOfBounds, \"Background image width is too small!\"\n end\n if height < other.height + offset_y\n raise ChunkyPNG::OutOfBounds, \"Background image height is too small!\"\n end\n end", "def no_scale_mask?\n end", "def display_image\n image.variant resize_to_limit: Settings.validation.post.img_resize\n end", "def clean_folder\n return unless cropped_image.croppers.any?\n\n cs = CropperService.new(cropped_image)\n cs.clean_variant_folder\n end", "def can_be_cropped?\n thumbnail_coordinates.present? &&\n thumbnail_coordinates['x'].to_i > 0 &&\n thumbnail_coordinates['y'].to_i > 0 &&\n thumbnail_coordinates['h'].to_i > 0 &&\n thumbnail_coordinates['w'].to_i > 0\n end", "def can_be_cropped?\n thumbnail_coordinates.present? &&\n thumbnail_coordinates['x'].to_i > 0 &&\n thumbnail_coordinates['y'].to_i > 0 &&\n thumbnail_coordinates['h'].to_i > 0 &&\n thumbnail_coordinates['w'].to_i > 0\n end", "def crop_logo\n logo.recreate_versions! if crop_logo_x.present?\n end", "def crop_bgimg\n if crop_x.present?\n bgimg.cache_stored_file!\n bgimg.retrieve_from_cache!(bgimg.cache_name)\n bgimg.recreate_versions!\n end\n end", "def cropping?\n !self.crop_x.blank? && !self.crop_y.blank? && !self.crop_w.blank? && !self.crop_h.blank?\n end", "def test_fallback\n output = tested 'fallback rms.jpg'\n\n assert_match url_matcher(format: 'webp', width: 35),\n output.at_css('img')['src']\n end", "def cropping?\n !crop_x.blank? && !crop_y.blank? && !crop_w.blank? && !crop_h.blank?\n end", "def cropping?\n !crop_x.blank? && !crop_y.blank? && !crop_w.blank? && !crop_h.blank?\n end", "def cropping?\n !crop_x.blank? && !crop_y.blank? && !crop_w.blank? && !crop_h.blank?\n end", "def thumbnail_is_null_if_false\n self.thumbnail = nil unless self.thumbnail?\n end", "def optimize_image!(original)\n original = ImagePath.new(original)\n if result = optimize_image(original)\n result.replace(original)\n true\n end\n end", "def optimize_image!(original)\n original = ImagePath.new(original)\n if result = optimize_image(original)\n result.replace(original)\n true\n end\n end", "def cropping?\n !crop_x.blank? and !crop_y.blank? and !crop_w.blank? and !crop_h.blank?\n end", "def crop?\n @crop\n end", "def crop?\n @crop\n end", "def cropping?\n !crop_x.blank? && !crop_y.blank? && !crop_w.blank? && !crop_h.blank?\n end", "def with_no_cover\n build_image\n self\n end", "def check_for_grey_scale\n checker = true\n self.exam_images.each do |image|\n if image.image_grey_scale == nil\n checker = false\n end\n end\n\n self.update(processed_grey_scale: checker)\n end", "def prepare!(max_side, watermark_img)\n if size == 1 and (columns > max_side or rows > max_side)\n resize_to_fit! max_side\n end\n\n watermark_mc watermark_img\n\n strip!\n end", "def prepDoneDirImages(pdftmp_dir, maxheight, maxwidth, grid, logkey='')\n images = Dir[\"#{Bkmkr::Paths.project_tmp_dir_img}/*\"].select {|f| File.file? f}\n image_count = images.count\n corrupt = []\n processed = []\n\n if image_count > 0\n FileUtils.cp Dir[\"#{Bkmkr::Paths.project_tmp_dir_img}/*\"].select {|f| test ?f, f}, pdftmp_dir\n pdfimages = Dir.entries(pdftmp_dir).select { |f| !File.directory? f }\n pdfimages.each do |i|\n puts \"resizing and grayscaling #{i}\"\n pdfimage = File.join(pdftmp_dir, \"#{i}\")\n if i.include?(\"fullpage\")\n #convert command for ImageMagick should work the same on any platform\n `convert \"#{pdfimage}\" -colorspace gray \"#{pdfimage}\"`\n processed << pdfimage\n else\n myres = `identify -format \"%y\" \"#{pdfimage}\"`\n if myres.nil? or myres.empty? or !myres\n corrupt << pdfimage\n else\n resize = calcImgSizes(myres, pdfimage, maxheight, maxwidth, grid)\n if !resize.match(/^error/)\n `convert \"#{pdfimage}\" -density #{myres} #{resize}-quality 100 -colorspace gray \"#{pdfimage}\"`\n else\n logstring = resize #log any errors returned from calcImgSizes method\n end\n end\n processed << pdfimage\n end\n end\n else\n logstring = 'n-a (no images in done dir)'\n end\n\n return image_count, corrupt, processed\nrescue => logstring\n return '',[],[]\nensure\n Mcmlln::Tools.logtoJson(@log_hash, logkey, logstring)\nend", "def cut_to_fit(options)\n %Q{-thumbnail #{options.width}x#{options.height}^ \\\n -gravity #{options.gravity} \\\n -unsharp 0x.5 \\\n -auto-orient \\\n -extent #{options.width}x#{options.height}}\n end", "def validate_images_alt_present\n errors.add('body', I18n.t('drgcms.img_alt_not_present')) unless DcPage.images_alt_present?(self.body)\nend", "def crop\n return unless model.cropping?\n manipulate! do |img|\n if original_filename.present? && File.extname(original_filename) == '.png'\n image_png = PngQuantizator::Image.new(model.send(mounted_as).path)\n image_png.quantize_to(model.send(mounted_as).path)\n else\n Piet.optimize(model.send(mounted_as).path, :quality => 50)\n end\n image ||= ::Magick::Image::read(model.send(mounted_as).path).first\n x = model.crop_x.to_i * (model.rate.to_f)\n y = model.crop_y.to_i * model.rate.to_f\n w = model.crop_w.to_i * model.rate.to_f\n h = model.crop_h.to_i * model.rate.to_f\n image.crop!(x.to_i, y.to_i, w.to_i, h.to_i)\n end\n end", "def uncropped_dynamic_image_tag(record_or_array, options = {})\n dynamic_image_tag(record_or_array, { action: :uncropped }.merge(options))\n end", "def validate_avatar\n if self.avatar.queued_for_write[:original]\n # self.errors.add(:change_pass)\n dimensions = Paperclip::Geometry.from_file(self.avatar.queued_for_write[:original])\n self.errors.add(:avatar, \"should at least 320px\") if dimensions.width > 320\n end\n end", "def clean_up_paperclip_errors\n errors.delete(:file) if errors[:file] == errors[:file_file_size]\n end", "def manualcrop\n if model.crop?\n x = model.x.to_d\n y = model.y.to_d\n x2 = model.x2.to_d\n y2 = model.y2.to_d\n scale = model.scale.to_d\n\n manipulate! do |img|\n img = img.scale(1/scale)\n img = img.crop(x, y, x2-x, y2-y)\n end\n end\n end", "def uncropped_dynamic_image_url(record_or_array, options = {})\n dynamic_image_url(record_or_array, { action: :uncropped }.merge(options))\n end", "def valid?\n !(image_too_small? || image_too_big?)\n end", "def sanitize_image_url\n if self.image_url \n if self.image_url.first != \"h\"\n self.image_url = \"http://#{self.image_url}\"\n end\n end\n end", "def safe_default_image\n if default_image.try(:filename).present? \n default_image\n elsif self.images.present?\n self.images.first\n else\n Product::generic_default_image\n end\n\n # To populate run task: assets::populate_default_image\n #default_image.presence || Product::generic_default_image\n end", "def cover_image(safe_mode = false)\n kitty_url = FakeImage.new\n cover = images.try(:last) ? images.last : kitty_url\n image = safe_mode == true ? kitty_url : cover\n image\n end", "def cropping?\n !!crop_x and !!crop_y and !!crop_w and !!crop_h\n end", "def apply_image_transformation?\n true\n end", "def save_crop_values\n crop_values = [ crop_x, crop_y, crop_w, crop_h ]\n \n case crop_priority\n when 'primary'\n self.primary_cropping = crop_values\n when 'secondary'\n self.secondary_cropping = crop_values\n else\n errors.add :base, \"Cannot crop without setting a crop priority.\" and return false\n end\n end", "def better?(new_image)\n image.size < MIN_GOOD_IMAGE_SIZE &&\n new_image.size > image.size\n end", "def fallbacks=(fallbacks); end", "def normalize_album(albid)\n require 'fileutils'\n FileUtils.mkdir_p(_(albid, 'thumbs'))\n FileUtils.mkdir_p(_(albid, 'trash'))\n all_images(albid).each{|tuple|\n source, target = _(tuple[:path]), _(tuple[:thumb])\n unless File.exists?(target)\n IMagick.create_thumbnail(source, target)\n end\n }\n end", "def thumbnailable?\n false\n end", "def process_small_image\n small_image.encode!(:png).convert!('-resize 50x50 -gravity center -background none -extent 50x50')\n end", "def cut\n rmagick_img.crop_resized!(@x, @y, gravity)\n end", "def cropping?\n model.cropping?\n end", "def with_crop(left, top, right, bottom); end", "def cover\n\t\tself.image.blank? ? \"default.jpg\" : self.image\n\tend", "def default_url\n \"/images/fallback/\" + [thumb, \"images.jpeg\"].compact.join('_')\n end", "def strict_resize image, w, h\n image.resize \"#{ w }x#{ h }!\"\n image\n end", "def fallbacks; end", "def fallbacks; end", "def image_as_medium_thumbnail\n image.variant(resize_to_fill: [350, 350]).processed\n end", "def sf_fix_imgs(imgs, uri, exts = [])\n sf_check_img_ext(imgs.map do |img|\n img = img.to_s\n unless img =~ sf_regex(:protocol)\n img = sf_fix_protocol(img, sf_domain(uri))\n end\n img if img =~ sf_regex(:image)\n end.compact, exts)\n end", "def is_small_imageable?\n return true\n end", "def prune_images\n if self.images.present?\n self.assets.where('id <> ?',self.default_image_id).destroy_all\n end\n end", "def rounding_error\n dif = (@y-rmagick_img.rows) + (@x-rmagick_img.columns)\n\n if dif > 0 && dif < 10 then\n rmagick_img.resize!(@x, @y)\n end\n end", "def image_is_too_small\n return false if CONFIG[\"min_mpixels\"].nil?\n return false if width.nil?\n return false if width * height >= CONFIG[\"min_mpixels\"]\n true\n end", "def set_image_as_unique_cover\n return unless media_type == 'image'\n cover_file = MediaFile\n .where(attachable: self.attachable, cover: true)\n .where.not(id: id)\n\n if cover?\n cover_file.update_all(cover: false)\n elsif cover_file.blank?\n self.cover = true\n end\n end", "def cover_and_crop(new_width, new_height, &block)\n scale_to_cover(new_width, new_height) do |scaled|\n return block.call(scaled) if new_width == scaled.width && new_height == scaled.height\n scaled.crop_to(new_width || width, new_height || height, &block)\n end\n end", "def set_defaults\n self.main_image ||= Placeholder.image_generator(height: '600', width: '400')\n self.thumb_image ||= Placeholder.image_generator(height: '350', width: '200')\n end", "def set_defaults\n self.main_image ||= Placeholder.image_generator(height: '600', width: '400')\n self.thumb_image ||= Placeholder.image_generator(height: '350', width: '200')\n end", "def set_defaults\n self.main_image ||= Placeholder.image_generator(height: '600', width: '400')\n self.thumb_image ||= Placeholder.image_generator(height: '350', width: '200')\n end", "def check_and_resize_images(path)\n # We don't want to modify the path so create\n # a temporary glob path and retain the original\n #\n # Just a simple hack to allow us to pass `path` to\n # the resize! method at the end of this method.\n glob_path = path\n glob_path += '/**/*'\n\n # Check the images before including the extensions\n # into the extensions attribute\n Dir.glob(glob_path) do |img|\n if image?(img)\n # get the extension of the file and making sure it is\n # included in the formats we have required to be valid\n ext = File.extname(img).gsub('.', '').downcase\n\n # This could be improved\n if VALID_FORMATS.map { |format| format.downcase }.include?(ext)\n extension = { name: ext }\n self.extensions << extension unless self.extensions.include?(extension)\n end\n end\n end\n\n # only resize if there are any files\n resize!(path) unless extensions.empty?\n end", "def image_1_is_from_google?\n !image_1_google_thumb.blank?\n end", "def check_print_image_mask_size\n return if print_image_mask.blank?\n expect_width = (width / 25.4 * dpi).to_i\n expect_height = (height / 25.4 * dpi).to_i\n # FIXME: private API may broken in the future, but we really need it at this time\n actual_width, actual_height = print_image_mask.send(:get_dimensions)\n return if actual_width == expect_width && actual_height == expect_height\n self.warning = \"上傳的遮罩圖大小為 #{actual_width}x#{actual_height}, 但產品圖的大小為 #{expect_width}x#{expect_height}\"\n end", "def url() processed_image.try(:url) || fallback_url end", "def cover?(options={})\n !options[:amazon] && cover_img\n end", "def remove_all_images\n self.cover_image.purge if self.cover_image.attached?\n self.images.each {|image| image.purge} if self.images.attached?\n end", "def no_attachment_errors\n unless label_image.errors.empty?\n # uncomment this to get rid of the less-than-useful interrim messages\n # errors.clear\n errors.add :label_image, \"Paperclip returned errors for file '#{label_image_file_name}' - check ImageMagick installation or image source file.\"\n false\n end\n end", "def display_image \r\n self.image.variant(resize_to_limit: [1000, 1000]) \r\n end", "def uncropped_dynamic_image_path(record_or_array, options = {})\n dynamic_image_path(record_or_array, { action: :uncropped }.merge(options))\n end", "def autosize(img_pub_path, opts)\n if opts[:maxwidth]\n if opts[:exact]\n width_opts = \"w#{opts[:maxwidth]}\"\n else\n width_opts = \"mxw#{opts[:maxwidth]}\"\n end\n else\n width_opts = \"wa\"\n end\n\n if opts[:maxheight]\n if opts[:exact]\n height_opts = \"h#{opts[:maxheight]}\"\n else\n height_opts = \"mxh#{opts[:maxheight]}\"\n end\n else\n height_opts = \"ha\"\n end\n\n ext = rescue_me(\".jpg\"){ img_pub_path[img_pub_path.rindex(\".\")..-1] }\n img_fixed_pub_path = \"#{img_pub_path}.#{width_opts}.#{height_opts}#{ext}\"\n\n img_priv_path = \"public#{img_pub_path}\"\n img_fixed_priv_path = \"public#{img_fixed_pub_path}\"\n\n unless File.exists?(img_fixed_priv_path)\n if(File.exists?(img_priv_path))\n begin\n img = MiniMagick::Image.from_file(img_priv_path)\n img.resize \"#{opts[:maxwidth]}x#{opts[:maxheight]}\"\n img.write img_fixed_priv_path\n rescue\n logger.error(\"Error writing image auto-resize: #{img_fixed_priv_path}: #{$!}\")\n end\n else\n logger.error(\"File does not exist: #{img_priv_path}\")\n end\n end\n\n return img_fixed_pub_path\n end", "def square_images\n @template[:message][:attachment][:payload][:image_aspect_ratio] = 'square'\n self\n end", "def apply_post_processing?\n if self.has_default_image?\n return false\n else\n return true\n end\n end", "def correct_image_type\n if image.attached? && !image.content_type.in?(%w(image/jpeg image/gif image/png))\n errors.add(:image, :blank, message: I18n.t(\"validates.image_format\"))\n end\n end", "def scale_crop=(v)\n Axlsx.validate_boolean v\n @scale_crop = v\n end", "def get_image_or_placeholder\n return (self.image != \"\") && (self.image != nil) ? self.image : \"http://cdn.browshot.com/static/images/not-found.png\"\n end", "def get_image_or_placeholder\n return (self.image != \"\") && (self.image != nil) ? self.image : \"http://cdn.browshot.com/static/images/not-found.png\"\n end", "def resize_to_fill(new_width, new_height)\n manipulate! do |image|\n\n image = resize_image image, new_width, new_height, :max\n\n if image.width > new_width\n top = 0\n left = (image.width - new_width) / 2\n elsif image.height > new_height\n left = 0\n top = (image.height - new_height) / 2\n else\n left = 0\n top = 0\n end\n\n # Floating point errors can sometimes chop off an extra pixel\n # TODO: fix all the universe so that floating point errors never happen again\n new_height = image.height if image.height < new_height\n new_width = image.width if image.width < new_width\n\n image.extract_area(left, top, new_width, new_height)\n\n end\n end", "def revise_cover_status\n if self.cover?\n Plant.find(self.plant_id).pictures.each do |picture|\n if (picture.cover? && picture.id != self.id)\n picture.cover = false\n picture.save\n end\n end\n end\n end", "def default_image_exists?\n !!(File.exists? Rails.root.join('public',\"#{default_image_path}_medium.jpg\"))\n end", "def set_defaults\n\t\tself.main_image ||= Placeholder.image_generator(height: '200', width: '200')\n\t\tself.thumb_image ||= Placeholder.image_generator(height: '300', width: '300')\n\tend", "def resize_all(size_constraint)\n require 'rmagick'\n\n Dir.new('.').each do |f|\n if f.match(/jpg/)\n if (i = Magick::Image.read(f).first)\n i.resize_to_fit!(size_constraint)\n i.write(f)\n end\n end\n end\nend", "def acts_as_image_holder(options={ })\n options = Options.new(options)\n \n #\n # define validators\n #\n validates_each options.images.collect(&:field) do |record, attr, value|\n record.instance_eval do \n if @__acts_as_image_holder_problems and !@__acts_as_image_holder_problems.blank?\n self.errors.add attr, \"is not an image\" if @__acts_as_image_holder_problems[attr] == :not_an_image\n self.errors.add attr, \"has wrong type\" if @__acts_as_image_holder_problems[attr] == :wrong_type\n \n elsif options.images.find{ |i| i.field == attr }.required and self[attr].blank?\n self.errors.add attr, \"is required\"\n end\n end\n end\n \n #\n # define the image files setting handling\n #\n options.images.each do |image|\n define_method \"#{image.field}=\" do |file|\n @__acts_as_image_holder_problems ||= { }\n @__acts_as_image_holder_filedata ||= { }\n @__acts_as_image_holder_thumbsdata ||= { }\n \n return if file.blank?\n \n begin\n # reading and converting the file\n filedata = ImageProc.prepare_data(file, image)\n origdata = ImageProc.to_blob(file) if image.original\n thumbs = image.thumbs.collect{ |thumb| [thumb, ImageProc.prepare_data(file, thumb)] }\n \n # check if the file has a right type\n if image.allowed_type? ImageProc.get_type(file)\n if options.directory\n # save the data for the future file-writting\n @__acts_as_image_holder_filedata[image.field] = filedata\n @__acts_as_image_holder_filedata[image.original] = origdata if origdata\n thumbs.each do |thumb|\n @__acts_as_image_holder_thumbsdata[thumb[0].field] = thumb[1]\n end\n \n # presetting the filenames for the future files\n self[image.field] = FileProc.guess_file_name(options, file, image)\n self[image.original] = FileProc.guess_original_file_name(options, file) if origdata\n image.thumbs.each do |thumb, i|\n self[thumb.field] = FileProc.guess_thumb_file_name(options, file, thumb, i)\n end\n \n else\n # blobs direct assignment\n self[image.field] = filedata\n self[image.original] = origdata\n thumbs.each do |thumb|\n self[thumb[0].field] = thumb[1]\n end\n end\n \n self[image.type_field] = \"#{ImageProc.get_type(filedata)}\" if image.type_field\n \n else\n @__acts_as_image_holder_problems[image.field] = :wrong_type\n end\n \n rescue Magick::ImageMagickError\n @__acts_as_image_holder_problems[image.field] = :not_an_image\n end\n end\n end\n \n #\n # defining file-based version additional features\n #\n if options.directory\n # assigning a constant to keep it trackable outside of the code\n const_set 'FILES_DIRECTORY', options.directory\n \n #\n # file url locations getters\n #\n options.images.each do |image|\n define_method \"#{image.field}_url\" do \n __file_url_for self[image.field] unless self[image.field].blank?\n end\n \n if image.original\n define_method \"#{image.original}_url\" do \n __file_url_for self[image.original] unless self[image.original].blank?\n end\n end\n \n image.thumbs.each do |thumb|\n define_method \"#{thumb.field}_url\" do \n __file_url_for self[thumb.field] unless self[thumb.field].blank?\n end\n end\n end\n \n # common file-urls compiler\n define_method \"__file_url_for\" do |relative_filename|\n full_filename = options.output_directory + relative_filename\n public_dir = \"#{RAILS_ROOT}/public\"\n \n full_filename[public_dir.size, full_filename.size]\n end\n \n \n #\n # define files handling callbacks\n #\n after_save :acts_as_image_holder_write_files\n after_destroy :acts_as_image_holder_remove_files\n \n # writting down the files\n define_method :acts_as_image_holder_write_files do \n [@__acts_as_image_holder_filedata, @__acts_as_image_holder_thumbsdata].each do |data_collection|\n data_collection.each do |field_name, filedata|\n FileProc.write_file(options, self[field_name], filedata)\n end\n end\n end\n \n # removing related files after the record is deleted\n define_method :acts_as_image_holder_remove_files do \n options.images.each do |image|\n FileProc.remove_file(options, self[image.field])\n FileProc.remove_file(options, self[image.original]) if image.original\n image.thumbs.each do |thumb|\n FileProc.remove_file(options, self[thumb.field])\n end\n end\n end\n end\n \n #\n # Some additional useful images handling methods\n #\n module_eval <<-\"end_eval\"\n #\n # Resize a file and a blob-string\n #\n # @param file - File object or a string file-path\n # @param size - [width, height] array or a \"widthxheight\" string\n # @param format - \"gif\", \"jpeg\", \"png\", or nil to keep the same\n # @param quality - jpeg - quality 0 - 100, nil to keep the same\n #\n def resize_file(file, size, format=nil, quality=nil)\n file = File.open(file) if file.is_a? String\n ActsAsImageHolder::ImageProc.resize(file, size, format, quality)\n end\n \n def resize_blob(blob, size, format=nil, quality=nil)\n ActsAsImageHolder::ImageProc.resize(blob, size, format, quality)\n end\n \n #\n # Puts a watermark on the given image with the given options\n #\n def watermark_file(file, options)\n ActsAsImageHolder::ImageProc.watermark(file, options)\n end\n \n def watermark_blob(blob, options)\n ActsAsImageHolder::ImageProc.watermark_blob(blob, options)\n end\n end_eval\n end", "def imagemagick7?; end", "def no_scale_mask=(scale_mask)\n end", "def find_and_resize!(path)\n check_and_resize_images(path)\n end", "def determine_whether_to_resize_image\n if label == :access && pdf? && format == \"pdf\"\n output_file = directives.fetch(:url).split('file:')[1]\n begin\n _stdin, _stdout, _stderr = popen3(\"cp #{source_path} #{output_file}\")\n rescue StandardError => e\n Rails.logger.error(\"#{self.class} copy error: #{e}\")\n end\n else\n create_resized_image\n end\n end", "def setup_available_sizes(file)\n# ::Rails.logger.debug \"setup_available_sizes: #{file.path}\"\n# if model.original_image_width.nil? || model.original_image_height.nil?\n# \n# img = ::Magick::Image::read(@file.file).first\n# model.original_image_width = img.columns\n# model.original_image_height = img.rows\n# ::Rails.logger.debug \"setup w/h for validtaion #{img.columns}x#{img.rows}\"\n# end\n\n model.class::IMAGE_CONFIG.keys.each do |key|\n self.class_eval do\n define_method(\"has_#{key}_config?\".to_sym) { |file| true }\n end\n end\n end" ]
[ "0.5822013", "0.5747133", "0.56986934", "0.567421", "0.5615147", "0.56128144", "0.5590237", "0.5526051", "0.5507453", "0.54916936", "0.54382104", "0.543451", "0.5424528", "0.5408385", "0.53995377", "0.53995377", "0.53948313", "0.5390894", "0.53841573", "0.53549534", "0.53278434", "0.53278434", "0.53278434", "0.53275704", "0.5322249", "0.5322249", "0.5283595", "0.52744687", "0.52744687", "0.52599657", "0.5259498", "0.5248248", "0.52379525", "0.52348036", "0.5229611", "0.5213043", "0.52121514", "0.520564", "0.51942474", "0.51933086", "0.519129", "0.5189447", "0.5158007", "0.5155157", "0.5123603", "0.5122001", "0.5118001", "0.5115016", "0.51102096", "0.50996196", "0.5094878", "0.5090498", "0.5089347", "0.5082712", "0.5065619", "0.5061683", "0.5054354", "0.50471175", "0.50379443", "0.503209", "0.5025445", "0.5025445", "0.50137645", "0.50094414", "0.49947038", "0.4977128", "0.49712837", "0.49694133", "0.4948714", "0.49486136", "0.4948441", "0.4948441", "0.4948441", "0.49455148", "0.49378046", "0.49340925", "0.49275294", "0.49266925", "0.49198627", "0.49197587", "0.49169418", "0.49157768", "0.4912805", "0.49086735", "0.4906545", "0.48956755", "0.489028", "0.4867615", "0.4867615", "0.48656267", "0.48567384", "0.48461792", "0.48351294", "0.48284835", "0.48238137", "0.48189834", "0.4809907", "0.48010004", "0.47977084", "0.47962552" ]
0.6703654
0
convert from each to each, make sure nothing breaks.
def test_conversions File.unstub(:exist?) formats = supported_formats presets['formats']['formats'] = formats formats.each do |input_format| output = tested "formats rms.#{input_format}" sources = output.css('source') formats.each do |output_format| mime = MIME::Types.type_for(output_format).first.to_s assert(sources.any? { |source| source['type'] == mime }, "Failed to generate a source with type #{mime}") end end files = Dir.entries(temp_dir('generated')) formats.each do |format| assert_equal( formats.length, files.count { |f| File.extname(f) == '.' + format } ) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def each\n to_a.each\n end", "def each\n to_a.each\n end", "def each\n to_a.each\n end", "def loop_through\n self.map! do |element| \n if !element.is_a?(Array)\n element\n elsif element.is_a?(Array)\n element = element.dup\n element = element.loop_through\n end\n end\n end", "def each(&block); end", "def each(&block); end", "def each(&block); end", "def each(&block); end", "def each(&block); end", "def each(&block); end", "def convert!\n # Fonts and headings\n semanticize_font_styles!\n semanticize_headings!\n\n # Tables\n remove_paragraphs_from_tables!\n semanticize_table_headers!\n\n # list items\n remove_paragraphs_from_list_items!\n remove_unicode_bullets_from_list_items!\n remove_whitespace_from_list_items!\n remove_numbering_from_list_items!\n end", "def to_a\n each.force\n end", "def each(*) end", "def test_try_each_instead_of_collect_change_array\n array = [1, 2, 3]\n array = array.each { |item| item + 10 }\n #assert_equal [11, 12, 13], array\n assert_equal [1, 2, 3], array\n end", "def transform_array_with_each(array)\n # On crée un tableau avant de faire l'itération.\n # On itère sur le tableau. Notez qu'il s'appelle \"array\" étant donné que c'est le paramètre\n # de la fonction.\n # On détecte les emails grâce au regex.\n # On élimine les cases vides grâce à la condition (ici unless).\n # On intègre les résultats au tableau.\n # On retourne le tableau results désormais rempli.\n # Notez qu'il faut le retourner sinon la fonction\n # renvoie la variable tweets.\n\n results = []\n array.each do |tweet|\n email = \"#{tweet.text}\".match(/\\w+\\.?\\+?\\w+?@\\w+\\-?\\w+\\.\\w+/)\n results << email.to_s unless email == nil\n end\n results\nend", "def each\n self.to_a.each do |el|\n yield(el)\n end\n end", "def each\n raise 'Not implemented'\n end", "def each; end", "def each; end", "def each; end", "def each; end", "def each; end", "def each; end", "def each; end", "def each; end", "def each; end", "def each; end", "def each; end", "def each(&block)\n to_a.each(&block)\n end", "def each_identity; end", "def each\n # passes block - if any - to upstream each.\n to_a.each(&Proc.new)\n end", "def clean\n (1..@rows).each do |x|\n (1..@cols).each do |y|\n self.cleanCell(x, y)\n end\n end\n end", "def each\n\t\t\[email protected]\n\t\tend", "def deconvert\n result = []\n yield result\n array.each do |converted_item|\n result << UniversalDumper.deconvert(converted_item)\n end\n result\n end", "def each(&blk)\n to_a.each(&blk)\n end", "def each\n yield self[0]\n yield self[1]\n end", "def convert_br(el)\r\n end", "def through; end", "def each_raw\n iterator.each { |i| yield i }\n end", "def each(&block)\n to_a.each(&block)\n end", "def each(&block)\n to_a.each(&block)\n end", "def each()\n self.to_a.each { |elt| yield elt }\n end", "def each\n return unless @result\n\n @result.each(as: :hash, symbolize_keys: true) do |row|\n next unless row # This sometimes happens when streaming results...\n row = Hash[row.map { |k, v| [k, v.to_s] }] if @type_translation == :string\n yield row\n end\n end", "def each(&blk)\r\n to_a.each(&blk)\r\n end", "def each\n for each element\n yield(element)\n end\nend", "def each\n yield to_s\n end", "def each\n yield to_s\n end", "def each\n super do |vals|\n yield [vals[0], unmarshal(vals[1])]\n end\n end", "def clean_result_rows\n raise \"Missing data\" if result_rows.empty?\n result_rows.map do |result|\n next if is_header_row?(result) || is_bye_week?(result)\n result\n end.compact\n end", "def each\n @reaktor_rows\n end", "def each()\n cur = @first\n while cur\n yield cur.value\n cur = cur.next\n end\n end", "def each(&a_proc); end", "def each(&block)\n to_a.each(&block)\n end", "def each # And define each on top of next\n loop {yield self.next }\n end", "def transform_values!; end", "def each_mid(&block)\n \n end", "def coerce(value)\n coerced = super\n return coerced unless coerced.respond_to?(:each_with_object)\n coerced.each_with_object(new_collection) do |entry, collection|\n coerce_and_append_member(collection, entry)\n end\n end", "def each a\n\ti = 0\n\tuntil i == a.size\n\t\tyield a[i]\n\t\ti += 1\n\tend\n\ta\nend", "def normalize!\n new_contents = []\n @contents.each{|c|\n if c.is_a? String\n next if c == \"\"\n if new_contents[-1].is_a? String\n new_contents[-1] += c\n next\n end\n else\n c.normalize!\n end\n new_contents.push c\n }\n @contents = new_contents\n end", "def reformat_for_next_generation!\n # create an array of dead cells and insert it as the first and last row of cells\n dead_cells = ([email protected]).map { Cell.new }\n # don't forget to deep copy the dead_cells\n @cells.unshift Marshal.load(Marshal.dump(dead_cells))\n @cells.push Marshal.load(Marshal.dump(dead_cells))\n\n # also insert a dead cell at the left and right of each row\n @cells.each do |row|\n row.unshift Cell.new\n row.push Cell.new\n end\n\n # validate to see if we broke the board\n validate\n end", "def each!\r\n each do |item, i, j|\r\n @table[i][j] = yield(@table[i][j], i, j) || @table[i][j]\r\n end\r\n\r\n self # Chainability! Yay!\r\n end", "def through\n dup\n end", "def each\n end", "def each(&block)\n end", "def each\n all.each do |el|\n yield el\n end\n end", "def each\n yield self\n end", "def _normalize( rows )\n rows.map do |row|\n h = row['_id']\n h['value'] = row['value'].to_i\n h\n end\n ensure\n rows.close\n end", "def process_into(output)\n while (!@input_row.nil?)\n output << shift\n end\n end", "def each_cell\n\t\teach_row do |row|\n\t\t\trow.each do |cell|\n\t\t\t\tyield cell if cell\n\t\t\tend\n\t\tend\n\tend", "def each\n @rows.each {|x| x.each {|e| yield(e)}}\n nil\n end", "def tidy(data); end", "def transformed_entries entries\n\t\tentries\n\tend", "def each\n current = @sentinel.next\n while current != @sentinel\n yield current.data\n current = current.next\n end\n end", "def each_set\n \n end", "def each\n all.each do |el|\n yield el\n end\n end", "def each_pair(*) end", "def cleanup(results)\n results.map { |r| r.value.strip }.reject(&:empty?).uniq\n end", "def cleanup(results)\n results.map { |r| r.value.strip }.reject(&:empty?).uniq\n end", "def each\n while row=self.next\n yield row\n end\n end", "def each\n while row=self.next\n yield row\n end\n end", "def break_types!(types)\n self.each_node do |node|\n # Need to break only in the case of a cast.\n if node.is_a?(Cast) then\n # node.type.break_types!(types)\n node.set_type!(node.type.break_types!(types))\n end\n end\n end", "def each\n end", "def each\n end", "def each\n end", "def each\n end", "def each\n end", "def each\n end", "def each\n @collection.each { |c| yield c }\n end", "def each\n# And define each on top of next\nloop { yield self.next }\nend", "def each\n# And define each on top of next\nloop { yield self.next }\nend", "def _each(&block)\n _next.each(&block) if _next\n end", "def break_types!(types)\n self.each_node do |node|\n node.break_types!(types)\n end\n end", "def each\n @source.each do |elem|\n yield DropDelegation.wrap_element(elem)\n end\n end", "def each\n group.each\n end", "def each # And define each on top of next\n loop { yield self.next }\n end", "def my_array_splitting_method(source)\n \n ints = []\n other = []\n out = []\n \n source.each {|idx| if idx.is_a?(Integer) then ints.push(idx) else other.push(idx) end}\n out.push(ints, other)\n \n p out\nend", "def break_types!(types)\n self.each_node do |node|\n # Need to break only in the case of a cast.\n if node.is_a?(Cast) then\n node.type.break_types!(types)\n end\n end\n end", "def flat_each(&block)\n map do |value|\n if value.is_a?(Enumerable)\n value.each(&block)\n else\n yield value\n end\n end\n end", "def each\n\n\t\[email protected] do |x|\n\t\t\tyield x\n\t\tend\n\tend", "def each\n self\n end", "def convert(el, opts = { indent: 0 })\n res = send(\"convert_#{el.type}\", el, opts)\n if !%i[html_element li dt dd td].include?(el.type) && (ial = ial_for_element(el))\n res << ial\n res << \"\\n\\n\" if Element.category(el) == :block\n elsif %i[ul dl ol codeblock].include?(el.type) && opts[:next] &&\n ([el.type, :codeblock].include?(opts[:next].type) ||\n (opts[:next].type == :blank && opts[:nnext] && [el.type, :codeblock].include?(opts[:nnext].type)))\n res << \"^\\n\\n\"\n elsif Element.category(el) == :block &&\n ![:li, :dd, :dt, :td, :th, :tr, :thead, :tbody, :tfoot, :blank].include?(el.type) &&\n (el.type != :html_element || @stack.last.type != :html_element) &&\n (el.type != :p || !el.options[:transparent])\n res << \"\\n\"\n end\n res\n end" ]
[ "0.56226206", "0.56226206", "0.56226206", "0.5456607", "0.54258895", "0.54258895", "0.54258895", "0.54258895", "0.54258895", "0.54258895", "0.5334028", "0.5311052", "0.52786386", "0.5277227", "0.5263029", "0.52068317", "0.51996076", "0.51908195", "0.51908195", "0.51908195", "0.51908195", "0.51908195", "0.51908195", "0.51908195", "0.51908195", "0.51908195", "0.51908195", "0.51908195", "0.5165478", "0.5160116", "0.51284647", "0.512617", "0.51063967", "0.509872", "0.5081488", "0.50648904", "0.505084", "0.5043628", "0.5041429", "0.50410897", "0.50410897", "0.5029443", "0.5020795", "0.49842808", "0.49831128", "0.49805608", "0.49805608", "0.4979865", "0.49711335", "0.49682", "0.49602136", "0.49548835", "0.49501848", "0.49345928", "0.49339166", "0.4924855", "0.4918329", "0.4917016", "0.49162233", "0.48976654", "0.48948193", "0.48844603", "0.48830554", "0.48763052", "0.48756546", "0.48743305", "0.4873106", "0.48707688", "0.48683816", "0.48647255", "0.48580128", "0.48540387", "0.4850387", "0.48486683", "0.48411077", "0.48409724", "0.48235944", "0.48235944", "0.48175827", "0.48175827", "0.4812231", "0.4800588", "0.4800588", "0.4800588", "0.4800588", "0.4800588", "0.4800588", "0.47965777", "0.47950494", "0.47950494", "0.47882947", "0.478241", "0.47823256", "0.47810832", "0.47791496", "0.47751182", "0.4774466", "0.47708446", "0.4756152", "0.47489408", "0.4747137" ]
0.0
-1
If width and height are set in the preset, they should be overridden rather than appended.
def test_dimension_attributes_replace_values output = tested 'dimension_attributes_replace_values rms.jpg' assert_equal '100', output.at_css('img')['width'] assert_equal '89', output.at_css('img')['height'] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_defaults\n self.width ||= 0.20\n self.height ||= 0.20\n end", "def size=(width, height)\n end", "def set_size(w=nil, h=nil)\n @window_width = w if w.is_a?(Numeric) && w > 0 # TODO: > min_width\n @window_height = h if h.is_a?(Numeric) && h > 0 # TODO: > min_height\n super(@window_width, @window_height)\nend", "def setPixelSize(width, height)\n setWidth(width + \"px\") # if width >= 0\n setHeight(height + \"px\") # if height >= 0\n end", "def set_size(params = {})\n @width = params[:width] if params[:width]\n @height = params[:height] if params[:height]\n @x_scale = params[:x_scale] if params[:x_scale]\n @y_scale = params[:y_scale] if params[:y_scale]\n @x_offset = params[:x_offset] if params[:x_offset]\n @y_offset = params[:y_offset] if params[:y_offset]\n end", "def setSize(width, height)\n setWidth(width)\n setHeight(height)\n end", "def settings\n size 400, 300\nend", "def size(width, height)\n self.width = width\n self.height = height\n end", "def update!(**args)\n @height = args[:height] if args.key?(:height)\n @width = args[:width] if args.key?(:width)\n end", "def update!(**args)\n @height = args[:height] if args.key?(:height)\n @width = args[:width] if args.key?(:width)\n end", "def update!(**args)\n @height = args[:height] if args.key?(:height)\n @width = args[:width] if args.key?(:width)\n end", "def set_size(width = nil, height = nil)\n @window_width = if ptrue?(width)\n # Convert to twips at 96 dpi.\n width.to_i * 1440 / 96\n else\n 16095\n end\n\n @window_height = if ptrue?(height)\n # Convert to twips at 96 dpi.\n height.to_i * 1440 / 96\n else\n 9660\n end\n end", "def update!(**args)\n @original_height_px = args[:original_height_px] if args.key?(:original_height_px)\n @original_width_px = args[:original_width_px] if args.key?(:original_width_px)\n end", "def dimensions(val); @dimensions = val; self; end", "def size=(size)\n self.width = self.height = @size = size\n end", "def fit_to(options = {})\n self.fit_to_width = options[:width] || 999\n self.fit_to_height = options[:height] || 999\n [@fit_to_width, @fit_to_height]\n end", "def width(val); @width = val; self; end", "def set_dimensions!\n # Silently return, if there's no `width` and `height`\n # Prevents old migrations from crashing\n return unless self.respond_to?(:width) && self.respond_to?(:height)\n\n geometry = extract_dimensions\n\n if geometry\n self.width = geometry.width.to_i\n self.height = geometry.height.to_i\n end\n end", "def size(width, height)\n if !width.nil? && (width.to_i > 0) && !height.nil? && (height.to_i > 0)\n @width = width\n @height = height\n @chart_size = nil\n end\n self\n end", "def width=(width)\n end", "def update!(**args)\n @dpi = args[:dpi] if args.key?(:dpi)\n @height_px = args[:height_px] if args.key?(:height_px)\n @m_size = args[:m_size] if args.key?(:m_size)\n @neng_size = args[:neng_size] if args.key?(:neng_size)\n @width_px = args[:width_px] if args.key?(:width_px)\n end", "def set_size(w,h)\n @width = w\n @height = h\n end", "def update!(**args)\n @height = args[:height] if args.key?(:height)\n @unit = args[:unit] if args.key?(:unit)\n @width = args[:width] if args.key?(:width)\n end", "def fit_width; end", "def update!(**args)\n @height_pixels = args[:height_pixels] if args.key?(:height_pixels)\n @width_pixels = args[:width_pixels] if args.key?(:width_pixels)\n end", "def update!(**args)\n @height_pixels = args[:height_pixels] if args.key?(:height_pixels)\n @width_pixels = args[:width_pixels] if args.key?(:width_pixels)\n end", "def configure(x: nil, y: nil, scale: nil)\n @x = x if x\n @y = y if y\n @scale = scale if scale\n self\n end", "def add_size!\n input_html_options[:size] ||= nil\n end", "def initialize(width:, height:)\n @width = width\n @height = height\n end", "def sized(width, height)\n\t\t\t@sized_thumb = @template\n\t\t\t@sized_thumb.sub! \"{width}\", width.to_s\n\t\t\t@sized_thumb.sub! \"{height}\", height.to_s\n\t\tend", "def set_original\n if keep_original\n if size_o.blank?\n image = MiniMagick::Image.open(name)\n self.size_o = \"#{image.width}x#{image.height}\"\n end\n else\n self.size_o = ''\n end\nend", "def set_scaled_info(lbl, width, height)\r\n @cards_scaled_info[lbl] = {:w => width, :h => height}\r\n end", "def set_defaults\n\t\tself.main_image ||= Placeholder.image_generator(height: '600', width: '400')\n\t\tself.thumb_image ||= Placeholder.image_generator(height: '350', width: '200')\n\tend", "def set_dimensions!\n if RMAGICK_SUPPORTED\n #MES- Turn the blob into an ImageMagick object\n img = Magick::Image.from_blob(data).first\n if img.nil?\n raise \"Error: could not get imagemagick image from picture #{self.id}'s data\"\n end\n \n #KS- grab width & height and save them\n self.height = img.rows\n self.width = img.columns\n end\n end", "def setCanvasSize\n if @intTargetX.to_s.to_i > 20 and @intTargetY.to_s.to_i > 20\n puts('setting new dimetions')\n @canvasRefrance.resizeCanvas(@intTargetY.to_s.to_i,@intTargetX.to_s.to_i)\n else \n puts('setting defult dimentions')\n @canvasRefrance.resizeCanvas(@minDimensions,@minDimensions)\n end\n end", "def setscale(*)\n super\n end", "def resize!\n end", "def resize(width, height); end", "def set_defaults\n self.main_image ||= Placeholder.image_generator(height: '600', width: '400')\n self.thumb_image ||= Placeholder.image_generator(height: '350', width: '200')\n end", "def set_defaults\n self.main_image ||= Placeholder.image_generator(height: '600', width: '400')\n self.thumb_image ||= Placeholder.image_generator(height: '350', width: '200')\n end", "def set_defaults\n self.main_image ||= Placeholder.image_generator(height: '600', width: '400')\n self.thumb_image ||= Placeholder.image_generator(height: '350', width: '200')\n end", "def set_defaults\n\t\tself.main_image ||= Placeholder.image_generator(height: '200', width: '200')\n\t\tself.thumb_image ||= Placeholder.image_generator(height: '300', width: '300')\n\tend", "def set_styles\n if self.class_type == 'variant'\n {:thumb => '300x300!'}\n elsif self.class_type == 'banner'\n {:banner => '800x100!'}\n elsif self.class_type == 'logo'\n {:logo => '400x60>'}\n end\n end", "def set_defaults\n self.main_image ||= Placeholder.image_generator(height: '600', width: '400')\n self.thumb_image ||= Placeholder.image_generator(height: '350', width: '200')\n end", "def initialize(**opts)\n defaults = {\n width: 1024,\n height: 768,\n method: :scale_by_bounds\n }\n super(opts, defaults)\n end", "def resizes_if_necessary\n if(@kv_height > @interieur_height || @kv_width > @interieur_width)\n @kv_height = (@kv_height / 2).ceil \n @kv_width = (@kv_width / 2).ceil \n resizes_if_necessary\n end\n end", "def initialize\n\t\t@height = 5\n\tend", "def initialize(width, height)\r\n \t#variables de instancia\r\n @width = width\r\n @height = height\r\n end", "def size=(size='300x200')\n @width, @height = size.split(\"x\").map { |dimension| dimension.to_i }\n end", "def defaults\n {\n height: Vedeu.height,\n name: nil,\n width: Vedeu.width,\n }\n end", "def height=(height)\n end", "def resize(width, height)\n end", "def initialize(width, height)\n @width = width\n @height = height\n @impassable_cells = Set.new\n end", "def initialize_dimensions\n @width = 150\n @height = 48\n @wheels_front = 31\n @wheels_rear = 126\n end", "def resize_to(width, height); end", "def record(width, height, &rendering_code); end", "def width=(val)\n super\n fire_dimension_changed :width\n end", "def set_dimensions\n\t\timg = Magick::Image::read(\"#{Rails.root}/public\"+image_url(:image).to_s).first\n\t\tself.width = img.columns\n\t\tself.height = img.rows\n\t\tself.size \t= img.filesize\n\t\tif self.v.nil? then self.v = 0 end\n\t\tself.url \t= img.filename\n\tend", "def update!(**args)\n @height = args[:height] if args.key?(:height)\n @horizontal_offset = args[:horizontal_offset] if args.key?(:horizontal_offset)\n @vertical_offset = args[:vertical_offset] if args.key?(:vertical_offset)\n @width = args[:width] if args.key?(:width)\n end", "def setwidth(width)\n @width = width\n end", "def set_image_size(file = local_file_name(:full_size))\n w, h = FastImage.size(file)\n return unless /^\\d+$/.match?(w.to_s)\n\n self.width = w.to_i\n self.height = h.to_i\n save_without_our_callbacks\n end", "def setCanvasDimensions(width, height)\n setCanvasWidth(width)\n setCanvasHeight(height)\n self\n end", "def size=(dimension); end", "def setup\n \n size 640, 360\n \nend", "def width=(value)\n # if width had changed\n if @width != value\n # delete old bitmap\n @background.bitmap.dispose if @background.bitmap != nil\n @width = value\n # create new background bitmap\n create_background_bitmap\n end\n end", "def update_size(x,y)\n @width = x if x > @width\n @height = y if y > @height\n end", "def update!(**args)\n @height = args[:height] if args.key?(:height)\n @width = args[:width] if args.key?(:width)\n @x = args[:x] if args.key?(:x)\n @y = args[:y] if args.key?(:y)\n end", "def update!(**args)\n @height = args[:height] if args.key?(:height)\n @width = args[:width] if args.key?(:width)\n @x = args[:x] if args.key?(:x)\n @y = args[:y] if args.key?(:y)\n end", "def width\n options[:width] || Config.width\n end", "def setlinewidth(*)\n super\n end", "def setImage(image, width: nil, height: nil)\n @image = Asset.new(image)\n @image.resize(width, height) if (width != nil && height != nil)\n @image.applyOn(@imageBox)\n end", "def set_offer_image_dimensions\n if offer_image.queued_for_write[:full_size]\n geometry = Paperclip::Geometry.from_file(offer_image.queued_for_write[:full_size])\n self.offer_image_width = geometry.width\n self.offer_image_height = geometry.height\n end\n end", "def resize\n\t\t@image = Qt::Image.new @parent.width/2, @parent.width/2, 7\n\t\[email protected] Qt::Color.new \"#ffffff\"\n\tend", "def resize(width)\n @cli_opts[:geometry] = \"#{width}x\"\n self\n end", "def new_dimensions_for(orig_width, orig_height)\n new_width = orig_width\n new_height = orig_height\n\n case @flag\n when :percent\n scale_x = @width.zero? ? 100 : @width\n scale_y = @height.zero? ? @width : @height\n new_width = scale_x.to_f * (orig_width.to_f / 100.0)\n new_height = scale_y.to_f * (orig_height.to_f / 100.0)\n when :<, :>, nil\n scale_factor =\n if new_width.zero? || new_height.zero?\n 1.0\n else\n if @width.nonzero? && @height.nonzero?\n [@width.to_f / new_width.to_f, @height.to_f / new_height.to_f].min\n else\n @width.nonzero? ? (@width.to_f / new_width.to_f) : (@height.to_f / new_height.to_f)\n end\n end\n new_width = scale_factor * new_width.to_f\n new_height = scale_factor * new_height.to_f\n new_width = orig_width if @flag && orig_width.send(@flag, new_width)\n new_height = orig_height if @flag && orig_height.send(@flag, new_height)\n when :aspect\n new_width = @width unless @width.nil?\n new_height = @height unless @height.nil?\n end\n\n [new_width, new_height].collect! { |v| v.round }\n end", "def new_dimensions_for(orig_width, orig_height)\n new_width = orig_width\n new_height = orig_height\n\n case @flag\n when :percent\n scale_x = @width.zero? ? 100 : @width\n scale_y = @height.zero? ? @width : @height\n new_width = scale_x.to_f * (orig_width.to_f / 100.0)\n new_height = scale_y.to_f * (orig_height.to_f / 100.0)\n when :<, :>, nil\n scale_factor =\n if new_width.zero? || new_height.zero?\n 1.0\n else\n if @width.nonzero? && @height.nonzero?\n [@width.to_f / new_width.to_f, @height.to_f / new_height.to_f].min\n else\n @width.nonzero? ? (@width.to_f / new_width.to_f) : (@height.to_f / new_height.to_f)\n end\n end\n new_width = scale_factor * new_width.to_f\n new_height = scale_factor * new_height.to_f\n new_width = orig_width if @flag && orig_width.send(@flag, new_width)\n new_height = orig_height if @flag && orig_height.send(@flag, new_height)\n when :aspect\n new_width = @width unless @width.nil?\n new_height = @height unless @height.nil?\n end\n\n [new_width, new_height].collect! { |v| v.round }\n end", "def image_options\n if height.blank?\n # save_image_dimensions\n end\n image_options = {\n :height => Nivo::Config.file['slideshow_dimensions']['height'],\n :width => Nivo::Config.file['slideshow_dimensions']['width'],\n :class => \"slide\",\n :title => (caption if Nivo::Config.file['caption'] == true)\n }\n end", "def initialize(width, height)\n @width = width.to_i\n @height = height.to_i\n\n # use default value if not set properly or TOO small\n @width = DEFAULT_WIDTH if @width < DEFAULT_WIDTH\n @height = DEFAULT_WIDTH if @height < DEFAULT_HEIGHT\n end", "def start_export( img_width, img_height)\n set_residual_factor\n @w, @h = (img_width * x_factor).to_i.abs, (img_height * y_factor).to_i.abs\n super(@w, @h)\n end", "def set_parameters(x, y, w, h)\n @x = x\n @y = y\n @width = w\n @height = h\n end", "def set_parameters(x, y, w, h)\n @x = x\n @y = y\n @width = w\n @height = h\n end", "def set_rect(width, height)\n @width, @height = width, height\n zoom_x, zoom_y = (@width.to_f/@image_w.to_f)*@scale[0], (@height.to_f/@image_h.to_f)*@scale[1]\n @background.zoom_x, @background.zoom_y = zoom_x, zoom_y\n if @frame then @frame.zoom_x, @frame.zoom_y = zoom_x, zoom_y end\n end", "def set(x, y, width, height)\n @x = x\n @y = y\n @width = width\n @height = height \n end", "def cut_to_fit(options)\n %Q{-thumbnail #{options.width}x#{options.height}^ \\\n -gravity #{options.gravity} \\\n -unsharp 0x.5 \\\n -auto-orient \\\n -extent #{options.width}x#{options.height}}\n end", "def set_defaults\n\t\t#when ever you are creating a new portfolio item (nothing else)\n\t\t#||= means if nil, replace with this:\n\t\tself.main_image ||= Placeholder.image_generator(height: '600', width: '400')\n\t\tself.thumb_image ||= Placeholder.image_generator(height: '350', width: '200')\n\tend", "def setBackgroundSize(width,height)\n super(width,height)\n @imageBox.set_size_request(width,height)\n self\n end", "def start_export( img_width, img_height)\n @width ||= img_width # If they be nil\n @height ||= img_height\n \n x_factor, y_factor = (@width / img_width.to_f), (@height / img_height.to_f) \n \n @stash = @exporter\n @exporter = Tracksperanto::Tool::Scaler.new(@exporter, :x_factor => x_factor, :y_factor => y_factor)\n super\n end", "def set_dimensions\n sign = get_sign\n if @character_anim == false || bat.anim_mode == :CHARSET\n if sign && sign.include?('$')\n @cw = bitmap.width / 3\n @ch = bitmap.height / 4\n else\n @cw = bitmap.width / 12\n @ch = bitmap.height / 8\n end\n @index_array = [0,1,2]\n return\n end\n w,h = @character.check_frame_pose_overrrides\n @cw = bitmap.width / w\n #Only GTBS mode needs all 4 directions of each stance, otherwise 1 row for ea.\n div = bat.anim_mode == :GTBS ? 4 : 1 \n @ch = ((bitmap.height / h) / div) \n update_frame_index_array #for changing bitmap\n end", "def resize_width(_width)\n raise \"#{self.class.name} is expected to define #resize_width, to properly set component sprite attributes\"\n end", "def setup_available_sizes(file)\n# ::Rails.logger.debug \"setup_available_sizes: #{file.path}\"\n# if model.original_image_width.nil? || model.original_image_height.nil?\n# \n# img = ::Magick::Image::read(@file.file).first\n# model.original_image_width = img.columns\n# model.original_image_height = img.rows\n# ::Rails.logger.debug \"setup w/h for validtaion #{img.columns}x#{img.rows}\"\n# end\n\n model.class::IMAGE_CONFIG.keys.each do |key|\n self.class_eval do\n define_method(\"has_#{key}_config?\".to_sym) { |file| true }\n end\n end\n end", "def update!(**args)\n @dimensions = args[:dimensions] if args.key?(:dimensions)\n @font_scale_factor = args[:font_scale_factor] if args.key?(:font_scale_factor)\n end", "def set_image_dimensions\n\t\tif !self.image_width.is_a?(Numeric) || !self.image_file_name.nil?\t \n\t\t if !image.queued_for_write[:original].nil?\n\t\t geo = Paperclip::Geometry.from_file(image.queued_for_write[:original])\n\t\t self.image_width = geo.width\n\t\t self.image_height = geo.height\n\t\t end\n\t\tend\n\tend", "def resized!\n self[:resized] = true\n node[:volumes][name][:resized] = true\n end", "def make_settings\n stub( \n chart_width: 130, \n x_axis_label_width: 10, \n y_axis_label_width: 20, \n line_height: 4, \n x_axis_label_y_coordinate: -3 )\n end", "def height=(value)\n # if width had changed\n if @height != value\n # delete old bitmap\n @background.bitmap.dispose if @background.bitmap != nil\n @height = value\n # create new background bitmap\n create_background_bitmap\n end\n end", "def add_image(path, point, width, height = 0.0)\n end", "def remake_window\n self.width = window_width\n self.height = window_height\n create_contents\n end", "def size(x, y=nil)\n settings.size = [x, y || x]\n end", "def initialize(options={})\n @url = options[:url]\n @width = options[:width].to_i || 0\n @height = options[:height].to_i || 0\n end", "def resizable?; true; end", "def set(*args)\n if (a = args[0]).is_a? Rect\n @x, @y, @width, @height = a.x, a.y, a.width, a.height\n else\n @x, @y, @width, @height = *args\n end\n compute\n self\n end" ]
[ "0.6931197", "0.6772534", "0.6566193", "0.6498647", "0.6341938", "0.6263508", "0.617338", "0.6144427", "0.6101942", "0.6101942", "0.6101942", "0.6070874", "0.6058934", "0.60096854", "0.6008641", "0.6001165", "0.5948111", "0.59463125", "0.5933111", "0.59201443", "0.58210623", "0.5807526", "0.58070374", "0.57925284", "0.57487273", "0.57487273", "0.5701691", "0.5692752", "0.5663394", "0.5640181", "0.56340915", "0.5624332", "0.56052375", "0.56033623", "0.56000006", "0.5589412", "0.55775476", "0.5575627", "0.55755305", "0.55755305", "0.55755305", "0.55746937", "0.5573212", "0.55719894", "0.556807", "0.5559409", "0.55519533", "0.55222046", "0.5519942", "0.55191624", "0.5516075", "0.5507538", "0.5505492", "0.5500376", "0.5494852", "0.54899806", "0.5485019", "0.5477908", "0.5459713", "0.5448776", "0.54467356", "0.54412055", "0.5439413", "0.5434584", "0.5412188", "0.5407903", "0.5396979", "0.5396979", "0.53924096", "0.53879994", "0.5383473", "0.537268", "0.5365036", "0.53582084", "0.5348899", "0.5348899", "0.5334225", "0.53209573", "0.5318305", "0.5302814", "0.5302814", "0.5301599", "0.53001356", "0.5293582", "0.52860665", "0.5281383", "0.52723485", "0.52696836", "0.5269038", "0.5265217", "0.52630436", "0.5259901", "0.52508783", "0.52465063", "0.5246419", "0.5241392", "0.52398676", "0.5239154", "0.52387404", "0.52300185", "0.5218196" ]
0.0
-1
We don't have an easy way to verify output image quality; the best we can do is make sure you don't get any errors when running it.
def test_calculated_quality assert_silent do tested 'calculated_quality rms.jpg' end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def img_resize( dat, w, h, options = {} )\n quality = options[:quality]\n format = options[:format]\n\n begin\n img = GD2::Image.load(dat)\n if h == 0\n h = ( w / img.aspect ).to_i\n end\n\n puts \"resizing image… width: #{w}, height: #{h}, quality: #{quality}\" if $debug\n\n # make sure it doesn't upscale image\n res = img.size\n\n if res[0] < w and res[1] < h\n w = res[0]\n h = res[1]\n elsif res[0] < w\n w = res[0]\n h = (w / img.aspect).to_i\n elsif res[1] < h\n h = res[1]\n w = (h / img.aspect).to_i\n end\n\n nimg = img.resize( w, h )\n\n if img_type(dat) == :jpeg and quality\n nimg.jpeg( quality.to_i )\n else\n case img_type(dat)\n when :png\n nimg.png\n when :jpeg\n nimg.jpeg\n when :gif\n nimg.gif\n else\n raise 'img_resize(), unknown output format'\n end\n end\n rescue => errmsg\n puts \"error: resize failed. #{w} #{h} #{quality}\"\n p errmsg\n return nil\n end\nend", "def process_small_image\n small_image.encode!(:png).convert!('-resize 50x50 -gravity center -background none -extent 50x50')\n end", "def convert_png_to_jpg(img_path)\n print_status(\"Converting #{img_path} to JPG to reduce image quality to #{JPGQUALITY}\")\n basename = File.basename(img_path, '.png')\n img = MiniMagick::Image.open(img_path)\n img.format('JPEG')\n img.quality(JPGQUALITY)\n dst = \"#{WORKFOLDER}/#{basename}.jpg\"\n img.write(dst)\n dst\nend", "def convert_to_img\n\t\t\t`gs -sDEVICE=png16m '-r#{OCR::MIN_DENSITY}' -o '#{@image}' '#{@input_file}'`\n\t\tend", "def imagemagick?; end", "def conform( image )\n @logger.info( \"T #{Thread.current[:id]}: Conform image: #{ image }\" )\n return @asset_functions.create_asset( image, @output_format ) {|a| @output_type_obj.convert_resize_extent_color_specs( image, a )}\n end", "def optimize_for_pagespeed\n # according to https://developers.google.com/speed/docs/insights/OptimizeImages\n if self.file.content_type == 'image/jpeg'\n # convert orig.jpg -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG orig_converted.jpg\n manipulate! do |img|\n img.sampling_factor '4:2:0'\n img.strip\n img.quality 85\n img.interlace 'JPEG'\n img\n end\n else\n # convert cuppa.png -strip cuppa_converted.png\n manipulate! do |img|\n img.strip\n img\n end\n end\n end", "def process_image(image_path, output_directory)\n parts = image_path.split(\"/\")\n filename = parts[parts.length - 1]\n image_small_path = output_directory + lowercase_filetype(filename)\n ratio = 0.125\n ratio = 0.071\n command = \"CoreImageTool load my_image #{image_path} \\\n filter my_image CILanczosScaleTransform scale=#{ratio} \\\n store my_image #{image_small_path} public.jpeg\"\n puts \"processing #{image_path} #{image_small_path}\"\n system(command) \n end", "def check_print_image_mask_size\n return if print_image_mask.blank?\n expect_width = (width / 25.4 * dpi).to_i\n expect_height = (height / 25.4 * dpi).to_i\n # FIXME: private API may broken in the future, but we really need it at this time\n actual_width, actual_height = print_image_mask.send(:get_dimensions)\n return if actual_width == expect_width && actual_height == expect_height\n self.warning = \"上傳的遮罩圖大小為 #{actual_width}x#{actual_height}, 但產品圖的大小為 #{expect_width}x#{expect_height}\"\n end", "def process_image(path)\n picture_name = File.basename(path)\n thumbnail_dir = File.join(File.dirname(path), \"thumbnails\")\n thumbnail_path = File.join(thumbnail_dir, \"#{File.basename(picture_name, File.extname(picture_name))}.jpg\")\n Dir.mkdir(thumbnail_dir) unless File.exist?(thumbnail_dir)\n\n image_optim = ImageOptim.new\n\n image = MiniMagick::Image.open(path)\n image_prop = {\n \"name\" => picture_name,\n \"thumb\" => \"thumbnails/#{picture_name}\",\n \"height\" => image.height,\n \"width\" => image.width\n }\n\n return image_prop if File.exist?(thumbnail_path)\n\n# -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG -colorspace RGB\n\n image.format \"jpeg\" unless File.extname(picture_name) == \"jpg\"\n image.combine_options do |b|\n b.resize \"#{MAX_DIMENSION}>\"\n b.sampling_factor \"4:2:0\"\n b.strip\n b.interlace \"JPEG\"\n b.colorspace \"RGB\"\n b.quality 85\n end\n image.write thumbnail_path\n\n image_optim.optimize_image!(path)\n image_optim.optimize_image!(thumbnail_path)\n\n image_prop\nend", "def process_image(src, dest, maxw, maxh)\n i = QuickMagick::Image.read(src).first\n # AMF - added quality setting to limit size of images (some sites had high quality jpeg, so files sizes were still big)\n i.quality = 75\n w, h = i.width, i.height\n extra = (w - h/(maxh.to_f/maxw.to_f)).to_i\n if extra > 0\n i.shave(\"#{extra>>1}x0\") if i.width > i.height\n w -= extra\n end\n if w > maxw or h > maxh\n i.resize(\"#{maxw}x#{maxh}\")\n end\n i.save(dest)\n end", "def compress_jpg(input, quality = 80, output = nil)\n unless output.nil?\n FileUtils.cp(input, output)\n input = output\n end\n\n options = [\n '-q -p -f',\n \"--max=#{quality}\",\n '--strip-all',\n '--all-progressive',\n input.shellescape\n ]\n\n command = \"jpegoptim #{options.join(' ')}\"\n `#{command}`\n\n return output unless output.nil?\n input\n end", "def main()\n img = ImageList.new($input)\n convert = ImageList.new\n page = Magick::Rectangle.new(0,0,0,0)\n $total_ops = (img.rows * img.columns).to_f\n\n for i in 0..img.rows\n for j in 0..img.columns\n pixel = generate_hex_pixel(rgb_to_hex(img.pixel_color(j,i)))\n convert << pixel\n page.x = j * pixel.columns\n page.y = i * pixel.rows\n pixel.page = page\n progress()\n end\n end\n\n puts 'Writing image, this could take a while...'\n convert.mosaic.write($output)\nend", "def imagemagick7?; end", "def calcImgSizes(res, file, maxheight, maxwidth, grid)\n myres = res.to_f\n myheight = `identify -format \"%h\" \"#{file}\"`\n myheight = myheight.to_f\n myheightininches = (myheight / myres)\n mywidth = `identify -format \"%w\" \"#{file}\"`\n mywidth = mywidth.to_f\n mywidthininches = (mywidth / myres)\n # if current height or width exceeds max, resize to max, proportionately\n if mywidthininches > maxwidth or myheightininches > maxheight then\n targetheight = maxheight * myres\n targetwidth = maxwidth * myres\n `convert \"#{file}\" -density #{myres} -resize \"#{targetwidth}x#{targetheight}>\" -quality 100 \"#{file}\"`\n end\n myheight = `identify -format \"%h\" \"#{file}\"`\n myheight = myheight.to_f\n myheightininches = (myheight / myres)\n mymultiple = ((myheight / myres) * 72.0) / grid\n if mymultiple <= 1\n resizecmd = \"\"\n else\n newheight = ((mymultiple.floor * grid) / 72.0) * myres\n resizecmd = \"-resize \\\"x#{newheight}\\\" \"\n end\n return resizecmd\nrescue => e\n return \"error method calcImgSize: #{e}\"\nend", "def resize_retina_image(image_filename)\n \n image_name = File.basename(image_filename)\n \n image = Magick::Image.read(image_filename).first # Read the image\n new_image = image.scale(SCALE_BY)\n \n if new_image.write(image_filename) # Overwrite image file\n puts \"Resizing Image (#{SCALE_BY}): #{image_name}\"\n else\n puts \"Error: Couldn't resize image #{image_name}\"\n end\n \nend", "def test_fit_within_smaller\n ImageScience.with_image @biggie do |img|\n img.fit_within(100, 100) do |thumb|\n assert thumb.save(@tmppath)\n end\n end\n\n assert File.exists?(@tmppath)\n\n ImageScience.with_image @tmppath do |img|\n assert_kind_of ImageScience, img\n assert_equal 100, img.width\n end\n end", "def resize_and_optimize(width, height)\n manipulate! do |img|\n img.format(\"jpg\") do |c|\n c.quality \"70\"\n c.resize \"#{width}x#{height}\"\n end\n\n img\n end\n end", "def image_is_too_small\n return false if CONFIG[\"min_mpixels\"].nil?\n return false if width.nil?\n return false if width * height >= CONFIG[\"min_mpixels\"]\n true\n end", "def thumbnail(width, input, output)\n profile_normalization_args=[\"--eprofile\", srgb_profile_path, \"--delete\"]\n vips_jpg_params=\"[Q=#{@jpeg_q },interlace,optimize_coding,strip]\"\n args = if width\n # The image will be resized to fit within a box\n # which is `width` wide and very, very very tall.\n # See:\n # https://github.com/libvips/libvips/issues/781\n # https://github.com/libvips/ruby-vips/issues/150\n [\n vips_thumbnail_command, input.path,\n *profile_normalization_args,\n \"--size\", \"#{width}x1000000\",\n \"-o\", \"#{output.path}#{vips_jpg_params}\"\n ]\n else\n [ vips_command, \"copy\", input.path,\n *profile_normalization_args,\n \"#{output.path}#{vips_jpg_params}\"\n ]\n end\n @cmd.run(*args)\n end", "def check_dimensions(image)\n if image.height < $max_height and image.width < $max_width\n return true\n else\n return false\n end\nend", "def compute_image_size src\n $stderr.puts \"c_i_s #{src.class} #{src.to_s.size} #{src.inspect}\" if src.to_s.size < 1024\n case src\n when Pathname\n # @verbose = true\n result = cmd_out(\"#{BIN_PREFIX}imgsize -r #{src.to_s.inspect}\")\n result = /(\\d+) (\\d+)/.match(result)\n result = result ? { :width => result[1].to_i, :height => result[2].to_i } : nil\n result\n when String\n compute_image_size(force_to_file)\n else\n raise TypeError, \"#{src.class}\"\n end\n end", "def generate_image(url)\n # Capture the screenshot\n kit = IMGKit.new(url, quality: 90, width: 1280, height: 720)\n\n # Resize the screengrab using rmagick\n Image.from_blob(kit.to_img(:jpg)).first.\n resize_to_fill!(params['width'].to_i, params['height'].to_i).to_blob\nend", "def test_png_size_determined_correctly\n assert_equal [120, 175], @page.get_png_size(@test_png)\n end", "def size_calculation(file_name)\n\t\t#file_name = \"file:///home/frakinho/image_manipulation/server_serial_port/app/assets/images/coisa.jpg\"\n\t original = Magick::Image::read(file_name).first\n\t\t\n\t\tpath_debug = get_path_without_image_name(file_name)\n\t \n\n\t #Copy for debug mod\n\t image = original\n\n\t #Apply Fitler twice for remove a max of noise \n\t image = image.median_filter(radius=3)\n\t image = image.median_filter(radius=3)\n\t \timage.write(\"#{path_debug}first_filter.jpg\")\n\t image = image.edge(radius=2)\n\t \timage.write(\"#{path_debug}edge.jpg\")\n\n\t image.image_type = Magick::BilevelType\n\t image.write(\"#{path_debug}BileveType.jpg\")\n\t image = image.median_filter(radius=1)\n\t image.write(\"#{path_debug}last_filter.jpg\")\n\n\t \t# Get Bounding_box\n\t\tbound = image.bounding_box\n\n\t\t#Calculate value in CM\n\t #Value top in CM\n\t # 237 is a variable value, depend the distance between table and camera\n\t value_width_cm = ((bound.width) * 21) / 380.0\n\t #Value of height\n\t value_height_cm = ((bound.height) * 21) / 380.0\n\n\n\t # Debug MOD \n\t\tif ServerSerialPort::Application.config.my_app.debug\n\t\t gc_1 = Magick::Draw.new\n\t\t gc_1.stroke(\"gray50\")\n\t\t gc_1.fill_opacity(0)\n\t\t gc_1.rectangle(bound.x, bound.y, bound.x+bound.width, bound.y+bound.height)\n\t\t gc_1.stroke(\"red\")\n\t\t gc_1.circle(bound.x, bound.y, bound.x+2, bound.y+2)\n\t\t gc_1.circle(bound.x+bound.width, bound.y, bound.x+bound.width+2, bound.y+2)\n\t\t gc_1.circle(bound.x, bound.y+bound.height, bound.x+2, bound.y+bound.height+2)\n\t\t gc_1.circle(bound.x+bound.width, bound.y+bound.height, bound.x+bound.width+2, bound.y+bound.height+2)\n\t\t gc_1.fill(\"white\")\n\t\t gc_1.stroke(\"transparent\")\n\t\t gc_1.text(bound.x-15, bound.y-5, \"\\'#{bound.x},#{bound.y}\\'\")\n\t\t gc_1.text(bound.x+(bound.width/2),bound.y-15,\"#{value_width_cm}\")\n\t\t gc_1.text(bound.x - 15,(bound.height / 2),\"#{value_height_cm}\")\n\t\t gc_1.text(bound.x+bound.width-15, bound.y-5, \"\\'#{bound.x+bound.width},#{bound.y}\\'\")\n\t\t gc_1.text(bound.x-15, bound.y+bound.height+15, \"\\'#{bound.x},#{bound.y+bound.height}\\'\")\n\t\t gc_1.text(bound.x+bound.width-15, bound.y+bound.height+15, \"\\'#{bound.x+bound.width},#{bound.y+bound.height}\\'\")\t \n\t\t gc_1.draw(original)\n\t\t original.write(\"#{path_debug}bounding.jpg\")\n\t\t\n\t\tend\n\t\timage_crop = original.crop(bound.x, bound.y, bound.width, bound.height)\n\t\timage_crop = image_crop.rotate(90)\n\t\n\t\timage_crop.write(\"#{path_debug}image_crop.jpg\")\n\n\n\n\t return value_width_cm,value_height_cm\n\tend", "def poster(input, output)\n \n input = input \n output = output \n \n scale(input, output)\n\n #Demonstrate the Image#polaroid method\n img = Magick::Image.read(output).first\n result = img.posterize\n \n #Write \n result.write(output)\n\nend", "def better?(new_image)\n image.size < MIN_GOOD_IMAGE_SIZE &&\n new_image.size > image.size\n end", "def rmagik_info(file)\n puts \"- - - - - :rmagik-S\"\n puts file\n puts \">> Checking for oversized file > 430px wide\"\n img = Magick::Image::read(file).first\n puts \"Geometry: #{img.columns}x#{img.rows} - #{img.columns.class}x#{img.rows.class}\"\n\n if img.columns > 430 # resize to 430 wide\n \n scale = (430.0 / img.columns.to_f).round(6) # calculate scaling factor for image\n \n puts \"RESIZING before copying x#{scale}\"\n \n file_large = file.sub(File.extname(file), '_LRG.jpg') # copy to image_name_LRG.jpg\n FileUtils.cp( file, \"scratch/#{file_large}\")\n \n img_430 = img.scale(scale)\n \n img_430.write(file)\n \n end\n \n #img = Magick::Image::read(file).first\n #puts \" Format: #{img.format}\"\n #puts \" Geometry: #{img.columns}x#{img.rows}\"\n #puts \" Class: \" + case img.class_type\n # when Magick::DirectClass\n # \"DirectClass\"\n # when Magick::PseudoClass\n # \"PseudoClass\"\n # end\n #puts \" Depth: #{img.depth} bits-per-pixel\"\n #puts \" Colors: #{img.number_colors}\"\n #puts \" Filesize: #{img.filesize}\"\n #puts \" Resolution: #{img.x_resolution.to_i}x#{img.y_resolution.to_i} \"+\n # \"pixels/#{img.units == Magick::PixelsPerInchResolution ?\n # \"inch\" : \"centimeter\"}\"\n #if img.properties.length > 0\n # puts \" Properties:\"\n # img.properties { |name,value|\n # puts %Q| #{name} = \"#{value}\"|\n # }\n #end\n puts \"- - - - - :rmagik-E\"\nend", "def generate_images_for(image_filename)\n source_image_path = source_path_of_file(image_filename)\n if source_image_path\n imgsrcbasename = File.basename(source_image_path, '.*').gsub(' ', '_')\n imgsrcextname = File.extname(source_image_path)\n FileUtils.mkdir_p(@asset_path)\n\n PROFILES.each do |profile|\n non_retina_dest_pathname = File.join(\n @asset_path,\n \"#{imgsrcbasename}-#{profile[:width]}#{imgsrcextname.downcase}\")\n retina_dest_pathname = File.join(\n @asset_path,\n \"#{imgsrcbasename}-#{profile[:width]}@2x#{imgsrcextname.downcase}\")\n\n unless File.exists?(non_retina_dest_pathname)\n # \\> will resize only larger-to-smaller\n system \"convert \\\"#{source_image_path}\\\" -quality #{profile[:quality]} \"\\\n \"-strip -interlace Plane -resize #{profile[:width]}x#{profile[:height]}\\\\> \"\\\n \"\\\"#{non_retina_dest_pathname}\\\"\"\n end\n unless File.exists?(retina_dest_pathname)\n system \"convert \\\"#{source_image_path}\\\" -quality #{profile[:quality]} \"\\\n \"-strip -interlace Plane -resize #{profile[:width] * 2}x#{profile[:height] * 2}\\\\> \"\\\n \"\\\"#{retina_dest_pathname}\\\"\"\n end\n end\n return true\n end\n @missing_images << image_filename if image_filename\n false\n end", "def small(input) # Method that returns the image\n self.images[input].variant(resize: \"300x300\").processed # Resizing the image and return it\n end", "def generate_image_sizes()\n\tKernel.system \"mkdir -p #{DESTINATION_DIRECTORY_NAME}\"\n\tSIZES.each do |size|\n\t\timagemagick_command = \"find . -maxdepth 1 -type f \\\\( -name '*.tif' -o -name '*.png' \\\\) | xargs -I@ #{IMAGEMAGICK_COMMAND} @ -resize #{size[:max_width]} -quality #{JPEG_QUALITY} -set filename:name '%t' '#{DESTINATION_DIRECTORY_NAME}/%[filename:name]-#{size[:name]}.#{OUTPUT_FILE_EXTENSION}'\"\n\t\tputs imagemagick_command\n\t\tKernel.system imagemagick_command\n\tend\nend", "def compress_png(input, quality = 80, output = nil)\n # Override file if no output selected\n output = input if output.nil?\n\n # PNGQuant does not allow update in place, so we save in a temp file\n output_tmp = Tempfile.new('temp_png').path\n\n options = [\n input.shellescape,\n '--force',\n \"--quality 01-#{quality}\",\n \"--output #{output_tmp.shellescape}\"\n ]\n\n command = \"pngquant #{options.join(' ')}\"\n `#{command}`\n\n # Move the tmp file back to the real output\n FileUtils.mv(output_tmp, output)\n\n output\n end", "def generate_test_image(file, params = {})\n # Set default size for sample test image.\n line_size = 1\n box_size = 6\n width = (box_size * 6) + (line_size * 7)\n height = (box_size * 5) + (line_size * 6)\n\n # Set parameters for image creation options.\n image_type = params[:image_type] || File.extname(file)\n bands = params[:bands] || 3\n color = params[:color] || 'rgb'\n depth = params[:depth] || 8\n cg_type = params[:cg_type] || 'adobe_rgb'\n compression = params[:compression]\n profile = params[:profile]\n\n temp_array = color_gauge_values(cg_type)\n temp_image = Vips::Image.black(width, height, bands: temp_array.first.size)\n 5.times do |i|\n b = (box_size * i) + (line_size * (i + 1))\n # d = b + box_size - line_size\n 6.times do |j|\n a = (box_size * j) + (line_size * (j + 1))\n # c = a + box_size - line_size\n colors = temp_array.shift\n temp_image = temp_image.draw_rect(colors, a, b, box_size, box_size, fill: true)\n end\n end\n\n temp_image = color.eql?('cmyk') ? temp_image.copy(interpretation: :cmyk) : temp_image.copy(interpretation: :srgb)\n\n temp_image = if color.eql?('grey') && bands == 3\n mean = temp_image.bandmean\n Vips::Image.bandjoin([mean, mean, mean])\n elsif color.eql?('grey') && bands == 1\n temp_image.bandmean\n elsif color.eql?('bin') && bands == 3\n mean = temp_image.bandmean < 128\n Vips::Image.bandjoin([mean, mean, mean])\n elsif color.eql?('bin') && bands == 1\n temp_image.bandmean < 128\n else\n temp_image\n end\n\n options = {}\n unless profile.nil?\n profile_file = File.join(Assembly::PATH_TO_IMAGE_GEM, 'profiles', \"#{profile}.icc\")\n options.merge!(profile: profile_file)\n end\n\n case image_type\n when '.tiff', '.tif'\n options.merge!(compression: compression) unless compression.nil?\n options.merge!(squash: true) if depth.eql?(1)\n temp_image.tiffsave(file, **options)\n when '.jpeg', '.jpg'\n temp_image.jpegsave(file, **options)\n else\n raise \"unknown type: #{image_type}\"\n end\nend", "def is_small_imageable?\n return true\n end", "def display_image\n image.variant resize_to_limit: Settings.validation.post.img_resize\n end", "def validate_log_image_size\n return unless logo.image_size.present?\n w, h = logo.image_size\n if (h < 100 || w < 100) || (h.to_f / w.to_f != 1)\n errors.add :base, 'Logo size width and height need gt 100px, and image should be square.'\n end\n end", "def test_method_size\n width, height = (1..100).to_a.sample( 2 )\n base_image = Magick::Image.new( width, height )\n image_adapter = Image::AdapterMagickImage.new( base_image )\n \n # maps width/height to size( :x ) / size ( :y )\n assert_equal width, image_adapter.size( :x )\n assert_equal height, image_adapter.size( :y )\n end", "def test_sizes\n output = tested('sizes rms.jpg')\n\n assert errors_ok? output\n\n assert_equal '(max-width: 600px) 80vw, 50%', output.at_css('img')['sizes']\n end", "def test_data_img_no_size\n output = tested('data_img_no_size rms.jpg')\n\n assert errors_ok? output\n\n assert_equal '(max-width: 600px) 80vw, 50%',\n output.at_css('img')['sizes']\n end", "def cover_need_optimize?(coverpath)\n escaped_coverpath = coverpath.shellescape\n width = `identify -format \"%w\" #{escaped_coverpath}`.chomp.to_i\n filesize = `stat -c '%s' #{escaped_coverpath}`.chomp.to_i\n return true if width != 610\n return true if filesize > 200_000\n false\n end", "def describe_image(image)\n puts \"#{image[:name]} is #{image[:width]}px * #{image[:height]}px\"\nend", "def create_advanced\n image_service = ImageGeneratingService.new(self, 'Advanced.jpg', 'image/jpeg', 69)\n output_path = image_service.generate\n original_size_mb = File.size(output_path).to_f / 2**20\n if original_size_mb > 1.0\n image_service.generate_resized(1200)\n end\n end", "def test_data_img_yes_size\n output = tested('data_img_yes_size rms.jpg')\n\n assert errors_ok? output\n\n assert_equal '(max-width: 600px) 80vw, 50%',\n output.at_css('img')['data-sizes']\n end", "def resize_and_write_file(filename, filename_output, max_width, max_height = nil)\n pic = Magick::Image.read(filename).first\n img_width, img_height = pic.columns, pic.rows\n ratio = img_width.to_f / max_width.to_f\n\n if max_height.nil?\n max_height = img_height / ratio\n end\n\n pic.change_geometry!(\"#{max_width}x#{max_height}>\") { |cols, rows, img|\n img.resize_to_fit!(cols, rows)\n img.write filename_output\n img.destroy!\n }\n\n nbytes, content = File.size(filename_output), nil\n File.open(filename_output, \"rb\") { |f| content = f.read nbytes }\n content\nend", "def quality(percent)\n manipulate! do |image|\n @_format_opts = { :quality => percent } if jpeg? || @_format=='jpeg'\n image\n end\n end", "def quality_and_strip(percentage)\n manipulate! do |img|\n img.format('jpg') # We want to enforce jpeg so we can use good compression.\n img.strip # Do not store EXIF data in the thumb to save space\n img.quality(percentage.to_s)\n img = yield(img) if block_given?\n img\n end\n end", "def quality_100_image_exists?\n image.present? and image.quality_100.file.exists?\n end", "def quality_85_image_exists?\n image.present? and image.quality_85.file.exists?\n end", "def optimize_cover(coverpath)\n puts 'Optimizing cover'\n `mogrify -resize 610 #{coverpath.shellescape}`\n `jpegoptim -m80 --strip-all #{coverpath.shellescape}`\n end", "def requested_image_resolution\n return resized_image_resolution unless resized_image_resolution.nil?\n original_image_resolution\n end", "def quality(percentage)\n manipulate! do |img|\n img.write(current_path){ self.quality = percentage }\n img = yield(img) if block_given?\n img\n end\nend", "def similarity\n size1 = pixel_count(@image_path_1)\n size2 = pixel_count(@image_path_2)\n\n if size1 < size2\n big = @image_path_2\n small = @image_path_1\n else\n big = @image_path_1\n small = @image_path_2\n end\n\n min_size = size(small)\n width = min_size[0] * @resize_factor\n height = min_size[1] * @resize_factor\n\n a = \"convert #{Shellwords.escape(small)} #{Shellwords.escape(big)} -resize '#{width}'x'#{height}'\\! MIFF:- | compare -metric AE -fuzz \\\"#{@color_fuzz}%\\\" - null: 2>&1\"\n result = `#{a}`\n\n result.to_i / (width * height)\n end", "def test_load_valid_png_files\n\n each_file_with_updated_info do\n |file_path|\n\n if @test_feature != \"x\"\n\n #Reading valid png files should not raise any exception\n assert_nothing_raised do\n Imgrb::Image.new(file_path)\n end\n\n img = Imgrb::Image.new(file_path, :only_metadata)\n\n assert_equal 0, img.rows.size, \"Only metadata loaded so no pixel data should be read.\"\n\n\n\n assert_equal @is_interlaced, img.header.interlaced?\n assert_equal @color_type_num, img.header.image_type\n assert_equal @bit_depth, img.header.bit_depth\n\n if @color_type_desc == \"g\"\n assert img.grayscale?\n assert !img.has_alpha? unless @test_feature == \"t\"\n end\n\n if @color_type_desc == \"c\" || @color_type_desc == \"p\"\n assert !img.grayscale?\n assert !img.has_alpha? unless @test_feature == \"t\"\n end\n\n if @color_type_num == 4\n assert img.grayscale?\n assert img.has_alpha?\n end\n\n if @color_type_num == 6\n assert !img.grayscale?\n assert img.has_alpha?\n end\n\n unless [\"df\", \"dh\", \"ds\"].include?(@parameter) || @test_feature == \"s\"\n assert_equal 32, img.width, \"Incorrect width reported!\"\n assert_equal 32, img.height, \"Incorrect height reported!\"\n end\n\n if @test_feature == \"s\"\n assert_equal img.width, img.height, \"Image size should be square, but is not!\"\n assert_equal @parameter.to_i, img.width, \"Incorrect image size reported!\"\n end\n end\n end\n end", "def resize_image(img_path)\n img = MiniMagick::Image.open(img_path)\n print_status(\"Original #{img_path} dimension = #{img.height}x#{img.width}\")\n new_width = img.width - (img.width * REIZEPERT).to_i\n new_height = img.height - (img.height * REIZEPERT).to_i\n img = img.resize(\"#{new_width}x#{new_height}\")\n print_status(\"Resized #{img_path} dimension = #{img.height}x#{img.width}\")\n img.write(img_path)\nend", "def quality_95_image_exists?\n image.present? and image.quality_95.file.exists?\n end", "def extract_thumb(input, output, width, height)\n Image::Editing::ResizeToFill.new(input, output, width, height).run\n end", "def normalized_sizes(width, height)\n if width.to_i > @image.width\n width = @image.width\n end\n if height.to_i > @image.height\n height = @image.height\n end\n \"#{width}x#{height}\"\n end", "def test_progressive_dct_based_jpeg_image\n testname = '35w x 35h progressive jpeg image.'\n data = %w(\n FF D8 FF E0 00 10 4A 46 49 46 00 01 02 01 00 96\n 00 96 00 00 FF E1 04 E7 45 78 69 66 00 00 4D 4D\n 00 2A 00 00 00 08 00 07 01 12 00 03 00 00 00 01\n 00 01 00 00 01 1A 00 05 00 00 00 01 00 00 00 62\n 01 1B 00 05 00 00 00 01 00 00 00 6A 01 28 00 03\n 00 00 00 01 00 02 00 00 01 31 00 02 00 00 00 14\n 00 00 00 72 01 32 00 02 00 00 00 14 00 00 00 86\n 87 69 00 04 00 00 00 01 00 00 00 9C 00 00 00 C8\n 00 00 00 96 00 00 00 01 00 00 00 96 00 00 00 01\n 41 64 6F 62 65 20 50 68 6F 74 6F 73 68 6F 70 20\n 37 2E 30 00 32 30 30 38 3A 30 39 3A 30 39 20 32\n 32 3A 32 33 3A 31 32 00 00 00 00 03 A0 01 00 03\n 00 00 00 01 FF FF 00 00 A0 02 00 04 00 00 00 01\n 00 00 00 23 A0 03 00 04 00 00 00 01 00 00 00 23\n 00 00 00 00 00 00 00 06 01 03 00 03 00 00 00 01\n 00 06 00 00 01 1A 00 05 00 00 00 01 00 00 01 16\n 01 1B 00 05 00 00 00 01 00 00 01 1E 01 28 00 03\n 00 00 00 01 00 02 00 00 02 01 00 04 00 00 00 01\n 00 00 01 26 02 02 00 04 00 00 00 01 00 00 03 B9\n 00 00 00 00 00 00 00 48 00 00 00 01 00 00 00 48\n 00 00 00 01 FF D8 FF E0 00 10 4A 46 49 46 00 01\n 02 01 00 48 00 48 00 00 FF ED 00 0C 41 64 6F 62\n 65 5F 43 4D 00 02 FF EE 00 0E 41 64 6F 62 65 00\n 64 80 00 00 00 01 FF DB 00 84 00 0C 08 08 08 09\n 08 0C 09 09 0C 11 0B 0A 0B 11 15 0F 0C 0C 0F 15\n 18 13 13 15 13 13 18 11 0C 0C 0C 0C 0C 0C 11 0C\n 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C\n 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 01 0D 0B 0B 0D\n 0E 0D 10 0E 0E 10 14 0E 0E 0E 14 14 0E 0E 0E 0E\n 14 11 0C 0C 0C 0C 0C 11 11 0C 0C 0C 0C 0C 0C 11\n 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C\n 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C FF C0 00 11\n 08 00 23 00 23 03 01 22 00 02 11 01 03 11 01 FF\n DD 00 04 00 03 FF C4 01 3F 00 00 01 05 01 01 01\n 01 01 01 00 00 00 00 00 00 00 03 00 01 02 04 05\n 06 07 08 09 0A 0B 01 00 01 05 01 01 01 01 01 01\n 00 00 00 00 00 00 00 01 00 02 03 04 05 06 07 08\n 09 0A 0B 10 00 01 04 01 03 02 04 02 05 07 06 08\n 05 03 0C 33 01 00 02 11 03 04 21 12 31 05 41 51\n 61 13 22 71 81 32 06 14 91 A1 B1 42 23 24 15 52\n C1 62 33 34 72 82 D1 43 07 25 92 53 F0 E1 F1 63\n 73 35 16 A2 B2 83 26 44 93 54 64 45 C2 A3 74 36\n 17 D2 55 E2 65 F2 B3 84 C3 D3 75 E3 F3 46 27 94\n A4 85 B4 95 C4 D4 E4 F4 A5 B5 C5 D5 E5 F5 56 66\n 76 86 96 A6 B6 C6 D6 E6 F6 37 47 57 67 77 87 97\n A7 B7 C7 D7 E7 F7 11 00 02 02 01 02 04 04 03 04\n 05 06 07 07 06 05 35 01 00 02 11 03 21 31 12 04\n 41 51 61 71 22 13 05 32 81 91 14 A1 B1 42 23 C1\n 52 D1 F0 33 24 62 E1 72 82 92 43 53 15 63 73 34\n F1 25 06 16 A2 B2 83 07 26 35 C2 D2 44 93 54 A3\n 17 64 45 55 36 74 65 E2 F2 B3 84 C3 D3 75 E3 F3\n 46 94 A4 85 B4 95 C4 D4 E4 F4 A5 B5 C5 D5 E5 F5\n 56 66 76 86 96 A6 B6 C6 D6 E6 F6 27 37 47 57 67\n 77 87 97 A7 B7 C7 FF DA 00 0C 03 01 00 02 11 03\n 11 00 3F 00 F5 54 0B 33 71 AB 79 AC BF 75 83 53\n 5B 01 7B 84 F1 B9 95 EE 73 54 F2 1C E6 D1 63 9B\n F4 9A C7 16 FC 40 5C F7 49 B7 1A FA 19 51 BF 23\n 1B 2C B4 3A EC 7B 2D 65 76 6E 23 DC FD 06 FB 58\n FF 00 A4 CB 92 53 1E B9 F5 9B 3E 96 DB 8D 83 D3\n B2 85 A7 DB 56 53 D8 1B 5C E9 EE 0F 7E E6 37 FE\n B8 AF FD 5B FD AA 71 9E EE A2 CB 6A 26 36 D7 7B\n C5 8F 07 5D EE DE 27 F4 7F 43 E9 21 E5 D5 85 8D\n 59 39 B9 04 56 EE 45 D9 6F F7 79 7A 6D 1E FF 00\n EA AB 9D 0A C3 67 4D AC 9A AC C7 01 CF 0C A6 D2\n 4B DA D0 E7 7A 61 FE A4 BF E8 7E FA 4A 74 12 49\n 24 94 FF 00 FF D0 F5 2B DA 5D 4D 8D 1C B9 A4 7D\n E1 66 F4 FB BA 7F 50 C3 C7 17 D4 CF 59 B5 33 F4\n 57 06 97 00 47 2D 9F CC 74 7D 26 2D 55 CC 7D 61\n CD 7F 40 38 66 BA 99 76 16 4D CE AD EC B8 4B 69\n 2E 06 C6 7A 76 0F 73 37 D9 EC D8 EF EC 24 A7 61\n 95 74 7C 70 6F 6B 28 AF 61 FE 72 1B 20 8F DD 77\n D2 44 E9 97 8C 8C 63 7B 5A E6 36 CB 2C 21 AE D1\n D0 1E EA F5 1F D8 58 1F 57 FA 95 DD 6B 23 25 B5\n D5 5E 23 31 F6 13 63 1A 1E F9 70 73 76 56 F7 7B\n 6A FE 6F 7F D0 FC F5 D3 63 D1 56 3D 2C A6 A6 ED\n AD 82 1A 12 52 44 92 49 25 3F FF D1 F5 55 47 AD\n C7 EC AC AD DE 84 7A 6E 9F B5 4F A3 11 FE 1B 67\n BF 67 F5 17 CC 69 24 A7 E9 6F AB BB 7F 66 55 B7\n EC BB 60 47 D8 B7 7A 5C 7F C2 7E 93 FC F5 A8 BE\n 55 49 25 3F 55 24 BE 55 49 25 3F FF D9 FF ED 09\n 94 50 68 6F 74 6F 73 68 6F 70 20 33 2E 30 00 38\n 42 49 4D 04 25 00 00 00 00 00 10 00 00 00 00 00\n 00 00 00 00 00 00 00 00 00 00 00 38 42 49 4D 03\n ED 00 00 00 00 00 10 00 96 00 00 00 01 00 01 00\n 96 00 00 00 01 00 01 38 42 49 4D 04 26 00 00 00\n 00 00 0E 00 00 00 00 00 00 00 00 00 00 3F 80 00\n 00 38 42 49 4D 04 0D 00 00 00 00 00 04 00 00 00\n 1E 38 42 49 4D 04 19 00 00 00 00 00 04 00 00 00\n 1E 38 42 49 4D 03 F3 00 00 00 00 00 09 00 00 00\n 00 00 00 00 00 01 00 38 42 49 4D 04 0A 00 00 00\n 00 00 01 00 00 38 42 49 4D 27 10 00 00 00 00 00\n 0A 00 01 00 00 00 00 00 00 00 01 38 42 49 4D 03\n F5 00 00 00 00 00 48 00 2F 66 66 00 01 00 6C 66\n 66 00 06 00 00 00 00 00 01 00 2F 66 66 00 01 00\n A1 99 9A 00 06 00 00 00 00 00 01 00 32 00 00 00\n 01 00 5A 00 00 00 06 00 00 00 00 00 01 00 35 00\n 00 00 01 00 2D 00 00 00 06 00 00 00 00 00 01 38\n 42 49 4D 03 F8 00 00 00 00 00 70 00 00 FF FF FF\n FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF\n FF FF FF 03 E8 00 00 00 00 FF FF FF FF FF FF FF\n FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 03\n E8 00 00 00 00 FF FF FF FF FF FF FF FF FF FF FF\n FF FF FF FF FF FF FF FF FF FF FF 03 E8 00 00 00\n 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF\n FF FF FF FF FF FF FF 03 E8 00 00 38 42 49 4D 04\n 08 00 00 00 00 00 10 00 00 00 01 00 00 02 40 00\n 00 02 40 00 00 00 00 38 42 49 4D 04 1E 00 00 00\n 00 00 04 00 00 00 00 38 42 49 4D 04 1A 00 00 00\n 00 03 59 00 00 00 06 00 00 00 00 00 00 00 00 00\n 00 00 23 00 00 00 23 00 00 00 12 00 54 00 43 00\n 50 00 5F 00 43 00 69 00 72 00 63 00 6C 00 65 00\n 5F 00 42 00 61 00 6C 00 6C 00 61 00 73 00 74 00\n 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00\n 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00\n 00 00 23 00 00 00 23 00 00 00 00 00 00 00 00 00\n 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00\n 00 00 00 00 00 00 00 00 00 00 00 10 00 00 00 01\n 00 00 00 00 00 00 6E 75 6C 6C 00 00 00 02 00 00\n 00 06 62 6F 75 6E 64 73 4F 62 6A 63 00 00 00 01\n 00 00 00 00 00 00 52 63 74 31 00 00 00 04 00 00\n 00 00 54 6F 70 20 6C 6F 6E 67 00 00 00 00 00 00\n 00 00 4C 65 66 74 6C 6F 6E 67 00 00 00 00 00 00\n 00 00 42 74 6F 6D 6C 6F 6E 67 00 00 00 23 00 00\n 00 00 52 67 68 74 6C 6F 6E 67 00 00 00 23 00 00\n 00 06 73 6C 69 63 65 73 56 6C 4C 73 00 00 00 01\n 4F 62 6A 63 00 00 00 01 00 00 00 00 00 05 73 6C\n 69 63 65 00 00 00 12 00 00 00 07 73 6C 69 63 65\n 49 44 6C 6F 6E 67 00 00 00 00 00 00 00 07 67 72\n 6F 75 70 49 44 6C 6F 6E 67 00 00 00 00 00 00 00\n 06 6F 72 69 67 69 6E 65 6E 75 6D 00 00 00 0C 45\n 53 6C 69 63 65 4F 72 69 67 69 6E 00 00 00 0D 61\n 75 74 6F 47 65 6E 65 72 61 74 65 64 00 00 00 00\n 54 79 70 65 65 6E 75 6D 00 00 00 0A 45 53 6C 69\n 63 65 54 79 70 65 00 00 00 00 49 6D 67 20 00 00\n 00 06 62 6F 75 6E 64 73 4F 62 6A 63 00 00 00 01\n 00 00 00 00 00 00 52 63 74 31 00 00 00 04 00 00\n 00 00 54 6F 70 20 6C 6F 6E 67 00 00 00 00 00 00\n 00 00 4C 65 66 74 6C 6F 6E 67 00 00 00 00 00 00\n 00 00 42 74 6F 6D 6C 6F 6E 67 00 00 00 23 00 00\n 00 00 52 67 68 74 6C 6F 6E 67 00 00 00 23 00 00\n 00 03 75 72 6C 54 45 58 54 00 00 00 01 00 00 00\n 00 00 00 6E 75 6C 6C 54 45 58 54 00 00 00 01 00\n 00 00 00 00 00 4D 73 67 65 54 45 58 54 00 00 00\n 01 00 00 00 00 00 06 61 6C 74 54 61 67 54 45 58\n 54 00 00 00 01 00 00 00 00 00 0E 63 65 6C 6C 54\n 65 78 74 49 73 48 54 4D 4C 62 6F 6F 6C 01 00 00\n 00 08 63 65 6C 6C 54 65 78 74 54 45 58 54 00 00\n 00 01 00 00 00 00 00 09 68 6F 72 7A 41 6C 69 67\n 6E 65 6E 75 6D 00 00 00 0F 45 53 6C 69 63 65 48\n 6F 72 7A 41 6C 69 67 6E 00 00 00 07 64 65 66 61\n 75 6C 74 00 00 00 09 76 65 72 74 41 6C 69 67 6E\n 65 6E 75 6D 00 00 00 0F 45 53 6C 69 63 65 56 65\n 72 74 41 6C 69 67 6E 00 00 00 07 64 65 66 61 75\n 6C 74 00 00 00 0B 62 67 43 6F 6C 6F 72 54 79 70\n 65 65 6E 75 6D 00 00 00 11 45 53 6C 69 63 65 42\n 47 43 6F 6C 6F 72 54 79 70 65 00 00 00 00 4E 6F\n 6E 65 00 00 00 09 74 6F 70 4F 75 74 73 65 74 6C\n 6F 6E 67 00 00 00 00 00 00 00 0A 6C 65 66 74 4F\n 75 74 73 65 74 6C 6F 6E 67 00 00 00 00 00 00 00\n 0C 62 6F 74 74 6F 6D 4F 75 74 73 65 74 6C 6F 6E\n 67 00 00 00 00 00 00 00 0B 72 69 67 68 74 4F 75\n 74 73 65 74 6C 6F 6E 67 00 00 00 00 00 38 42 49\n 4D 04 11 00 00 00 00 00 01 01 00 38 42 49 4D 04\n 14 00 00 00 00 00 04 00 00 00 01 38 42 49 4D 04\n 0C 00 00 00 00 03 D5 00 00 00 01 00 00 00 23 00\n 00 00 23 00 00 00 6C 00 00 0E C4 00 00 03 B9 00\n 18 00 01 FF D8 FF E0 00 10 4A 46 49 46 00 01 02\n 01 00 48 00 48 00 00 FF ED 00 0C 41 64 6F 62 65\n 5F 43 4D 00 02 FF EE 00 0E 41 64 6F 62 65 00 64\n 80 00 00 00 01 FF DB 00 84 00 0C 08 08 08 09 08\n 0C 09 09 0C 11 0B 0A 0B 11 15 0F 0C 0C 0F 15 18\n 13 13 15 13 13 18 11 0C 0C 0C 0C 0C 0C 11 0C 0C\n 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C\n 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 01 0D 0B 0B 0D 0E\n 0D 10 0E 0E 10 14 0E 0E 0E 14 14 0E 0E 0E 0E 14\n 11 0C 0C 0C 0C 0C 11 11 0C 0C 0C 0C 0C 0C 11 0C\n 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C\n 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C 0C FF C0 00 11 08\n 00 23 00 23 03 01 22 00 02 11 01 03 11 01 FF DD\n 00 04 00 03 FF C4 01 3F 00 00 01 05 01 01 01 01\n 01 01 00 00 00 00 00 00 00 03 00 01 02 04 05 06\n 07 08 09 0A 0B 01 00 01 05 01 01 01 01 01 01 00\n 00 00 00 00 00 00 01 00 02 03 04 05 06 07 08 09\n 0A 0B 10 00 01 04 01 03 02 04 02 05 07 06 08 05\n 03 0C 33 01 00 02 11 03 04 21 12 31 05 41 51 61\n 13 22 71 81 32 06 14 91 A1 B1 42 23 24 15 52 C1\n 62 33 34 72 82 D1 43 07 25 92 53 F0 E1 F1 63 73\n 35 16 A2 B2 83 26 44 93 54 64 45 C2 A3 74 36 17\n D2 55 E2 65 F2 B3 84 C3 D3 75 E3 F3 46 27 94 A4\n 85 B4 95 C4 D4 E4 F4 A5 B5 C5 D5 E5 F5 56 66 76\n 86 96 A6 B6 C6 D6 E6 F6 37 47 57 67 77 87 97 A7\n B7 C7 D7 E7 F7 11 00 02 02 01 02 04 04 03 04 05\n 06 07 07 06 05 35 01 00 02 11 03 21 31 12 04 41\n 51 61 71 22 13 05 32 81 91 14 A1 B1 42 23 C1 52\n D1 F0 33 24 62 E1 72 82 92 43 53 15 63 73 34 F1\n 25 06 16 A2 B2 83 07 26 35 C2 D2 44 93 54 A3 17\n 64 45 55 36 74 65 E2 F2 B3 84 C3 D3 75 E3 F3 46\n 94 A4 85 B4 95 C4 D4 E4 F4 A5 B5 C5 D5 E5 F5 56\n 66 76 86 96 A6 B6 C6 D6 E6 F6 27 37 47 57 67 77\n 87 97 A7 B7 C7 FF DA 00 0C 03 01 00 02 11 03 11\n 00 3F 00 F5 54 0B 33 71 AB 79 AC BF 75 83 53 5B\n 01 7B 84 F1 B9 95 EE 73 54 F2 1C E6 D1 63 9B F4\n 9A C7 16 FC 40 5C F7 49 B7 1A FA 19 51 BF 23 1B\n 2C B4 3A EC 7B 2D 65 76 6E 23 DC FD 06 FB 58 FF\n 00 A4 CB 92 53 1E B9 F5 9B 3E 96 DB 8D 83 D3 B2\n 85 A7 DB 56 53 D8 1B 5C E9 EE 0F 7E E6 37 FE B8\n AF FD 5B FD AA 71 9E EE A2 CB 6A 26 36 D7 7B C5\n 8F 07 5D EE DE 27 F4 7F 43 E9 21 E5 D5 85 8D 59\n 39 B9 04 56 EE 45 D9 6F F7 79 7A 6D 1E FF 00 EA\n AB 9D 0A C3 67 4D AC 9A AC C7 01 CF 0C A6 D2 4B\n DA D0 E7 7A 61 FE A4 BF E8 7E FA 4A 74 12 49 24\n 94 FF 00 FF D0 F5 2B DA 5D 4D 8D 1C B9 A4 7D E1\n 66 F4 FB BA 7F 50 C3 C7 17 D4 CF 59 B5 33 F4 57\n 06 97 00 47 2D 9F CC 74 7D 26 2D 55 CC 7D 61 CD\n 7F 40 38 66 BA 99 76 16 4D CE AD EC B8 4B 69 2E\n 06 C6 7A 76 0F 73 37 D9 EC D8 EF EC 24 A7 61 95\n 74 7C 70 6F 6B 28 AF 61 FE 72 1B 20 8F DD 77 D2\n 44 E9 97 8C 8C 63 7B 5A E6 36 CB 2C 21 AE D1 D0\n 1E EA F5 1F D8 58 1F 57 FA 95 DD 6B 23 25 B5 D5\n 5E 23 31 F6 13 63 1A 1E F9 70 73 76 56 F7 7B 6A\n FE 6F 7F D0 FC F5 D3 63 D1 56 3D 2C A6 A6 ED AD\n 82 1A 12 52 44 92 49 25 3F FF D1 F5 55 47 AD C7\n EC AC AD DE 84 7A 6E 9F B5 4F A3 11 FE 1B 67 BF\n 67 F5 17 CC 69 24 A7 E9 6F AB BB 7F 66 55 B7 EC\n BB 60 47 D8 B7 7A 5C 7F C2 7E 93 FC F5 A8 BE 55\n 49 25 3F 55 24 BE 55 49 25 3F FF D9 00 38 42 49\n 4D 04 21 00 00 00 00 00 55 00 00 00 01 01 00 00\n 00 0F 00 41 00 64 00 6F 00 62 00 65 00 20 00 50\n 00 68 00 6F 00 74 00 6F 00 73 00 68 00 6F 00 70\n 00 00 00 13 00 41 00 64 00 6F 00 62 00 65 00 20\n 00 50 00 68 00 6F 00 74 00 6F 00 73 00 68 00 6F\n 00 70 00 20 00 37 00 2E 00 30 00 00 00 01 00 38\n 42 49 4D 04 06 00 00 00 00 00 07 00 08 01 01 00\n 01 01 00 FF E1 12 48 68 74 74 70 3A 2F 2F 6E 73\n 2E 61 64 6F 62 65 2E 63 6F 6D 2F 78 61 70 2F 31\n 2E 30 2F 00 3C 3F 78 70 61 63 6B 65 74 20 62 65\n 67 69 6E 3D 27 EF BB BF 27 20 69 64 3D 27 57 35\n 4D 30 4D 70 43 65 68 69 48 7A 72 65 53 7A 4E 54\n 63 7A 6B 63 39 64 27 3F 3E 0A 3C 3F 61 64 6F 62\n 65 2D 78 61 70 2D 66 69 6C 74 65 72 73 20 65 73\n 63 3D 22 43 52 22 3F 3E 0A 3C 78 3A 78 61 70 6D\n 65 74 61 20 78 6D 6C 6E 73 3A 78 3D 27 61 64 6F\n 62 65 3A 6E 73 3A 6D 65 74 61 2F 27 20 78 3A 78\n 61 70 74 6B 3D 27 58 4D 50 20 74 6F 6F 6C 6B 69\n 74 20 32 2E 38 2E 32 2D 33 33 2C 20 66 72 61 6D\n 65 77 6F 72 6B 20 31 2E 35 27 3E 0A 3C 72 64 66\n 3A 52 44 46 20 78 6D 6C 6E 73 3A 72 64 66 3D 27\n 68 74 74 70 3A 2F 2F 77 77 77 2E 77 33 2E 6F 72\n 67 2F 31 39 39 39 2F 30 32 2F 32 32 2D 72 64 66\n 2D 73 79 6E 74 61 78 2D 6E 73 23 27 20 78 6D 6C\n 6E 73 3A 69 58 3D 27 68 74 74 70 3A 2F 2F 6E 73\n 2E 61 64 6F 62 65 2E 63 6F 6D 2F 69 58 2F 31 2E\n 30 2F 27 3E 0A 0A 20 3C 72 64 66 3A 44 65 73 63\n 72 69 70 74 69 6F 6E 20 61 62 6F 75 74 3D 27 75\n 75 69 64 3A 34 37 38 34 61 35 39 66 2D 37 65 64\n 66 2D 31 31 64 64 2D 39 61 37 39 2D 61 31 62 66\n 63 38 33 61 61 63 63 36 27 0A 20 20 78 6D 6C 6E\n 73 3A 78 61 70 4D 4D 3D 27 68 74 74 70 3A 2F 2F\n 6E 73 2E 61 64 6F 62 65 2E 63 6F 6D 2F 78 61 70\n 2F 31 2E 30 2F 6D 6D 2F 27 3E 0A 20 20 3C 78 61\n 70 4D 4D 3A 44 6F 63 75 6D 65 6E 74 49 44 3E 61\n 64 6F 62 65 3A 64 6F 63 69 64 3A 70 68 6F 74 6F\n 73 68 6F 70 3A 34 37 38 34 61 35 39 64 2D 37 65\n 64 66 2D 31 31 64 64 2D 39 61 37 39 2D 61 31 62\n 66 63 38 33 61 61 63 63 36 3C 2F 78 61 70 4D 4D\n 3A 44 6F 63 75 6D 65 6E 74 49 44 3E 0A 20 3C 2F\n 72 64 66 3A 44 65 73 63 72 69 70 74 69 6F 6E 3E\n 0A 0A 3C 2F 72 64 66 3A 52 44 46 3E 0A 3C 2F 78\n 3A 78 61 70 6D 65 74 61 3E 0A 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 0A 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 0A 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 0A 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 0A 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 0A 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 0A 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 0A 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 0A 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 0A 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 0A 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 0A 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 0A\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 0A 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 0A 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 0A 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 0A 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 0A 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 0A 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 0A 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 0A 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 0A 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 0A 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 0A 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 0A 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 0A 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 0A\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 0A 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 0A 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 0A 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 0A 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 0A 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 0A 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 0A 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 0A 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 0A 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20\n 20 20 20 20 20 20 20 20 20 0A 3C 3F 78 70 61 63\n 6B 65 74 20 65 6E 64 3D 27 77 27 3F 3E FF EE 00\n 21 41 64 6F 62 65 00 64 40 00 00 00 01 03 00 10\n 03 02 03 06 00 00 00 00 00 00 00 00 00 00 00 00\n FF DB 00 84 00 01 01 01 01 01 01 01 01 01 01 01\n 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01\n 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01\n 02 02 02 02 02 02 02 02 02 02 02 03 03 03 03 03\n 03 03 03 03 03 01 01 01 01 01 01 01 01 01 01 01\n 02 02 01 02 02 03 03 03 03 03 03 03 03 03 03 03\n 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03\n 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03 03\n 03 03 03 03 03 03 FF C2 00 11 08 00 23 00 23 03\n )\n @image.__send__(\"process_jpg\", [data.join('')].pack('H*'))\n assert_equal(@type, @image.type)\n assert_equal(35, @image.width)\n assert_equal(35, @image.height)\n end", "def display_image \r\n self.image.variant(resize_to_limit: [1000, 1000]) \r\n end", "def optimize_retina!(name, options={})\n config = versions[name]\n options[:retina] = false\n\n processors = if config.respond_to?(:processors)\n config.processors.dup\n else\n config[:uploader].processors.dup\n end\n dimensions_processor = nil\n\n ## Check if there's a resize processor to get the dimensions\n processors.each do |p|\n dimensions_processor = processors.delete(p) if p[0].to_s.scan(/resize_to_fill|resize_to_limit|resize_to_fit|resize_and_pad/).any?\n end\n\n ## Define a retina version if processor is present\n if dimensions_processor\n dimensions = dimensions_processor[1].dup\n\n width = dimensions[0] * 2\n height = dimensions[1] * 2\n\n 2.times { dimensions.delete_at(0) }\n\n dimensions.insert(0, height)\n dimensions.insert(0, width)\n\n ## Reset the processors\n if config.respond_to?(:processors)\n config.processors = []\n else\n config[:uploader].processors = []\n end\n\n ## Override version with double height and width\n version name, options do\n process dimensions_processor[0] => dimensions\n\n quality_processor = nil\n\n ## Set other processors\n processors.each do |processor|\n process processor[0] => processor[1]\n\n quality_processor = true if processor[0] == :retina_quality\n end\n\n ## Set default quality if retina_quality is not defined\n process :retina_quality => 60 if quality_processor.nil?\n\n ## Store dimensions\n process :store_retina_dimensions\n end\n end\n end", "def large_process\n case [model.attachable_type, model.image_type]\n when ['User', 'avatar'] then\n resize_to_fill 1024, 683 # 3x2\n when ['User', 'inspiration'] then\n resize_to_fit 1024, 9999 # fixed width\n when ['Message', 'avatar'] then\n resize_to_fit 1024, 9999 # fixed width\n when ['Message', 'alternate'] then\n resize_to_fit 1024, 9999 # fixed width\n when ['Alternative', 'avatar'] then\n resize_to_fill 1024, 683 # 3x2\n else\n resize_to_fit 1024, 9999 # fixed width\n end\n # TODO: Test and implement this.\n # fix_exif_rotation\n quality 70\n end", "def upRes(file_path)\t\n\t\toriginal_image = Magick::Image.read(file_path) { self.density = \"300.0x300.0\" }\n\t\toriginal_image.each do |image|\n\t\t\t image = image.resample(300.0, 300.0)\n\t\t\t image.write(file_path) { self.quality = 100 }\n\t\tend\n\tend", "def quality(percent)\n write_opts[:Q] = percent\n get_image\n end", "def image_size\n if image.size > 2.megabytes\n errors.add(:image, \"Cover size after resize process should be less than 2MB\")\n end\n end", "def optimize_retina!(name)\n attachment = attachment_definitions[name]\n\n ## Check for style definitions\n styles = attachment[:styles]\n\n retina_options = if attachment[:retina].is_a?(Hash)\n attachment[:retina]\n else\n { :quality => 60 }\n end\n\n ## Get retina quality\n retina_quality = retina_options[:quality] || 40\n\n if styles\n\n retina_styles = {}\n retina_convert_options = {}\n convert_options = attachment[:convert_options]\n\n ## Iterate over styles and set optimzed dimensions\n styles.each_pair do |key, value|\n dimensions = value.kind_of?(Array) ? value[0] : value\n new_dimensions = dimensions.gsub(/\\d+/) { |dimension| dimension.to_i * 2}\n retina_styles[key.to_sym] = value.kind_of?(Array) ? [new_dimensions, value[1]] : new_dimensions\n\n ## Set quality convert option\n convert_option = convert_options[key] if convert_options\n convert_option = convert_option ? \"#{convert_option} -quality #{retina_quality}\" : \"-quality #{retina_quality}\"\n retina_convert_options[key.to_sym] = convert_option\n\n end\n\n ## Override styles with new retina dimensions\n attachment[:styles].merge!(retina_styles)\n\n ## Set quality convert options\n attachment[:convert_options] = {} if attachment[:convert_options].nil?\n attachment[:convert_options].merge!(retina_convert_options)\n\n ## Set save dimensions processor\n if attachment[:processors]\n attachment[:processors] << :save_dimensions\n attachment[:processors] << :thumbnail\n else\n attachment[:processors] = [:thumbnail, :save_dimensions]\n end\n\n end\n end", "def run_examination\n if stream.missing?\n @original_width, @original_height = 1, 1\n false\n else\n output = `identify -format \"%w %h %[exif:Orientation]\" #{stream.path} 2> /dev/null`\n if $?.success? && output.present?\n width, height, orientation = *output.scan(/(\\d+) (\\d+) (\\d?)/).first.map{|s| s.to_i}\n rotated = (5..8).include?(orientation)\n @original_width = rotated ? height : width\n @original_height = rotated ? width : height\n true\n else\n Bulldog.logger.warn \"command failed (#{$?.exitstatus})\"\n @original_width, @original_height = 1, 1\n false\n end\n end\n end", "def create_resized_image\n create_image do |xfrm|\n if size\n MiniMagick::Tool::Convert.new do |cmd|\n cmd << xfrm.path # input\n cmd.flatten\n cmd.resize(size)\n cmd << xfrm.path # output\n end\n end\n end\n end", "def resize_image(img, size)\n size = size.first if size.is_a?(Array) && size.length == 1 && !size.first.is_a?(Fixnum)\n if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))\n size = [size, size] if size.is_a?(Fixnum)\n img.thumbnail!(*size)\n elsif size.is_a?(String) && size =~ /^c.*$/ # Image cropping - example geometry string: c75x75\n dimensions = size[1..size.size].split(\"x\")\n img.crop_resized!(dimensions[0].to_i, dimensions[1].to_i)\n elsif size.is_a?(String) && size =~ /^b.*$/ # Resize w/border - example geometry string: b75x75\n dimensions = size[1..size.size].split(\"x\")\n img.change_geometry(dimensions.join(\"x\")) do |cols, rows, image| \n image.resize!(cols<1 ? 1 : cols, rows<1 ? 1 : rows ) \n end\n img.background_color = \"black\"\n x_offset = (img.columns - dimensions[0].to_i) / 2\n y_offset = (img.rows - dimensions[1].to_i) / 2\n img = img.extent(dimensions[0].to_i, dimensions[1].to_i, x_offset, y_offset)\n else\n img.change_geometry(size.to_s) { |cols, rows, image| image.resize!(cols<1 ? 1 : cols, rows<1 ? 1 : rows) }\n end\n img.strip! unless attachment_options[:keep_profile]\n temp_paths.unshift write_to_temp_file(img.to_blob)\n end", "def print\n Catpix::print_image self.img_url,\n :limit_x => 1.0,\n :limit_y => 0,\n :center_x => true,\n :center_y => true,\n :bg => \"white\",\n :bg_fill => true,\n :resolution => \"low\"\n end", "def processed_image(image, options = {})\n size = options[:size]\n upsample = !!options[:upsample]\n\n return image unless size.present? && has_convertible_format?\n\n if options[:crop]\n crop(size, options[:crop_from], options[:crop_size], upsample)\n else\n resize(size, upsample)\n end\n end", "def strict_resize image, w, h\n image.resize \"#{ w }x#{ h }!\"\n image\n end", "def resize\n if size.max > 1024\n res = %x( #{magick_bin_name(\"convert\")} -auto-orient -resize 1024x768 #{Shellwords.shellescape path} #{Shellwords.shellescape path})\n Rails.logger.info res\n end\n unless has_thumbnail?\n unless File.exists? path.gsub(/(.+)\\/.+/, '\\1/thumbs')\n Dir.mkdir path.gsub(/(.+)\\/.+/, '\\1/thumbs')\n end\n ## that's a bit broken on windows - why?\n res = %x( #{magick_bin_name(\"convert\")} -verbose -auto-orient -strip -thumbnail 300x160 #{Shellwords.shellescape path} #{Shellwords.shellescape path.gsub(/(.+)\\/(.+)/, '\\1/thumbs/\\2')})\n Rails.logger.info res\n end\n end", "def resize_pic(filename,resizewidth,out_path)\n nw = resizewidth\n n = File.basename(filename)\n i = QuickMagick::Image.read(filename).first\n w = i.width.to_f # Retrieves width in pixels\n h = i.height.to_f # Retrieves height in pixels\n pr = w/h\n nh = nw/pr \n i.resize \"#{nw}x#{nh}!\"\n i.save \"#{out_path}/#{n}\"\nend", "def image_size\n\t\tif image.size > 500.kilobytes\n\t\t\terrors.add(:image, \"should be less than 500kB\")\n\t\tend\n\tend", "def thumbnail input\n return self.images[input].variant(resize: '300x300').processed\n end", "def valid?\n !(image_too_small? || image_too_big?)\n end", "def optimize(image_path)\n print_status(\"Optimizing #{image_path}, this may take a while...\")\n ImageOptimizer.new(image_path, quiet: true).optimize\nend", "def im_identify(source_name)\n \n # configure in local_config.rb\n identify = \"#{IMAGE_MAGICK_PATH}identify\"\n\n #raise \"Failed to find 'identify' binary on your system. Check your ImageMagick installation.\" unless `#{identify} --version`[\"ImageMagick\"]\n \n # Finally figured out how to make identify fast (-ping)\n # assume identify is in PATH for compatibility\n cmd = \"#{identify} -ping -format '%m:%w:%h' #{source_name}\"\n # logger.info(\"$PATH is: \" + `echo $PATH`)\n logger.info(\"Executing '#{cmd}'\")\n \n res = `#{cmd}`.strip.gsub(\"'\",'').split(\":\") # the gsub fixes a bug on PCs where additional characters were added\n {:type => res[0], :width => res[1], :height => res[2]}\n end", "def display_image\n image.variant(resize_to_limit: [500,500])\n end", "def resize_image(img, size)\n size = size.first if size.is_a?(Array) && size.length == 1 && !size.first.is_a?(Fixnum)\n if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))\n size = [size, size] if size.is_a?(Fixnum)\n img.thumbnail!(*size)\n elsif size.is_a?(String) && size =~ /^c.*$/ # Image cropping - example geometry string: c75x75\n dimensions = size[1..size.size].split(\"x\")\n img.crop_resized!(dimensions[0].to_i, dimensions[1].to_i)\n elsif size.is_a?(String) && size =~ /^b.*$/ # Resize w/border - example geometry string: b75x75\n dimensions = size[1..size.size].split(\"x\")\n img.change_geometry(dimensions.join(\"x\")) do |cols, rows, image|\n image.resize!(cols<1 ? 1 : cols, rows<1 ? 1 : rows )\n end\n img.background_color = \"black\"\n x_offset = (img.columns - dimensions[0].to_i) / 2\n y_offset = (img.rows - dimensions[1].to_i) / 2\n img = img.extent(dimensions[0].to_i, dimensions[1].to_i, x_offset, y_offset)\n else\n img.change_geometry(size.to_s) { |cols, rows, image| image.resize!(cols<1 ? 1 : cols, rows<1 ? 1 : rows) }\n end\n img.strip! unless attachment_options[:keep_profile]\n temp_paths.unshift write_to_temp_file(img.to_blob)\n end", "def generate_compressed path, img\n img.write(path) { self.quality = 70 }\n end", "def image_too_small?\n @temp_file.open if @temp_file.closed?\n @temp_file.size < options[:min_size]\n end", "def resize_image(file_name,resize_file_name=\"test\",resized_width=0,resized_height=0,render_file_as=\"png\")\n image = Image.import(file_name)\n resize_image = image.resize(resized_width, resized_height,true)\n\n file=File.new(resize_file_name,\"wb\")\n if render_file_as == \"png\"\n file.write resize_image.png\n elsif\t render_file_as == \"jpeg\"\n file.write resize_image.jpeg\n elsif\t render_file_as == \"gd\"\n file.write resize_image.gd\n elsif\t render_file_as == \"gd2\"\n file.write resize_image.gd2\n else\n puts \"Provide proper image\"\n end\n file.close\n end", "def check_for_resize; end", "def old_resize_image(img, size)\n size = size.first if size.is_a?(Array) && size.length == 1 && !size.first.is_a?(Fixnum)\n if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))\n size = [size, size] if size.is_a?(Fixnum)\n img.thumbnail!(*size)\n elsif size.is_a?(String) && size =~ /^c.*$/ # Image cropping - example geometry string: c75x75\n dimensions = size[1..size.size].split(\"x\")\n img.crop_resized!(dimensions[0].to_i, dimensions[1].to_i)\n else\n img.change_geometry(size.to_s) { |cols, rows, image| image.resize!(cols<1 ? 1 : cols, rows<1 ? 1 : rows) }\n end\n self.width = img.columns if respond_to?(:width)\n self.height = img.rows if respond_to?(:height)\n img.strip! unless attachment_options[:keep_profile]\n quality = img.format.to_s[/JPEG/] && get_jpeg_quality\n out_file = write_to_temp_file(img.to_blob { self.quality = quality if quality })\n temp_paths.unshift out_file\n self.size = File.size(self.temp_path)\n end", "def display_image\n image.variant(resize_to_limit: [500, 500])\n end", "def display_image\n image.variant(resize_to_limit: [500, 500])\n end", "def display_image\n image.variant(resize_to_limit: [500, 500])\n end", "def display_image\n image.variant(resize_to_limit: [500, 500])\n end", "def display_image\n image.variant(resize_to_limit: [500, 500])\n end", "def display_image\n image.variant(resize_to_limit: [500, 500])\n end", "def image_too_big?\n @temp_file.open if @temp_file.closed?\n @temp_file.size > options[:max_size]\n end", "def calculate_aspect_ratio(info, options)\n if options[:preserve_aspect_ratio]\n composited_size = SmartImage::RatioCalculator.new(\n :source_width => info.width,\n :source_height => info.height,\n :dest_width => Integer(options[:width]), \n :dest_height => Integer(options[:height])\n ).size\n\n return composited_size.width, composited_size.height\n else\n return options[:width], options[:height]\n end\n end", "def successful_conversion?\n source = File.join(\"tmp\", \"#{@user.screen_name}_full_size\")\n full_size = File.join(DIRECTORY, filename)\n thumbnail = File.join(DIRECTORY, thumbnail_name)\n File.open(source, \"wb\") { |f| f.write(@image.read) }\n img = system(\"#{convert} #{source} -resize #{IMG_SIZE} #{full_size}\")\n thumb = system(\"#{convert} #{source} -resize #{THUMB_SIZE} #{thumbnail}\")\n File.delete(source) if File.exists?(source)\n unless img and thumb\n errors.add_to_base(\"File upload failed: Try a different image\")\n return false\n end\n return true\n end", "def file_converter()\n pdf_files = populate_files(/.*\\.pdf$|.*\\.PDF$/)\n\n #converting pdf to jpg then to tiff\n pdf_files.each { |pdf_file|\n\n required = false;\n key = pdf_file\n $requiredDocs.each do |requiredFileName|\n if(pdf_file.include?(requiredFileName))\n required=true\n key = requiredFileName\n end\n end\n\n next if !required\n\n jpg_file = pdf_file.chomp('.pdf').chomp('.PDF').chomp('.png') + '.jpg'\n gs_tiff_file = pdf_file.chomp('.pdf').chomp('.PDF').chomp('.png')\n\n if $sysdocMapMiniMalImg[key] == false\n jpg_file=jpg_file.split(\".\")[0] << \"_converted.\"+jpg_file.split(\".\")[1]\n jpg_file_name = File.basename jpg_file, \".jpg\"\n puts \"converted file name #{jpg_file_name}\"\n\n #command to convert pdf to jpg\n convertCmdJPG = \"convert -strip -density 150 \\\"#{pdf_file}\\\" -quality 30 -colorspace Gray \\\"#{jpg_file}\\\"\"\n # both image and text quality is maintained\t\n #gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=tiffgray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r120 -sCompression=lzw -dBackgroundColor=16#ffffff -sOutputFile=AADHAAR_manual4.tiff AADHAAR.PDF\n # text quality maintained but image quality suffers\n #gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=tiffg4 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r120 -sCompression=lzw -dBackgroundColor=16#ffffff -sOutputFile=AADHAAR_manual5.tiff AADHAAR.PDF\n # for very high resolution images use the below to flags\n # -sPAPERSIZE=a4 -dFitPage \n # tmp convert to png\n # gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=pnggray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r150 -dCompatibilityLevel=1.4 -sCompression=lzw -sPAPERSIZE=a4 -dFitPage -dBackgroundColor=16#ffffff -sOutputFile=BANK_STATEMENT-150-tmp-%02d.png BANK_STATEMENT.PDF\n # convert the png to jpeg with 20% compression\n # convert -verbose -density 150 BANK_STATEMENT-150-tmp-*.png -quality 80 BANK_STATEMENT-150-80-tmp-%02d.jpg\n\n # convert directly to pnggray from ghost script\n # gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=jpeggray -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r150 -sCompression=lzw -dFitPage -dBackgroundColor=16#ffffff -dJPEGQ=50 -sOutputFile=APPLICATION_PDF-r120-30-jgray-clzw-%02d.jpg APPLICATION_PDF.pdf\n\n #%x is used to run from shell\n %x(#{convertCmdJPG})\n\n\n converted_file_path= populate_files(/.*#{jpg_file_name}*.jpg$/)\n #if pdf has one or more page then convert will create new no of files depend on the pages.So combining them those one. So that when uploading it wont cause confusion\n puts \"Number of Converted files - #{converted_file_path.size()}\"\n if converted_file_path.size() == 0\n converted_file_path= populate_files(/.*#{jpg_file_name}-*[0-9].jpg$/)\n puts \"Number of Converted files - #{converted_file_path.size()}\"\n end\n\n # if the page count is more than N, two things can\n # happen :-\n # 1. CMS upload will fail\n # 2. If we try to combine the jpg to a single jpg, max resolution exceeded error will pop up\n\n if converted_file_path.size > 40\n puts \"Page limit exceeded. This request will fail\"\n # TODO send out error PAGE_LIMIT_EXCEEDED\n end\n converted_file_path.each_with_index { |jpg, fileCount|\n #all_jpg_files = \"#{jpg_file_name}-*[0-9][0-9].jpg\"\n #puts \"All JPG Files - #{all_jpg_files}\"\n #combine_jpg_file = \"#{jpg_file_name}-combined.jpg\"\n #puts \"Combined file - #{combine_jpg_file}\"\n #combineCmd = \"convert \\\"#{all_jpg_files}\\\" -append \\\"#{combine_jpg_file}\\\" \"\n #command to combine all the jpg\n #%x(#{combineCmd})\n\n # convert to tiff or\n # TODO upload to cms one by one\n\n #tiff_file = jpg.chomp('.jpg').chomp('.JPG').chomp('.JPEG').chomp('.jpeg').chomp('.png') + '.tiff'\n #tiff_file=tiff_file.split(\".\")[0] << \"_converted.\"+tiff_file.split(\".\")[1]\n #tiff_file_name = File.basename tiff_file, \".tiff\"\n #puts \"converted file name #{tiff_file}\"\n\n #command to convert jpg to tiff\n #convertCmdTIFF = \"convert -strip \\\"#{jpg}\\\" \\\"#{tiff_file}\\\"\"\n #%x is used to run from shell\n #%x(#{convertCmdTIFF})\n }\n\n # combine if one pdf generated multiple jpg/tiff\n #if converted_file_path.size()> 1\n # all_tiff_files = $file_path + \"/*#{jpg_file_name}*.tiff\"\n # combine_tiff_file = $file_path+\"/#{jpg_file_name}-combined.tiff\"\n # combineCmd = \"convert -append \\\"#{all_tiff_files}\\\" \\\"#{combine_tiff_file}\\\" \"\n # #command to combine all the jpeg to a final tiff\n # %x(#{combineCmd})\n #end\n else\n # Using Ghost script\n # command to convert PDF to tiff\n convertCmdgsTIFF = \"gs -q -dNOPAUSE -sDEVICE=tiffgray -r150 -sCompression=lzw -sOutputFile='#{gs_tiff_file}-%02d.tiff' #{pdf_file} -c quit\"\n #%x is used to run from shell\n %x(#{convertCmdgsTIFF})\n # TODO if resolution is more than A4 r=120/900x1400 then resize it to A4\n # TODO upload to cms\n end\n }\n\n #all_converted_files = $file_path + \"/*_converted.tiff\"\n #all_combined_files = $file_path + \"/*_converted-combined.tiff\"\n #final_file = $file_path+\"/converted-final.tiff\"\n #puts \"Final tiff files\"\n #populate_files(all_converted_files)\n #populate_files(all_combined_files)\n #combineCmd = \"convert -append \\\"#{all_converted_files}\\\" \\\"#{all_combined_files}\\\" \\\"#{final_file}\\\" \"\n #command to combine all the tiff\n #%x(#{combineCmd})\n\nend", "def write_png_from_svg(input, output, width, height)\n success = true\n begin\n Magick::Image.read(input).first.resize(width, height).write(output)\n rescue\n success = false\n end\n success\nend", "def thumbnail(data, options = {})\n source_info = info data\n \n opts = {\n :width => source_info.width,\n :height => source_info.height,\n :preserve_aspect_ratio => true,\n :format => :png\n }.merge(options)\n \n width, height = calculate_aspect_ratio source_info, opts\n \n # Set res so we can assign it within the SmartImage.new block\n res = nil\n \n SmartImage.new(width, height) do |image|\n image.composite data, :width => width,\n :height => height,\n :preserve_aspect_ratio => false\n \n res = image.encode opts[:format]\n end\n \n res\n end", "def quality?(quality)\n quality >= 0 && quality < 50\n end", "def convert_image\n i = 0 \n main = [small\t=\t[\"jpg\",\"small\",240,160], \n\t medium\t=\t[\"jpg\",\"medium\",640,427], \n\t large\t=\t[\"jpg\",\"large\",1024,683]]\n while i < main.count\n # Runs the resize function with params to each size\n resize_image(main[i])\n i +=1\n end\n end", "def floatable_size?\n image_width && image_width < 500\n end" ]
[ "0.64244705", "0.6380331", "0.63627076", "0.63494796", "0.6327457", "0.6321721", "0.63078254", "0.62726974", "0.6209394", "0.6186229", "0.61421037", "0.6132888", "0.6129049", "0.6117874", "0.60891587", "0.60744673", "0.60596305", "0.60316795", "0.6023955", "0.60224074", "0.6013769", "0.6013338", "0.60054207", "0.5994689", "0.59513694", "0.59304786", "0.5921177", "0.5913429", "0.5874443", "0.58469427", "0.5841118", "0.58370996", "0.5832283", "0.5826234", "0.5823878", "0.58237135", "0.5786463", "0.57830036", "0.57305473", "0.571901", "0.56645757", "0.5656943", "0.56446815", "0.56431115", "0.5637492", "0.5631809", "0.56275225", "0.5609257", "0.5567874", "0.5552013", "0.55517113", "0.5551075", "0.55483407", "0.55475557", "0.55354184", "0.5530938", "0.5523686", "0.55212575", "0.5508003", "0.5505001", "0.5501624", "0.5495868", "0.54939115", "0.54808867", "0.5473901", "0.54678476", "0.54674286", "0.5464954", "0.54626656", "0.5451778", "0.5447934", "0.54469365", "0.5445692", "0.5444138", "0.5438639", "0.54319113", "0.5429627", "0.5428865", "0.54246473", "0.541997", "0.5419293", "0.5418709", "0.541514", "0.54143107", "0.5412901", "0.5403827", "0.5403827", "0.5403827", "0.5403827", "0.5403827", "0.5403827", "0.5398966", "0.5393478", "0.5389835", "0.5388121", "0.53740644", "0.5367295", "0.536491", "0.5361929", "0.53580964" ]
0.6312013
6
Metodo para la indexacion
def [](i) @m_Matrix[i] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def construct_index\n end", "def ta_index\n end", "def add_index_field(*) super end", "def index ; @index ; end", "def index; @index; end", "def index\n set_index\n end", "def index_signature; end", "def index elemento\n end", "def setting_index\n end", "def index\r\n build_index unless @index\r\n @index\r\n end", "def indexes\n raise 'not implemented'\n end", "def index=(_arg0); end", "def indexed\n meta(index: true)\n end", "def index_on( field, opts={} )\n opts = Gnash.new( opts )\n design_document(true).add!( opts.merge!(:name => field) )\n unless indexes.include?( field )\n indexes << field.to_sym \n indexes << field.to_s \n end \n self \n end", "def indexed\n self['indexed']\n end", "def lttfindex\n end", "def index_information\n @db.index_information(@name)\n end", "def indexes(*rest) end", "def indexes(*rest) end", "def index_type\n name\n end", "def index_finalized\n index\n end", "def index\n raise NotImplementedError\n end", "def index_information\n @db.index_information(@name)\n end", "def index\n @index ||= self.class.index\n end", "def index\r\n @index ||= 0\r\n end", "def index()\n @index\n end", "def require_index(name); end", "def require_index(name); end", "def index\n @index ||= 1\n end", "def [](index_or_name)\n end", "def [](index_or_name)\n end", "def index\n raise \"not supported\"\n end", "def index?; end", "def student_index\n end", "def index\n logger.info 'Index of elements'\n end", "def business_indices(*args)\n end", "def index\n\t\t\n\tend", "def index\n\t\t\n\tend", "def index\n\t\t\n\tend", "def index\n\t\t\n\tend", "def index\n\t\t\n\tend", "def atributos_index\n [ :id,\n :nusuario,\n :nombre,\n :email,\n :grupo_ids,\n :foto,\n :habilitado,\n ]\n end", "def tax_index\n\n end", "def index\n self.class.all.index(self)\n end", "def biodiversity_index(specimens)\nend", "def biodiversity_index(specimens)\nend", "def tableau index_tableau\n tableaux_in(resultat_final)[index_tableau]\n end", "def add_indexes\n if hereditary? && !index_options[{ _type: 1 }]\n index({ _type: 1 }, { unique: false, background: true })\n end\n true\n end", "def index\n @ole.Index\n end", "def index\n @ole.Index\n end", "def index\n @ole.Index\n end", "def index\n @ole.Index\n end", "def default_index_subaction\n list_all\n end", "def create_index\n self[:create_index]\n end", "def indexes\n @indexes ||= []\n end", "def index_template\n :index\n end", "def index_template\n :index\n end", "def index_name\n @element[:name] || @element[:column]\n end", "def index\n raise(NotImplementedError, \"You need to define your own index() method\")\n end", "def index\n @title = \"Tenjin\"\n @inst_var_one = \"INST_VAR_ONE\"\n @inst_var_two = \"INST_VAR_TWO\"\n return \"#{self.class}: INDEX RETURN STRING\"\n end", "def index_information\n collection.index_information\n end", "def index_information\n collection.index_information\n end", "def index_information\n collection.index_information\n end", "def index(name, type = :find)\n @defined_indexes ||= {}\n @defined_indexes[name.to_sym] = type\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", "def index; end", "def index; end", "def index()\n INDEXES.find { |i| (self + i).exist? }&.yield_self { |i| self + i }\n end", "def supports_partial_indexes?\n true\n end", "def index\t\t\n\tend", "def check_index_finder\n # Leave it alone\n end" ]
[ "0.81736577", "0.7801928", "0.77983326", "0.77701855", "0.75958234", "0.75148547", "0.74871033", "0.74796593", "0.7478186", "0.746287", "0.74186707", "0.7293735", "0.7249419", "0.7233055", "0.7229382", "0.71772736", "0.71559036", "0.71418726", "0.71418726", "0.7043069", "0.7031591", "0.69702214", "0.6945715", "0.69402736", "0.6935342", "0.69302523", "0.6913891", "0.6913891", "0.690711", "0.69036686", "0.69036686", "0.6892668", "0.6887027", "0.68827295", "0.6875243", "0.6837596", "0.67866164", "0.67866164", "0.67866164", "0.67866164", "0.67866164", "0.6784131", "0.6779318", "0.6757341", "0.6739375", "0.6739375", "0.66982937", "0.6696902", "0.6695238", "0.6695238", "0.6695238", "0.6695238", "0.66929007", "0.6689877", "0.6686117", "0.6677576", "0.6677576", "0.6665952", "0.6649244", "0.66419923", "0.6641621", "0.6641621", "0.6641621", "0.6629369", "0.6627437", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.662631", "0.66139424", "0.6604991", "0.65975237", "0.65930647" ]
0.0
-1
Metodo que retorna un SparseVector con los valores de una columna.
def cols(j) c = {} for r in @m_Matrix.keys do c[r] = @m_Matrix[r].vector[j] if @m_Matrix[r].vector.keys.include? j end SparseVector.new c end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def covector\n SparseMatrix.row_vector(self)\n end", "def column_vectors\n # (0 .. column_size - 1).collect { |i| column(i) }\n my_rows = @rows\n r_size = my_rows.size\n col_size = my_rows[0].size\n vector_cls = Vector\n array_cls = Array\n res = array_cls.new(col_size)\n for j in 0..col_size-1 do\n a_col = array_cls.new(r_size)\n for i in 0..r_size-1 do\n a_col[i] = my_rows[i][j]\n end\n res[j] = Vector.elements(a_col, false)\n end\n res\n end", "def to_sparse(label = nil)\n sparse_elems = []\n self.each_with_index do |v, i, j|\n sparse_elems << [i, j, v] if v != 0\n end\n return SparseMatrix.new(rows, columns, sparse_elems, label: label)\n end", "def row_vectors\n # (0 .. row_size - 1).collect { |i| row(i) }\n my_rows = @rows\n r_size = my_rows.size\n res = Array.new(r_size)\n vector_cls = Vector\n for i in 0..r_size-1 do\n a_row = my_rows[i]\n res[i] = vector_cls.elements(a_row) \n end\n res\n end", "def to_s\n \"SparseVector[\" + @elements.join(\", \") + \"]\"\n end", "def vectorizar\n\t\t\taux = Array.new(0)\n\t\t\tfor i in 0...colum\n\t\t\t\tfor j in 0...filas\n\t\t\t\t\taux << pos[i][j]\n\t\t\t\tend\n\t\t\tend\n\t\t\tArray.new(aux)\n\t\tend", "def col(j)\n \tc = {}\n \tfor r in @matrix.keys do\n \tc[r] = @matrix[r].vector[j] if @matrix[r].vector.keys.include? j\n \tend\n \tVector_disperso.new c\n\tend", "def vectorizar\n aux = Array.new(0)\n for i in 0...colum do\n for j in 0...filas do\n aux << pos[i][j]\n end\n end\n Array.new(aux)\n end", "def covector\n Matrix.row_vector(self)\n end", "def clone\n SparseVector.elements(@elements, true, size)\n end", "def singular_values\n info, astor, sstor, ustor, vtstor =\n Lapack::gesvd!(clone.storage)\n if info > 0\n raise RNum::Error, \"Algorithm did not converge.\"\n end\n RNum::Vector.new sstor\n end", "def transposed_search_vector\n @transposed_search_vector ||= super\n end", "def feature_vector\n out = []\n field_names.each { |f| out << @profile[f] }\n out\n end", "def sparse_matrix\n Hash.new do |hash, pairer|\n hash[pairer] = Hash.new { |hash, pairee| hash[pairee] = 0 }\n end\n end", "def column_values attribute\n self.map{|row| row[attribute]}.to_a.uniq\n end", "def initialize(h = {})\r\n\t\t@m_Matrix = Hash.new({})\r\n\t\trow, col = 0, 0\r\n\t\tarrayCol=[]\r\n\t\tj = 0\r\n\t\tfor k in h.keys do\r\n\t\t\trow = k if (row < k.to_i == true) \r\n\t\t\tif h[k].is_a? SparseVector\r\n\t\t\t\t@m_Matrix[k] = h[k]\r\n\t\t\telse \r\n\t\t\t\t@m_Matrix[k] = SparseVector.new(h[k])\r\n\t\t\tend\r\n\t\tend\r\n\r\n\t\tfor r in @m_Matrix.keys do\r\n\t\t\tj= 0\r\n\t\t\twhile j < @m_Matrix[r].vector.keys.size do \r\n\t\t\t\t col= @m_Matrix[r].vector.keys[j] if (col < @m_Matrix[r].vector.keys[j].to_i == true)\r\n\t\t\t\t j += 1\t\t\r\n\t\t\tend\r\n\t\tend\r\n\t\trow = row + 1\r\n\t\tcol = col + 1 \r\n\t\tsuper(row,col)\r\n\tend", "def initialize(sparse_vector, source_object = nil)\n @values = sparse_vector\n @cluster = nil\n @source_object = source_object\n end", "def column2matrix(c)\n a = self.send(:column, c).to_a\n if c.is_a?(Range) and c.entries.size > 1\n return Matrix[*a]\n else\n return Matrix[*a.collect{|x| [x]}]\n end\n end", "def to_a\n @vector\n end", "def to_v\n Vector.elements(to_a)\n end", "def columns\n ColumnCollection.new(@data)\n end", "def [](i)\n values[column_index i]\n end", "def get_column(column)\n validate_pos(0, column)\n\n new_matrix_contents = [] #for a column, this should be a list of single item arrays to create a column vector later.\n\n # iterate through each column index in the internal array and add that as a column to the new_matrix_contents.\n (column ... @fm.length).step(@cols) do |index|\n new_matrix_contents << [@fm[index]]\n end\n\n FMatrix.new(new_matrix_contents)\n end", "def classify_vector(values)\n raise \"Unsupported vector length\" unless values.size == @u.row_size || values.size == @v.row_size\n vector = Matrix.row_vector(values)\n mult_matrix = (values.size == @u.row_size ? @u : @v)\n comp_matrix = (values.size == @u.row_size ? @v : @u)\n \n position = vector * Matrix[*mult_matrix] * @s.inverse\n x = position[0,0]\n y = position[0,1]\n results = []\n \n comp_matrix.row_size.times do |index|\n results << [index, cosine_similarity(x, y, comp_matrix[index, 0], comp_matrix[index, 1])]\n end\n \n results.sort {|a, b| b[1] <=> a[1]}\n end", "def create_vector(vector_name = \"vectors\")\n sql = []\n if column_names().include?(vector_name)\n sql << \"alter table #{table_name} drop column #{vector_name}\"\n end\n sql << \"alter table #{table_name} add column #{vector_name} tsvector\"\n sql << \"CREATE INDEX #{table_name}_fts_#{vector_name}_index ON #{table_name} USING gist(#{vector_name})\"\n sql.each do |s|\n begin\n connection.execute(s)\n #puts s\n reset_column_information\n rescue StandardError => bang\n puts \"Error in create_vector executing #{s} \" + bang.to_yaml\n puts \"\"\n end\n end\n end", "def values(column_header)\n rows.map { |row| row[column_header] }\n end", "def values(column)\n rows do |row|\n row[column]\n end\n end", "def update_search_vector!\n ActiveRecord::Base.connection.execute(%{\n UPDATE #{self.class.table_name}\n SET search_vector = #{self.tsvector_construction_string}\n WHERE id = #{id}\n }.squish)\n end", "def to_a(column_major=true)\n a = []\n if column_major\n for j in 0..3\n for i in 0..3\n a << self[i,j]\n end\n end\n else\n for i in 0..3\n for j in 0..3\n a << self[i,j]\n end\n end\n end\n a\n end", "def keys\n \t\[email protected]\n \tend", "def column_values(column)\r\n assert_exists\r\n arr_rows = rows\r\n values = Array.new(arr_rows.length)\r\n for i in 0..arr_rows.length - 1 do\r\n values[i] = arr_rows[i][column].to_s \r\n end\r\n return values\r\n end", "def sparse_tuples\n tuples = to_a\n [tuples.first] + each_cons(2).map { |prev, cur|\n left = cur.zip(prev).drop_while { |c, p| c == p }\n [nil] * (cur.size - left.size) + left.map(&:first)\n }\n end", "def sparse_tuples\n tuples = to_a\n [tuples.first] + each_cons(2).map { |prev, cur|\n left = cur.zip(prev).drop_while { |c, p| c == p }\n [nil] * (cur.size - left.size) + left.map(&:first)\n }\n end", "def sparse_tuples\n tuples = to_a\n [tuples.first] + each_cons(2).map { |prev, cur|\n left = cur.zip(prev).drop_while { |c, p| c == p }\n [nil] * (cur.size - left.size) + left.map(&:first)\n }\n end", "def subMatrix(rows,cols)\n newDelegate = @delegate.clone\n newDelegate.subMatrix(rows,cols)\n newMatrix = SparseMatrix.new(newDelegate)\n return newMatrix\n end", "def to_vector\n return @vector_formatted_value if @vector_formatted_value\n\n vals = map(&:to_vector)\n vals.reverse! if endian == :little\n @vector_formatted_value = vals.join('')\n end", "def to_indexed_verts_array a=[]\n\t\[email protected] do |v|\n\t\t\ta += v[:vector]\n\t\tend\n\t\ta\n\tend", "def sparse_to_full(sparse , o = {})\n def_val = o[:def_val] || 0\n \n max_rno = sparse.map{|e|e[0]}.max\n max_cno = sparse.map{|e|e[1]}.max\n #full = Array.new( max_rno , Array.new(max_cno , def_val)) # LESSON Same Element is copied\n full = Array.new\n 0.upto(max_rno-1) do |i|\n full[i] = Array.new if !full[i] \n 0.upto(max_cno-1){|j| full[i][j] = 0 }\n end\n #puts max_rno , max_cno , full.to_s\n sparse.each do |row|\n rno , cno , value = *row\n #uts \"[#{rno},#{cno},#{value}]\"\n full[rno-1][cno-1] = value\n end\n full\n end", "def columns; @columns_hash.values; end", "def read_sparse_matrix(str)\n sparse = str.split(SEP_LINE).map do |line|\n row , col , value = line.split(SEP_ITEM)\n [row.to_i , col.to_i , value.to_f]\n end\n sparse_to_full(sparse)\n end", "def get_array_by_col()\n\t\tprepare(@dim_i,@dim_j)\n\t\ttmpTab = Array.new\n\t\tfor j in 0..@dim_j-1\n\t\t\ttmpTab.push get_col(j)\n\t\tend\n\t\treturn tmpTab\n\tend", "def [](fila, columna)\n @container[Posicion.new(fila, columna)]\n end", "def vec \n\t\t\tODE::Vector::new( @elem[0..2] )\n\t\tend", "def raw_vector_with(word_list)\n clear_cache!\n super\n end", "def columns\n CellCollection.new(@data, @row)\n end", "def horizontal_vector(index)\n @matrix[index][0...@width]\n end", "def add_one_vector(*matrices)\n matrices.map { |m|\n \tnum_rows = m.row_size\n \tnum_cols = m.column_size \t\n \tcolumns = [ Array.new(num_rows) { 1.0 } ]\n \tcolumns.push *(m.column_vectors.map { |v| v.to_a })\n \tMatrix.columns(columns)\n }\n end", "def cvss_vector\n @cvss_vector ||= if @event.at('cvss_vector')\n @event.at('cvss_vector').inner_text\n else\n false\n end\n end", "def get_column(index)\n column = []\n self.rows.times do |i|\n column.push(@state[i][index])\n end\n\n column\n end", "def to_a\n array = []\n rows.times do |row|\n col_array = []\n cols.times do |col|\n col_array << self.value_at(row,col)\n end\n array << col_array\n end\n\n return array\n end", "def *(a)\n if a.is_a? Vector\n if @column\n raise RuntimeError, \"Not yet implemented\" # FIXME\n else\n raise CalcoloNumericoError, \"Vector size mismatch\" if self.size[1] != a.size[0]\n ret = 0\n @vector.each_with_index { |e, k| ret += e * a[k] }\n return ret\n end\n elsif a.is_a? Numeric\n return Vector.new(@dim) { |e| @vector[e] * a }\n else\n raise ArgumentError, \"Required a Numeric or a Vector\"\n end\n end", "def columns \n @c\n end", "def to_a(column_major=true)\n a = []\n if column_major\n for j in 0..cols()-1\n for i in 0..rows()-1\n a << self[i,j]\n end\n end\n else\n for i in 0..rows()-1\n for j in 0..cols()-1\n a << self[i,j]\n end\n end\n end\n a\n end", "def to_a(column_major=true)\n a = []\n if column_major\n for j in 0..cols()-1\n for i in 0..rows()-1\n a << self[i,j]\n end\n end\n else\n for i in 0..rows()-1\n for j in 0..cols()-1\n a << self[i,j]\n end\n end\n end\n a\n end", "def to_vector\n\t\t\treturn ODE::Vector::new( *@elem )\n\t\tend", "def calculate_feature_vector\n fd = current_domain.dictionary\n fd_ids = fd.keys.sort\n\n @feature_vector = fd_ids.map do |fd_id|\n feature = fd[fd_id]\n @feature_set.member?( feature ) ? 1 : 0 # TODO: TF-IDF here -- Thu Mar 1 19:25:21 2012\n end\n end", "def __sparse_initial_set__(ary) #:nodoc:\n self[0...self.shape[0],0...self.shape[1]] = ary\n end", "def vector\n result = []\n next_candiate = 2\n while result.size < @table_size\n (result << next_candiate) if prime?(next_candiate)\n next_candiate += 1\n end\n result\n end", "def to_a\n @columns.values.flatten.compact\n end", "def arrays\n @vectors\n end", "def values\n rows.map{|r| r.value}\n end", "def _columns\n cache_get(:_columns)\n end", "def to_matrix\n rows = Matrix.zero(@row_size, @column_size).to_a\n @data.to_enum().map{\n |k,v| rows[split_xy(k).last][split_xy(k).first] = v\n }\n Matrix.rows(rows)\n end", "def setVariable(name, var)\n\n # Since this code was already written for three separate values,\n # I'm just splitting it back up for now.\n\n arg_names = var.old_args\n cells = Array.new\n var.cells.each do |cell|\n c = Array.new\n c << cell.onset\n c << cell.offset\n c << Array.new\n var.arglist.each do |arg|\n t = eval \"cell.#{arg}\"\n c[2] << t.to_s()\n end\n cells << c\n end\n print \"creating column\"\n # If the column already exists, delete it and build a new one.\n # If it doesn't, just add a new one.\n if not $db.col_name_in_use(name)\n col = DataColumn.new($db, name, MatrixVocabElement::MatrixType::MATRIX)\n $db.add_column(col)\n else\n oldcol = $db.get_column(name)\n numcells = oldcol.get_num_cells\n numcells.downto(1) do |i|\n $db.remove_cell($db.get_cell(oldcol.get_id, i).get_id)\n end\n #$db.remove_column(oldcol.get_id)\n\n #col = DataColumn.new($db, name, MatrixVocabElement::MatrixType::MATRIX)\n #$db.add_column(col)\n end\n # Check if matrix already defined\n col = $db.get_column(name)\n mve0 = $db.get_matrix_ve(col.its_mve_id)\n if mve0.get_num_formal_args() == 1\n # Setup structure of matrix column\n mve0 = MatrixVocabElement.new(mve0)\n\n mve0.delete_formal_arg(0)\n arg_names.each do |arg|\n farg = NominalFormalArg.new($db, arg)\n mve0.append_formal_arg(farg)\n end\n\n $db.replace_matrix_ve(mve0)\n end\n col = $db.get_column(name)\n mve0 = $db.get_matrix_ve(col.its_mve_id)\n matID0 = mve0.get_id()\n cells.each do |cell|\n #print \"writing cell\"\n c = DataCell.new($db, col.get_id, matID0)\n mat = Matrix.new($db, matID0)\n\n if cell[0].to_i > 0\n c.onset = TimeStamp.new(1000, cell[0].to_i)\n end\n if cell[1].to_i > 0\n c.offset = TimeStamp.new(1000, cell[1].to_i)\n end\n\n narg = 0\n cell[2].each do |dv|\n argid = mve0.get_formal_arg(narg).get_id()\n if dv == \"\" or dv == nil\n a = arg_names[narg]\n fdv = NominalDataValue.new($db, argid)\n fdv.clearValue()\n else\n fdv = NominalDataValue.new($db, argid, dv)\n end\n\n mat.replaceArg(narg,fdv)\n narg += 1\n end\n c.set_val(mat)\n $db.append_cell(c)\n end\nend", "def getcolumnvalue(r,c)\r\n\t\t\tvalue = @matrix[r][c]\r\n\t\t\treturn value\r\n\t\tend", "def [](row, column)\n (@values[row] || [])[column]\n end", "def [](column)\n @values[column]\n end", "def vertical_vector(index)\n @matrix[0...@height].map{|vector| vector[index]}\n end", "def inspect\n \"<Vector #{object_id} : dim = #{@dim} values = #{@vector}>\"\n end", "def collect2(v) # :yield: e1, e2\n raise TypeError, \"Integer is not like SparseVector\" if v.kind_of?(Integer)\n SparseVector.Raise ErrDimensionMismatch if size != v.size\n return to_enum(:collect2, v) unless block_given?\n Array.new(size) do |i|\n yield @elements[i], v[i]\n end\n end", "def to_tsvectors\n []\n end", "def columns; @columns; end", "def column_vector?\n raise NotImplementedError\n end", "def getVariable(name)\n index = -1\n\n # Find the internal database index of the column we are looking for.\n $db.get_col_order_vector.each do |col_index|\n if name == $db.get_data_column(col_index).get_name\n index = col_index\n end\n end\n\n #puts \"Got column index.\"\n #puts index\n\n\n dc = $db.get_data_column(index)\n mve = $db.get_matrix_ve(dc.get_its_mve_id)\n\n # Convert each cell into an array and store in an array of arrays\n cells = Array.new\n arg_names = Array.new\n\n if dc.get_its_mve_type == MatrixVocabElement::MatrixType::MATRIX\n for i in (0 .. (mve.get_num_formal_args - 1))\n fa = mve.get_formal_arg_copy(i)\n arg_names << fa.get_farg_name\n end\n end\n\n for i in (1 .. dc.get_num_cells)\n cell = dc.get_db.get_cell(dc.get_id, i)\n c = Array.new\n c << cell.get_onset.get_time\n c << cell.get_offset.get_time\n c << cell.get_val.to_escaped_string.tr_s(\"(\", \"\").tr_s(\")\", \"\").split(\",\")\n c << i\n cells << c\n end\n\n\n v = Variable.new\n v.name = name\n v.old_args = arg_names\n #v.type = dc.get_its_mve_type\n v.set_cells(cells, arg_names)\n\n\n return v\nend", "def input_matrix(file_name)\n\t\tc_arr = []\n\t\tFile.open(file_name, \"r\").each_line do |line|\n\t\t\t#If this is the first line, initialize each strain and add it to the array\n\t\t\tif $. == 1\n\t\t\t\tline.split.each do |strain|\n\t\t\t\t\tc_arr.push(PA_vector.new(strain)) unless strain == 'cluster_names'\n\t\t\t\tend\n\t\t\t\t#otherwise, add the cluster to each strain vector\n\t\t\telse\n\t\t\t\tcluster = line.split\n\t\t\t\t(1..cluster.length-1).each do |i|\n\t\t\t\t\tc_arr[i-1].clusters[cluster[0]] = cluster[i].to_i\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\tc_arr\n\tend", "def array_for_document(uid)\n @term_vectors.each_slice(2).each do |(_, array)|\n _, tv_uid, _, vectors = array\n next unless tv_uid == uid\n\n return nil if !vectors.is_a?(Array) || vectors.empty?\n return vectors\n end\n end", "def initialize(row, col, v, representacion)\n\t\tsuper(row, col)\n\t\t\t\t\n\t\tcontador = 0\n\t\tfor i in 0..v.size\n\t\t \tif(v[i] != 0)\n\t\t \t\tcontador+=1\n\t\t \tend\n\t\tend\n\t\t@nnz = contador\n\t\t@A = Array.new\n\t\t@IA = Array.new\n\t\t@JA = Array.new\n\t\t@representacion = representacion\n\t\n\t\tcase representacion\n\t\t when \"COO\"\n\t\t construirCOO(v)\n\t\t when \"CSR\"\n\t\t construirCSR(v)\n\t\tend\n\tend", "def to_ary_cols\n ary = Array.new\n cola = Array.new\n coli = 0\n each_index_by_cols do |row, col|\n if coli != col\n coli = col\n ary << cola\n cola = Array.new\n end\n\n cola << self[row, col]\n end\n\n ary << cola\n ary\n end", "def as_set\n content = as_content_array\n set = Set.new\n content.each {|row| row.each {|column_name, column_data| set << column_data}}\n set\n end", "def [](*values)\n\t\t\tm = Memory[*values]\n\t\t\treturn MemoryVector.__new__(m)\n\t\tend", "def category_vector(word)\n raise \"No vectors in *Cosine models\"\n end", "def vector max_value = 1\n log_once :consider_to_vector!, <<-S\n* WARNGING: ~Numeric#vector~ is deprecated. Use ~Numeric#to_vector~.\n~Numeric#to_vector~ is more preformant and returns a ~Hash~ containing the keys ~x~ and ~y~ as opposed\nto an ~Array~ of ~[x, y]~. Please note that you will lose the ability to destucture the values of a ~Hash~.\n\nS\n [vector_x(max_value), vector_y(max_value)]\n end", "def to_ary\n ary = Array.new\n each_index do |row, col|\n ary << self[row,col]\n end\n ary\n end", "def [](column)\n @values[column]\n end", "def [](column)\n @values[column]\n end", "def check_for_vector_column(vector_name = \"vectors\")\n #check for the basics\n if !column_names().include?(vector_name)\n #puts \"Creating vector column\"\n create_vector(vector_name)\n #puts \"Update vector index\"\n update_vector(nil,vector_name)\n # raise \"Table is missing column [vectors]. Run method create_vector and then \n # update_vector to create this column and populate it.\"\n end\n end", "def columns \n []\n end", "def [](column_key)\n @values[column_key]\n end", "def [](*indexes)\n location = indexes[0]\n if @index.is_a?(MultiIndex)\n result = \n if location.is_a?(Integer)\n element_from_numeric_index(location)\n elsif location.is_a?(Range)\n arry = location.inject([]) do |memo, num|\n memo << element_from_numeric_index(num)\n memo\n end\n\n new_index = Daru::MultiIndex.new(@index.to_a[location])\n Daru::Vector.new(arry, index: new_index, name: @name, dtype: dtype)\n else\n sub_index = @index[indexes]\n\n if sub_index.is_a?(Integer)\n element_from_numeric_index(sub_index)\n else\n elements = sub_index.map do |tuple|\n @data[@index[(indexes + tuple)]]\n end\n Daru::Vector.new(elements, index: Daru::MultiIndex.new(sub_index.to_a),\n name: @name, dtype: @dtype)\n end\n end\n\n return result\n else\n unless indexes[1]\n case location\n when Range\n range = \n if location.first.is_a?(Numeric)\n location\n else\n first = location.first\n last = location.last\n\n (first..last)\n end\n indexes = @index[range]\n else\n return element_from_numeric_index(location)\n end\n end\n\n Daru::Vector.new indexes.map { |loc| @data[index_for(loc)] }, name: @name, \n index: indexes.map { |e| named_index_for(e) }, dtype: @dtype\n end\n end", "def d; Matrix.new(RAtlas.vec2diag(@storage)); end", "def single_value(row)\n row.values.at(0)\n end", "def column_names\n self[0].keys\n end", "def map2_nz(v, &block) # :yield: e1, e2\n return to_enum(:map2_nz, v) unless block_given?\n els = collect2_nz(v, &block)\n SparseVector.elements(els, false)\n end", "def to_libSVM (sel_features = nil)\n \n #Load the selected features into a Hash\n sf = Hash.new\n if (sel_features)\n sel_features.each do |f| \n sf[f] = 1 \n end\n end\n \n self.define_features if (@train) #This method is needed only for training data\n \n output = Array.new\n @fvs.each do |vector, label|\n line = Array.new\n line.push(label)\n \n ([email protected]_count).each do |id| #OPTIMIZE: Change this line to consider sorting in case of terms being features\n term = @features.term(id)\n if ( value = vector[term] ) then\n line.push([id, value].join(\":\")) if sf[term] or not sel_features\n end\n end\n output.push(line.join(\" \"))\n end\n output.join(\"\\n\")\n end", "def uniq\n uniq_vector = @vector.uniq\n new_index = uniq_vector.inject([]) do |acc, element| \n acc << index_of(element) \n acc\n end\n\n Daru::Vector.new uniq_vector, name: @name, index: new_index, dtype: @dtype\n end", "def initialize(filas, columnas)\n #Variable que guarda el numero de filas de la matriz.\n @filas=filas\n #Variable que guarda el numero de columnas de la matriz. \n @columnas=columnas \n end", "def attribute_values\n @columns.map do |column|\n @attributes[column.to_sym]\n end\n end", "def cols_array\n arr = Array.new\n @columns_hash.each{|k,v| arr << k}\n return arr\n end", "def col0(coords)\n i, j = self.class.coords2indices( coords )\n j2col(j0(i,j))\n end", "def column_collect(j, &block)\n f = MMatrix.default_block(block)\n (0...row_size).collect {|r| f.call(self[r, j])}\n end" ]
[ "0.6700544", "0.6443182", "0.5867511", "0.58196855", "0.57611173", "0.55526966", "0.554979", "0.55270654", "0.54024434", "0.5329452", "0.5295366", "0.5284604", "0.5232551", "0.51945686", "0.5126178", "0.51055133", "0.5076098", "0.50242144", "0.50167465", "0.4987222", "0.49630553", "0.49501595", "0.493056", "0.49287656", "0.49124965", "0.4901187", "0.48985824", "0.48957187", "0.48792213", "0.48778868", "0.48710316", "0.48471218", "0.48471218", "0.48471218", "0.48409343", "0.48396552", "0.48200032", "0.480716", "0.48060158", "0.48039374", "0.4801176", "0.47751492", "0.47543854", "0.47537133", "0.4753189", "0.47433004", "0.47406432", "0.47260213", "0.4725019", "0.47201955", "0.47191593", "0.4692681", "0.467734", "0.467734", "0.4664558", "0.46527022", "0.46509594", "0.46506122", "0.4644279", "0.4623989", "0.46238783", "0.4617956", "0.4614238", "0.46139312", "0.46125188", "0.46125105", "0.4610106", "0.46099836", "0.46095842", "0.46094993", "0.4608188", "0.46062624", "0.4605481", "0.46031046", "0.45910096", "0.45891336", "0.45837972", "0.45744", "0.45742232", "0.4573577", "0.45625976", "0.45517", "0.45490497", "0.45475912", "0.45475912", "0.4533606", "0.45306605", "0.45249647", "0.45212767", "0.45199126", "0.4519489", "0.4517014", "0.45099014", "0.4508669", "0.45034212", "0.44996175", "0.44984096", "0.4493097", "0.44879866", "0.448395" ]
0.68450993
0
Metodo para la operacion aritmetica de la suma.
def +(matrizb) #sumita={} #for r in @m_Matrix.keys do # sum = {} # if matrizb.m_Matrix.keys.include? r # for j in @m_Matrix[r].vector.keys do # sum[j] = @m_Matrix[r].vector[j]+matrizb[r].vector[j] # sumita[r] = {j=>sum[j]} # end # else # sum[r]=@m_Matrix[r] # end #end #SparseMatrix.new(sumita) for r in @m_Matrix.keys do for j in @m_Matrix[r].vector.keys do matrizb[r][j]= @m_Matrix[r][j]+matrizb[r][j] end end matrizb end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def sum; end", "def sum\n\t\treturn self.reduce(:+)\n\tend", "def sum(x, op, y)\n x.send(op, y)\nend", "def sum (operator, a, b)\n if operator == \"add\"\n a + b\n elsif operator == \"subtract\"\n a - b\n elsif operator == \"multiply\"\n a * b\n elsif operator == \"divide\"\n a / b\n end\nend", "def calculadora(uno,dos,tres=0, opciones= {})\n if(opciones['suma']==1)\n return uno +dos+tres\n end\n if(opciones['multiplica']==1)\n return uno * dos *tres\n end\nend", "def sum(a, b)\n\n\tsum = a + b #=> zwroci nam sume zmiennych a i b\n\nend", "def suma(dato1,dato2)\n return dato1 + dato2\nend", "def pega_soma (valor1, valor2)\n valor1 + valor2\nend", "def pega_soma(valor1, valor2)\n #resultado =\n valor1 + valor2\n #return resultado\nend", "def pega_soma(v1,v2)\r\n v1 + v2\r\nend", "def total(a)\n\ta.reduce(:+)\nend", "def sum(x, y)\n\nend", "def sum\n self.inject(:+)\n end", "def +(op)\n CAS::Sum.new [self, op]\n end", "def sumar (valor1,valor2=0)\n valor1 + valor2\nend", "def sum (operator, a, b)\n if operator == \"exponents\"\n a ** b\n elsif operator == \"square root\"\n Math.sqrt(a)\n end\nend", "def sum(x,y)\r\n\t x + y\r\n\tend", "def calculate( op, a1, a2 = nil )\n case op\n when :abs; a2\n when :rel; a2\n when :mul; a1 * a2\n when :add; a1 + a2\n when :sub; a1 - a2\n when :inv; a1 * -1\n else 0\n end\n end", "def total(a,b)\r\n return (a+b)\r\nend", "def total; end", "def sum_of(a,b)\n\treturn a + b\nend", "def calculate(starting_value, operations)\n sum = starting_value\n operations.each do |ops|\n operator = ops[0]\n operand = ops[1]\n \n case operator\n when '+'\n sum += operand \n when '-'\n sum -= operand\n when '*'\n sum *= operand\n when '/'\n sum /=operand\n else \n end\n end \n sum \nend", "def sum(number, other)\n number + other\n end", "def plus(iva,ivb)\n return sum([iva,ivb]) \n end", "def sum\n [@r,@g,@b].inject(:+)\n end", "def sum (a, b)\n a + b\nend", "def total_amount\n \t amount = 0\n \t operation_items.each do | oi |\n \t\tamount = amount + oi.amount\n end\n amount\n end", "def sum_create\n total = add_create.reduce(:+)\nend", "def sum(element)\n element.reduce(:+)\nend", "def get_sum(a, b)\n [a,b].reduce(&:+)\nend", "def getSum ( x , y )\n\tsum = x + y\n\treturn sum\nend", "def calculation\n end", "def square_of_sum\n end", "def addition(a, b)\n\treturn a + b\nend", "def addition(a, b)\n\ta + b\nend", "def calculated; end", "def sum a, b\n a + b\nend", "def sum(a, b)\n a + b\nend", "def sum(a, b)\n a + b\nend", "def sum(num, total) => total += num", "def addition(a,b)\n\ta + b\nend", "def sum (tableau)\n chiffre = 0\n tableau.each do |element|\n chiffre = chiffre + element\n end\n return chiffre\nend", "def sum(a,b)\n a + b\nend", "def suma(numero_uno:0,numero_dos:0)\n\treturn numero_uno+numero_dos\n\t\nend", "def sum(a)\n a.reduce(&:+)\nend", "def sumar_insumo(nombreInsumo, cantidad)\n\t\tcase nombreInsumo\n\t\t\twhen \"cebada\" then (@cebada += cantidad)\n\t\t\twhen \"arroz_maiz\" then (@arroz_maiz += cantidad)\n\t\t\twhen \"levadura\" then (@levadura += cantidad)\n\t\t\twhen \"lupulo\" then (@lupulo += cantidad)\n\t\t\twhen \"producto_silos_cebada\" then \n\t\t\t\t(@producto_silos_cebada += cantidad)\n\t\t\twhen \"producto_molino\" then \n\t\t\t\t(@producto_molino += cantidad)\n\t\t\twhen \"producto_paila_mezcla\" then \n\t\t\t\t(@producto_paila_mezcla += cantidad)\n\t\t\twhen \"producto_cuba_filtracion\" then \n\t\t\t\t(@producto_cuba_filtracion += cantidad)\n\t\t\twhen \"producto_paila_coccion\" then \n\t\t\t\t(@producto_paila_coccion += cantidad)\n\t\t\twhen \"producto_tanque_preclarificador\" then \n\t\t\t\t(@producto_tanque_preclarificador += cantidad)\n\t\t\twhen \"producto_enfriador\" then \n\t\t\t\t(@producto_enfriador += cantidad)\n\t\t\twhen \"producto_tcc\" then (@producto_tcc += cantidad)\n\t\t\twhen \"producto_filtro_cerveza\" then \n\t\t\t\t(@producto_filtro_cerveza += cantidad)\n\t\t\twhen \"producto_tanque_cerveza\" then \n\t\t\t\t(@producto_tanque_cerveza += cantidad)\n\t\t\twhen \"cerveza\" then (@cerveza += cantidad)\n\t\tend\n\tend", "def sum(number1, number2)\ntotal = number1 + number2 \nend", "def addition (a, b)\n a + b\nend", "def sum #using a method name that already exists in that class, will overwrite that method\n total = 1\n self.each { |element| total += element if element.is_a?(Numeric) }\n total\n end", "def sum(a,b)\n a + b \nend", "def sum a, b\n return a + b\nend", "def simpleArraySum(ar)\n #\n # Write your code here.\n #\n ar.reduce(&:+)\nend", "def addition(a, b) \n return a + b\nend", "def sum\n self.reduce('lambda{|sum, item| sum + item}')\n end", "def calcular_total\n\t\treturn calcular_seguro*calcular_incremento\n\tend", "def op; end", "def sum(a, b)\n return a + b\nend", "def sum(a, b)\n return a + b\nend", "def test_suma\n \t\tassert_equal(@mr,(@mq+@mp)) #dispersas\n \t\tassert_equal(@c,(@a+@b)) #fraccionales\n\t\tassert_equal(@md,(@ma+@mz)) #densa\n \tend", "def sum\n reduce(0, &:+)\n end", "def add\n\t number_1 + number_2\n end", "def add(val1, val2) val1 + val2 end", "def element_sum\n\t\tif !self.numeric?\n\t\t\treturn false\n\t\tend\n\t\treturn self.inject(0) {|memo,n| memo + n}\t\n\tend", "def total ( numbers )\r\n\r\n\treturn numbers.reduce(:+);\r\n\r\nend", "def suma_arreglo(array)\n array.reduce(:+)\nend", "def test_suma\n assert_equal 12,@a.suma(@b).num\n assert_equal 7, @a.suma(@b).denom\n end", "def add(a, b)\n sum = a + b\n return sum\nend", "def add(a, b)\r\n a + b \r\n end", "def total(num1, num2)\n num1 + num2\nend", "def arithmetic2(a, b)\nend", "def sum(x,y)\n return x + y\nend", "def add(first_num, second_num)\n @result = (first_num + second_num)\nend", "def simpleArraySum(ar)\n ar.sum\nend", "def oper\n return @oper\n end", "def odb_sum\n \"sum(#{to_s})\"\n end", "def calculate (stat = Hash{add:true},*num)\n sum = 0\n stat.each_key do |key|\n if (key == :add)\n sum = add(*num)\n else\n first, *list = num\n sum = substract(first,*list)\n end\n end\n return sum\nend", "def addition(parameter1, parameter2)\n return parameter1 + parameter2\nend", "def sum(p = nil)\n output = self.compact\n if p.nil?\n return output.inject(0){ |memo,n| memo + n.to_f }\n else\n return output.inject(0){ |memo,n| memo + n.send(p).to_f }\n end\n end", "def addittion(x, y)\n return (x + y)\nend", "def add (a, b) \n return a + b; \nend", "def add(x, y)\n result = x + y \nend", "def simpleArraySum(ar)\n ar.sum\nend", "def soma_numeros (x, y)\r\n x + y\r\nend", "def qty_to_add\n 0\n end", "def qty_to_add\n 0\n end", "def add(a, b)\n\ta + b \nend", "def add(num_1, num_2)\n sum = num_1 + num_2\nend", "def sum_of_sums(array)\r\nend", "def sum(numbers)\r\n numbers.reduce(0, :+)\r\nend", "def add(a,b)\n a + b\n end", "def sum_numbers (numbers)\n\n numbers.sum\n \nend", "def calculo_valor_energetico\n\t\t\t(@carbohidratos*4) + (@lipidos*9) + (@proteinas*4)\n\t\tend", "def sum_or_product(num, op)\n case op\n when 'sum' then (1..num).to_a.reduce(:+)\n when 'product' then (1..num).to_a.reduce(:*)\n end\nend", "def opcion4(inventario)\n sum = 0\n inventario.each do |llave,valor|\n sum += valor\n end\n \n puts \"El stock total de la tienda es: #{sum}\"\nend", "def sum\n turn[0] + turn[1]\n end", "def add one, two\r\n\tone + two\r\nend", "def result \n return @left_operand + @right_operand\n end", "def add(term1, term2)\n return term1 + term2\nend", "def calculate_sum\n 1000000000000\n end", "def sumar (valor1,valor2=0,valor3)\n puts \"#{valor1},#{valor2},#{valor3}\"\n valor1+valor2+valor1\nend", "def sum(sums)\r\n if sums.empty?\r\n 0\r\n else\r\n sums.reduce(:+)\r\n end\r\nend" ]
[ "0.76462483", "0.69342417", "0.69295937", "0.6904479", "0.6823284", "0.68148553", "0.6810283", "0.68043506", "0.6761971", "0.67081374", "0.6699157", "0.6697887", "0.6693527", "0.6657674", "0.6647919", "0.6622925", "0.6612619", "0.6612072", "0.6599355", "0.6588482", "0.6578472", "0.6574691", "0.6562649", "0.6518606", "0.65152717", "0.6501854", "0.65015286", "0.64841664", "0.6472646", "0.64663404", "0.6446081", "0.64448035", "0.64367", "0.6429189", "0.64210725", "0.6414582", "0.6413207", "0.64121175", "0.64121175", "0.64092064", "0.6397985", "0.6384615", "0.6382669", "0.6380395", "0.63781625", "0.63645273", "0.63577056", "0.6354729", "0.6332978", "0.6331813", "0.63303715", "0.630483", "0.62933725", "0.6287874", "0.6286268", "0.62766016", "0.6257151", "0.6257151", "0.62531066", "0.6247993", "0.62445205", "0.6230476", "0.6216276", "0.6215672", "0.62104887", "0.620229", "0.62008977", "0.6198172", "0.61962086", "0.61959887", "0.6189652", "0.6184033", "0.6181722", "0.61739624", "0.6168726", "0.6159434", "0.61574566", "0.6152903", "0.61491156", "0.6148514", "0.6148417", "0.6137461", "0.61277854", "0.6122517", "0.6122517", "0.61197555", "0.61189836", "0.6112221", "0.6110786", "0.6110679", "0.6109223", "0.61034924", "0.6098029", "0.6093435", "0.6091625", "0.6091471", "0.6081343", "0.60792476", "0.60758495", "0.60745335", "0.60735327" ]
0.0
-1
Metodo para la operacion aritmetica de la resta.
def -(matrizb) restita={} for r in @m_Matrix.keys do res = {} if matrizb.m_Matrix.keys.include? r for j in @m_Matrix[r].vector.keys do res[j] = @m_Matrix[r].vector[j]-matrizb[r].vector[j] restita[r] = {j=>res[j]} end else res[r]=@m_Matrix[r] end end SparseMatrix.new(restita) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def oper\n return @oper\n end", "def op; end", "def operation; end", "def operations; end", "def operations; end", "def operator; end", "def oper=(value)\n @oper = value\n end", "def ops!\n @ops\n end", "def cops; end", "def cops; end", "def cops; end", "def operation(*_)\n raise 'not implemented'\n end", "def calculate( op, a1, a2 = nil )\n case op\n when :abs; a2\n when :rel; a2\n when :mul; a1 * a2\n when :add; a1 + a2\n when :sub; a1 - a2\n when :inv; a1 * -1\n else 0\n end\n end", "def op()\n @model.op\n end", "def operation\n nil\n end", "def mi_carrera\n\n\tend", "def suivre; end", "def rla\n end", "def calculated; end", "def operations\n @operations\n end", "def operate( op, val = nil )\n case val\n when Coord\n @rel |= true\n @ops.push [ op, val ]\n when Numeric, NilClass\n if @rel == false\n @ops[-1][1] = calculate( op, @ops[-1][1], val )\n else\n @ops.push [ op, val ]\n end\n end\n end", "def basic_op(operator, value1, value2)\nvalue1.send(operator,value2)\nend", "def rrca\n end", "def operator\n self.class.operator\n end", "def rra\n end", "def agc_2(operador)\n @pOper << operador\nend", "def operators\n [:is]\n end", "def operation\n parsed_operation\n end", "def operators= new_ops\n @operators = new_ops.gsub(/[^+*-]/, '').split(//)\n reset\n end", "def operators\n {\n \"+\" => -> {@num1 + @num2},\n \"-\" => -> {@num1 - @num2}\n }\n end", "def operation\n return @operation\n end", "def operation_of(a, b, op)\n if op == \"add\"\n return a + b\n elsif op == \"subtract\"\n return a - b \n elsif op == \"multiply\"\n return a * b \n elsif op == \"divide\"\n if b == 0\n return \"undefined\"\n else\n return a / b\n end\n end\nend", "def operations\n send(params[:ac])\n end", "def operator\n case @matches[2]\n when \"plus\" then :+\n when \"minus\" then :-\n when \"divided by\" then :/\n when \"multiplied by\" then :*\n end\n end", "def operation\n @component.operation\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 operation_of(a, b, op)\n if op == \"add\"\n return a + b\n elsif op == \"subtract\"\n return a - b\n elsif op == \"multiply\"\n return a * b\n elsif op == \"divide\"\n if b == 0\n return \"undefined\"\n else\n return a / b\n end\n end\nend", "def basic_op(operator, value1, value2)\nvalue1.send operator, value2\nend", "def operator_method(string)\n known_operations[string]\n end", "def count_ops()\n 0\n end", "def resta(a,b)\r\n $resultado = a - b\r\n puts $resultado\r\nend", "def relatorios\n end", "def basic_op(operator, value1, value2)\n case operator\n when \"+\"\n value1 + value2\n when \"-\"\n value1 - value2\n when \"*\"\n value1 * value2\n when \"/\"\n value1 / value2\n end\nend", "def operation\n arguments.first\n end", "def operator\n return @operator\n end", "def operator\n return @operator\n end", "def operator\n return @operator\n end", "def operators\n to_array search_by_text 'оператор'\n end", "def getopcode(op)\n field_m(op)\nend", "def calculadora(uno,dos,tres=0, opciones= {})\n if(opciones['suma']==1)\n return uno +dos+tres\n end\n if(opciones['multiplica']==1)\n return uno * dos *tres\n end\nend", "def check_op (oper)\n if oper == 'add' || oper == '+'\n puts \"+ + Let's add 'em up! + +\"\n return operator = '+'\n elsif oper == 'subtract' || oper == '-'\n puts \"- - Let's subtract! - -\"\n return operator = '-'\n elsif oper == 'multiply' || oper == '*'\n puts \"* * It's time to multiply! * *\"\n return operator = '*'\n elsif oper == 'divide' || oper == '/'\n puts \"/ / Let's divide 'em up! / /\"\n return operator = '/'\n elsif oper == 'exponent' || oper == '**'\n puts \"^ ^ Let's power 'em up! ^ ^\"\n return operator = '**'\n elsif oper == 'remainder' || oper == '%'\n puts \"% % Let's find the remainder! % %\"\n return operator = '%'\n end\nend", "def basic_op(operator, value1, value2)\n value1.send(operator, value2)\nend", "def operation meth, n_operator_sticks, operator, x\n\tToothNumber.new @value.send(meth, x.value),\n\t \t @num + x.num + n_operator_sticks,\n\t\t\t@pic + operator + x.pic\n end", "def convertArithmetic(op)\n case op\n\n #basic arithmetic operations\n when \"add\"\n cmds = \"//add\"+\"\\n\" + arithmeticBinary(\"+\")\n\n when \"sub\"\n cmds = \"//subtract\"+\"\\n\" +arithmeticBinary(\"-\")\n\n when \"neg\"\n cmds = \"//negate\" +\"\\n\"+arithmeticUnary(\"-\")\n\n #basic bitwise operations\n when \"and\"\n cmds = \"//and\" +\"\\n\"+arithmeticBinary(\"&\")\n\n when \"or\"\n cmds = \"//or\" +\"\\n\"+arithmeticBinary(\"|\")\n\n when \"not\"\n cmds = \"//not\" +\"\\n\"+arithmeticUnary(\"!\")\n else\n cmds = \"//not a legal command\"\n end\n\n return cmds\nend", "def optimize\n operand\n end", "def basic_op(operator, value1, value2)\n case operator\n when '+'\n value1 + value2\n when '-'\n value1 - value2\n when '*'\n value1 * value2\n when '/'\n value1 / value2\n end\nend", "def plus(number)\n @operation = '+' \n @number = number\nend", "def select_operator\n return '>' if self.class.name.downcase.include?('arm')\n return '==' if self.class.name.downcase.include?('leg')\n end", "def basic_op(operator, value1, value2)\n value1.send(operator.value2)\nend", "def aon; end", "def /(other)\n @a=other.b*@a\n @b=other.a*@b\n self.to_s #devuelve el resultado como cadena. la operacion modifica el valor del objeto.\n end", "def promotion\r\n\r\n end", "def optimize\n operand\n end", "def anchored; end", "def operations\n @operations.dup\n end", "def operations\n @operations.dup\n end", "def binary_operator?\n Mutant::BINARY_METHOD_OPERATORS.include?(node.name)\n end", "def operator=(_arg0); end", "def calculate_answer(operator, a, b)\r\n\r\n if operator == \"add\"\r\n return result= a + b\r\n elsif operator == \"subtract\"\r\n return result = a - b\r\n elsif operator == \"multiply\"\r\n return result = a * b\r\n elsif operator == \"divide\"\r\n return result = a / b\r\n\r\n end\r\n\r\nend", "def normalized_operation\n parse_operation\n end", "def calculation\n end", "def-(a) end", "def test_operaciones\n\t\t#Con la Suma\n\t\tassert_equal(\"6\", Fraccion.new(25,5).suma(3,3).to_s)\n\t\tassert_equal(\"8/3\", Fraccion.new(2,3).suma(4,2).to_s) \n\t\t#Con la Resta\n\t\tassert_equal(\"-4/3\", Fraccion.new(2,3).resta(4,2).to_s)\n\t\tassert_equal(\"-3\", Fraccion.new(-4,2).resta(2,2).to_s)\n\t\t#Con la Multiplicacion\n\t\t#Se comprueban todas las posibilidades\n\t\tassert_equal(\"4/15\", Fraccion.new(2,3).mult(2,5).to_s)\n\t\tassert_equal(\"-2/5\", Fraccion.new(1,1).mult(-2,5).to_s)\n\t\tassert_equal(\"1\", Fraccion.new(5,5).mult(1,1).to_s)\n\t\tassert_equal(\"-1\", Fraccion.new(-5,5).mult(1,1).to_s)\n\t\tassert_equal(\"-1\", Fraccion.new(5,-5).mult(1,1).to_s)\n\t\tassert_equal(\"1\", Fraccion.new(-5,-5).mult(1,1).to_s)\n\t\tassert_equal(\"1/2\", Fraccion.new(5,5).mult(1,2).to_s)\n\t\tassert_equal(\"-1/2\", Fraccion.new(-5,5).mult(1,2).to_s)\n\t\tassert_equal(\"-1/2\", Fraccion.new(5,-5).mult(1,2).to_s)\n\t\tassert_equal(\"1/2\", Fraccion.new(-5,-5).mult(1,2).to_s)\n\t\tassert_equal(\"0\", Fraccion.new(0,5).mult(1,2).to_s)\n\t\tassert_equal(\"0\", Fraccion.new(0,-5).mult(1,2).to_s)\n\t\tassert_equal(\"0\", Fraccion.new(5,-5).mult(0,2).to_s)\n\t\tassert_equal(\"0\", Fraccion.new(-5,-5).mult(0,2).to_s)\n\t\t#Con la Division\n\t\tassert_equal(\"5/3\", Fraccion.new(2,3).div(2,5).to_s)\n\t\tassert_equal(\"-1\", Fraccion.new(25,5).div(-10,2).to_s)\n\t\tassert_equal(\"-1\", Fraccion.new(-25,5).div(10,2).to_s)\n\tend", "def reverse_operation\n case operation\n when '+'\n return '-'\n when '-'\n return '+'\n when 'x', '=>'\n raise NotImplementedError, \"Error: using an x or => in a pristine file is not implemented yet\"\n else\n raise ArgumentError, \"Error: invalid operation #{operation} is used in the pristine file\"\n end\n end", "def eta; end", "def operator\n node_parts[1]\n end", "def sum (operator, a, b)\n if operator == \"add\"\n a + b\n elsif operator == \"subtract\"\n a - b\n elsif operator == \"multiply\"\n a * b\n elsif operator == \"divide\"\n a / b\n end\nend", "def getsimm(op)\n o = field_o(op);\n m = 1 << (16 - 1);\n\n (o ^ m) - m;\nend", "def parse_operation\n case operation\n when 'indexes', 'columns' then nil # not under developer control\n when 'load' then 'find'\n when 'destroy', 'find', 'save', 'create', 'exists' then operation\n when 'update' then 'save'\n else\n if model == 'Join'\n operation\n end\n end\n end", "def acosh\n math :acosh\n end", "def sub_e\n end", "def unary\r\n if consume(\"+\")\r\n unary()\r\n elsif consume(\"-\")\r\n new_binary(ND_SUB, new_num(0), unary())\r\n else\r\n primary()\r\n end\r\nend", "def operation(modifier)\n { modifier => { path => cast_value } }\n end", "def or_a\n end", "def visit_Squeel_Nodes_Operation(o, parent)\n args = o.args.map do |arg|\n case arg\n when Nodes::Function, Nodes::KeyPath, Nodes::As, Nodes::Literal\n visit(arg, parent)\n when Symbol, Nodes::Stub\n Arel.sql(arel_visitor.accept contextualize(parent)[arg.to_sym])\n else\n quote arg\n end\n end\n\n op = case o.operator\n when :+\n Arel::Nodes::Addition.new(args[0], args[1])\n when :-\n Arel::Nodes::Subtraction.new(args[0], args[1])\n when :*\n Arel::Nodes::Multiplication.new(args[0], args[1])\n when :/\n Arel::Nodes::Division.new(args[0], args[1])\n else\n Arel.sql(\"#{arel_visitor.accept(args[0])} #{o.operator} #{arel_visitor.accept(args[1])}\")\n end\n o.alias ? op.as(o.alias) : op\n end", "def controlQxxt(jugadalot)\n \n @modelo = Aliasmodelosiglasorteot.where(:siglasorteo => jugadalot.sorteot.sigla).first.modelocontrolq \n @modelo = @modelo.capitalize.classify.constantize # Esto para convertir string en constante y poder acceder al modelos de Active Record. Scado de este link: https://stackoverflow.com/questions/34757582/using-variables-for-model-names-in-active-record \n c = @modelo.where(:numero => jugadalot.n1.to_i).first\n (c.limite - c.vendida) - jugadalot.monto # retorna la diferencia. # Disponible = (c.limite - c.vendida) \n\n end", "def real_operator\n case @op\n when :while_mod\n :while\n when :until_mod\n :until\n else\n @op\n end\n end", "def refute_operator(o1, op, o2 = T.unsafe(nil), msg = T.unsafe(nil)); end", "def result \n return @left_operand + @right_operand\n end", "def arithmetic(a, b, operator)\n if operator == \"add\"\n a + b\n elsif operator == \"subtract\"\n a - b\n elsif operator == \"multiply\"\n a * b\n elsif operator == \"divide\"\n a/b\n else\n print \"hahaa\"\n end\nend", "def calculate_answer(operator, a, b)\n\n if operator == \"add\"\n return result= a + b\n elsif operator == \"subtract\"\n return result = a - b\n elsif operator == \"multiply\"\n return result = a * b\n elsif operator == \"divide\"\n return result = a / b\n\nend", "def alu_op(instr)\n add call(instr.result, instr.operand1, instr.oper, instr.operand2)\n end", "def arithmetic2(a, b)\nend", "def pred\n self - ONE\n end", "def guardar_resultado_operacion\n @resultado= @@calculadora.send(session[:accion].to_sym, session[:operando1].to_i, session[:operando2].to_i)\n end", "def succ!() end", "def calculo \n self.minutos_reales = 5 * 480 #cantidad de OPERARIOS * Jornada de Trabajo(Turnos)\n self.costo_minuto = 89 #Costo Real por minuto\n self.otros_costos = 540 * 89 #Tiempo Total(Minutos) * Costo Real por Minutos\n self.costo_mano_obra = 420 * 5 * 89 # Jornada Minutos * Cantidad Operarios * Costo Real por minutos \n self.manoObraPlaneada = 650.000 * 5 # Salario Total * Cantidad de operarios \n end", "def sum(x, op, y)\n x.send(op, y)\nend", "def revalue\n @value = nil\n @ops.each do |v|\n v[1].revalue\n end\n end", "def prescedence_of operator\n case operator\n when \"*\" then 2\n when \"/\" then 2\n when \"+\" then 1\n when \"-\" then 1\n when \"(\" then 0 \n end\n end", "def method_missing(name, *args, &blk)\n name = :and if name == :ane\n if OP_CODES.has_key? name\n begin\n if args.length == 0\n op = Operand.new(name)\n else\n arg = args.first\n mod = args[1] or false\n op = Operand.new(name, arg, mod)\n end\n rescue OperandError => e\n parse_error \"Operand error: #{e.to_s}\"\n end\n @code.push(op)\n op\n elsif @vars.has_key? name\n @vars[name]\n else\n name.to_sym\n end\n end" ]
[ "0.73056257", "0.7152441", "0.7005722", "0.68248516", "0.68248516", "0.67099226", "0.64829224", "0.62090945", "0.6032426", "0.6032426", "0.6032426", "0.60213053", "0.60083264", "0.59783834", "0.5942082", "0.5846438", "0.58102375", "0.5806722", "0.57830805", "0.57605016", "0.5743332", "0.5742539", "0.5719074", "0.57187766", "0.5712361", "0.57112616", "0.569399", "0.5663796", "0.5661541", "0.56587124", "0.56584895", "0.5654657", "0.5640887", "0.5632079", "0.56209135", "0.5596949", "0.5593611", "0.5579716", "0.5565806", "0.5560831", "0.5552275", "0.55514824", "0.5549695", "0.5537112", "0.5500311", "0.5500311", "0.5500311", "0.548843", "0.5486777", "0.5484273", "0.54817474", "0.54580414", "0.54504573", "0.54441124", "0.54341054", "0.54331714", "0.54313844", "0.5428525", "0.5421893", "0.54120195", "0.54102314", "0.54079676", "0.5405626", "0.53957033", "0.53954005", "0.53954005", "0.53947514", "0.53928095", "0.5384891", "0.53621155", "0.5359813", "0.53554964", "0.5352215", "0.5351623", "0.53496206", "0.53495324", "0.5336773", "0.53265846", "0.5320888", "0.5318372", "0.5317501", "0.5313607", "0.53094023", "0.5306958", "0.53023356", "0.53014004", "0.5300857", "0.52993715", "0.5297719", "0.5297126", "0.52963746", "0.52904445", "0.52819395", "0.5280159", "0.5277283", "0.5275377", "0.5270215", "0.5269173", "0.526579", "0.52655953", "0.5264724" ]
0.0
-1
The algorithm does not provide a guarantee when the data does not have a majority, returning a random value, then we need a step to check the result
def majority_vote(votes) count = 0 most_voted = 0 votes.each do |vote| most_voted = vote if count.zero? count += vote == most_voted ? 1 : -1 end majority?(votes, most_voted) ? most_voted : -1 end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def mc\n rnd = rand(total_count)\n @possibility_distribution.detect{ |pos| (rnd -= pos.last) <= 0 }.first\n end", "def find_by_bayer_moore(array)\n candidate = 0\n count = 0\n # Pass 1 - Find the candidate maintaing a count \n for i in 0..array.size-1\n # binding.pry\n candidate = array[i] if count == 0\n if array[i] == candidate\n count += 1\n else\n count -= 1\n end\n end\n counter = 0\n # Pass 2 - To verify that the candidate from pass1 is acutally a majority\n array.each do |i|\n if i == candidate\n counter += 1\n end\n end\n if counter > array.size/2\n puts \"Found majority element is: #{candidate}\"\n else\n puts \"No majority element\"\n end\nend", "def secretary\n\t\trejects, considered = distr.partition.with_index{|t,i| i < count/EXP}\n\t\tlow = rejects.min\n\t\tconsidered.detect{|good| good <= low} or low\n\tend", "def should_invent?\n rand(100) < @probability * 100\n end", "def nostalgia; return rand end", "def probability_n_of_a_kind(minimum_count, actual_count)\n debug = false\n gap = [(minimum_count - actual_count), 0].max # number of dice needed for minimum\n puts \"minimum count: #{minimum_count}, actual count: #{actual_count}, gap: #{gap}\" if debug\n if gap == 0 \n useful_results = 1\n reroll_count = 0\n else\n case [minimum_count, gap]\n when [3, 1] # need 1 of 3 to match\n # sequences with 1 of 3 dice: --*, -*-, *--\n # sequences with 2 of 3 dice: -**, *-*, **-\n # sequences with 3 of 3 dice: *** \n useful_results = (3*5*5)+(3*5)+1 \n when [3, 2] # need 2 of 4 to match\n # sequences with 2 of 4 dice: --**, -*-*, -**-, *--*, *-*-, **--\n # sequences with 3 of 4 dice: -***, *-**, ***-\n # sequences with 4 of 4 dice: ****\n useful_results = (6*5*5)+(4*5)+1\n when [3, 3] # need 3 of 5 to match\n # sequences with 3 of 5: --***, -**-*, -***-, *--**, *-*-*, *-**-, **--*, **-*-, ***--\n # sequences with 4 of 5: -****, *-***, ***-*, ****-\n # sequences with 5 of 5: ***** \n useful_results = (9*5*5)+(4*5)+1\n when [4, 1] # need 1 of 2 to match\n # sequences with 1 of 2 dice: -*, *-\n # sequences with 2 of 2 dice: **\n useful_results = (2*5)+1 \n when [4, 2] # need 2 of 3 to match\n # sequences with 2 of 3: -**, *-*, **-\n # sequences with 3 of 3: ***\n useful_results = (4*5)+1\n when [4, 3] # need 3 of 4 dice to match\n # sequences with 3 of 4 dice: -***, *-**, ***-\n # sequences with 4 of 4 dice: ****\n useful_results = (3*5)+1\n when [4, 4] # need 4 of 5 dice to match\n # sequences with 4 of 5: -****, *-***, ***-*, ****-\n # sequences with 5 of 5: ***** \n useful_results = (4*5)+1 \n else\n raise \"pair [#{minimum_count}, #{gap}] not expected\"\n end\n reroll_count = 5 - actual_count\n end\n puts \"useful results: #{useful_results}, reroll count: #{reroll_count}\" if debug\n p = calculate_probability(useful_results, reroll_count)\n return p\n end", "def is_majority_element(nums, target)\n last_index = get_target_index(nums, target, true)\n return false if last_index == -1\n first_index = get_target_index(nums, target, false)\n (last_index - first_index + 1) > (nums.length / 2) \nend", "def most_likely\n prob = 0\n num_people = 1\n until prob > 0.5\n num_people += 1\n prob = give_prob_with_n_people(num_people)\n end\n num_people\nend", "def majority_element(a)\n len=a.length\n maj_index=0\n count=1\n for i in 1...len\n if a[i]==a[maj_index]\n count+=1\n else\n count-=1\n end\n if count==0\n a[maj_index]=a[i]\n count=1\n end\n end\n candidate=a[maj_index]\n count=0\n for i in 0...len\n if a[i]==candidate\n count+=1\n end\n end\n \n if count > (len/2)\n return candidate\n else\n return -1\n end\nend", "def is_majority_element(nums, target)\n return false if !nums.include?(target)\n @last_element = target == nums.last ? nums.length : nums.bsearch_index { |element| element > target}\n @first_element = nums.bsearch_index { |element| element == target}\n (@last_element - @first_element) > (nums.length / 2)\nend", "def majority_element(nums)\n majority_1 = nil\n majority_2 = nil\n count_1 = 0\n count_2 = 0\n nums.each { |x|\n if count_1 == 0 || x == majority_1\n count_1 += 1\n majority_1 = x\n elsif count_2 == 0 || x == majority_2\n count_2 += 1\n majority_2 = x\n else\n count_1 -= 1\n count_2 -= 1\n end\n }\n\n result = []\n if nums.count{ |x| x == majority_1 } > nums.size / 3\n result << majority_1 unless majority_1.nil?\n end\n if majority_1 != majority_2 && nums.count{ |x| x == majority_2 } > nums.size / 3\n result << majority_2 unless majority_2.nil?\n end\n\n result\nend", "def test_ce_deBoer_1\n NArray.srand(567) # must use NArray's generator, not Ruby's\n\n n = 10\n y_true = NArray[1,1,1,1,1,0,0,0,0,0]\n\n mp = CrossEntropy::MatrixProblem.new\n mp.pr = NArray.float(2, n).fill!(0.5)\n mp.num_samples = 50\n mp.num_elite = 5\n mp.max_iters = 10\n\n mp.to_score_sample do |sample|\n y_true.eq(sample).count_false # to be minimized\n end\n\n mp.solve\n\n if y_true != mp.most_likely_solution\n warn \"expected #{y_true}; found #{mp.most_likely_solution}\" \n end\n assert mp.num_iters <= mp.max_iters\n end", "def pick\n float = BigDecimal.new(@rnd.uniform.to_s)\n from = to = BigDecimal.new(\"0.0\")\n value = nil\n @distribution.each do |value, probabillity|\n to += probabillity\n if float >= from && float < to\n return value\n end\n from = to\n end\n\n throw \"probabillity sum not 1.0, was #{to} for #{@distribution}\" if to < 0.999\n return value\n end", "def majority_vote(nums)\n candidate = nil\n count = 0\n nums.each do |num|\n candidate = num if count == 0\n if candidate == num\n count += 1\n else\n count -= 1\n end\n end\n\n count = 0\n nums.each do |num|\n if num == candidate\n count += 1\n end\n end\n\n return candidate if count > nums.size / 2\n return -1\nend", "def majority_element(nums)\n counter_hash = Hash.new(0)\n\n nums.each do |num|\n counter_hash[num] += 1\n end\n\n counter_hash.find { |k,v| v == counter_hash.values.max }.first\nend", "def is_straight?\n return !!@max_straight_value if @max_straight_value\n \n cards = @sorted_cards.clone\n # To check an low ace straight, add a phantom ace with value 1:\n if @sorted_cards.last.value == 14\n ace = @sorted_cards.last\n cards.unshift Card.new(1, ace.suit) \n end\n\n max_connected_cards = 1\n connected_card_count = 1\n prev_value = nil\n max_value = nil\n cards.each do |card|\n if prev_value\n if card.value == prev_value + 1\n connected_card_count += 1\n max_connected_cards = connected_card_count if connected_card_count > max_connected_cards\n max_value = card.value\n if connected_card_count >= 5\n @max_straight_value = max_value\n end\n elsif card.value != prev_value\n # dont reset if the prev card has the same value\n connected_card_count = 1\n end\n end\n\n prev_value = card.value\n end\n\n return @max_straight_value\n end", "def lexicase_tournament_winner(tournament,objective_names, quantile=0.5)\n objective_names.shuffle!\n tournament.shuffle!\n objective_names.each do |criterion|\n break if tournament.length <= 1\n extremes = tournament.collect {|dude| dude.abs_errors[criterion]}.minmax\n median = (extremes[1]-extremes[0])*quantile + extremes[0]\n tournament = tournament.find_all {|dude| dude.abs_errors[criterion] <= median}\n end\n return tournament.sample\nend", "def splitOn?\r\n\t\tmaxGain = 0\r\n\t\tbestFeature = nil\r\n\t\tfor i in 0..self.featureCount-1\r\n\t\t\tgain = self.gain(i)\r\n\t\t\tif gain >= maxGain\r\n\t\t\t\tmaxGain = gain\r\n\t\t\t\tbestFeature = i\r\n\t\t\tend\r\n\t\tend\r\n\t\tif maxGain == 0\r\n\t\t\tbestFeature = rand(0..self.featureCount-1)\r\n\t\tend\r\n\t\treturn bestFeature\r\n\tend", "def splitOn?\r\n\t\tmaxGain = 0\r\n\t\tbestFeature = nil\r\n\t\tfor i in 0..self.featureCount-1\r\n\t\t\tgain = self.gain(i)\r\n\t\t\tif gain >= maxGain\r\n\t\t\t\tmaxGain = gain\r\n\t\t\t\tbestFeature = i\r\n\t\t\tend\r\n\t\tend\r\n\t\tif maxGain == 0\r\n\t\t\tbestFeature = rand(0..self.featureCount-1)\r\n\t\tend\r\n\t\treturn bestFeature\r\n\tend", "def discrete(float_ary)\n#sum of float_ary must = 1, put in a try block.\n r = rand() # come up with a random number\n sum = 0.0\n float_ary.each do |num| \n sum += num #sum up all of the values in the array\n if sum >= r \n return num.index #when sum >= r, return the position of the current value in the array\n end\n end\n -1 # not sure why we return a negative one here. I think if the array is empty, we return a -1\nend", "def kawabanga?(rarity)\n (0..rand(0...100)).include?(100 - rarity)\nend", "def getMostOccur \n tmpArry=[]\n tmpWArry=[];\n\t @maxparam =0 #use for store the param\n @maxelement =0 #use for store the element\n\t\t i=0\n while i<@parameters.paramsArr.length do\n \t temelementslength = @parameters.paramsArr[i].elementsArr.length\t\n \t j=0\n while j < temelementslength do\t\t\n if @parameters.paramsArr[i].elementsArr[j].times == @parameters.paramsArr[@maxparam].elementsArr[@maxelement].times\n \n tmpArry << [i , j]\n elsif @parameters.paramsArr[i].elementsArr[j].times > @parameters.paramsArr[@maxparam].elementsArr[@maxelement].times\n tmpArry.clear\n tmpArry << [i , j]\n\t\t \t @maxparam = i \n @maxelement = j\n end\t \n j+=1\n end\n i+=1\n end\n #add by chuangye -----------------------------start\n if @useweight==1\n [email protected][tmpArry[0][0]].elementsArr[tmpArry[0][1]].weight\n for k in 0...tmpArry.length do\n if @parameters.paramsArr[tmpArry[k][0]].elementsArr[tmpArry[k][1]].weight==maxweight\n tmpWArry << tmpArry[k]\n elsif @parameters.paramsArr[tmpArry[k][0]].elementsArr[tmpArry[k][1]].weight>maxweight\n tmpWArry.clear\n tmpWArry << tmpArry[k]\n end\n end\n tmp=randchar(0,tmpWArry.length-1)\n @maxparam = tmpWArry[tmp][0]\n @maxelement = tmpWArry[tmp][1]\n else\n #add by chuangye -----------------------------end\n tmp = randchar(0 , tmpArry.length-1)\n @maxparam = tmpArry[tmp][0]\n @maxelement = tmpArry[tmp][1]\n end\n end", "def majority_element(a)\n \tlen=a.length\n \tlo=0\n \thi=len-1\n \tcandidate=a[lo+(hi-lo)/2]\n while hi-lo>1\n mid=lo+(hi-lo)/2\n if a[mid]>=candidate\n hi=mid\n else\n lo=mid\n end\n end\n \n if a[hi]==candidate\n \tleft_index=hi\n \tright_index=left_index+(len/2)\n \t\tif a[right_index]==candidate\n return candidate\n \t\telse\n \t\treturn -1\n \t\tend\n end\n \n \nend", "def majority(arr)\n\ttab = {}\n\tn = arr.length\n\tmax = 1\n\t(0...n).each do |i|\n\t\ttab[arr[i]] ||= 0\n\t\ttab[arr[i]] += 1\n\t\tif tab[arr[i]] > max && tab[arr[i]] > (n/2)\n\t\t\tmax = arr[i]\n\t\tend\n\t\tp tab\n\tend\n\tif max > 1\t\n\t\treturn max\n\telse\n\t\treturn 0\n\tend\nend", "def majority_element(nums)\n return nums.first if nums.size == 1\n return nums.sort[nums.size/2]\nend", "def majority_element(nums)\n len=nums.length\n maj_index=0\n count=1\n for i in 1...len\n if nums[i]==nums[maj_index]\n count+=1\n else\n count-=1\n end\n if count==0\n nums[maj_index]=nums[i]\n count=1\n end\n end\n candidate=nums[maj_index]\n count=0\n for i in 0...len\n if nums[i]==candidate\n count+=1\n end\n end\n \n if count > (len/2)\n return candidate\n else\n return -1\n end\nend", "def select(pop,fit,fitsum,totalfit)\n r = rand()\n j = 0\n while fitsum[j+1]/totalfit <= r\n j += 1\n end\n return j\nend", "def majority_element(nums)\n return [] if nums.nil? || nums.empty?\n\n length = nums.length\n i = 0\n candidate1 = nil\n candidate2 = nil\n count1 = 0\n count2 = 0\n while(i<length)\n if(nums[i] == candidate1)\n count1 += 1\n elsif(nums[i] == candidate2)\n count2 += 1\n elsif(count1 == 0)\n candidate1 = nums[i]\n elsif(count2 == 0)\n candidate2 = nums[i]\n else\n count1 -= 1\n count2 -= 1\n end\n i += 1\n end\n count1 = 0\n count2 = 0\n i = 0\n while(i<length)\n count1 += 1 if(nums[i] == candidate1)\n count2 += 1 if(nums[i] == candidate2)\n i += 1\n end\n count1 > count2 ? candidate1 : candidate2\nend", "def check_priority_trigger_quick_claw(pokemon)\n return rand(100) < 20\n end", "def pick(target)\n res = count = 0\n @N.each_with_index do |n, i|\n next unless n == target\n\n count += 1\n res = i if rand(1..10**9) % count == 0\n end\n res\n end", "def majority(array)\n \n array.sort!\n puts array[array.length/2]\n \n end", "def select_promising(game)\n max_score, max_moves = 0, []\n game.valid_moves.each do |move|\n game.mark *move\n n = g.valid_moves.length\n if n > max_score\n max_score, max_moves = n, [move]\n elsif n == max_score\n max_moves << move\n end\n game.unmark *move\n end\n max_moves.sample\nend", "def majority_element(nums)\n major = nums.first\n count = 0\n\n nums.each do |num|\n if major == num\n count += 1\n else\n count.zero? ? major = num : count -= 1\n end\n end\n major\nend", "def pick\n r = rand(@upper_threshold)\n @thresholds.find { |value, x| r < x }.first\n end", "def accuracy_check(acc)\n return acc > rand \nend", "def biased_random_number(prob_arr)\n # http://stackoverflow.com/questions/479236/how-do-i-simulate-biased-die-in-python\n rand_roll = rand()\n sum = 0 \n result = 0\n prob_arr.each do |i|\n sum += i\n if rand_roll < sum\n return result\n end\n result += 1\n end\n # puts \"prob_arry:\" + prob_arr.to_s\n # puts \"rand_roll: \" + rand_roll.to_s\n # puts prob_arr.join(\" \")\n return result - 1\n end", "def probability_exact\n\t\t str_format=\"%0#{nr}b\"\n\t\t combinations=2**nr\n\t\t #p str_format\n\t\t total_w=combinations.times.map do |i|\n comb=sprintf(str_format,i)\n w_local=comb.length.times.inject(0) do |ac,j|\n sgn=comb[j]==\"0\" ? -1 : 1\n\t\t\t\t ac+(j+1)*sgn\n end\n\t\t end.sort\n\n \t\t total_w.find_all do |v| \n if @tails==:both\n v<=-w.abs or v>=w.abs\n elsif @tails==:left\n v<=w\n elsif @tails==:right\n \t\t\t\t v>=w\n end\n \t\t end.count/(combinations.to_f)\n end", "def fudge(stat)\n stat * rand(0.8..1.2)\n end", "def generate_harder_value(rnd_obj, _)\n # generate from the top 70% upwards\n min, max = fetch_min_max_values\n diff = max-min\n top_seventy_percent = 0.7 * diff\n @value = rnd_obj.rand(Integer(top_seventy_percent)..max)\n end", "def most_likely_duplicate\n possible_matching_people.first\n end", "def chance(c)\n return rand < c\nend", "def generateAccuracy()\n return (rand 0.6..0.8)\nend", "def key_for_min_value(name_hash)\n small_hash = nil\n \n lowest_num = rand(1..10)\n \n name_hash.each do |k, v|\n \n if v < lowest_num \n small_hash = k \n end \n end \n small_hash\nend", "def rand\n num = SecureRandom.random_number(@n)\n @bins.each do |k, freq|\n num -= freq\n return k if num < 0\n end\n end", "def add_wrong(high_bit, input_array)\n\tnum = (2..high_bit).to_a.sample # rand(2..high_bit)\n\tuntil good_wrong?(num, input_array)\n\t\tnum = (2..high_bit).to_a.sample #rand(2..high_bit)\n\tend\n\treturn num\nend", "def find_best_ratio(samples, n, step_sz)\n spam = samples.select { |s| s.kind == :spam }.shuffle\n ham = samples.select { |s| s.kind == :ham }.shuffle\n\n # bests = {\n # :accuracy => {:step => 0, :value => 0.0, :ratio => nil, :mat => nil},\n # :precision => {:step => 0, :value => 0.0, :ratio => nil, :mat => nil},\n # :recall => {:step => 0, :value => 0.0, :ratio => nil, :mat => nil},\n # }\n\n steps = {}\n\n (step_sz).step(0.99, step_sz).each do |i|\n ratio = {:spam => (n * i).round, :ham => (n * (1 - i)).round}\n limited_samples = spam.take(ratio[:spam]) + ham.take(ratio[:ham])\n\n STDERR.puts \"Step %0.2f, #{ratio.inspect}, n=#{ratio.values.reduce(:+)}\" % i\n\n mat = CrossValidate.run(limited_samples, Classifier.fetch(0, :unigram))\n\n steps[i] = {:ratio => ratio, :mat => mat}\n # if mat[:accuracy] > bests[:accuracy][:value]\n # bests[:accuracy] = {:step => i, :value => mat[:accuracy], :ratio => ratio, :mat => mat}\n # end\n\n # if mat[:precision] > bests[:precision][:value]\n # bests[:precision] = {:step => i, :value => mat[:precision], :ratio => ratio, :mat => mat}\n # end\n\n # if mat[:recall] > bests[:recall][:value]\n # bests[:recall] = {:step => i, :value => mat[:recall], :ratio => ratio, :mat => mat}\n # end\n end\n\n steps\n # bests\nend", "def this_one_should_fail_randomly?\n (rand * 5).round == 0\n end", "def test_equiprobability\n winners_1, winners_2 = nil, nil\n\n @unique_advertises_count.times do\n winners_1 = Auctioneer.auction(\n creatives: @creatives,\n number_of_winners: @unique_advertises_count\n )\n winners_2 = Auctioneer.auction(\n creatives: @creatives,\n number_of_winners: @unique_advertises_count\n )\n\n break if winners_1 != winners_2\n end\n\n assert { winners_1 != winners_2 }\n end", "def get_random_type(entropy = 0)\n entropy ||= 21\n dice = rand(0..100)\n\n return 2 if dice < entropy / 3\n\n return 3 if dice < entropy / 3 * 2\n\n return 4 if dice < entropy\n\n 1\n end", "def pick_value(random_number, prev_value)\n\tnext_value = @frequencies[prev_value]\n\tif next_value.nil? then\n\t\tnext_value = @frequencies[nil]\n\tend\n\n succ_list = next_value.sort_by{|key, value| value}\n freq_counter = 0.0\n \n succ_list.each { |succ_value, freq|\n freq_counter += freq\n return succ_value if freq_counter >= random_number\n }\n end", "def poisson_minority_cutoff(seq_array, error_rate = 0.0001, fold_cutoff = 20)\n if seq_array.size == 0\n return 0\n else\n cut_off = 1\n l = seq_array[0].size\n rate = seq_array.size * error_rate\n count_mut = variant_for_poisson(seq_array)\n max_count = count_mut.keys.max\n poisson_hash = poisson_distribution(rate, max_count)\n\n poisson_hash.each do |k,v|\n cal = l * v\n obs = count_mut[k] ? count_mut[k] : 0\n if obs >= fold_cutoff * cal\n cut_off = k\n break\n end\n end\n return cut_off\n end\nend", "def maximum_likehood_dichotomic(pred,real)\n preda,reala=Statsample.only_valid_clone(pred,real) \n sum=0\n preda.each_index{|i|\n sum+=(reala[i]*Math::log(preda[i])) + ((1-reala[i])*Math::log(1-preda[i]))\n }\n sum\n end", "def cuddle\n attempt = [0, 1]\n hug = attempt.sample\n end", "def allow?(val = nil)\n val = val.nil? ? random_val : hashed_val(val)\n val < ramp_val\n end", "def allow?(val = nil)\n val = val.nil? ? random_val : hashed_val(val)\n val < ramp_val\n end", "def majority_elements(nums)\n threshold = nums.size / 2\n counts = Hash.new(0)\n\n nums.each do |n|\n counts[n] += 1\n if counts[n] > threshold\n return n\n end\n end\nend", "def next_discretionary_item\n @items.select { |item| item.rule.max.positive? }.sample(1).first\n end", "def highest_match_value\n values = @hand.select { |dice| @hand.count(dice) == highest_match_count }\n values.max\n end", "def randomRarity\n\t\tr = Random.rand\n\t\tfor rarity in RARITIES\n\t\t\tif r < DISTRIBUTION[rarity]\n\t\t\t\treturn rarity\n\t\t\tend\n\t\tend \n\tend", "def card_value\n card_values = cards.map { |card| card.straight_value }\n [4, 3, 2].each do |num|\n if card_values.any? { |value| card_values.count(value) == num }\n return card_values.select { |value| card_values.count(value) == num }.max\n end\n end\n card_values.max\n end", "def majority_element(stream)\n candidate, count = \"\", 0\n\n stream.each(\" \") do |w|\n if count == 0\n candidate = w\n count = 1\n elsif candidate == w\n count += 1\n else\n count -= 1\n end\n end\n\n candidate\nend", "def mine_fake(random)\n if @max_fake.zero?\n 0\n else\n fake = random.rand(@max_fake + 1)\n fake\n end\n end", "def majority_element(nums)\n left = nums.min \n right = nums.max \n while left <= right do\n \t\tmid = (left + right) / 2;\n \t\tcount = 0;\n \t\tnums.each {|x| count+=1 if x >=mid}\n \t\tif count > nums.length/2 \n \t\t\tans = mid\n \t\t\tleft = mid + 1\n \t\telse\n \t\t\tright = mid - 1\n \t\tend;\n end \n return ans\nend", "def rareness\n return @rareness || data.rareness\n end", "def attack_effect_first_hit_result(attacker)\r\n return (rand(100) < attacker.hit)\r\n end", "def next_state\n STATES.find do |_, state|\n state[:probability] && state[:probability] > rand\n end\n end", "def majority_element_3(nums)\n majority = nums.size / 3\n result = []\n counts = nums.inject({}) { |acc, n| \n acc[n] ||= 0\n acc[n] += 1\n if acc[n] > majority && !result.include?(n)\n result << n\n end\n \n acc\n }\n \n return result\nend", "def rps(n)\n c = [1,2,3].sample\n if c == n \n puts \"w\"\n else\n puts \"L\"\n end\nend", "def change_from_wild_probability\n # TODO: 2+ skips\n has_wild_probability\n end", "def full_house\n repetitions(2).any? && repetitions(3).any? ? repetitions(3).keys.max.to_i : 0 \n end", "def calc_critical_hit(user, target, initial_critical_count)\n # 100_000 = 100%\n current_value = @move_critical_rng.rand(100_000)\n return current_value < CRITICAL_RATES[calc_critical_count(user, target, initial_critical_count)]\n end", "def min_unfairness (candy, n, k)\n # First, sorting the array\n candy.sort!\n\n # puts candy.inspect\n\n # Initialize with the first and k element \n min = candy[k-1] - candy[0]\n\n # For each subsequential k elements, we have to find the min. unfairness\n for i in 1..(n-k) \n # puts \"i=#{i} n[i+k]=#{candy[i+k-1]} n[i]=#{candy[i]} : #{candy[i+k-1] - candy[i]} | min=#{min}\"\n min = candy[i+k-1] - candy[i] if candy[i+k-1] - candy[i] < min\n end\n\n return min\nend", "def probability(a)\n total=0\n\n for j in 0..9\n if(a[j]==nil)\n next\n end\n total += a[j]\n end\n for i in 0..9\n if(a[i]==nil)\n next\n end\n puts 'P(' + i.to_s + ') = '+ (a[i]/total).to_s\n end\n max(a,total)\nend", "def key_for_min_value(name_hash)\n\n\n winner_1 = 100\n winner_2 = ''\nname_hash.each do |key, value|\n if value < winner_1\n winner_1 = value\n winner_2 = key\n end\nend\n\nif name_hash.length == 0\n nil\nelse\nwinner_2\nend\nend", "def fitness\n Sequences.inject(0.0) do |fitness, sequence|\n # count matches\n matches = 0\n 0.upto(size - 1) do |index|\n if(self[index] == sequence[0][index])\n matches += 1\n end\n end\n # more is worse\n fitness - (sequence[1] - matches).abs\n end\n end", "def positive_dominant(arr)\n #Your code here\n arr_uniq = arr.uniq\n pos_arr = []\n neg_arr = []\n arr_uniq.map do |x|\n if x > 0\n pos_arr.push(x)\n else\n neg_arr.push(x)\n end\n end\n\n if pos_arr.length > neg_arr.length\n return true\n else\n return false\n end\n\nend", "def is_straight_flush?\n cards = @sorted_cards.clone\n # To check an low ace straight, add a phantom ace with value 1:\n if @sorted_cards.last.value == 14\n ace = @sorted_cards.last\n cards.unshift Card.new(1, ace.suit) \n end\n\n max_connected_cards = 1\n suited_connector_count = 1\n prev_card = nil\n max_value = nil\n cards.each do |card|\n if prev_card\n if card.value == prev_card.value + 1 && card.suit == prev_card.suit\n suited_connector_count += 1\n max_connected_cards = suited_connector_count if suited_connector_count > max_connected_cards\n max_value = card.value\n if suited_connector_count >= 5\n @max_straight_flush_value = max_value\n end\n elsif card.value != prev_card.value\n # dont reset if the prev card has the same value\n suited_connector_count = 1\n end\n end\n\n prev_card = card\n end\n\n return @max_straight_flush_value\n end", "def take_best\n roll_all.max\n end", "def wtf?\r\n wtf = self.maybe?\r\n aFactor = 0\r\n done = 10\r\n while(done != 0) do\r\n done +=1 if done == rand(0..10) unless Maybe.maybe?\r\n \r\n wtf = self.maybe? unless Maybe.maybe? == self.maybe?\r\n wtf ||= self.maybe?\r\n if wtf == Maybe.maybe? then\r\n wtf = !wtf unless @maybe\r\n elsif @maybe != Maybe.maybe? then\r\n a = Maybe.new\r\n wtf = a.true? unless wtf == a.true?\r\n end\r\n \r\n if !wtf && !@maybe then\r\n n = rand\r\n wtf = self.wtf? if ( done == rand(0..10) && done == rand(0..10) )\r\n wtf = !Maybe.maybe? if (n > 0.3 && n < 0.4)\r\n wtf = !wtf if wtf == self.maybe?\r\n wtf = nil unless !self.maybe?\r\n end\r\n \r\n wtf ||= Maybe.maybe?\r\n wtf = !wtf if (Maybe.maybe? && self.maybe?)\r\n\r\n done -= 1 unless Maybe.maybe?\r\n aFactor += done unless wtf\r\n aFactor -= done if wtf\r\n aFactor += rand( 0..( rand(0..11) ) )\r\n end\r\n\r\n choices = Array.new\r\n (1..10).each do \r\n choices << wtf if Maybe.maybe?\r\n choices << !wtf if Maybe.maybe?\r\n choices << @maybe if Maybe.maybe? \r\n choices << !@maybe if Maybe.maybe?\r\n end\r\n\r\n choice = rand(0..(choices.size))\r\n choice *= aFactor\r\n while choice > choices.size\r\n choice /= choices.size\r\n end\r\n choice += choices.size/2 if Maybe.maybe?\r\n return choices.at( -choice )\r\n end", "def sequential\n return true if hand_to_val.last - hand_to_val.first == 4\n return false \n end", "def get_inflation_rate()\r\n #assume a inflation rate between 2% and 7%\r\n inflation_rate=(rand(7)*0.01)\r\n if inflation_rate > 0.02\r\n return inflation_rate\r\n else\r\n return 0.02\r\n end\r\nend", "def generate_totalrand\n return @challenges[0] if @challenges.size == 1\n loop do\n rand_index = rand(@challenges.size)\n chall = @challenges[rand_index]\n if Lecode_BattleChallenge::Use_Frequency\n if rand(100) < chall.freq\n update_lastlyUsed(chall)\n return chall\n end\n else\n update_lastlyUsed(chall)\n return chall\n end\n end\n end", "def roll_if_value_is_nil\n self.value = (rand(6) + 1) if not self.value\n end", "def probA0(bit)\n\n # not quite zero, to avoid paying infinitely large\n # penalty when calculating score (div by zero)\n if bit == 0\n return 0.999999\n else #bit == 1\n # This value can be used to tweak coverage vs\n # exclusivity of modules\n return 0.000005\n end\nend", "def most_likely_play\n @must_learn = true\n best_move = nil\n max = 0\n\n search_space = SearchSpace.new(@board, @most_alike_board, @color)\n search_space.each do |move|\n prob = probability_of(move)\n return move if prob >= Config::PROBS_THRESHOLD\n if max < prob\n max = prob\n best_move = move\n end\n end\n\n best_move\n end", "def to_be_a_factor?\n return false if @factor_percentage.nil? || @factor_of.nil?\n Random.new().rand(1..100) <= @factor_percentage\n end", "def key_for_min_value(ha)\nans = 999999999\n ha.each do |hash, key|\n if key < ans\n ans = key\n end\n end\n \n ha.each do |hash1, key1|\n if key1===ans\n return hash1\n end\n end\n puts ans\n\nend", "def narcissistic?(value)\n # Code me to return true or false\n ans = []\n dig = value.to_s.length\n arr = value.to_s.split(\"\")\n arr.each {|x| ans << x.to_i ** dig}\n sum = ans.reduce(:+)\n sum == value ? true : false\n\nend", "def take_worst\n roll_all.min\n end", "def rating\n if in_the_future\n return nil\n else\n #TODO replace this with actual rating\n return rand(1..5)\n end\n end", "def worst_case board\n\t\tworst = 0\n\t\topp_board = board.rotate 7\n\t\t6.times {|i|\n\t\t\t\ts = score_for(opp_board, i)\n\t\t\t\tworst = s if worst < s\n\t\t\t}\n\t\t\tworst\n\tend", "def generate_averagerand\n return @challenges[0] if @challenges.size == 1\n chall = nil\n while chall == nil\n rand_index = rand(@challenges.size)\n if $game_temp.lbchll_lastly_used != rand_index\n if Lecode_BattleChallenge::Use_Frequency #!chall.lastly_used\n chall = @challenges[rand_index]\n if !(rand(100) < chall.freq)\n chall = nil\n end\n else\n chall = @challenges[rand_index]\n end\n end\n end\n msgbox \"Error - Nil Challenge\" if chall.nil?\n update_lastlyUsed(chall)\n return chall\n end", "def bi_rand(v)\n rand(2) > 1 ? v : nil\n end", "def roll_if_value_is_nil\n self.value = (rand(3) + 1) if not self.value\n end", "def probability\n rand(1..100)\n end", "def replace_by_most_seen_value!\n each_sample do |k, s|\n each_feature do |f|\n fv = get_feature_values(f)\n next if fv.size == get_sample_size # no missing values\n \n seen_count, seen_value = 0, nil\n fv.uniq.each do |v|\n count = fv.count(v)\n if count > seen_count\n seen_count = count\n seen_value = v\n end\n end\n \n if not s.has_key? f\n s[f] = seen_value\n end\n end\n end\n \n # clear variables\n clear_vars\n end", "def poisson_calc(expected, prng) #expected number of occurences\n\t\tl = Math.exp(-expected) #(P|X = 0) \n\t\tk = 0.0 #(number of occurences)\n\t\tp = 1.0 #The product of the urandoms\n\t\tk = 1.0 unless p > l # need because 1.0 !> 1.0\n\t\twhile p > l \n\t\t\tu = prng.rand\n\t\t\tp *= u\n\t\t\tk += 1 \n\t\tend\n\t (k - 1)\n\tend", "def uret(n)\n (1..n).each do\n arr=[]\n (1..6).each do\n r=rand(1..49)\n while arr.include?(r) do# bu while dongusu aynı sayi geilmesin diye\n r=rand(49)+1\n end\n arr<< r\n end\n\n arr.sort!\n puts arr.inspect\n end\nend", "def dominant(arr)\n\tsorted = Array.merge_sort(arr){|a,b| a.length <=> b.length}\n\tsorted[-1]\nend", "def is_straight?\n order_by_value.each_cons(2).all? { |x,y| y.point == x.point + 1 }\n end" ]
[ "0.6645303", "0.63677937", "0.6246012", "0.6203457", "0.6181281", "0.61715794", "0.6151797", "0.61277753", "0.6095637", "0.6087085", "0.60553885", "0.6046146", "0.60302943", "0.6003618", "0.59460115", "0.5924459", "0.5901495", "0.5895271", "0.5895271", "0.5889197", "0.58813566", "0.58800036", "0.58779275", "0.5810673", "0.58090615", "0.57998556", "0.57815045", "0.5773084", "0.5771232", "0.5752332", "0.57361484", "0.57228404", "0.57167476", "0.5708626", "0.5704261", "0.5703429", "0.57011014", "0.5689395", "0.5679688", "0.5674156", "0.5657536", "0.5657001", "0.56528246", "0.5646188", "0.56314456", "0.5625323", "0.56251216", "0.56224406", "0.5601332", "0.55983514", "0.55931413", "0.5577726", "0.55749094", "0.55745566", "0.55745566", "0.55724585", "0.55681163", "0.5565537", "0.5544373", "0.55383694", "0.55367404", "0.5531316", "0.5523554", "0.5516035", "0.5506908", "0.5505552", "0.5500718", "0.54997385", "0.5494706", "0.5494419", "0.54870677", "0.54858243", "0.54849285", "0.54827815", "0.54824793", "0.54720896", "0.5457055", "0.54535145", "0.5449981", "0.54472", "0.54460543", "0.5442413", "0.54284656", "0.5418042", "0.5413936", "0.54116505", "0.54111725", "0.5411082", "0.54092264", "0.53990406", "0.5398956", "0.5397623", "0.5385476", "0.5374988", "0.53749037", "0.53707504", "0.5368801", "0.5365513", "0.5363641", "0.5361681" ]
0.56161517
48
Cria atributos de apenas leitura Cria o inicializador da classe, passando os valores dos parametros para os atributos da classe
def initialize(titulo, preco, ano_lancamento, possui_reimpressao) @titulo = titulo @ano_lancamento = ano_lancamento @possui_reimpressao = possui_reimpressao @preco = calcula_preco(preco) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def initialize(nombre,edad) #--> se crean los metodos, y se inicializan para darles un valor al crear el objeto \n @nombre = nombre #-->la variable local nombre es asignada a la var. de instancia @nombre, al realizar esto cada instancia tendra un valor propio.\n @edad = edad #--> lo mismo para edad\n\nend", "def initialize(name) # aqui ionicializamos nuestro contructor ahora que instanciemos un objeto este ira primero aqui \n @nombre = name #esta es una variable de instancia \n end", "def initialize(nombre,gei,terreno,proteinas,lipidos,glucidos)\n @nombre, @gei, @terreno, @proteinas, @lipidos, @glucidos = nombre, gei, terreno, proteinas, lipidos, glucidos\n end", "def initialize(params)\n @params = params \n end", "def initialize(nombre,peso,talla,edad,sexo,imc,estados,rcc,rcca) #constructor\n super(nombre,peso,talla,edad,sexo,imc,estados,rcc,rcca)\n end", "def initialize(parametros)\n # En cada variable intanciada le asignamos un hash con la variable correspondiente\n @villano = parametros[:villano]\n @frase = parametros[:frase]\n end", "def initialize(name)\n @name = name\n @nota\n #declaracion v instancia\n end", "def initialize(parms)\n \n # Enlever les activites\n tmpActivites = parms && parms.delete(:activites) || nil\n tmpParticipations = parms && parms.delete(:participations) || nil\n \n super\n \n # Lorsque la date est sous forme de hash {:year, :month, :day}, faire la conversion\n if parms && parms[:naissance] && parms[:naissance][:year]\n nd = parms.delete(:naissance)\n self.naissance = Date.civil(nd[:year].to_i, nd[:month].to_i, nd[:day].to_i)\n else\n self.naissance = Date.civil(Date.today.year - 5, 7, 15)\n end\n \n saveActivites(tmpActivites)\n saveParticipations(tmpParticipations)\n \n # Des defaults\n self.nom = '' unless parms && parms[:nom]\n self.prenom = '' unless parms && parms[:prenom]\n self.activites.build unless parms\n self.participations.build unless parms\n self.nom.capitalize!\n self.prenom.capitalize!\n end", "def initialize(params=nil)\r\n super\r\n end", "def initialize(numero, titular, saldo)\n @numero = numero#variavel de instacia\n @titular = titular\n @saldo = saldo\n end", "def initialize(nombre, proteinas, glucidos, lipidos)\n\t\t\t@nombre = nombre\n\t\t\t@proteinas = proteinas\n\t\t\t@glucidos = glucidos\n\t\t\t@lipidos = lipidos\n\t\tend", "def initialize\n \n end", "def initialize(params)\n @id = params[:id]\n @nombre = params[:nombre]\n @genero = params[:genero]\n @id_tropicos = params[:id_tropicos]\n @color1 = params[:color1]\n @color2 = params[:color2]\n @forma_vida1 = params[:forma_vida1]\n @forma_vida2 = params[:forma_vida2]\n @descripcion_es = params[:descripcion_es]\n @descripcion_en = params[:descripcion_en]\n @distribucion_es = params[:distribucion_es]\n @distribucion_en = params[:distribucion_en]\n @thumbnail = params[:thumbnail]\n end", "def initialize(params)\n params.each do |key, value| \n instance_variable_set(\"@#{key}\", value) if Legislator.instance_methods.include? key\n end\n end", "def initialize(nombre, proteinas, glucidos, lipidos, datos)\n\t\t@nombre = nombre\n\t\t@proteinas = proteinas\n\t\t@glucidos = glucidos\n\t\t@lipidos = lipidos\n\t\t@datos = datos\n\tend", "def initialize(*args)\n super\n self.estructura = estructura_maxima\n self.escudo = escudo_maximo\n end", "def initialize(nombre,alimentos,cantidad)\n @nombre_plato = nombre # Nombre del Plato\n @lista_alimentos = alimentos # Lista con los alimentos que forman el plato\n @lista_cantidades = cantidad # Lista con las cantidades que hay que usar de cada alimento\n end", "def initialize(nome) #inicializando os atributos\n self.saldo = 0.0\n self.nome = nome\n end", "def initialize(ciclos, lupula, cebada, mezcla, levadura)\n\n @ciclos = ciclos\n @almacen = Almacen.new(lupula,cebada,mezcla,levadura)\n @silosCebada = Silos_Cebada.new\n @molino = Molino.new\n @pailaMezcla = Paila_Mezcla.new\n @cuba = Cuba_Filtracion.new\n @pailaCoccion = Paila_Coccion.new\n @tanquePreclarif = Tanque_Preclarificador.new \n @enfriador = Enfriador.new\n @tcc = TCC.new\n @filtroCerveza = Filtro_Cerveza.new\n @tanqueFiltroCerveza = Tanque_Cerveza.new\n @llenadora = Llenadora.new\n\n end", "def initialize(params)\n @params = params\n end", "def initialize(params)\n @params = params\n end", "def initialize\n\t\t\n\tend", "def initialize(params = {})\n parameters(params)\n end", "def initialize (nombre, saturadas, monoinsaturadas, polinsaturadas, azucares, polialcoles, almidon, fibra, proteinas, sal)\n\t\t@nombre, @saturadas, @monoinsaturadas, @polinsaturadas, @azucares, @polialcoles, @almidon, @fibra, @proteinas, @sal = nombre, saturadas, monoinsaturadas, polinsaturadas, azucares, polialcoles, almidon, fibra, proteinas, sal\n\tend", "def initialize(nombre, carrera)\n # se ejecuta el consutrctor de la clase Chileno que solo recibe nombre\n super nombre\n # se asigna carrera\n @carrera = carrera\n end", "def initialize params = nil\n \n end", "def constructor; end", "def initialize(nombre,alimentos,cantidad)\n super(nombre,alimentos,cantidad) # Llamada al contructor de la clase padre\n @emisiones_diarias = 0 # Variable para almacenar valor de efceto invernadero\n @metros_terreno = 0 # variable para almacenar valor del terreno\n end", "def initialize(nome)\n # Variável de instância\n @nome = nome\n end", "def initialize\n\n\tend", "def initialize\n\n\tend", "def initialize(*args)\n\t\t\t\t\tself.track_changed_attributes = true\n\t\t\t\t\tself.changed_attributes_aado = []\n\n\t\t\t\t\tsuper(*args)\n\t\t\t\t\t\n\t\t\t\t\trequire \"obdb/AR_DatabaseObject\"\t# its here because of a circular reference problem\n\t\t\t\t\tself.database_object = DatabaseObject.create_do(self.class, self.id, self)\n\t\t\t\tend", "def initialize(nombre,apellidos,peso,talla,edad,sexo,cintura,cadera,tricipital,bicipital,subescapular,suprailíaco, factorActividadFisica)\n \tsuper(nombre,apellidos,edad,sexo)\n\n \t@peso = peso\n \t@talla = talla\n \t@cintura = cintura\n \t@cadera = cadera\n \t@tricipital = tricipital\n \t@bicipital = bicipital\n \t@subescapular = subescapular\n \t@suprailíaco = suprailíaco\n\t\t@factorActividadFisica = factorActividadFisica\n \tend", "def initialize(name) # je recrée un initialize et je fais appel aux caractéristiques de la classe mère avec super\n super(name)\n\n @life_points = 100 # j'ajoute les caractéristiques propres au joueur humain\n @weapon_level = 1\n end", "def initialize(data)\n @parms = data\n end", "def initialize\n\t\t@age = 10#age aqui es una variable de instancia\n\tend", "def initialize(name)\n @nombre = name\n end", "def initialize(nombre,apellido)#Debe recibir dos parametros: nombre y apellido\n @nombre=nombre\n @apellido=apellido\n @@persona.push self\n end", "def initialize (nombre, lista_alimentos, gramos)\n super(nombre,lista_alimentos,gramos)\n end", "def initialize\n @params = {}\n end", "def initialize\n super()\n @params = {}\n end", "def initialize(campos = {})\n super campos\n\n # TODO Remover código quando removido codigo específico\n # do Cnab400 da classe Brcobranca::Remessa::Pagamento\n @codigo_multa = nil if @codigo_multa == '0'\n end", "def initialize(nombre, cantidad = 1)\n @nombre = nombre\n @cantidad = cantidad\n end", "def initialize ( params = {})\r\n @parent1 = params.fetch(:p1,\"xxx\")\r\n @parent2 = params.fetch(:p2,\"xxx\")\r\n @f2_wild = params.fetch(:f2wild,\"xxx\")\r\n @f2_p1 = params.fetch(:f2p1,\"xxx\")\r\n @f2_p2 = params.fetch(:f2p2,\"xxx\")\r\n @f2_p1p2 = params.fetch(:f2p1p2,\"xxx\")\r\n \r\n\r\n @@almacen[parent1]=self \r\n end", "def initialize(*) end", "def initialize(*) end", "def initialize(*) end", "def initialize(*) end", "def initialize(*) end", "def initialize() end", "def initialize()\n\t\tend", "def initialize( * )\n super\n end", "def initialize(nome, comentario)\n @nome = nome\n @comentario = comentario\n @estrelando = []\n end", "def initialize(*_)\n super\n end", "def initialize\r\n\r\n end", "def initialize(nombre,peso,talla,edad,sexo,imc,estados,rccm,rcca) #constructor\n @peso = peso\n @talla = talla\n\t@edad = edad\n\t@sexo = sexo\n\t@nombre = nombre\n\t@imc = imc\n\t@estados = estados\n\t@rccm = rccm\n\t@rcca = rcca\n end", "def initialize\n\t\tself.parameters = {}\n\t\tself.user_id = -1\n\t\tself.new_user = false\n\tend", "def initialize(name, protein, carbo, lipido, g, t)\n\t\t\t@nombre = name\t\t\t\t\t\t# Atributo utilizado para almacenar el nombre del alimento\n\t\t\t@proteinas = protein\t\t\t# Atributo utilizado para almacenar las proteinas del alimento\n\t\t\t@carbohidratos = carbo\t\t# Atributo utilizado para almacenar los carbohidratos del alimento\n\t\t\t@lipidos = lipido\t\t\t\t\t# Atributo utilizado para almacenar los lipidos del alimento\n\t\t\t@gei = g\t\t\t\t\t\t\t\t\t# Atributo utilizado para almacenar el valor de gases de efecto invernadero\n\t\t\t@terreno = t\t\t\t\t\t\t\t# Atributo utilizado para almacenar el valor del terreno del alimento\n\t\tend", "def initialize(params)\n @params = normalize(params)\n end", "def initialize (name) #actions qui s'exécuteront dès lors de la création d'une nouvelle instance\r\n\t\t@name = name\r\n\t\t@life_points = 10 #n'est pas prit en argument dans la méthode car a une valeur fixe\r\n\tend", "def initialize(object)\n @this = object\n @local_attributes = Doodle::OrderedHash.new\n @local_validations = []\n @validation_on = true\n @local_conversions = {}\n @arg_order = []\n @errors = []\n #@parent = nil\n @parent = Doodle.parent\n end", "def initialize(villano , frase)\n # Declaramos las variables de intancia.\n @villano = villano\n @frase = frase\n end", "def initialize(params={})\n params.each do |attribute, value|\n if @@object_attributes.include? attribute\n objs = []\n value.each do |sub_val|\n objs << Ottoman.const_get(self.get_object_name(attribute)).new(sub_val)\n end if value\n self.public_send(\"#{attribute}=\", objs)\n elsif @@object_attribute.include? attribute\n self.public_send(\"#{attribute}=\", Object::const_get(self.get_object_name(attribute)).new(value)) if value\n else\n self.public_send(\"#{attribute}=\", value)\n end\n end if params\n\n super()\n end", "def initialize(nombre,sexo,menu)\r\n @nombre = nombre\r\n @sexo = sexo\r\n @menu = menu\r\n end", "def initialize(*args)\n super\n self.absorbido = {}\n self.absorbido[batalla.flota_atacante.object_id] = 0\n self.absorbido[batalla.flota_defensora.object_id] = 0\n end", "def initialize(parameters = {})\n @parameters = parameters\n end", "def initialize (nombre, lista_alimentos, lista_cantidades)\n\t\t@nombre = nombre\n\t\t@lista_alimentos = lista_alimentos\n\t\t@lista_cantidades = lista_cantidades\n\tend", "def initialize(nomee, idadee, alturaa, pesoo)\n \t@nome = nomee\n \t@idade = idadee\n \t@altura = alturaa\n \t@peso = pesoo\n end", "def initialize(name)\r\n @nombre = name #propiedad del objeto\r\n\r\n #puts @nombre\r\n\r\n end", "def initialize(mesa, *recaudacion) #* toma varios argumentos y permite trabajar con ellos separados pero todos a la vez\n @mesa = mesa\n @recaudacion = recaudacion.map(&:to_i) # todos pasan a entero :& \n end", "def construct\n end", "def initialize(*args)\r\n super(*args)\r\n end", "def initialize(nume, prenume)\n #Variabile de instanta\n @nume = nume\n @prenume = prenume\n end", "def initialize(*args)\n super\n end", "def initialize\n\n\n\n end", "def initialize(*args)\n set_instance_variables args\n end", "def initialize(params={})\n\t\t\t\tparams.each_pair do |k,v|\n\t\t\t\t\tinstance_variable_set(\"@#{k}\", v)\n\t\t\t\tend\n\t\t\tend", "def initialize (marca,modelo)\n @marca = marca\n @modelo = modelo\n end", "def initialize(*params)\n @params = *params\n end", "def initialize(params={})\n @name = params[:name]\n if params.key? :service\n @services = [ params[:service] ]\n else\n @services = params[:services] || []\n end\n if params.key? :protocol\n @protocols = [ params[:protocol] ]\n else\n @protocols = params[:protocols] || []\n end\n if params.key? :ontology\n @ontologies = [ params[:ontology] ]\n else\n @ontologies = params[:ontologies] || []\n end\n if params.key? :language\n @languages = [ params[:language] ]\n else\n @languages = params[:languages] || []\n end\n @lease_time = params[:lease_time]\n end", "def initialize(*rest) end", "def initialize(name)\n\t\t@nombre = name\n\tend", "def initialize(param)\n @param = param\n end", "def initialize(a,b,c)\r\n @valor = nil\r\n super(a,b,c) \r\n end", "def initialize(nombre, proteinas, glucidos, lipidos, datos, grupo)\n\t\tsuper(nombre, proteinas, glucidos, lipidos, datos)\n\t\t@grupo = grupo\n\tend", "def init; end", "def init; end", "def init; end", "def init; end", "def initialize\n\n\nend", "def initialize(model, year) #metodo constructor permite definir como se contruiran los objetos\n @model = model #guarda lo que sea que tenga en la variable \"model\"\n @year = year\n end", "def initialize(*args)\n super\n end", "def initialize(*args)\n super\n end", "def initialize(*args)\n super\n end", "def initialize\n @params = {} # Mimics params hash available within controllers in rails app\n end", "def initialize()\r\n\r\n end", "def initialize *args\n super\n end", "def initialize( param, param2 , param3 = 'default value'); # can pass in an object\n @param = param\n @param2 = param2\n @param3 = param3 # has default value of nothing input\n end", "def initialize\n super()\n init_data()\n end", "def initialize(args={})\n # could have problem where everything blank, or you could make save fail if not have an attribute\n #? formatting below?\n @name = args[:name] || \"\"\n @cuisine = args[:cuisine] || \"\"\n @price = args[:price] || \"\"\n end", "def initialize( params )\n super( Parametrization.permit( params, whitelist, model_name ) )\n @params = @params.with_indifferent_access # After building the internal params hash, make it a little friendlier.\n end" ]
[ "0.7060042", "0.68208", "0.6819683", "0.67807245", "0.6780606", "0.6765753", "0.671401", "0.6693817", "0.66931564", "0.6686258", "0.6677564", "0.6639425", "0.6638173", "0.6633336", "0.6627243", "0.66172147", "0.66078943", "0.66000974", "0.66000706", "0.6566535", "0.6566535", "0.6552161", "0.6548066", "0.6504419", "0.6500254", "0.64929926", "0.6483073", "0.6473882", "0.64665186", "0.6459059", "0.6459059", "0.64524966", "0.6447853", "0.64292634", "0.6422258", "0.642209", "0.640615", "0.64045966", "0.6393867", "0.63860226", "0.63851845", "0.6384774", "0.63760376", "0.63651335", "0.636407", "0.636407", "0.636407", "0.636407", "0.636407", "0.6347617", "0.6340491", "0.63342416", "0.6331471", "0.6318586", "0.63179445", "0.63145876", "0.6304791", "0.6291513", "0.62909293", "0.6289661", "0.628924", "0.628781", "0.6287773", "0.62825876", "0.62825304", "0.62797946", "0.6272066", "0.6258824", "0.6251605", "0.6246562", "0.6241292", "0.6238052", "0.6235082", "0.6217291", "0.6217284", "0.62102616", "0.6205624", "0.6205497", "0.6204181", "0.6203971", "0.61936945", "0.6191924", "0.61899495", "0.6186961", "0.61863774", "0.6185137", "0.6185137", "0.6185137", "0.6185137", "0.6183105", "0.6179498", "0.61774886", "0.61774886", "0.61774886", "0.6176326", "0.6171027", "0.6168779", "0.6167847", "0.61678445", "0.6162735", "0.61627054" ]
0.0
-1
Metodos apenas chamados na classe mesmo
def calcula_preco(base) if @ano_lancamento <2006 if @possui_reimpressao base * 0.9 else base * 0.5 end elsif @ano_lancamento <= 2010 if @possui_reimpressao base * 0.96 else base end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def private; end", "def mi_carrera\n\n\tend", "def checks; end", "def informational?; end", "def suivre; end", "def usable?; end", "def probers; end", "def marquer!\n fail \"Doit etre defini dans la sous-classe\"\n end", "def cumple_requisitos?\n propietario.hangar.nivel >= 4 && propietario.cuenta.tecnologia_energia.nivel >= 3 && propietario.cuenta.tecnologia_laser.nivel >= 6 && super\n end", "def zuruecksetzen()\n end", "def who_we_are\r\n end", "def celebration; end", "def check\n \n end", "def check\n \n end", "def cumple_requisitos?\n propietario.hangar.nivel >= 6 && propietario.cuenta.tecnologia_energia.nivel >= 6 && propietario.cuenta.tecnologia_militar.nivel >= 3 && propietario.cuenta.tecnologia_defensa.nivel >= 1 && super\n end", "def used?; end", "def object_status\n super\n end", "def object_status\n super\n end", "def object_status\n super\n end", "def flags; end", "def statistics\n super\n end", "def statistics\n super\n end", "def statistics\n super\n end", "def statistics\n super\n end", "def statistics\n super\n end", "def statistics\n super\n end", "def statistics\n super\n end", "def statistics\n super\n end", "def statistics\n super\n end", "def statistics\n super\n end", "def statistics\n super\n end", "def statistics\n super\n end", "def transferred_properties; end", "def transferred_properties; end", "def somme\n fail \"Doit etre defini dans la sous-classe\"\n end", "def status\n super\n end", "def flag; end", "def extra; end", "def offences_by; end", "def specie; end", "def specie; end", "def specie; end", "def specie; end", "def properties; end", "def properties; end", "def properties; end", "def properties; end", "def properties; end", "def properties; end", "def properties; end", "def properties; end", "def methods() end", "def remaining; end", "def checaMeta\n\t\t@goals = self.goals\n\t\[email protected] do |g|\n\t\t\tself.categories.each do |c|\n\t\t\t\tsaldo = c.valor_receita_efetivado - c.valor_despesa_efetivado\n\t\t\t\tif ((g.fim < Date.today) && (saldo < g.valor))\n\t\t\t\t\tg.estado = -1\t\t\t\t\t\n\t\t\t\telsif ((g.fim < Date.today) && (saldo >= g.valor)) \n\t\t\t\t\tg.estado = 1\t\t\t\t\t\n\t\t\t\tend\n\t\t\tend\n\t\t\tg.save\n\t\tend\n\tend", "def methods; end", "def methods; end", "def methods; end", "def methods; end", "def class_variables() end", "def covered?; end", "def used\n raise NotImplementedError\n end", "def sos_piedra?() raise NotImplementedError end", "def stat() end", "def verdi; end", "def missed?; end", "def overrides; end", "def prepare\n Maadi::post_message(:More, \"Model (#{@type}) is ready\")\n\n super\n end", "def calculated; end", "def status_age\n super\n end", "def caveats; nil end", "def caveats; nil end", "def causas_conocidas\n %w{ cheque-propio cheque-de-terceros efectivo transferencia retenciones }\n end", "def attr_reader(*)\n end", "def count\n # implement in subclasses\n end", "def appropriate\n notes.map(&:class).uniq.size >= @chord.notes.size\n end", "def informacoes_da_conta(local)\n\t\t\t\t\traise NotImplementedError.new('Sobreescreva este método na classe referente ao banco que você esta criando')\n\t\t\t\tend", "def check\n each { |m| m.check }\n end", "def control_infos\n @log.info 'Info control started!'\n return false unless @infos.class == Hash\n\n props = [YEAR, PROP, LESSON, STUDENT, EXAM]\n return false unless props.sort == @infos.keys.sort\n @log.info 'Info control succesful!'\n true\n end", "def uncertain?\r\n @@maybes\r\n end", "def estConsomable()\n\t\treturn false\n\tend", "def conditions; end", "def conditions; end", "def hambriento?\n # Los nombres de los metodos pueden terminar en \"?\".\n # Generalmente, hacemos esto si el método debe\n # devolver verdadero o falso, como esto:\n @panzaLlena <= 2\n end", "def hambriento?\n # Los nombres de los metodos pueden terminar en \"?\".\n # Generalmente, hacemos esto si el método debe\n # devolver verdadero o falso, como esto:\n @panzaLlena <= 2\n end", "def ignores; end", "def class_variables; end", "def stats; end", "def stats; end", "def get_celebrity_status\n set_imdb if @imdb_data\n set_wikipedia if @wikipedia_data\n set_social_data if @fullcontact_data\n end", "def initialize(nombre,alimentos,cantidad)\n super(nombre,alimentos,cantidad) # Llamada al contructor de la clase padre\n @emisiones_diarias = 0 # Variable para almacenar valor de efceto invernadero\n @metros_terreno = 0 # variable para almacenar valor del terreno\n end", "def ismn; end", "def celebrity; end", "def celebrity; end", "def agregarMetodos unaClase\n self.metodos.each do |metodo|\n self.agregar_metodo(unaClase,metodo[0],&metodo[1])\n end\n end", "def checked; end", "def incomplete\r\n\r\n end", "def metodos_con(letras,*clase) # puede ser metodos de una clase, una lista de clases, o una lista de metodos\n if not clase.none? # si no hay parametros busca en los metodos_observados\n self.get_metodos_de(clase) # aca los setea en @metodos_observados\n end\n @metodos_observados.select{|metodo| metodo[0..letras.size].include? letras}\n end", "def available; end", "def available; end", "def cardinal; end", "def reason; end" ]
[ "0.59491336", "0.58105725", "0.56839466", "0.5679155", "0.56448257", "0.5592401", "0.55302614", "0.5513648", "0.55124253", "0.5512297", "0.5510457", "0.5481711", "0.54707146", "0.54707146", "0.54556906", "0.5429441", "0.54177994", "0.54177994", "0.54177994", "0.53667456", "0.53661895", "0.53661895", "0.53661895", "0.53661895", "0.53661895", "0.53661895", "0.53661895", "0.53661895", "0.53661895", "0.53661895", "0.53661895", "0.53661895", "0.53219455", "0.53219455", "0.5320797", "0.52788997", "0.5278899", "0.52788836", "0.5268118", "0.5264689", "0.5264689", "0.5264689", "0.5264689", "0.5238772", "0.5238772", "0.5238772", "0.5238772", "0.5238772", "0.5238772", "0.5238772", "0.5238772", "0.5210419", "0.52012265", "0.5198523", "0.5187475", "0.5187475", "0.5187475", "0.5187475", "0.5184616", "0.51838946", "0.5180732", "0.5176214", "0.5134788", "0.5133229", "0.51280534", "0.51165915", "0.5115754", "0.51134205", "0.51115274", "0.5108428", "0.5108428", "0.5102404", "0.50950056", "0.5092122", "0.50889146", "0.5075068", "0.50648475", "0.5048559", "0.504833", "0.50401133", "0.5039163", "0.5039163", "0.5037864", "0.5037864", "0.5035539", "0.50354415", "0.50164014", "0.50164014", "0.50109607", "0.50103295", "0.501", "0.5008622", "0.5008622", "0.50044185", "0.5000903", "0.49940085", "0.49927965", "0.49922395", "0.49922395", "0.4985618", "0.49836552" ]
0.0
-1
ensure that there are no line items referencing this product
def ensure_not_referenced_by_any_line_item if line_items.empty? return true else errors.add(:base, 'Line Items present') return false end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ensure_not_referenced_by_any_line_item\n\t\t\tunless line_items.empty?\n\t\t\t\terrors.add(:base, 'Line items reference this product')\n\t\t\t\tthrow :abort\n\t\t\tend\n\t\tend", "def ensure_not_referenced_by_any_line_item_product\n unless line_item_products.empty?\n errors.add(:base, 'Line Items Products present')\n throw :abort\n end\n end", "def ensure_not_referenced_by_any_line_item\n unless line_items.empty?\n raise Error.new \"Line Items present\"\n end\n end", "def ensure_not_referenced_by_any_line_item\n\t\tunless line_items.empty?\n\t\t\terrors.add(:base, 'Line Items Presents')\n\t\t\tthrow :abort\n\t\tend\n\tend", "def ensure_not_referenced_by_any_line_item\n\t\tif line_items.empty?\n\t\t\treturn true\n\t\telse\n\t\t\terrors.add(:base, 'Product sedang di referensikan oleh Line Item')\n\t\t\treturn false\n\t\tend\n\tend", "def ensure_not_referenced_by_any_line_item\n\t\tunless line_items.empty?\n\t\t\terrors.add(:base, 'Line Items present')\n\t\t\tthrow :abort\n\t\tend\n\tend", "def ensure_not_referenced_by_any_line_item #in this case before destroy a row in the database\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Itens present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n return if line_items.empty?\n\n errors.add(:base, \"Line Items present\")\n throw :abort\n end", "def ensure_not_referenced_by_any_line_item\n unless line_items.empty?\n errors.add(:base, 'Line Items Present')\n throw :abort\n end\n end", "def ensure_not_referenced_by_any_line_item\n unless line_items.empty?\n errors.add(:base, 'Line Items present')\n throw :abort\n end\n end", "def ensure_not_referenced_by_any_line_item\n\t\tif line_items.count.zero?\n\t\t\treturn true\n\t\telse\n\t\t\terrors[:base] << \"Line Items Prsent\"\n\t\t\treturn false\n\t\tend\n\tend", "def ensure_not_referenced_by_any_line_item\r\n\t\tunless line_items.empty?\r\n\t\t\terrors.add(:base, 'Line Items Present')\r\n\t\t throw :abort\r\n\t\tend\r\n\t\r\n\tend", "def ensure_not_referenced_by_any_line_item\n unless line_items.empty?\n errors.add(:base, 'Line Items present')\n throw :abort\n end\n end", "def ensure_not_referenced_by_any_line_item\n unless line_items.empty?\n errors.add(:base, 'Line Items present')\n throw :abort\n end\n end", "def ensure_not_referenced_by_any_line_item\n unless line_items.empty?\n errors.add(:base, 'Line Items present')\n throw :abort\n end\n end", "def ensure_not_referenced_by_any_line_item # hook method (a method that Rails calls automatically at a given point in an object’s life)\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n unless line_items.empty?\n errors.add(:base, 'Line Items present')\n throw :abort\n end\n end", "def ensure_not_referenced_by_any_line_item\n unless line_items.empty?\n errors.add(:base, 'Line Items present')\n throw :abort\n end\n end", "def ensure_not_referenced_by_any_line_item\n unless line_items.empty?\n errors.add(:base, 'Line Items present')\n throw :abort\n end\n end", "def ensure_not_referenced_by_any_line_item\n unless line_items.empty?\n errors.add(:base, 'Line items present')\n throw :abort\n end\n end", "def ensure_not_referenced_by_any_line_item\n unless line_items.empty?\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item \n if line_items.empty?\n return true \n else\n errors.add(:base, 'Line Items present')\n return false \n end\n end", "def ensure_not_referenced_by_any_line_item\n unless line_items.empty?\n errors.add(:base, \"Line Items present\")\n throw :abort\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Istnieja powiazania z Line Items')\n return false;\n end\n end", "def ensure_not_referenced_by_any_line_item\n\t\tif line_items.count.zero?\n\t\t\treturn true\n\t\telse\n\t\t\terrors.add(:base, 'Line Items present')\n\t\t\treturn false\n\t\tend\n\tend", "def ensure_not_referenced_by_any_line_item\n\t\tif line_items.count.zero?\n\t\t\treturn true\n\t\telse\n\t\t\terrors.add(:base, 'Line Items present' )\n\t\t\treturn false\n\t\tend\n\tend", "def ensure_not_referenced_by_any_line_item\n\t\tif line_items.count.zero?\n\t\t\treturn true\n\t\telse\n\t\t\terrors.add(:base, 'Line Items present' )\n\t\t\treturn false\n\t\tend\n\tend", "def ensure_not_referenced_by_any_line_item\n if line_items.count.zero?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n \tif line_items.empty?\n \t\treturn true\n \telse\n \t\terrors.add(:base, 'Line Items Present')\n \t\treturn false\n \tend\n end", "def ensure_not_referenced_by_any_line_item\n\t\tif line_items.count.zero?\n\t\t\treturn true\n\t\telse\n\t\t\terrors[:base] << \"Line Items present\"\n\t\t\treturn false\n\t\tend\n\tend", "def ensure_not_referenced_by_any_line_item\n\t\tif line_items.empty?\n\t\t\treturn true\n\t\telse\n\t\t\terrors.add(:base,'Line Items present') #We associate errors with the base object\n\t\t\treturn false\n\t\tend\n\tend", "def ensure_not_referenced_by_any_line_items\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items Present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n\t\tif line_items.emty?\n\t\t\treturn true\n\t\tesle\n\t\t\terrors.add(:base, 'Line Items present')\n\t\t\treturn false\n\t\tend\n\tend", "def ensure_not_referenced_by_any_line_item \n \tif line_items.empty?\n return true \n else\n errors.add(:base, 'Line Items present')\n return false \n end\n end", "def ensure_not_referenced_by_any_line_item\n\t\t\tif line_items.empty?\n\t\t\t\treturn true \n\t\t\telse\n\t\t\t\terrors.add(:base, 'Line Items present')\n\t\t\t\treturn false \n\t\t\tend\n\t\tend", "def ensure_not_referenced_by_any_line_item\n\t\tif line_items.count.zero?\n\t\t\treturn true\n\t\t\telse\n\t\t\terrors.add(:base, 'Line Items present' )\n\t\t\treturn false\n\t\t\tend\n\tend", "def ensure_not_referenced_by_any_line_item\n if line_items.count.zero?\n return true\n else\n errors[:base] << \"Line Items present\"\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.count.zero?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.count.zero?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.count.zero?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n\tif line_items.empty?\n \t return true\n \telse\n \t errors.add(:base, 'Line Items present' )\n \treturn false\n \tend\n end", "def ensure_not_referenced_by_any_line_item\n \tif line_items.empty?\n \t\treturn true\n \telse\n \t\terrors.add(:base, 'Line Items present')\n \t\treturn false\n \tend \t\t\n end", "def ensure_not_referenced_by_any_line_item \n\t\tif line_items.empty?\n\t\t\treturn true \n\t\telse\n\t\t\terrors.add(:base, 'Line Items present')\n\t\treturn false\n\t\tend\n\tend", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n\tif line_items.empty?\n\treturn true\n\telse\n\terrors.add(:base, 'Line Items present')\n\treturn false\n\tend\n\tend", "def ensure_not_referenced_by_any_line_item \n if line_items.empty?\n return true \n else\n errors.add(:base, 'Line Items present')\n return false \n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n\t return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item \n if line_items.empty?\n return true \n else\n errors.add(:base, 'Line Items present')\n return false \n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_item1s.count.zero?\n return true\n else\n errors[:base] << \"Line Items present\"\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n\t\tif line_items.empty?\n\t\t return true\n\t \telse\n\t \t errors.add(:base, 'Line Items present')\n\t return false\n\t end\n end", "def ensure_not_referenced_by_any_line_item\n\t\t\tif line_items.empty?\n\t\t\t\treturn true\n\t\t\telse\n\t\t\t\terrors.add(:base, 'Line Items present')\n\t\t\t\treturn false\n\t\t\tend\n\t\tend", "def ensure_not_referenced_by_any_line_item\n\t\t\tif line_items.empty?\n\t\t\t\treturn true\n\t\t\telse\n\t\t\t\terrors.add(:base, 'Line Items present')\n\t\t\t\treturn false\n\t\t\tend\n\t\tend", "def ensure_not_referenced_by_any_line_item\n\t\t\tif line_items.empty?\n\t\t\t\treturn true\n\t\t\telse\n\t\t\t\terrors.add(:base, 'Line Items present')\n\t\t\t\treturn false\n\t\t\tend\n\t\tend", "def ensure_not_referenced_by_any_line_item\n\t\t\tif line_items.empty?\n\t\t\t\treturn true\n\t\t\telse\n\t\t\t\terrors.add(:base, 'Line Items present')\n\t\t\t\treturn false\n\t\t\tend\n\t\tend", "def ensure_not_referenced_by_any_line_item\n\t\t\tif line_items.empty?\n\t\t\t\treturn true\n\t\t\telse\n\t\t\t\terrors.add(:base, 'Line Items present')\n\t\t\t\treturn false\n\t\t\tend\n\t\tend", "def ensure_not_referenced_by_any_line_item\n\t\t\tif line_items.empty?\n\t\t\t\treturn true\n\t\t\telse\n\t\t\t\terrors.add(:base, 'Line Items present')\n\t\t\t\treturn false\n\t\t\tend\n\t\tend", "def ensure_not_referenced_by_any_line_item\n\t\t\tif line_items.empty?\n\t\t\t\treturn true\n\t\t\telse\n\t\t\t\terrors.add(:base, 'Line Items present')\n\t\t\t\treturn false\n\t\t\tend\n\t\tend", "def ensure_not_referenced_by_any_line_item\n if line_items.count.zero?\n return true\n else\n errors[:base] << \"Line Items present\"\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n\tif line_items.count.zero?\n\treturn true\n\telse\n\terrors[:base] << \"Line Items present\"\n\treturn false\n\tend\nend", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n\t\tif line_items.empty?\n\t\t\treturn true\n\t\telse\n\t\t\terrors.add(:base, 'Line Items present')\n\t\t\treturn false\n\t\tend\n\tend", "def ensure_not_referenced_by_any_line_item\n\t\tif line_items.empty?\n\t\t\treturn true\n\t\telse\n\t\t\terrors.add(:base, 'Line Items present')\n\t\t\treturn false\n\t\tend\n\tend", "def ensure_not_referenced_by_any_line_item\n\t\tif line_items.empty?\n\t\t\treturn true\n\t\telse\n\t\t\terrors.add(:base, 'Line Items present')\n\t\t\treturn false\n\t\tend\n\tend", "def ensure_not_referenced_by_any_line_item\n\t\tif line_items.empty?\n\t\t\treturn true\n\t\telse\n\t\t\terrors.add(:base, 'Line Items present')\n\t\t\treturn false\n\t\tend\n\tend", "def ensure_not_referenced_by_any_line_item\n\t\tif line_items.empty?\n\t\t\treturn true\n\t\telse\n\t\t\terrors.add(:base, 'Line Items present')\n\t\t\treturn false\n\t\tend\n\tend", "def ensure_not_referenced_by_any_line_item\n\t\tif line_items.empty?\n\t\t\treturn true\n\t\telse\n\t\t\terrors.add(:base, 'Line Items present')\n\t\t\treturn false\n\t\tend\n\tend", "def ensure_not_referenced_by_any_line_item\n\t\tif line_items.empty?\n\t\t\treturn true\n\t\telse\n\t\t\terrors.add(:base, 'Line Items present')\n\t\t\treturn false\n\t\tend\n\tend", "def ensure_not_referenced_by_any_line_item\n \t if line_items.empty?\n \t \treturn true\n \t else\n \t \terrors.add(:base, 'Line items present')\n \t \treturn false\n \t end\n \tend", "def ensure_not_referenced_by_any_line_item\n if line_items.count.zero?\n return true\n else\n errors[:base] << \"Line Items present\" #这是什么意思\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n\t\t\tif line_items.empty?\n\t\t\t\treturn true\n\t\t\telse\n\t\t\t\terrors.add(:base, 'Line Items present')\n\t\t\t\treturn false\n\t\tend\n\tend", "def ensure_not_referenced_by_any_line_item\n if line_items.count.zero?\n return true\n else\n errors[:base] << \"Line Items present\"\n return false\n end \n end", "def ensure_not_referenced_by_any_line_item\n\t\tif line_items.empty?\n\t\t\treturn true\n\t\telse\n\t\t\terrors.add(:base, 'Line items present')\n\t\t\treturn false\n\t\tend\n\tend", "def ensure_not_referenced_by_any_line_item\n\t if line_items.count.zero?\n\t\t return true\n\t else\n\t\t errors[:base] << \"Line Items present\"\n\t\t return false\n\t end\n\tend", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n unless line_items.empty?\n errors.add(:base, 'Line Items present')\n throw :abort\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end", "def ensure_not_referenced_by_any_line_item\n if line_items.empty?\n return true\n else\n errors.add(:base, 'Line Items present')\n return false\n end\n end" ]
[ "0.8736616", "0.853958", "0.8289557", "0.8246923", "0.82232034", "0.82068616", "0.8206619", "0.81594956", "0.81327915", "0.8104883", "0.81018025", "0.80855167", "0.8076766", "0.8076766", "0.80568", "0.8037973", "0.8020351", "0.8020351", "0.8020351", "0.80173016", "0.8011286", "0.8010101", "0.80063355", "0.7984239", "0.7982983", "0.7972746", "0.7972746", "0.796831", "0.796309", "0.79618263", "0.79607385", "0.79537976", "0.7946839", "0.7944792", "0.79428923", "0.7942568", "0.79402906", "0.793406", "0.793406", "0.793406", "0.7926673", "0.7919657", "0.7916912", "0.7916262", "0.7914657", "0.79127026", "0.791117", "0.79110795", "0.7910755", "0.79104286", "0.7909076", "0.7904992", "0.79046524", "0.79046524", "0.79046524", "0.79046524", "0.79046524", "0.79046524", "0.79046524", "0.79024816", "0.7898809", "0.7895409", "0.78943604", "0.78941166", "0.78941166", "0.78941166", "0.78941166", "0.78941166", "0.78941166", "0.78941166", "0.7892181", "0.78880906", "0.7884762", "0.7883583", "0.78734857", "0.7860402", "0.78557384", "0.78552985", "0.78552985", "0.78552985", "0.78552985", "0.78552985", "0.78552985", "0.78552985", "0.78552985", "0.78552985", "0.78552985", "0.78552985", "0.78552985", "0.78552985", "0.78552985", "0.78552985", "0.78552985", "0.78552985", "0.78552985", "0.785006", "0.7848537", "0.7848537", "0.7848537", "0.7848537", "0.7848537" ]
0.0
-1
=begin The method returns the list of hotel items using the city and token parameters passed in the url. =end
def index hotels_list = get_hotels(params[:city_id].downcase,params[:token]) render_with_protection hotels_list end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_hotels(city,token)\n results = []\n lat,lng = get_coordinates(city)\n if lat.nil? or lng.nil?\n return [].append({:results=>[],:token=>nil}).to_json\n end\n if(token.nil?)\n if((results = $redis.get(lat.to_s+':'+lng.to_s+':hotel')).nil?)\n hotel = get_hotels_list(city,lat,lng)\n return hotel\n else\n return results\n end\n else\n results = $redis.get(lat.to_s+':'+lng.to_s+':hotel:'+token)\n return results\n end\n end", "def index\n\n response = @api.get_list({:destinationString => 'Media', :stateProvinceCode => 'PA'})\n @hotels = response.body['HotelListResponse']['HotelList']['HotelSummary']\n\n end", "def show\n @comment = Comment.new\n # create a empty array if not hotel return\n @hotels = []\n begin\n response = HTTParty.get(\"http://api.hotwire.com/v1/deal/hotel?dest=#{URI.encode(@idea.destination)}&currency=USD&apikey=cg54gruz8zva5n67p6jnqu8b&limit=5&sort=price&sortorder=desc&format=JSON\", {format: :json})\n if response.code and response[\"Errors\"].size == 0\n @hotels = response[\"Result\"]\n end\n rescue HTTParty::Error => e\n logger.debug(\"HTTParty Error: #{e}\")\n rescue StandardError => e\n logger.debug(\"Fail to get hotel list: #{e}\")\n end\n end", "def hotel\n if params[:city_id] != nil \n session[:city_id] = params[:city_id]\n end\n @package = GenPackage.find_by_id(session[:city_id])\n end", "def search(term, location)\n url = \"#{API_HOST}#{SEARCH_PATH}\"\n params = {\n term: term,\n location: location,\n limit: SEARCH_LIMIT\n }\n#this takes info from params hash\n response = HTTP.auth(bearer_token).get(url, params: params)\n response.parse[\"businesses\"]\nend", "def index\n @hotels = if params[:term]\n Hotel.where(\"name LIKE (?) OR address LIKE (?)\", \"%#{params[:term]}%\", \"%#{params[:term]}%\").paginate(page: params[:page], per_page: 5)\n else\n Hotel.paginate(page: params[:page], per_page: 6)\n end\n end", "def get_all_hotel_location\n service_data = hotel_service.get_all_hotel_location(params[:hotelIds])\n result = false\n if service_data[:hotel]\n result = {\n :places => service_data[:list_hotel_response]\n }\n end\n respond_to do |format|\n format.json {render :json => {:data => result}}\n end\n end", "def hotel_search(result_or_hotel_id)\n hotel_id = result_or_hotel_id.is_a?(Fixnum) ? result_or_hotel_id : result_or_hotel_id.hotel_id\n params = parameters\n params.delete(:city_id)\n params.delete(:region_id)\n params[:hotel_id] = hotel_id\n TAPI::V3::Hotels::Search.new(params)\n end", "def get_cities\n cities = {}\n doc = nil\n retry_if_exception do\n doc = Nokogiri::HTML( easy_curl(@host_url) )\n end\n return [] if not doc\n a_cities = doc.css(\"ul[class='s-dropdown afh-dd-city'] li a\")\n a_cities.each do |city|\n city_name = city.text\n city_code = city['href'].scan(/\\w+(?=\\/changecity)/).pop\n next if not city_code\n cities[city_code] = city_name\n end\n cities\nend", "def get(params = {})\n client.get(\"/v1/shopping/hotels/#{@hotel_id}/hotel-offers\", params)\n end", "def search_by_city\n space(1)\n puts \"Where would you like to look?\"\n space(1)\n city = get_input\n url = \"https://app.ticketmaster.com/discovery/v2/events?apikey=pyLDDCYURYJ8LZfAUnOayESRsPBTWnKM&locale=*&city=#{city}&sort=date,asc\"\n response = RestClient.get(url)\n if JSON.parse(response).key?(\"_embedded\")\n events = JSON.parse(response)[\"_embedded\"][\"events\"]\n events[0...20]\n else\n puts \"Sorry, your search returned no results. Try again.\"\n search_by_city\n end\nend", "def get_food(city,token)\n results = []\n lat,lng = get_coordinates(city)\n if lat.nil? or lng.nil?\n return [].append({:results=>[],:token=>nil}).to_json\n end\n if(token.nil?)\n if((results = $redis.get(lat.to_s+':'+lng.to_s+':food')).nil?)\n food = get_food_items(city,lat,lng)\n puts food[0][:results]\n if(food[0][:results].length != 0)\n $redis.set(lat.to_s+':'+lng.to_s+':food',food.to_json)\n end\n return food.to_json\n else\n return results\n end\n else\n if((results = $redis.get(lat.to_s+':'+lng.to_s+':food:'+token)).nil?)\n food = get_food_others(token,city)\n if(food[0][:results].length != 0)\n $redis.set(lat.to_s+':'+lng.to_s+':food:'+token,food.to_json)\n end\n return food.to_json\n else\n return results\n end\n end\n end", "def get\n puts '>>> GEO WS'\n puts 'Lat Lng'\n ap params['latlng']\n \n if params.has_key?('latlng')\n \n consumer_key = 'yQOQxtNtpLyPOtPVeOFiuQ'\n consumer_secret = 'wbGrz176uFBeQZazJx_OkYkAng8'\n token = '1St_-kOKX8rKJYf33hO-MB0qdVKJJcQm'\n token_secret = 'X5l9MQ9IBRXrr5eb2jCUU6r-GZM'\n \n api_host = 'api.yelp.com'\n \n consumer = OAuth::Consumer.new(consumer_key, consumer_secret, {:site => \"http://#{api_host}\"})\n access_token = OAuth::AccessToken.new(consumer, token, token_secret)\n \n limit = 10\n offset = params['p'].to_i * limit\n \n # path = \"/v2/search?sort=1&ll=\" + params['latlng'] + \"&limit=\" + limit.to_s + \"&offset=\" + offset.to_s + \"&category_filter=restaurants\"\n path = \"/v2/search?sort=1&ll=\" + params['latlng'] + \"&limit=\" + limit.to_s + \"&category_filter=restaurants\"\n \n ap path\n \n response = JSON.parse(access_token.get(path).body)\n \n # ap response\n \n if response[\"error\"]\n ap response[\"error\"]\n payload = Hash.new\n payload[:success] = false\n payload[:error] = response[\"error\"][\"text\"]\n \n # Create dummy results data\n results = []\n result_r = Hash.new\n result_r[\"yelp_id\"] = \"restaurant-chicago\"\n result_r[\"name\"] = \"Dummy Restaurant\"\n result_r[\"address\"] = \"123 Chicago Ave\"\n result_r[\"phone\"] = \"(312) 555-5555\"\n result_r[\"categories\"] = []\n result_r[\"categories\"] << \"American\"\n result_r[\"categories\"] << \"Food\"\n result_r[\"neighborhoods\"] = []\n result_r[\"neighborhoods\"] << \"River North\"\n results << result_r\n result_b = Hash.new\n result_b[\"yelp_id\"] = \"bar-chicago\"\n result_b[\"name\"] = \"Dummy Bar\"\n result_b[\"address\"] = \"555 Chicago Ave\"\n result_b[\"phone\"] = \"(312) 555-5555\"\n result_b[\"categories\"] = []\n result_b[\"categories\"] << \"Bar\"\n result_b[\"categories\"] << \"Sports Bar\"\n result_b[\"neighborhoods\"] = []\n result_b[\"neighborhoods\"] << \"River North\"\n results << result_b\n results << result_r\n results << result_r\n results << result_r\n results << result_b\n results << result_r\n results << result_b\n results << result_r\n payload[:results] = results\n \n render json: payload and return\n end\n \n results = []\n \n response[\"businesses\"].each do |item|\n # ap item\n \n result = Hash.new\n \n result[\"yelp_id\"] = item[\"id\"]\n result[\"name\"] = item[\"name\"]\n result[\"address\"] = item[\"location\"][\"address\"][0]\n result[\"phone\"] = item[\"display_phone\"]\n result[\"categories\"] = []\n \n item[\"categories\"].each do |category|\n result[\"categories\"] << category[0]\n end\n \n result[\"neighborhoods\"] = []\n \n item[\"location\"][\"neighborhoods\"].each do |neighborhood|\n result[\"neighborhoods\"] << neighborhood\n end\n \n # # CANT SAVE TO DB BECAUSE YELP DATA\n # Create new place if it does not exist\n # place = Place.find_by_uid(result[\"uid\"])\n # if !place\n # puts '>>> place not in DB'\n # place = Place.new\n # \n # ### !!! NOTE: taking uid, location, city out since its not used yet (Open API potentially)\n # \n # # place.uid = result[\"uid\"]\n # place.name = result[\"name\"]\n # # place.location = result[\"vicinity\"]\n # \n # ap result\n # # ap place.location\n # ap place\n # \n # # # Taking city and location out, not used currently\n # # city_const = \", \"\n # # \n # # index = place.location.rindex(city_const)\n # # if index\n # # place.city = place.location.slice(index + city_const.length..place.location.length)\n # # else\n # # place.city = place.location\n # # end\n # \n # # Save the place to DB\n # place.save\n # \n # # # check if exists in OT\n # # place.ot_rid = ot_rid(place)\n # # \n # # puts '>>> ot_rid:'\n # # ap place.ot_rid\n # end\n \n # # if exists in OT then send data to front end\n # result[\"ot\"] = place.ot_rid\n \n results << result\n end\n \n # puts '>>> results:'\n # puts results\n # ap results\n \n payload = Hash.new\n payload[:success] = !results.empty?\n \n payload[:results] = results\n \n render json: payload\n end\n end", "def search_by_keyword\n space(1)\n puts \"What do you want to search for?\"\n space(1)\n keyword = get_input\n url = \"https://app.ticketmaster.com/discovery/v2/events?apikey=pyLDDCYURYJ8LZfAUnOayESRsPBTWnKM&keyword=#{keyword}&locale=en&sort=date,asc\"\n response = RestClient.get(url)\n if JSON.parse(response)[\"_embedded\"][\"events\"]\n attractions = JSON.parse(response)[\"_embedded\"][\"events\"]\n attractions[0...20]\n else\n puts \"Sorry, your search returned no results. Try again.\"\n search_by_city\n end\nend", "def city_list(url)\n\troot = Nokogiri::HTML(open(url))\n list = root.css(\"a\").map do |link|\n\n\t\t# This makes sure that we only store actual links, then stores the text & link for each valid link in an array.\n\n if link[:href] =~ /http/ \n [link.text, link[:href]] \n end \n end\n\n\t# This cleans up the array and gets rid of nil elements\n\n\tlist = list.reject {|x| x.nil?} \n\t\t\n\t## Here we have various sections of CL that we can search in for various gigs. \n\t## If you wanted to see more software development stuff, you may search in /sof and /eng\n\t\n\t\t\n\t# list.map! {|f,l| [f, l + \"/cpg/\"]}\n\t# list.map! {|f,l| [f, l + \"/web/\"]}\n\tlist.map! {|f,l| [f, l + \"/web/\", l + \"/cpg/\"]}\t\n\t# list.map! {|f,l| [f, l + \"/web/\", l + \"/cpg/\", l + \"/eng/\", l + \"/sof/\", l + \"/sad/\"]}\n\t\nend", "def index\n \t#Change to make a response flexible from a query method\n \tresponse = HTTP.auth(\"Bearer #{ENV['YELP_API_KEY']}\").get('https://api.yelp.com/v3/businesses/search?term=coffee&location=nyc')\n \t@yelps = response.parse['businesses']\n end", "def index\n @hotels = Hotel.all.page params[:page]\n end", "def index\n @hotels = Hotel.where(aasm_state: \"approved\").order(created_at: :desc).page(params[:page])\n end", "def get_by_location\n \tlat = params[:lat]\n \tlng = params[:lng]\n \tnext_start = params[:next_start]\n \tshops = Hotpepper.search_location(lat, lng, next_start);\n \tset_to_results(shops);\n end", "def api_request(city)\n url = \"https://jobs.github.com/positions.json?utf8=%E2%9C%93&description=&location=\"+city\n #Escape and parse URL for proper formatting.\n escaped_url = URI.escape(url)\n parsed_url = URI.parse(escaped_url)\n #Make the HTTP request.\n request = Net::HTTP.get(parsed_url)\n #Parse the JSON response.\n response = JSON.parse(request)\n #Returns all listings for the given city.\n return response\n end", "def index\n #@queried_hotels = Hotel.page params[:page]\n @hotels = Hotel.all.order(created_at: :desc)\n @hotels = pagy_custom(@hotels)\n render json: @hotels, only: [:id, :name, :phone, :email, :user_id]\n end", "def get_city_list\r\n url = \r\n page = Nokogiri::HTML(URI.open('http://annuaire-des-mairies.com/val-d-oise.html'))\r\n citys = page.css('a.lientxt[href]').each {|city| @citys_list << city.text.downcase.gsub(' ', '-')}\r\nend", "def get_weather(city)\n #collects the weather conditions from the specefied location\n response = HTTP.get(\"http://api.openweathermap.org/data/2.5/weather?q=#{city},us&units=imperial&APPID=INSERT\")\n weather_data = response.parse\n return weather_data\nend", "def index\n @city_names = ClockCity.all.pluck(:name)\n @brand_names = ClockBrand.all.pluck(:name)\n @hotels = ClockHotel.where(id: (1..1000).to_a.sample(18)).select(:id,:name,:shop_time,:price,:room_hour).to_a\n @rand_hotels = BkCnHotel.where(\"id > ? and status = 2\", rand(1940)).limit(10).select(:url_path_md5, :hotel_name, :address, :images)\n end", "def get_list_cities\n City.get_all_cities\n end", "def index\n @items = Item.includes(:user, :category, :reviews)\n @cities = City.all\n @cat_param = params[:category]\n @items = @items.by_category(@cat_param) if @cat_param\n if params[:beg_date] && params[:end_date]\n @beg_date =params[:beg_date]\n @end_date = params[:end_date]\n else\n @beg_date = Time.new.to_date\n @end_date = 1.day.from_now.to_date\n end\n @items = @items.available(@beg_date, @end_date)\n @items = @items.by_user_id(params[:user_id]) if params[:user_id]\n @items = @items.search(params[:q]) if params[:q] && !params[:q].empty?\n\n @items = @items.page(params[:page]).per(10)\n end", "def index\n\t\t@hotels = Hotel.order(:name)\n\tend", "def show\n\n @client = Yelp::Client.new\n\n @request = Location.new(\n :term => @event.topPrefs,\n :zipcode => @event.zip,\n :limit => \"3\"\n #:category_filter => @yelp_search.category_filter,\n #:radius_filter => @yelp_search.radius_filter,\n )\n\n @response = @client.search(@request)\n @businesses = @response.to_h[\"businesses\"]\n end", "def extract_hotels(hotels_json)\n if hotels_json.is_a?(Array)\n hotels_json.map do |hotel|\n ExpediaApi::Entities::PackageHotel.new(hotel)\n end\n else\n [ExpediaApi::Entities::PackageHotel.new(hotels_json)]\n end\n end", "def show\n\n @user = User.find_by(params[:id])\n @weather = OpenWeatherApi.new(\"dae8d10e4ffe898434f2932fc31d48d2\").get_weather(current_user.checklists.last.destination)\n\n @description = @weather['weather'][0]['description']\n @icon = @weather['weather'][0]['icon']\n @temp = @weather['main']['temp']\n @humidity = @weather['main']['humidity']\n wind = @weather['wind']['speed']\n @wind = wind.round\n\n\n # @temp = @weather.get_weather('miami')['weather'][0]['description']\n @date = @user.checklists.last.date\n\n # @weather = OpenWeatherApi.new('dae8d10e4ffe898434f2932fc31d48d2').get_weather(@user.checklists.last.destination)['main']\n # Start of destination scrape\n destUrl = \"http://www.10best.com/destinations/all/\"\n\n destResponse = HTTParty.get(destUrl)\n # p response.headers['Content-Type']\n\n #String => Nokgiri::HTML => DocumentObjectModel (DOM)\n destDom = Nokogiri::HTML(destResponse.body)\n # p dom.css('html') #gives everything wthin the html tag\n\n destinations = destDom.css('a.rss')\n\n @cities = []\n destinations.each do |city|\n @cities << city.text\n end\n\n @links = []\n destinations.each do |link|\n @links << 'http://www.10best.com' + link['href']\n end\n # End of destination scrape\n\n @cityQuery = @cities.sample\n cat = \"Miami\"\n\n if @cities.include? @@citySearch\n @cityQuery = @@citySearch\n cat = @@cityCat\n @tryit = @@cityCat\n else\n @tryit = \"NOpe!\"\n end\n\n\n\n\n @citySelect = @cityQuery.split(\",\")[0]\n\n @cityIndex = @cities.index(@cityQuery)\n\n # Start of attractions scrape\n @attrUrl = @links[@cityIndex] + \"attractions/best-attractions-activities/\"\n attrResponse = HTTParty.get(@attrUrl)\n\n #String => Nokgiri::HTML => DocumentObjectModel (DOM)\n attrDom = Nokogiri::HTML(attrResponse.body)\n # p dom.css('html') #gives everything wthin the html tag\n\n attractions = attrDom.css('.list-headline h2')\n\n @venue = []\n attractions.each do |place|\n @venue << place.text\n end\n\n # Get two random attractions and give them their own variables\n @venues = @venue.sample(3)\n @venue_one = @venues[0]\n @venue_two = @venues[1]\n @venue_three = @venues[2]\n\n\n # Index of random photo to grab correct picture\n @index_one = @venue.index(@venue_one)\n @index_two = @venue.index(@venue_two)\n @index_three = @venue.index(@venue_three)\n\n\n images = attrDom.css('img.lazy')\n\n @image = []\n images.each do |picture|\n @image << 'https:' + picture['data-src']\n end\n\n # Select image link based on index of random photo\n @image_one = @image[@index_one]\n @image_two = @image[@index_two]\n @image_three = @image[@index_three]\n\n # End of attractions scrape\n\n # # Start of Flickr API\n FlickRaw.api_key=\"3d403357fbd5a290f43a9b6cd0216a4a\"\n FlickRaw.shared_secret=\"7ea1e588cac6c790\"\n\n args = {:tags => \"#{@citySelect} #{cat}\"}\n\n @flickrsearch = []\n\n discovered_pictures = flickr.photos.search args\n discovered_pictures.each{|p| url = FlickRaw.url p; @flickrsearch << url}\n\n # @flickrpics = @flickrsearch.map {|f| \"<img src='#{f}'>\"}\n\n # End of Flickraw API\n\n\n\n\n end", "def new_items_list\n @items = Item.where(:activated => true).sort{ |b,a| a.created_at <=> b.created_at } #TODO: Add availability\n @items = @items.first(16)\n #TODO: Once we have populated more data, maybe show 12 items instead of four\n @categories = Category.all\n @search = Item.search(params[:search])\n @keyword = params[:search]\n end", "def index\n @class_hotels = ClassHotel.all\n end", "def yahoo_weather_query(loc_ids, units)\n weather = []\n loc_ids.each do |l|\n h = {}\n open(\"http://xml.weather.yahoo.com/forecastrss?p=#{l}&u=#{units}\") do |http|\n response = http.read\n doc = REXML::Document.new(response)\n channel = doc.root.elements['channel']\n title = channel.elements['title'].text\n if title !~ /Error/ then\n location = channel.elements['yweather:location']\n h[:city] = location.attributes[\"city\"]\n h[:region] = location.attributes[\"region\"]\n h[:country] = location.attributes[\"country\"]\n h[:temp] = channel.elements[\"item\"].elements[\"yweather:condition\"].attributes[\"temp\"]\n weather << h\n end\n end\n end\n weather\nend", "def index\n @listings = Listing.search(params[:search], params[:city])\n end", "def index\n @hotels = Hotel.all\n end", "def restaurant\n if params[:hotel_id] != nil\n session[:hotel_id] = params[:hotel_id]\n end\n @package = GenPackage.find_by_id(session[:city_id])\n end", "def index\n @admin_itineraries= City.find(session[:current_city_id]).discover.itineraries.page(params[:page]).per(10)\n end", "def get_hotel_information(hotel_ids: [], request_parameters: {})\r\n default_parameters = {}\r\n default_parameters[:hotel_ids] = hotel_ids.join(\",\") if hotel_ids.any?\r\n http_service.request_post(\"/json/bookings.getHotels\", default_parameters.merge(request_parameters))\r\n end", "def show\n response = @api.get_list({:hotelId => @hotel_id, :destinationString => 'Media'})\n @hotel = response.body['HotelListResponse']['HotelList']['HotelSummary'][0]\n end", "def get_localities(query)\n p query_escaped = CGI::escape(query)\n @url = \"#{URLBASE}/feed/search.ashx?key=#{KEY}&q=#{query_escaped}&format=#{FORMAT}&num_of_days=2\"\n\n rawdata = ''\n open(@url).each do |line|\n rawdata << line\n end\n data = JSON.parse(rawdata)\n return data[\"search_api\"][\"result\"]\n \n# @city = data[0][\"areaName\"][0][\"value\"]\n# @country = data[0][\"country\"][0][\"value\"]\n# @latitude = data[0][\"latitude\"]\n# @longitude = data[0][\"longitude\"]\n# @population = data[0][\"population\"]\n# @weatherUrl = data[0][\"weatherUrl\"][0][\"value\"]\n end", "def get_recommended_venues\n uri = \"https://api.foursquare.com/v2/venues/explore?near=#{@location}&client_id=#{CLIENT_ID}&client_secret=#{CLIENT_SECRET}&v=#{Time.now.strftime(\"%Y%m%d\")}&categoryId=4d4b7105d754a06374d81259&limit=10\"\n encoded = URI.parse(URI.encode(uri)) # to handle spaces in the location\n @api_response = HTTParty.get(encoded)\n @api_response['response']['groups'][0][\"items\"].each do |item|\n @recommended_venues << item[\"venue\"]\n end\n @recommended_venues\n # puts encoded # uncomment to see the uri that is being used in the HTTP get request\n end", "def show\n set_meta_tags title: \"#{@place.name} en Waydda\",\n description: \"Visita la tienda en línea de #{@place.name} en Waydda\"\n @available_distance = @place.available_distance?(current_or_guest_user.get_ll)\n # @place.products.paginate(page: params[:page], per_page: 30)\n @items = @place.items.includes(:recent_products).paginate(page: params[:page], per_page: 30)\n @item_arrays = @items.select { |item| item.recent_products.length > 0 }\n # @products = @place.products.where(:items_recents.with_size => 0, status: \"active\")\n @products = []\n end", "def parse_city_month_url(agent,url,year,city,state,fast_forward=false)\n puts \"fetching #{url}...\"\n body,cached = fetch_url(agent,url,30)\n if cached and fast_forward\n puts \"... cached, fast-forwarding\"\n return\n end\n doc = Hpricot(body)\n tds = (doc/\"td.dayCellOtherMonth\")\n tds.each_with_index{|td,i|\n date_string = (td/\"div.date\").inner_html\n elems = date_string.split(\" - \")\n day = elems.first\n month = elems.last\n (td/\"a\").each{|a|\n\n # extract meat of listing\n body = a.inner_html\n title = a.attributes['title']\n href = a.attributes['href']\n\n # make sure this is a proper listing\n next unless href=~/TicketsList\\.aspx/\n\n # get url\n url = href\n \n # get time\n time_string = title.split(\" - \").first.strip\n datetime_string = \"#{month} #{day}, #{year} #{time_string}\"\n datetime = DateTime.parse(datetime_string)\n # get venue name\n venue_name = body.scan(/\\((.+?)\\)/).first.first\n\n # get artist name\n artist_name = body.scan(/(.+?)\\(/).first\n\n # get uid\n uid = \"ticketsnow_#{url.scan(/\\=(\\d+)$/)[0][0] rescue Digest::MD5.hexdigest(url)}\"\n # add venue\n venue = Venue.add_or_find(venue_name,city,state,\"ticketsnow\")\n url = \"#{url}&id=13119\"\n # add imported_event\n _ie,verb = add_imported_event(uid,datetime_string,venue,artist_name.to_s,url,'ticketsnow','primary')\n\n puts \"+++ #{verb} event #{_ie.body} on #{_ie.date.month}/#{_ie.date.day} at #{venue.name} (#{city}, #{state}).\" \n }\n }\n end", "def item_url(result)\n query = CGI.parse(env.url.query.to_s)\n url = \"#{env.url.scheme}://#{env.url.host}/officers/#{result['identifiers'][0]['identifier']}\"\n if query['api_token'].any?\n url += \"?api_token=#{CGI.escape(query['api_token'][0].to_s)}\"\n end\n url\n end", "def fetch\n VACUUM_QUERIES.collect { |query|\n Craigslist.city(:boulder).free.query(query).fetch\n }.flatten\n end", "def get_recommended_venues\n uri = \"https://api.foursquare.com/v2/venues/explore?near=#{@location}&client_id=#{CLIENT_ID}&client_secret=#{CLIENT_SECRET}&v=#{Time.now.strftime(\"%Y%m%d\")}&categoryId=4d4b7105d754a06374d81259\"\n encoded = URI.parse(URI.encode(uri)) # to handle spaces in the location\n @api_response = HTTParty.get(encoded)\n @api_response['response']['groups'][0][\"items\"].each do |item|\n @recommended_venues << item[\"venue\"][\"name\"]\n end\n # puts encoded # uncomment this to see the uri that is being used in the HTTP get request\n @recommended_venues\n end", "def extract_raw_hotels_from_json(json)\n if json[:HotelList] && json[:HotelList][:Hotel]\n json[:HotelList][:Hotel]\n else\n []\n end\n end", "def list_passengers(url)\n req = setup_http_request($dashboard, @cookie, {:url => url})\n res = @http.request(req)\n if res.code != '200'\n puts \"[?] Acces impossible a mes reservations\"\n return [\"erreur de la récupération des passagers\"]\n else\n body = CGI.unescapeHTML(res.body).force_encoding('utf-8')\n return body.scan(/<li class=\"Booking-occupant\">\\s*<img class=\"PhotoWrapper-user PhotoWrapper-user--smaller tip u-block u-rounded\" title=\"([^\"]*)\" alt=\"[^\"]*\"/).flatten\n end\n end", "def index\n\n @q = Hotel.ransack(params[:q])\n @hotels = @q.result(distinct: true)\n @hotel = Hotel.new\n end", "def list\n @history_params = params\n arrival_date_obj = Date.strptime(params[\"arrival_date\"], \"%m/%d/%Y\")\n departure_date_obj = Date.strptime(params[\"departure_date\"] , \"%m/%d/%Y\")\n @dates_of_stay = (departure_date_obj - arrival_date_obj).to_i\n \n @money_sign = MONEY_SIGN[(!params[\"currencyCode\"].blank?) ? params[\"currencyCode\"] : DEFAUL_CURRENCY]\n ## get nightly rates\n @rate_filters = [\n {:name => \"Any Rate\", :value => \"-1\", :selected => 'selected'},\n {:name => \"#{@money_sign}1 - #{@money_sign}100\", :value => \"1-100\", :selected => ''},\n {:name => \"#{@money_sign}100 - #{@money_sign}200\", :value => \"100-200\", :selected => ''},\n {:name => \"#{@money_sign}200 - #{@money_sign}300\", :value => \"200-300\", :selected => ''},\n {:name => \"#{@money_sign}300 - #{@money_sign}500\", :value => \"300-500\", :selected => ''},\n {:name => \"#{@money_sign}500 - #{@money_sign}1000\", :value => \"500-1000\", :selected => ''},\n {:name => \"#{@money_sign}1000+\", :value => \"1000-999999999\", :selected => ''}\n ]\n\n if params[:use_local] == 'true' ## Use local database for searching\n @hotels = HotelTest.find(\n :all,\n :conditions => [\"LOWER(Name) LIKE ?\", params[\"destination_string\"]],\n :limit => 70\n )\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @hotels }\n end ## End Use local database for searching\n\n else ## use EAN service\n params[:use_local] = 'false'\n ## search by EAN service\n if (params[\"item_category\"] == HotelService::ITEM_CATEGORY[:AIRPORT] || params[\"item_category\"] == HotelService::ITEM_CATEGORY[:LANDMARK])\n list_hotel_response = hotel_service.index(params)\n service_reponse = process_response(list_hotel_response, 'HotelListResponse')\n ## search by Hotels on local database\n elsif params[\"item_category\"] == HotelService::ITEM_CATEGORY[:HOTELS]\n id = params[\"item_id\"]\n render(:update) do |page| \n page.redirect_to hotel_path(id,params: params)\n end \n #redirect_to :controller => :hotels, :action => :show, :id => id, :params => params\n return\n else\n list_hotel_response = hotel_service.index(params)\n service_reponse = process_response(list_hotel_response, 'HotelListResponse')\n end\n if service_reponse\n if service_reponse[\"status\"] == OK\n response = JSON.parse(service_reponse[\"response\"])\n\n @cache_key = \"\";\n @cache_location = \"\";\n @is_more_results = response[\"HotelListResponse\"][\"moreResultsAvailable\"]\n @total_hotels = response[\"HotelListResponse\"][\"HotelList\"][\"activePropertyCount\"]\n @cache_key = response[\"HotelListResponse\"][\"cacheKey\"]\n @cache_location = response[\"HotelListResponse\"][\"cacheLocation\"]\n @hotels = response[\"HotelListResponse\"][\"HotelList\"]\n \n @temp =[]\n temp_not_room_rate = [] \n if [email protected]? && !@hotels[\"HotelSummary\"].nil?\n if @hotels[\"HotelSummary\"].instance_of?(Array)\n @hotels[\"HotelSummary\"].each {|x|\n if (!x[\"RoomRateDetailsList\"].nil? && !x[\"RoomRateDetailsList\"][\"RoomRateDetails\"].nil? && !x[\"RoomRateDetailsList\"][\"RoomRateDetails\"][\"RateInfo\"].nil? && !x[\"RoomRateDetailsList\"][\"RoomRateDetails\"][\"RateInfo\"][\"ChargeableRateInfo\"][\"@averageRate\"].nil?)\n @temp.push x\n else\n temp_not_room_rate.push x\n end\n }\n\n @hotels = @temp\n if params[\"sort\"] ==\"PRICE\"\n @hotels = @temp.sort_by {|hsh| hsh[\"RoomRateDetailsList\"][\"RoomRateDetails\"][\"RateInfo\"][\"ChargeableRateInfo\"][\"@averageRate\"].to_f}\n elsif params[\"sort\"] ==\"PRICE_REVERSE\"\n @hotels = @temp.sort_by {|hsh| hsh[\"RoomRateDetailsList\"][\"RoomRateDetails\"][\"RateInfo\"][\"ChargeableRateInfo\"][\"@averageRate\"].to_f}.reverse\n end\n temp_not_room_rate.each do |tnrr|\n @hotels << tnrr\n end\n else\n hotel_list = []\n hotel_list << @hotels[\"HotelSummary\"]\n hotel_list.each {|x|\n if (!x[\"RoomRateDetailsList\"].nil? && !x[\"RoomRateDetailsList\"][\"RoomRateDetails\"].nil? && !x[\"RoomRateDetailsList\"][\"RoomRateDetails\"][\"RateInfo\"].nil? && !x[\"RoomRateDetailsList\"][\"RoomRateDetails\"][\"RateInfo\"][\"ChargeableRateInfo\"][\"@averageRate\"].nil?)\n @temp.push x\n end\n }\n @hotels = @temp\n @is_more_results = false\n \n if params[\"sort\"] ==\"PRICE\"\n @hotels = @temp.sort_by {|hsh| hsh[\"RoomRateDetailsList\"][\"RoomRateDetails\"][\"RateInfo\"][\"ChargeableRateInfo\"][\"@averageRate\"].to_f}\n end\n end\n @rooms_information = params[:rooms_information]\n else\n ##TODO: handle exception with special cases here\n @hotels = []\n\n render :text => result(t('hotels.no_result'))\n return\n end\n\n\n\n ## get rooms information\n number_of_rooms = params[:search_room]\n number_of_adults = 0\n number_of_children = 0\n\n rooms = JSON.parse(params[\"rooms\"])\n\n rooms.each_with_index do |r, index|\n number_of_adults = number_of_adults + r[\"adults\"].to_i\n number_of_children = number_of_children + r[\"children\"].to_i\n end\n\n @rooms_information = {\n :number_of_rooms => number_of_rooms,\n :number_of_adults => number_of_adults,\n :number_of_children => number_of_children,\n :rooms => rooms\n }\n\n respond_to do |format|\n format.html { render :layout => false }\n format.xml { render :xml => @hotels }\n end\n else\n ##TODO: handle Errors here\n @error = service_reponse[\"error\"]\n if @error[\"error_code\"] == I18n.t('label.error_code.multiple_locations')\n possible_locations = []\n if @error[\"other_info\"]\n @error[\"other_info\"].each do |location|\n possible_location = location[\"city\"]\n country_code = location[\"countryCode\"]\n country = Carmen::Country.coded(country_code)\n if country && country.subregions?\n state = country.subregions.coded(location[\"stateProvinceCode\"])\n if state\n location[\"stateName\"] = state.name\n possible_location = possible_location + \", \" + location[\"stateName\"]\n else\n location[\"stateName\"] = ''\n end\n possible_location = possible_location + \", \" + location[\"countryName\"]\n possible_locations << possible_location\n end\n end\n end\n render :text => result(\"#{I18n.t('message.multiple_locations')} #{possible_locations.join('; ')}\")\n return\n else\n render :text => result(t('hotels.no_result'))\n return\n end\n end\n end\n end\n end", "def market_listings_for(item_url)\n render_url = item_url.sub(/\\/$/,'') + '/render/?query=&start=0&count=10'\n begin\n listings = JSON.parse(@c.get_content(render_url))\n rescue\n puts \"Error getting listing info\"\n return []\n end\n begin\n return listings[\"listinginfo\"].map(&:last).map do |listing|\n {\n id: listing[\"listingid\"],\n price: listing[\"converted_price\"] + listing[\"converted_fee\"],\n base_amount: listing[\"converted_price\"],\n fee_amount: listing[\"converted_fee\"],\n page_url: item_url\n }\n end\n rescue\n puts \"Converted price not there. try again\"\n return []\n end\n end", "def planets\n data = JSON.parse(open(\"http://swapi.co/api/planets\").read)\n @results = data[\"results\"]\n end", "def get_json(state, city)\n HTTParty.get(\"http://api.wunderground.com/api/b0938627f87459c4/conditions/q/#{state}/#{city}.json\").parsed_response\nend", "def index\n @admin_markets = City.find(session[:current_city_id]).around.markets.page(params[:page]).per(10)\n end", "def yelp\n \n if params.has_key?('reference')\n # Call Google Places to get phone number\n places_url = URI.encode('https://maps.googleapis.com/maps/api/place/details/json?reference=' + params['reference'] + '&sensor=true&key=AIzaSyDfvlLdmPj5jPMYy54KLcmkgvD68oFt5fM')\n places_response = HTTParty.get(places_url)['result']\n \n # puts '>>> google details response'\n # ap response\n \n phone_number = places_response['formatted_phone_number']\n phone_digits = places_response['international_phone_number'].delete(\"+ ()-\")\n \n categories = []\n neighborhoods = []\n \n api_host = 'api.yelp.com'\n ywsid = 'QyGURgxJPFWajTpsNPJeJg'\n \n yelp_url = \"http://#{api_host}\" + '/phone_search?phone=' + phone_digits + '&ywsid=' + ywsid\n \n # HTTParty hard the above path\n yelp_response = HTTParty.get(yelp_url, :format => :json)[\"businesses\"][0]\n \n # puts '>>>> yelp response'\n # ap yelp_response\n \n if yelp_response\n # puts '>>> categories'\n # ap yelp_response[\"categories\"]\n \n yelp_response[\"categories\"].each do |category|\n categories << category[\"name\"]\n end\n \n yelp_response[\"neighborhoods\"].each do |neighborhood|\n neighborhoods << neighborhood[\"name\"]\n end\n \n address = yelp_response[\"address1\"]\n \n results = Hash.new\n results[\"address\"] = address\n results[\"phone\"] = phone_number\n results[\"categories\"] = categories\n results[\"neighborhoods\"] = neighborhoods\n \n response = Hash.new\n response[:success] = true\n response[:results] = results\n else\n response = Hash.new\n response[:success] = false\n end\n \n render json: response\n end\n end", "def nearby\n nearby_cities = @city.nearbys((params[:within] || 15).to_i)\n return json_response([]) unless newest_city = nearby_cities.sort_by(&:updated_at).last\n Rails.logger.info \"newest_city is #{newest_city.inspect}\"\n render_if_stale(nearby_cities, last_modified: newest_city.updated_at.utc, etag: newest_city) do |city_presenters|\n city_presenters.map(&:hash)\n end\n # explicitly setting the Cache-Control response header to public and max-age, to make the response cachable by proxy caches\n expires_in caching_time, public: true\n end", "def index\n if (params[:city_id])\n @city = City.find(params[:city_id].to_i)\n @oxygen_suppliers = @city.oxygen_suppliers.active_list\n else\n @oxygen_suppliers = OxygenSupplier.active_list\n end\n end", "def get_townhall_urls(url)\n page = Nokogiri::HTML(open(url))\n cities_url = page.xpath('//a[@class=\"lientxt\"]').to_a\n links = (cities_url.map {|url| url[\"href\"][1..-1]}).to_a\n #puts links\n return links\nend", "def index\n if params['hotel_ids'].present? && params['destination_ids'].present?\n @hotels = Hotel.where(hotel_id: params['hotel_ids'])\n @hotels = @hotels.or(Hotel.where(destination_id: params['destination_ids']))\n elsif params['hotel_ids'].present?\n @hotels = Hotel.where(hotel_id: params['hotel_ids'])\n elsif params['destination_ids'].present?\n @hotels = Hotel.where(destination_id: params['destination_ids'])\n else\n @hotels = Hotel.all\n end\n render json: @hotels\n end", "def index\n @guest_hotels = GuestHotel.all\n end", "def get_urls( search_url )\n urls = []\n result_json = parse_json( search_url )\n result_json['items'].each do |item|\n urls << item['url']\n end\n\n return urls\nend", "def get_character_movies_from_api(character)\n film_urls = get_film_urls(character)\n film_urls.collect do |movie_url|\n look_up(movie_url)\n end\nend", "def weather_hourly(city, state)\n request = \"http://api.wunderground.com/api/747e267558954ba9/hourly/q/#{state}/#{city}.json\"\n hourly = HTTParty.get(request)\n hourly[\"hourly_forecast\"].each do |hour| \n puts \"#{hour[\"FCTTIME\"][\"civil\"]}: #{hour[\"temp\"][\"english\"]}F\"\n end\nend", "def city_scraper\n #Id,Id2,Geography,Target Geo Id,Target Geo Id2,Geographical Area,Geographical Area,,,Total area,Water area,Land area,Population,Housing units\n #0400000US01,01,Alabama,1600000US0107000,0107000,\"Alabama - PLACE - Birmingham city, Alabama\",\"Birmingham city, Alabama\",242820,111927,151.95,2.04,149.92,1619.7,746.6\n # 0 1 2 3 4 5 6 7 8 9 10 11 12 13 \n @states = Array.new\n @cities = Array.new\n \n count = 0\n state_name = \"\"\n CSV.foreach(\"data/DEC_10_SF1_GCTPH1.ST13.csv\") do |row|\n count = count + 1\n city_name = \"\"\n population = 0\n elevation = 0\n lat_dir = \"\"\n lat_deg = 0\n lat_min = 0\n lat_sec = 0\n lon_dir = \"\"\n lon_deg = 0\n lon_min = 0\n lon_sec = 0\n if(row[2] == row[5])\n #its a state\n puts \"State: #{row[2]}\"\n state_name = row[2]\n state = State.new(:name => row[2])\n if(@states.length == 51)\n break\n end\n @states << state\n next\n end\n \n geographical_area = CSV.parse(row[6])\n city_name = geographical_area[0][0]\n if(city_name.match(/(part)/))\n #puts \"skipping #{city_name}\"\n next\n end\n \n city_name = city_name.downcase.gsub(/ city/,'').gsub(/ town/,'').gsub(/ village/,'').gsub(/ cdp/,'').gsub(/ borough/,'').gsub(/ municipality/,'').gsub(/ and/,'')\n city_name.strip.capitalize!\n city_name = city_name.capitalize\n #puts \"#{city_name} #{count}\"\n \n city_name_uri = URI.escape(city_name, Regexp.new(\"[^#{URI::PATTERN::UNRESERVED}]\"))\n state_name_uri = URI.escape(state_name, Regexp.new(\"[^#{URI::PATTERN::UNRESERVED}]\"))\n city_html = Net::HTTP.get(URI.parse(\"http://www.geonames.org/search.html?q=#{city_name_uri}%2C+#{state_name_uri}&country=US\"))\n #puts \"http://www.geonames.org/search.html?q=#{city_name}%2C+#{state_name}&country=US\"\n @city_doc = Hpricot(city_html)\n \n @city_doc.search(\"//table[@class='restable']\") do |table|\n tr_count = 0\n table.search(\"//tr\") do |tr|\n #puts \"in tr search\"\n tr_count = tr_count + 1\n if(tr_count < 3)\n next\n end\n #puts \"in tr search 2\"\n td_count = 0\n tr.search(\"//td\") do |td|\n #puts \"in td search\"\n td_count = td_count + 1\n if(td_count < 4)\n next\n end\n if(td_count == 4)\n td.search(\"//small\") do |small|\n #population = \"#{small.match(/\\\\d+/)[1]}\"\n #puts \"!!!!!!!!!!!!!!!!!!\"\n #puts td_count\n #puts \"#{small.inner_html}\"\n #puts \"!!!!!!!!!!!!!!!!!!\"\n pop_elev = small.inner_html\n #population = \"#{pop_elev.match(/\\d+,\\d*/)}\".gsub(/,/,'')\n elevation = \"#{pop_elev.match(/\\d+m/)}\".gsub(/m/,'')\n #puts population\n #puts elevation\n end\n end\n if(td_count == 5)\n lat_dir = td.inner_html[0]\n matches = td.inner_html.scan(/(\\d+)/)\n lat_deg = matches[0][0]\n lat_min = matches[1][0]\n lat_sec = matches[2][0]\n end\n if(td_count == 6)\n lon_dir = td.inner_html[0]\n matches = td.inner_html.scan(/(\\d+)/)\n lon_deg = matches[0][0]\n lon_min = matches[1][0]\n lon_sec = matches[2][0]\n end\n end\n break\n \n end \n end\n city = City.new(\n :name => city_name,\n :states_id => @states.length,\n :total_area => row[9],\n :water_area => row[10],\n :land_area => row[11],\n :population => row[7],\n :population_density => row[12],\n :lat_deg => lat_deg,\n :lat_min => lat_min,\n :lat_sec => lat_sec,\n :lat_dir => lat_dir,\n :lon_deg => lon_deg, \n :lon_min => lon_min,\n :lon_sec => lon_sec,\n :lon_dir => lon_dir,\n :elevation => elevation)\n \n @cities << city\n if(count % 10 == 0)\n puts count\n end\n end\n \n @states.each do |state|\n state.save\n end\n \n @cities.each do |state|\n state.save\n end\n \n end", "def get_feature_collection(params)\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::Post.new('/api/search.json')\n request.add_field('Content-Type', 'application/json')\n request.add_field('Accept', 'application/json')\n request.body = JSON.generate(params)\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 return {}\n end\n\n return JSON.parse(response.body, symbolize_names: true)\n end", "def get_movie_characters_from_api(movie)\nmovie_hash = make_search('http://www.swapi.co/api/films/')\ncharacters_array = []\n movie_hash[\"results\"].each do |item|\n if item[\"title\"].downcase == movie\n item[\"characters\"].each do |character| #urls \n character_info_hash = make_search(character)\n characters_array << character_info_hash\n end \n end\n end \n #characters_array #all the info on films an array of hashes\n parse_movie_character(characters_array)\nend", "def index\n if params[:search]\n @pet_hotels = PetHotel.search(params[:search]).order(\"created_at DESC\")\n else\n @pet_hotels = PetHotel.all.order('created_at DESC')\n end \n end", "def index\n @urlitems = Urlitem.all\n end", "def hotel_location\n service_data = hotel_service.get_location(params[:hotelId].to_i)\n result = false\n status = 'nok'\n\n if service_data[:hotel]\n #convert the JSON data to hash\n success_response = process_response(service_data[:list_hotel_response], \"LocationInfoResponse\")\n \n result = {\n :hotel => service_data[:hotel],\n :places => JSON.parse(success_response['response'])['LocationInfoResponse']['LocationInfos']['LocationInfo']\n }\n status = success_response['status']\n end\n respond_to do |format|\n format.json {render :json => {:data => result, :status => status}}\n end\n end", "def index\n @admin_city_hall_stories = City.find(session[:current_city_id]).commonplace.city_hall_story\n end", "def city_events(city)\n response = RestClient.get('https://app.ticketmaster.com/discovery/v2/events.json?city=' + city + '&apikey=' + $ticket_master_api_key)\n jason_response = JSON.parse(response)\nend", "def afficeur\n @city_link.map do |element|\n villes = get_city_names(element)\n email = get_townhall_email(element)\n @result = []\n @result << {villes => email}\n end\n end", "def regional_sitelist\n query('txt/wxfcs/regionalforecast/json/sitelist')\n end", "def perform\n url = build_request_url\n req = open(url).read\n response_body = JSON.parse(req)\n build_museum_objects_from_response(response_body['features'])\n end", "def city_openings(start, ending)\n open_listing = []\n self.listings.each do |listing|\n if listing.available?(start, ending)\n open_listing << listing\n end\n end\n open_listing\n end", "def get_by_freeword\n\t\tkey_word = params[:key_word]\n\t\tnext_start = params[:next_start]\n\t\tshops = Hotpepper.search_keyword(key_word, 15, next_start)\n\t\t@results_available = shops.attributes['results_available']\n\t\t@results_start = shops.attributes['results_start']\n\t\t@results_returned = shops.attributes['results_returned']\n\t\t@next_start = get_next_start\n\n\t\t@shops = shops.attributes['shop']\n\t\t@key_word = key_word \t\n end", "def guest_list\n extract_data = ExtractData.new(@data_file)\n locations = extract_data.load_file\n customers = FindCustomers.new(locations, @radius, @home_latitude, @home_longitude).search\n if customers.empty?\n puts \"\\n No guests found.\"\n else\n puts \"\\nGuest list\\n\"\n puts \"==========\\n\"\n customers.each {|customer|p \"#{customer[\"user_id\"]} -- #{customer[\"name\"]}\"}\n end\n nil\n rescue => e\n puts \"There was an error retrieving the guest list. \\n\"\n puts \"ERROR: #{e.message}\"\n puts \"\\n #{e.backtrace}\"\n end", "def list\n # list possible locations \n\n @location_suggest = get_location_suggest\n\n if params[:location]\n locations = WoeidHelper.search_by_name params[:location]\n if not locations.nil? and locations.count == 1\n set_location locations[0]\n else\n @location_asked = locations\n end\n end\n end", "def initial_parse\n # page = 291\n # term = \"restaurant\"\n # restaurant max pages\n # max_pages=351\n # term = \"dance\"\n # page = 123\n # max_pages=201\n # while page <= max_pages do\n # puts \"CURRENT PAGE #{page}\"\n restaurant_data = RestClient.get(\"https://developers.zomato.com/api/v2.1/search?entity_id=#{@api_city}&entity_type=city&start=1\", {user_key: @apikey})\n parsed_restaurant_data = JSON.parse(restaurant_data)['restaurants']\n # puts parsed_restaurant_data\n more_detailed_search(parsed_restaurant_data)\n # page+=1\n # end\nend", "def fetch_listing\n districts = district_name_and_permalink_hash \n district_permalink = districts.fetch(district.name) { \n raise \"Whoa, cannot fetch listing,-- #{district.name} -- not a park or general listing of resorts.\" \n }\n\n # Technical: Class (self) instead of an instance variable is used to access HTTParty params\n @listing = TouringPlansComFeed.get(district_permalink).parsed_response\n end", "def get_restaurants(location)\n latitude, longitude = convert_location(location)\n\n food_query = Addressable::URI.new(\n :scheme => \"https\",\n :host => \"maps.googleapis.com\",\n :path => \"/maps/api/place/nearbysearch/json\",\n :query_values => {:location => \"#{latitude},#{longitude}\",\n :radius => \"#{get_distance}\",\n :types => \"food\",\n :key => \"#{KEY}\",\n :sensor => \"false\",\n :keyword => \"#{get_food_kind}\"}\n )\n food_query_json = RestClient.get(food_query.to_s)\n JSON.parse(food_query_json)[\"results\"]\n end", "def yahoo_loc_search(loc)\n return [loc] if loc =~ /\\d/ #places usually don't have numbers in their names\n locs = []\n open(\"http://weather.yahoo.com/search/weather2?p=#{URI.escape(loc)}\") do |http|\n return [$1] if http.base_uri.to_s =~ LOC_MATCH\n http.each {|line| locs << $1 if line =~ LOC_MATCH }\n end\n locs\nend", "def fetch_trips(origin_city)\r\n return if origin_city.nil?\r\n\r\n airport_type = AIRPORT_TYPE_MEDIUM_KEY\r\n\r\n case\r\n when origin_city.downcase == 'helsinki'\r\n # Helsinki-Vantaa on ainoa poikkeus!\r\n airport_type = AIRPORT_TYPE_LARGE_KEY\r\n end\r\n\r\n # Suomesta tapahtuvien lähtöjen lentokentät ovat pääsääntöisesti medium-luokkaa.\r\n journey_airports = AIRPORTS.find({MUNICIPALITY_KEY => origin_city.capitalize, AIRPORT_TYPE_KEY => airport_type})\r\n unless journey_airports.nil?\r\n journey_airports.each do |airport|\r\n\r\n fetch_origin_country(airport)\r\n\r\n @trips = TRIPS.find({AIRPORT_ORIGIN_CITY => airport[MUNICIPALITY_KEY]})\r\n end\r\n end\r\n\r\n #@wikipedia_link = COUNTRIES.find(\r\n\r\nend", "def index\n items = Item.all\n if params[:filter]\n params[:by_title].strip!\n items = items.book_interval(container_time[:start_booking], container_time[:end_booking])\n .filter(params.slice(%i[by_title by_city by_category]))\n end\n items = items.where.not(user: current_user)\n render json: items\n end", "def index\n @popular_locations = PopularLocation.all\n @top_locations = PopularLocation.get_top\n end", "def index_all\n if params[:filter]\n params[:by_title].strip!\n items = Item.book_interval(container_time[:start_booking], container_time[:end_booking])\n .filter(params.slice(%i[by_title by_city by_category]))\n render json: items\n else\n items = Item.all\n render json: items\n end\n end", "def list\n user = current_user\n if !params[:distance].nil? and params[:distance].to_i > 0\n distance = params[:distance].to_i\n else\n distance = 10000\n end\n if !params[:latitude].blank? \n latitude = params[:latitude].to_f\n else\n latitude = user.latitude\n end\n if !params[:longitude].blank? \n longitude = params[:longitude].to_f\n else\n longitude = user.longitude\n end\n\n if !params[:latitude].blank? and !params[:longitude].blank? \n user.latitude = latitude\n user.longitude = longitude\n user.save\n end\n\n if !params[:without_featured_venues].blank? \n without_featured_venues = params[:without_featured_venues]=='1'\n else\n without_featured_venues = false\n end\n\n # venues = Venue.all\n venues = Venue.near_venues(latitude, longitude, distance, without_featured_venues)\n\n page_number = nil\n venues_per_page = nil\n page_number = params[:page].to_i + 1 if !params[:page].blank?\n venues_per_page = params[:per_page].to_i if !params[:per_page].blank?\n\n if !page_number.nil? and !venues_per_page.nil? and venues_per_page > 0 and page_number >= 0\n pagination = Hash.new\n pagination['page'] = page_number - 1\n pagination['per_page'] = venues_per_page\n pagination['total_count'] = venues.length\n venues = Kaminari.paginate_array(venues).page(page_number).per(venues_per_page) if !venues.nil?\n end\n\n data = Venue.venues_object(current_user, venues)\n \n render json: success((JSON.parse data), 'data', pagination)\n end", "def get_vacancies( urls )\n vacancies = []\n urls.each do |url|\n vacancies << parse_json( url )\n end\n\n return vacancies\nend", "def get_nearby_food_pictures\n if params[:lat] and params[:lng]\n @restaurants = Restaurant.all\n # @buildings = Building.find( :all, :conditions => [ 'name LIKE ?', '%' + params[:q].downcase + '%'], :limit =&gt; 20)\n \n end\n\n render :json => @restaurants\n end", "def index\n set_meta_tags title: \"#{@place.is_restaurant? ? \"Categorías\" : \"Departamentos\"} | #{@place.name}\",\n description: \"#{@place.is_restaurant? ? \"Categorías\" : \"Departamentos\"} | #{@place.name}\"\n @items = @place.items.includes(:recent_products).select { |item| item.recent_products.length > 0 }\n end", "def hotel_details(id)\n results = []\n if((results = $redis.get(id)).nil?)\n details = get_hotel_details(id)\n $redis.set(id,details.to_json)\n return details.to_json\n else\n return results\n end\n end", "def show\n \n @new_city = @destination.city\n @new_city_array = @new_city.split(\" \")\n @new_city = @new_city_array.join('_')\n \n @abbr_state = State.find_by name: @destination.state\n \n @weather_lookup = WeatherLookup.new(@abbr_state.statecode, @new_city)\n \n # @states = %w(HI AK CA OR WA ID UT NV AZ NM CO WY MT ND SD NB KS OK TX LA AR MO IA MN WI IL IN MI OH KY TN MS AL GA FL SC NC VA WV DE MD PA NY NJ CT RI MA VT NH ME DC )\n \n # @states.sort!\n \n # if params[:city] != nil\n # params[:city].gsub! \" \", \"_\"\n # end\n \n # if params[:city] != nil\n # response = HTTParty.get(\"http://api.wunderground.com/api/4600419770d3f8f8/geolookup/conditions/q/#{params[:state]}-#{params[:city]}.json\")\n # else \n # redirect_to root_path\n # end\n \n # @location = response['location'][:city]\n # @temp_f = response['current_observation']['temp_f']\n # @temp_c = response['current_observation']['temp_c']\n # @weather_icon = response['current_observation']['icon_url']\n # @weather_words = response['current_observation']['weather'] \n # @forecast_link = response['current_observation']['forecast_url']\n # @real_feel = response['current_observation']['feelslike_f']\n end", "def index\n @offers = Offer.search_offers(params[:keyword],\n params[:pick_up_point], params[:drop_off_point],\n params[:vancancy_lower_limit], params[:vancancy_upper_limit],\n params[:cost_lower_limit], params[:cost_upper_limit])\n end", "def results\n raw_input = params[:search].to_s\n formatted_input = raw_input.gsub(\" \", \"+\")\n\n @client = HTTParty.get(\"http://api.shopstyle.com/api/v2/products?pid=uid5001-30368749-95&fts='#{formatted_input}'&offset=0&limit=20\")\n\n render json: @client\n end", "def show\n \n return_value = (HotelService.new).get_hotel_detail(params)\n @currencies = return_value[:currencies]\n @hotel_link = return_value[:otel_link]\n @destination_string = return_value[:destination_string]\n @rooms_info = return_value[:rooms_info]\n @history_params = return_value[:history_params]\n @currencies = return_value[:currencies]\n @money_sign = return_value[:money_sign]\n @hotel_info = return_value[:hotel_info]\n @hotel_details = return_value[:hotel_details]\n @hotel_amenities = return_value[:hotel_amenities]\n @room_types = return_value[:room_types]\n @hotel_images_info = return_value[:hotel_images_info]\n @dates_of_stay = return_value[:dates_of_stay]\n @rooms = return_value[:rooms]\n @book_info = return_value[:book_info]\n @hotel_address = return_value[:hotel_address]\n @error = return_value[:error] \n @latitude = return_value[:latitude]\n @longitude = return_value[:longitude]\n \n if !@error\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @hotel }\n end\n else\n ##TODO: handle Errors here\n respond_to do |format|\n format.html { render :template => \"shared/hotel_detail_error\"}\n format.json { render :json => @error }\n end\n end\n end", "def city_openings(start_date, end_date)\n Listing.find_openings(listings, Date.parse(start_date), Date.parse(end_date))\n end", "def filter_by_city\n @restaurants = @restaurants.where(city: params[:city])\n end", "def ShowHomeDetails(streetAddress, citystatezip)\n #Key to access Zillow API\n zwsID = 'X1-ZWz1dn6tpoopvv_18y6r'\n #uri = \"http://www.zillow.com/webservice/GetSearchResults.htm?#{'zws-id=X1-ZWz1dmvv3i5qtn_3fm17&address=2114+Bigelow+Ave&citystatezip=Seattle%2C+WA'}\"\n uri = \"http://www.zillow.com/webservice/GetDeepSearchResults.htm?#{'zws-id=' + zwsID + '&address=' + streetAddress + '&citystatezip=' + citystatezip}\"\n #@uri = uri\n rest_resource = RestClient::Resource.new(uri, '', '')\n users = rest_resource.get\n users= users.gsub('SearchResults:searchresults','SearchResults')\n users= users.gsub('xsi:schemaLocation','schemaLocation')\n xmldoc = Document.new(users)\n root = xmldoc.root\n longitude=\"\"\n latitude=\"\"\n xmldoc.elements.each('SearchResults/response/results/result/taxAssessmentYear') do |long|\n @taxAssessmentYear = long.text\n end\n xmldoc.elements.each('SearchResults/response/results/result/taxAssessment') do |long|\n @taxAssessment = number_to_currency(long.text, :unit => \"$\")\n end\n xmldoc.elements.each('SearchResults/response/results/result/yearBuilt') do |long|\n @yearBuilt = long.text\n end\n xmldoc.elements.each('SearchResults/response/results/result/lotSizeSqFt') do |long|\n @lotSizeSqFt = number_with_delimiter(long.text)\n end\n xmldoc.elements.each('SearchResults/response/results/result/finishedSqFt') do |long|\n @finishedSqFt = number_with_delimiter(long.text)\n end\n xmldoc.elements.each('SearchResults/response/results/result/bathrooms') do |long|\n @bathrooms = long.text\n end\n xmldoc.elements.each('SearchResults/response/results/result/bedrooms') do |long|\n @bedrooms = long.text\n end\n xmldoc.elements.each('SearchResults/response/results/result/lastSoldDate') do |long|\n @lastSoldDate = long.text\n end\n xmldoc.elements.each('SearchResults/response/results/result/lastSoldPrice') do |long|\n @lastSoldPrice = number_to_currency(long.text, :unit => \"$\")\n end\n end", "def explore\n @center = Geocoder.coordinates(params[:city])\n @trips = Trip.nearest_with_index(@center) \n end", "def index\n json_response(current_restaurant.restaurant_food_items)\n end" ]
[ "0.7186517", "0.6746002", "0.6483955", "0.6184442", "0.6137089", "0.6105003", "0.6084849", "0.605834", "0.60118616", "0.59888697", "0.5953563", "0.59356654", "0.5895931", "0.5889715", "0.587097", "0.58280563", "0.58265257", "0.58216214", "0.5820304", "0.5662635", "0.56516993", "0.5637597", "0.5636429", "0.5633696", "0.56260604", "0.56120557", "0.5611957", "0.560913", "0.56062347", "0.55856615", "0.55594134", "0.5549402", "0.5548376", "0.55452025", "0.5542127", "0.5540267", "0.55364347", "0.55186343", "0.5512256", "0.5500325", "0.5490345", "0.54898226", "0.5485407", "0.54784393", "0.5473418", "0.545463", "0.54510766", "0.5442948", "0.5437099", "0.5428334", "0.54225844", "0.5421535", "0.5420801", "0.54136556", "0.5410754", "0.5402084", "0.5401897", "0.539647", "0.53876317", "0.53850245", "0.5383965", "0.5381593", "0.5370376", "0.5363807", "0.53434056", "0.53422034", "0.5336834", "0.5336182", "0.533481", "0.5321201", "0.53177243", "0.53169215", "0.53117496", "0.5309808", "0.53068703", "0.5306583", "0.5295196", "0.5285477", "0.52800435", "0.52672434", "0.5265056", "0.5263813", "0.525848", "0.52576447", "0.5256345", "0.52504253", "0.52435285", "0.52427125", "0.5242492", "0.52423644", "0.524133", "0.5237252", "0.52306366", "0.52293175", "0.5226058", "0.52057993", "0.520328", "0.51993775", "0.51956296", "0.51943547" ]
0.7102496
1
=begin The method returns the details of the object identified by the id passed in the url. =end
def show details = hotel_details(params[:id]) render_with_protection details end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def retrieve(id)\n instance = self.new(id)\n url = instance.url\n requestor = Requestor.new\n response = requestor.request(:get, url)\n instance.load_from(response)\n instance\n end", "def id\n self.url\n end", "def get_info(id)\n url = \"http://www.omdbapi.com/?i=#{id}&y=&plot=short&r=json\"\n return_result(url)\n end", "def getObject(id)\n\t\tdoc.search(\"[@id='#{id}']\").first\n\tend", "def url\n \"/#{self.class.rest_name}s/#{id}\"\n end", "def id\n @id || @url\n end", "def get_by_id(id)\n if @data == nil\n url = make_url(:fq => \"id:#{id}\")\n\n begin\n @data = Net::HTTP.get(URI.parse(url))\n rescue Exception => e\n @error = \"Unable to connect to #{url}\"\n end\n end\n \n return @data\n end", "def url_id\n id\n end", "def show\n\t\t@url = UrlGenerator.find_by(encoded_url:params[:id])\n\t\tif @url.nil?\n\t\t\trender json:{error:\"not found\"}\n\t\telse\n\t\t\trender json:{orginal_url:@url.url}\n\t\tend\n\tend", "def details\n @details ||= Tmdb::Collection.detail(@id)\n return @details\n end", "def retrieve\n self.class.get( id )\n end", "def show\n @url = Url.find(params[:id])\n \n respond_to do |format|\n format.html\n end\n end", "def getDetails id\n\t\tticket = @tickets.read ['id', 'pid', 'title', 'description', 'tracker', 'creator', 'created', 'status'], ['id', id]\n\t\tticket = ticket[0]\n\tend", "def show\n\n\t\t@url_data_model = UrlDataModel.find(params[:id])\n\t\t\n\tend", "def get_details(id)\n if((results = $redis.get(id)).nil?)\n details = get_details_item(id)\n $redis.set(id,details.to_json)\n return details.to_json\n else\n return results\n end\n end", "def get_details\n return self if detailed?\n res = client.get(path_base).to_h\n update(res)\n res\n end", "def show(params = {})\n validate_id(params)\n submit(id_url(params.delete(:id)), :get)\n end", "def find_one(id)\n response = request(:get, \"/#{resource_name}/#{id}\")\n #puts response\n construct_record_from_singular(response)\n end", "def details\n @details ||= fetch_details\n end", "def details\n @details ||= Tmdb::TV.detail(@id)\n return @details\n end", "def details_by_type_and_id(type, id)\n get(resource_path_for_entity_type(type) + \"/#{id}\")\n end", "def object_result(url, criteria)\n begin\n archivesspace.get_record(url, criteria)\n rescue RecordNotFound\n {}\n end\n end", "def get_details(resource, id, **params)\n ops_hash = {\n id: id\n }\n ops_hash.merge! params\n resp = _make_request(resource, ops_hash)\n ComicVine::Resource.create_resource(resp['results'])\n end", "def view_detail\n @object = params[:class_name].constantize.find(params[:id])\n set_object_data\n end", "def id\n object[\"id\"]\n end", "def details\n @details ||= Tmdb::Movie.detail(@id)\n return @details\n end", "def find(id)\n end", "def show\n @url = Url.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @url }\n end\n end", "def show\n @url = @oi.urls.new\n end", "def load(id)\n @details.load id\n render!\n end", "def show\n hash = params[:id]\n if hash.nil?\n redirect_to '/'\n else\n id = Base32::Crockford.decode(hash.upcase)\n begin \n @link = Link.find(id)\n @link.count = @link.count + 1\n impressionattributes = Hash.new\n \n impression = Impression.new;\n impression.attributes.each_key { |key|\n impressionattributes[key] = request.env[key.upcase]\n }\n \n impression.attributes = impressionattributes\n @link.impressions << impression\n @link.save\n redirect_to @link.url\n rescue ActiveRecord::RecordNotFound => ex\n logger.error \"Error!\" << ex.message\n found = false\n flash[:error] = 'Sorry! We don\\'t know about that URL'\n redirect_to '/'\n end\n end\n \n \n end", "def show\n @course = Course.load params[:id] # load object from TISS REST API\n end", "def show\n @entry = Ruote::Sylrplm::HistoryEntry.find(params[:id])\n unless params[:obj_id].nil? || params[:obj_type].nil?\n @object = PlmServices.get_object(params[:obj_type], params[:obj_id])\n end\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @entry }\n end\n end", "def detail(params={})\n self.request(__method__, params)\n end", "def lookup(id)\n\t\t@objects[id]\n\tend", "def info(id)\n http.get(\"/nfse/#{id}\") do |response|\n respond_with_entity(response)\n end\n end", "def get(id, params={})\n response = Shippo.request(:get, \"#{url}/#{CGI.escape(id)}/\", params)\n self.construct_from(response)\n end", "def find_object\n url = get_object_url()\n\n response = self.send_request('HEAD', url)\n\n case response.code\n when '404'\n return\n when '200'\n response = self.send_request('GET', url)\n @obj = JSON.parse(response.body)['_source']\n else\n fail(\"Fail to retrieve object '%s' (HTTP response: %s/%s)\" %\n [url, response.code, response.body])\n end\n end", "def name\n \"#{id}: #{url}\"\n end", "def get(id)\n server.get(\"#{name}/#{CGI.escape(id)}\")\n end", "def getObjectFromUrl(url,type=nil)\n method = 'getObjectFromUrl'\n type = BaseObj if not type\n args = {:url=>url}\n return_object type,method,args,true\n end", "def find(id); end", "def find(id); end", "def fetch_object(object_id)\n catalog_api = SquareConnect::CatalogApi.new\n catalog_api.retrieve_catalog_object(object_id).object\n end", "def object(object_id, opts = {})\n response = fetch_object(Array(object_id).join(':'), opts)\n response.body\n end", "def details\n\n end", "def id\n @obj['id']\n end", "def fetch(id)\n search(id: id)[:records].first\n end", "def full_details\n data = self.class\n .data_keys\n .map { |k| [k, send(\"#{k}\")] }\n .to_h\n { id: id,\n url: url }.merge(data)\n end", "def show(id)\n GistObject.new(get(format(SHOW, id)))\n end", "def get(id)\n Basuco::Resource.get(id)\n end", "def showJSON\n\n\t\trender json: UrlDataModel.find(params[:id])\n\n\tend", "def scrape_detail\n self.doc = Scrapable::Helpers.parse detail_url\n self.class.attributes.each do |attribute,id|\n if id['anchor'] # substring\n self[attribute] = doc.at_css('#' + id).andand[:href]\n else\n self[attribute] = doc.at_css('#' + id).andand.text.andand.sub(/\\A[[:space:]]+\\z/, '')\n end\n end\n end", "def show\n url = Url.find(params[:id].to_i)\n @stats = {\n shortened_url: \"#{request.base_url}/#{url.shortened_url}\",\n original_url: url.original_url,\n usage_count: url.count,\n created_at: url.created_at,\n most_recent_use: url.updated_at\n }\n end", "def show\n @short_url = ShortUrl.find(params[:id])\n end", "def details\n data.details\n end", "def url(id)\n entry(id).url(@user)\n rescue exception_block\n end", "def show\n @page = Page.find(params[:page_id])\n # @url = Url.find(params[:id]) # set_url\n end", "def url(id)\n entry(id).url(@user)\n end", "def get_details\n theSelection = \"sel=Number\" \n @MAP.each do |k, v|\n theSelection << \",\" << v\n end \n \n uri=\"#{$V1HOST['base_uri']}/rest-1.v1/Data/Defect?#{theSelection}&where=Number\"\n details = self.class.get(\"#{uri}=\\'#{@story}\\'\", :verify => false)\n return details\n end", "def retrieve_with_details(repo_id)\n retrieve(repo_id, :details => true)\n end", "def show\n respond_with DisDoseformDoseunitLink.find(params[:id])\n end", "def get_by_id(id)\n self.class.get(\"/aldebaran-instances/instances/#{id}\", :basic_auth => @auth)\n end", "def edit\n \n @decode=hashing_decode(params[:id])\n @shortened_url = Url.find(@decode)\n \n respond_to do |format|\n format.json { render json: @shortened_url}\n end\n end", "def show\n @remoteobject = Remoteobject.find(params[:id])\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @remoteobject }\n end\n end", "def show_details(id_to_show_details_from_db)\n @db.query(\"SELECT * FROM products WHERE id = '#{id_to_show_details_from_db}'\", :symbolize_keys => true).first\n end", "def find(id)\n @objects[id]\n end", "def find(id)\n @api.get(\"api/#{id.to_s}.json\")\n end", "def find id\n model.find id\n end", "def get(model, id=nil, opts = {})\n name = model_name(model)\n opts.symbolize_keys!\n data = do_restful_action(\"get\", name) do\n self.nagyo[\"#{name}/#{URI.encode(id.to_s)}\"].get({:format => :json, :accept => :json}.merge(opts))\n end\n if id\n # NOTE: if we have an ID and get a Hash - single record matched, \n # otherwise no match and might have returned first page of records\n return data if data.is_a?(Hash)\n else\n return data\n end\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 get\n object\n end", "def inspect\n \"#<#{self.class}:#{object_id.to_s(16)} #{uri.inspect}>\"\n end", "def retrieve(id)\n @client.make_request(:get, \"parcels/#{id}\", MODEL_CLASS)\n end", "def get\n url = prefix + \"get\" + id_param\n return response(url)\n end", "def checkin_details(id)\n options = { :id => id }\n get('/details', options)\n end", "def get_object(type, id)\n raise ArgumentError.new(\"type needs to be one of 'node', 'way', and 'relation'\") unless type =~ /^(node|way|relation)$/\n raise TypeError.new('id needs to be a positive integer') unless(id.kind_of?(Fixnum) && id > 0)\n response = get(\"#{type}/#{id}\")\n check_response_codes(response)\n parser = OSM::StreamParser.new(:string => response.body, :callbacks => OSM::ObjectListCallbacks.new)\n list = parser.parse\n raise APITooManyObjects if list.size > 1\n list[0]\n end", "def get_person(id)\n self.class.get(url(\"people/#{id}\"), headers: @token.headers).parsed_response\n end", "def show\n\t\t#params[:id] is the number in the url we are looking for\n\t\t#@story = Story.find(params[:id])\n\tend", "def set_url\n # @url = Url.find(params[:id])\n end", "def details\n #permalink = params[:id]+\".html\"\n @photoset = Photoset.find_by_permalink(params[:id])\n @photos = Photo.find(:all,:conditions => [\"photoset_id LIKE ?\",@photoset.id])\n end", "def show url\n function = ''\n \n params = {}\n params[:url] = url\n\n request(@resource, function, params)\n end", "def detail \n\t\t@listing = Listing.find(params[:id]) \n\t\t@image = Image.new #should this link somewhere else?\n\n\t\trespond_to do |format| \n\t\t\tformat.html # show.html.erb \n\t\t\tformat.xml { render :xml => @listing } \n\t\tend \n\tend", "def get(id:)\n response = client.get(path(id)).parsed_body\n new(response)\n end", "def details\n end", "def show\n @content_url = ContentUrl.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @content_url }\n end\n end", "def item_detail_url(id)\n \"#{@baseurl}/agdocs.aspx?doctype=agenda&itemid=#{id}\"\n end", "def id\n object.to_param\n end", "def details(id, params = {})\n wrike.execute(:get, api_url(\"comments/#{id}\"), params)\n end", "def url\n @url\n end", "def get_url_name(id)\n Url.find(id).url\n end", "def get(id)\n return nil if id.nil?\n\n return objects[id] if objects.has_key?(id)\n\n type, content = get_object(id)\n\n klass = TYPE_CLASS[type] or raise NotImplementedError, \"type not supported: #{type}\"\n\n objects[id] = klass.new(self, id, content)\n end", "def load_purl\n @purl = PurlResource.find(params[:id])\n end", "def load_purl\n @purl = PurlResource.find(params[:id])\n end", "def show\n\n @long = params[:id].to_i(36)\n\n if Url.exists?(@long)\n\n @url = Url.find(@long).url\n\n redirect_to @url\n\n else\n redirect_to root_path\n end\n\n end", "def person(id)\n get(\"/catalog/people/#{id.to_s}\")\n end", "def show\n @object = Interest.find(params[:id])\n end", "def show\n @url = ShortenedUrl.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @url }\n end\n end", "def show\n @url = @digital_object_identifier.urls.build\n @comment = @digital_object_identifier.comments.build #(params[:comment].merge(:user_id => current_user.id))\n end", "def show\n require 'open-uri' #for screen scraping\n \n @album = Album.find(params[:id])\n @artists = @album.artists\n @sources = @album.sources\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @album }\n end\n \n #adding in automation functionality\n # if @album.catalognumber.blank? == true \n # url = @album.reference\n # if url.split('/')[2] == \"vgmdb.net\"\n # doc = Nokogiri::HTML(open(url))\n # @catalognum = doc.xpath(\"//table[@id='album_infobit_large']//tr[1]//td[2]\").text\n # @album.catalognumber = @catalognum.split(' ')[0]\n # @album.save\n # end\n # end\n\n end", "def show\n @ptid = Ptid.find(params[:id])\n @title = Ptid.find(params[:id]).ptid + \" Details\"\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @ptid }\n end\n end" ]
[ "0.7056304", "0.70362073", "0.69295615", "0.668905", "0.6654831", "0.66308546", "0.66008276", "0.65544236", "0.64788526", "0.64471495", "0.64265245", "0.6424871", "0.64235514", "0.63908786", "0.6351275", "0.6345247", "0.6254293", "0.6239257", "0.6238694", "0.6236622", "0.62290144", "0.62183136", "0.6215642", "0.619515", "0.61863536", "0.6177818", "0.6170705", "0.6155394", "0.61246186", "0.6120722", "0.61036676", "0.6102228", "0.609924", "0.60930616", "0.6082562", "0.60799897", "0.60733914", "0.6068294", "0.60570234", "0.6052352", "0.6035904", "0.6011867", "0.6011867", "0.6010533", "0.59856653", "0.59823036", "0.59807384", "0.5979277", "0.59778965", "0.59730715", "0.5971851", "0.59715784", "0.596976", "0.596676", "0.5957169", "0.59528244", "0.5950676", "0.5939909", "0.5935163", "0.59225166", "0.59215224", "0.59214586", "0.59108657", "0.5908229", "0.5907652", "0.5904738", "0.5902711", "0.5899487", "0.5892817", "0.5889227", "0.58892035", "0.58887935", "0.5883244", "0.58822316", "0.5876573", "0.5868731", "0.58681315", "0.5861636", "0.5861059", "0.58595353", "0.58491975", "0.5847669", "0.58374137", "0.58364815", "0.58342594", "0.58333945", "0.5830519", "0.58218515", "0.582134", "0.5819369", "0.5813427", "0.58132756", "0.5812564", "0.5812564", "0.5812302", "0.581221", "0.58117044", "0.5811078", "0.5809407", "0.5804851", "0.58011526" ]
0.0
-1
This action is called from the redbox in the offer forms. It responds only to POST and xhr.
def create_for_offer @customer = @current_account.customers.build(params[:customer]) @customer.build_address(params[:address]) if @customer.save # Create dummy objects to be able to rebuild the customer selector. @offer = @current_account.offers.build @offer.customer = @customer end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def POST; end", "def post; end", "def xhr?; end", "def submit\n\t\tset_post_data\n get_response @url\n parse_response\n\tend", "def post_data; end", "def perform(request, options); end", "def post\r\n end", "def perform(request, response); end", "def post_request\n\t\turl = request.fullpath.gsub(\"/api\", \"\")\n\t\t@rr = Rr.where(\"url = ?\", url).first\n\t\trespond_to do |format|\n\t\t\tformat.json { render :json => rr.response}\n\t\t\tformat.xml { render :xml => @rr.response}\n\t\t\tformat.js { render :js => @rr.response}\n\t\tend\n\tend", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def do_request\n\t\t\tself.response = post_request(options)\n\t\tend", "def send_request; end", "def post_request(object)\n end", "def post\n end", "def process\n send_request @action\n end", "def new\n render :json => { }, :status => 405\n end", "def xhr_script; end", "def xhr_post *args, params_or_action\n Presto::Browser.new(@controller, env, 'POST', true).body *args, params_or_action\n end", "def http_send url, form_data, headers, &block\n if form_data['action'] == 'query'\n log.debug(\"GET: #{form_data.inspect}, #{@cookies.inspect}\")\n headers[:params] = form_data\n RestClient.get url, headers, &block\n else\n log.debug(\"POST: #{form_data.inspect}, #{@cookies.inspect}\")\n RestClient.post url, form_data, headers, &block\n end\n end", "def post!\n request! :post\n end", "def http_callback\n # sleep 4\n if @params[\"status\"] == \"error\"\n @answer_backend = {\"submit_error_message\"=> Localization::Request[:no_network]}\n WebView.navigate url_for :action => :request, :query => @answer_backend\n end\n @answer_backend = Rho::JSON.parse(@params[\"body\"])\n WebView.navigate url_for :action => :process_submit_result, :query => @answer_backend\n end", "def response; end", "def response; end", "def response; end", "def response; end", "def response; end", "def response; end", "def response; end", "def response; end", "def response; end", "def response; end", "def response; end", "def response; end", "def response; end", "def send_sale_offer_form\n code = send_email(params[:id])\n message = code == '$err' ? t(:send_error) : t(:send_ok)\n @json_data = { \"code\" => code, \"message\" => message }\n render json: @json_data\n end", "def post(target, data, &block)\n xhr = XMLHttpRequest.new()\n xhr.open('POST', \"actions/#{target}\", true)\n xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8')\n xhr.responseType = 'text'\n\n def xhr.onreadystatechange()\n if xhr.readyState == 4\n data = nil\n\n begin\n if xhr.status == 200\n data = JSON.parse(xhr.responseText)\n elsif xhr.status == 404\n alert \"Not Found: actions/#{target}\"\n elsif xhr.status >= 400\n console.log(xhr.responseText)\n alert \"Exception\\n#{JSON.parse(xhr.responseText).exception}\"\n end\n rescue => e\n console.log(e)\n end\n\n block(data)\n end\n end\n\n xhr.send(JSON.stringify(data))\nend", "def request_data; end", "def post\n Rentlinx.client.post(self)\n end", "def http_send_action\n http = http_inst\n req = http_post\n Response.new http.request req\n end", "def post\n resource.post(request, response)\n end", "def set_request; end", "def post(options)\n options.assert_valid_keys :url, :form, :params, :eval_response\n options.default! :form => nil, :params => {}, :eval_response => false\n\n if Eschaton.current_view.protect_against_forgery?\n options[:url][:authenticity_token] = Eschaton.current_view.form_authenticity_token\n end\n\n form_fields = if options[:form]\n \"jQuery('##{options[:form]}').serialize()\"\n else\n options[:params].to_js\n end\n\n url = Eschaton.url_for_javascript(options[:url])\n self << \"jQuery.post(#{url}, #{form_fields}, function(data) {\"\n\n yield :data if block_given?\n\n self.eval(:data) if options[:eval_response]\n \n self << \"});\" \n end", "def submit; end", "def post(action, **args); end", "def perform!\n options_key = request_method == :get ? :query : :form\n resp = self.class.public_send(request_method, uri.to_s,{ options_key => options })\n Response.new(api_key, resp.code, resp.body, resp.parsed_response,\n resp.headers).validate!\n end", "def submit\n # validate_line_items\n Wheretocard::Response.from_order_request(self)\n end", "def check_carrier \n\n @check_carrier = RestClient.post \"http://api.ezsms.biz/vK2FIDJSrp4Tt5gBuLhdRZXsqf7NUezi/hlrdb/query/\", { :mobilenumber => params[:mobilenumber], :password => params[:password]}, :content_type => 'application/json'\n\n respond_to do |format|\n format.html { render :html => @check_carrier }\n format.text { render :text => @check_carrier }\n format.json { render :json => @check_carrier }\n end\n end", "def edit\n respond_with(reagent)\n end", "def post\n request_object.post_query\n end", "def process_offer\n respond_to do |format|\n format.json {\n param = params[:payload]\n @project_application = ProjectApplication.find_by_id(param[:application])\n\n if @project_application\n if @current_user.administrator\n @project_application.administrator_approved = param[:approved]\n elsif @current_user.professor\n @project_application.professor_approved = param[:approved]\n else\n @project_application.student_approved = param[:approved]\n end\n\n if @project_application.save\n render :json => @project_application\n else\n render :nothing => true, :status => 200, :content_type => 'text/html'\n end\n else\n render :nothing => true, :status => 200, :content_type => 'text/html'\n end\n }\n end\n end", "def request_result\n \n end", "def offers \n @host.offers.create(offer_params) if request.post?\n @offers = @host.offers\n end", "def bindPostToExpirance\r\n errors ||= Array.new\r\n if params[:id].blank? ||params[:id].is_int\r\n errors.push(I18n.t(\"errors.messages.element_not_id\"))\r\n end\r\n if params[:ue_id].blank? ||params[:ue_id].is_int\r\n errors.push(I18n.t(\"errors.messages.element_not_id\"))\r\n end\r\n if params[:feeling_id].blank? ||params[:feeling_id].is_int\r\n errors.push(I18n.t(\"errors.messages.element_not_id\"))\r\n end\r\n if errors.length == 0 \r\n self.default_response\r\n else\r\n render :json => Api::Init.ShowErrorJson(API_CODE_ERRORS['Services']['Global']['formInputError'],I18n.t(\"errors.messages.feelike.input_error\"), errors).to_json\r\n end\r\n end", "def request_method; end", "def post_and_run(options)\n options[:eval_response] = true\n\n self.post options\n end", "def raw_post; end", "def onSubmit(request, response, form, errors) \r\n return form\r\n end", "def onSubmit(request, response, form, errors) \r\n return form\r\n end", "def onSubmit(request, response, form, errors) \r\n return form\r\n end", "def onSubmit(request, response, form, errors) \r\n return form\r\n end", "def onSubmit(request, response, form, errors)\r\n return form\r\n end", "def onSubmit(request, response, form, errors)\r\n return form\r\n end", "def post_form_to_external?\n true\n end", "def ajax\n\n uri_string = @params[:uri]\n # uri_string = \"http://www.phase-eight.com#{path_string}\"\n uri = construct_uri_object uri_string\n response = network_response uri\n logger.debug \"XHR response type #{response.content_type}\"\n logger.debug \"XHR response body #{response.body.html_safe}\"\n render text: response.body\n end", "def post(request)\n # sure thing!\n json_response(200, { message: \"This dummy POST endpoint didn't do anything.\" })\n end", "def submit\n end", "def manager_forward_hold\n @req_ids = params[:req_id]\n\t\t@status = params[:r_status]\n\t @resume = params[:resume] \n\t\t@res_id = @resume.to_s\n\t\trespond_to do |format|\n\t\t format.js\n\t\tend\n\tend", "def action; end", "def action; end", "def action; end", "def action; end", "def action; end", "def send_action(method_name, *args)\n #call the action, and store return value\n rval = self.send(method_name, *args)\n\n unless response_body\n #set the view variable with the return value\n name = self.class.instance_variable_get(:@view_var_name)\n name = name.pluralize if name && method_name.to_s == \"index\" #pluralize the @view_var_name if it was set at the class and this is GET/index\n name ||= \"data\"\n self.instance_variable_set :\"@#{name}\", rval\n\n #always follow responder pattern passing in the action's return value unless already rendered\n respond_with rval, (@respond_opts || {})\n end\n end", "def post(request, response)\n NotImplemented\n end", "def post(request, response)\n NotImplemented\n end", "def accept\n @assignment.active_offer.accepted!\n render_success @assignment.active_offer\n end", "def onSubmit(request, response, form, errors)\r\n\treturn form\r\n end", "def update\n @request.accept\n redirect_to posts_url\n end", "def _eval_post\n _eval_action('post')\n end", "def remote!\n @remote_form = true\n end", "def handle_non_xhr\n file_upload = params['X-Requested-With'] == 'IFrame'\n export = params[:view_request] && request.put? && !request.xhr?\n export ||= params[:export_data_id] || request.post?\n skip = params[:xhr] == 'true'\n unless export || request.xhr? || file_upload || skip\n if request.path != root_path\n path = current_user ? corrected_path : root_path\n redirect_to root_url, flash: { initial_path: path }\n else\n render 'blank', layout: 'application'\n end\n end\n if skip\n headers['Content-Type'] = 'text/plain'\n end\n end", "def blocklisted_response; end", "def GET; end", "def new\n @accepted_offer = AcceptedOffer.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @accepted_offer }\n end\n end", "def onSubmit(request, response, form, errors) \n return form\n end", "def run\n super\n\n # first, ensure we're fingerprinted\n require_enrichment\n\n uri = _get_entity_name\n\n headers = {}\n headers[\"Content-Type\"] = \"%{#context['com.opensymphony.xwork2.dispatcher.HttpServletResponse'].addHeader('X-Intrigue-Struts',888*888)}.multipart/form-data\"\n response = http_request(:get, uri, nil, headers) # no auth\n\n unless response\n _log_error \"No response received\"\n return\n end\n\n # show the response in the logs \n response.headers.each {|x| _log \"#{x}: #{response.headers[x]}\"}\n \n if response.headers['X-Intrigue-Struts'] =~ /788544/\n \n instance_details = { \n proof: \"#{response.headers['X-Intrigue-Struts']}\",\n }\n _create_linked_issue \"apache_struts_jakarta_parser\", instance_details\n end\n end", "def new\n @smartgraph_range_question = Embeddable::Smartgraph::RangeQuestion.new\n if request.xhr?\n render :partial => 'remote_form', :locals => { :smartgraph_range_question => @smartgraph_range_question }\n else\n respond_to do |format|\n format.html # renders new.html.haml\n format.xml { render :xml => @smartgraph_range_question }\n end\n end\n end", "def new\n @ms_offer = MsOffer.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @ms_offer }\n end\n end", "def submit\n if @vote.nil?\n if @answer.nil?\n flash[:notice] = t(\".no_answer_selected\")\n else\n @vote = ::Refinery::Polls::Vote.vote_by_ip(@answer, request.remote_ip)\n end\n end\n respond_to do |format|\n format.js\n format.html\n end\n end", "def submits; end", "def sharerequests\n @group = Group.find(session[:group_id])\n @membership = Membership.find_by(user_id: session[:user_id], group_id: session[:group_id])\n @requests = Request.where(item_id: Item.where(owner_id: @membership)).order('requesting_at DESC')\n authorize @requests, :index?\n respond_to do |format|\n format.js\n format.html\n end\n end" ]
[ "0.6717174", "0.6370963", "0.63504535", "0.63321084", "0.6293219", "0.6177772", "0.6172585", "0.61117923", "0.60632414", "0.60466045", "0.60466045", "0.60466045", "0.60466045", "0.60466045", "0.60466045", "0.60466045", "0.60466045", "0.60466045", "0.60466045", "0.60466045", "0.5994053", "0.5988755", "0.5909748", "0.5856312", "0.5848935", "0.58134556", "0.58040005", "0.5797535", "0.57916695", "0.57884496", "0.57619727", "0.57537955", "0.57537955", "0.57537955", "0.57537955", "0.57537955", "0.57537955", "0.57537955", "0.57537955", "0.57537955", "0.57537955", "0.57537955", "0.57537955", "0.57537955", "0.5736403", "0.56628066", "0.566043", "0.5645589", "0.5643377", "0.5615956", "0.56057966", "0.5602935", "0.5587213", "0.55864894", "0.5583996", "0.5577815", "0.5558249", "0.55568826", "0.5553487", "0.5540696", "0.5517978", "0.5503486", "0.54981947", "0.547695", "0.54769236", "0.5460002", "0.5451004", "0.5451004", "0.5451004", "0.5451004", "0.54453164", "0.54453164", "0.5441315", "0.54361063", "0.54269296", "0.5426305", "0.5426095", "0.5425054", "0.5425054", "0.5425054", "0.5425054", "0.5425054", "0.54229426", "0.54117787", "0.54117787", "0.54102933", "0.54076284", "0.54006356", "0.53773004", "0.5375574", "0.5364468", "0.53543276", "0.53431576", "0.5341455", "0.5340344", "0.53279126", "0.5327558", "0.53233606", "0.5323277", "0.5320475", "0.531766" ]
0.0
-1
Configuration changes to be done. Nothing needed here either.
def configure(root_config) super(root_config) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def configure\n end", "def configuration; end", "def configuration; end", "def configuration; end", "def configuration; end", "def configuration; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def config; end", "def configure; end", "def configurations; end", "def sync_configuration\n end", "def config=(config); end", "def config\n\n end", "def configure\n # do nothing\n end", "def configure(update); end", "def setup_config\n # To be Extended\n end", "def configure\n load_all_configs \n end", "def after_configuration\n # do nothing by default\n end", "def configure(conf)\n super\n end", "def post_configure\n # noop\n end", "def set_config(config)\n\t\tend", "def before_configuration_tasks \n end", "def auto_configuration_state\n super\n end", "def confine\n @confined = true\n end", "def config_store; end", "def settings; end", "def settings; end", "def prepare_for_configuration \n # clear_base_directory\n make_base_directory\n copy_misc_templates\n copy_custom_monitors\n store_keys_in_file\n Script.save!(self)\n # not my favorite...\n copy_ssh_key\n before_configuration_tasks\n end", "def _init_configuration\n\t\t# Set defaults\n\t\t@setup = { \"create\" => false, \"environment\" => false, \"test\" => true, \"destroy\" => false }\n\t\t@config = false\n\tend", "def configure\n\n # config file default options\n configuration = {\n :options => {\n :verbose => false,\n :coloring => 'AUTO'\n },\n :mount => {\n :source => {\n :name => nil\n },\n :mountpoint => {\n :name => nil\n },\n :passphrasefile => {\n :name => 'passphrase'\n },\n :keyfile => {\n :name => 'encfs6.xml'\n },\n :cmd => nil,\n :executable => nil\n },\n :unmount => {\n :mountpoint => {\n :name => nil\n },\n :cmd => nil,\n :executable => nil\n },\n :copy => {\n :source => {\n :name => nil\n },\n :destination => {\n :name => nil\n },\n :cmd => nil,\n :executable => nil\n }\n }\n\n # set default config if not given on command line\n config = @options[:config]\n unless config\n config = [\n File.join(@working_dir, \"revenc.conf\"),\n File.join(@working_dir, \".revenc.conf\"),\n File.join(@working_dir, \"config\", \"revenc.conf\"),\n File.expand_path(File.join(\"~\", \".revenc.conf\"))\n ].detect { |filename| File.exists?(filename) }\n end\n\n if config && File.exists?(config)\n # rewrite options full path for config for later use\n @options[:config] = config\n\n # load options from the config file, overwriting hard-coded defaults\n config_contents = YAML::load(File.open(config))\n configuration.merge!(config_contents.symbolize_keys!) if config_contents && config_contents.is_a?(Hash)\n else\n # user specified a config file?, no error if user did not specify config file\n raise \"config file not found\" if @options[:config]\n end\n\n # the command line options override options read from the config file\n @options = configuration[:options].merge!(@options)\n @options.symbolize_keys!\n\n # mount, unmount and copy configuration hashes\n @options[:mount] = configuration[:mount].recursively_symbolize_keys! if configuration[:mount]\n @options[:unmount] = configuration[:unmount].recursively_symbolize_keys! if configuration[:unmount]\n @options[:copy] = configuration[:copy].recursively_symbolize_keys! if configuration[:copy]\n end", "def configure\n load_configuration\n verify_configuration\n end", "def configure(&block); end", "def configure(&block); end", "def configure_connection\n end", "def config=(_arg0); end", "def config=(_arg0); end", "def config=(_arg0); end", "def config=(_arg0); end", "def config=(_arg0); end", "def configure(root_config)\n\n end", "def initialize\n set_config\n end", "def set_config\n redirect\n end", "def configure_organization\n configure_information\n configure_colors\n configure_logo\n configure_email\n configure_phone\n configure_faq\n configure_form\n configure_admin\n output_config_for_locale(\"en\")\n output_config_for_locale(\"es\")\n success_box(\"Your app is now configured!\")\nend", "def get_config\n\t\tend", "def configure\n\t\t\tyield configuration\n\t\tend", "def process_configuration\n self.configuration = YAML::load(File.read('.codecom.yml'))\n end", "def load_config()\n self.config = Kitchenplan::Config.new().config\n end", "def configure(root_config)\n end", "def configure(root_config)\n end", "def load_config\n\t\t# load conifg\n\t\tend", "def config\r\n\t\t\t\"<p>No additional configuration is available</p>\"\r\n\t\tend", "def configure(opts)\n #This is a stub, used for indexing\n end", "def update_all_config\n @admin.updateConfiguration\n end", "def execute\n report_invalid_config_items\n begin\n AppConfig[:logger].info('Configuration Editor')\n\n # get the list of config fields\n fields = AppConfig.navigation.collect do |page|\n page.values.flatten.select do|field|\n AppConfig.data_type[field]\n end\n end.flatten.uniq.compact\n\n # edit the fields\n while(field = menu_select('field', fields))\n begin\n edit_field(field)\n rescue\n end\n end\n\n # save changes?\n if agree(\"Save? yes/no\") {|q| q.default = 'yes'}\n AppConfig.save\n end\n rescue\n end\n end", "def link_auto_configuration_state\n super\n end", "def configure!\n conf = YAML::load_file(@config)\n conf.merge!({\n \"initial_token\" => 0,\n \"partitioner\" => \"org.apache.cassandra.dht.RandomPartitioner\",\n # have to force ascii or YAML will come out as binary\n \"data_file_directories\" => [@data.encode(\"us-ascii\")],\n \"commitlog_directory\" => @commit.encode(\"us-ascii\"),\n \"saved_caches_directory\" => @caches.encode(\"us-ascii\"),\n \"storage_port\" => @storage_port.to_i,\n \"ssl_storage_port\" => @ssl_storage_port.to_i,\n \"listen_address\" => @host.encode(\"us-ascii\"),\n \"rpc_address\" => @host.encode(\"us-ascii\"),\n \"rpc_port\" => @rpc_port.to_i,\n # DSE doesn't work OOTB as a single node unless you switch to simplesnitch\n \"endpoint_snitch\" => \"org.apache.cassandra.locator.SimpleSnitch\",\n })\n File.open(@config, \"w\") { |file| file.puts YAML::dump(conf) }\n\n # relocate the JMX port to avoid conflicts with running instances\n env = File.read(@envfile)\n env.sub!(/JMX_PORT=['\"]?\\d+['\"]?/, \"JMX_PORT=\\\"#{@jmx_port}\\\"\")\n File.open(@envfile, \"w\") { |file| file.puts env }\n\n # relocate the system.log\n log = File.read(@log4j)\n log.sub!(/log4j.appender.R.File=.*$/, \"log4j.appender.R.File=#{@logfile}\")\n File.open(@log4j, \"w\") do |file| file.puts log end\n end", "def configure_connection\n end", "def configuration\n @config ||= setup\n end", "def cop_config; end", "def configure\n send_command \"--configure\"\n end", "def reconfig\n KEYS_AND_QUESTIONS.each do |key, question|\n ask_question_and_force_update_config(question, key)\n end\n config_update_success\n end", "def setup()\n @configuration = {}\n @configuration.merge!(defaults)\n @configuration\n end", "def setting; end", "def sync_configuration!\n load_configuration_if_needed! and save\n save_configuration_if_needed!\n end", "def configuring what\n puts \"Configuring: #{what}...\"\n end", "def configure_backdat\n @commands = parse_options\n\n begin\n ::File.open(config[:config_file]) { |f| apply_config(f.path) }\n rescue Errno::ENOENT => error\n msg = \"Did not find the config file: #{config[:config_file]}\"\n msg << \", Using command line options.\"\n Backdat::Log.warn \"*****************************************\"\n Backdat::Log.warn msg\n Backdat::Log.warn \"*****************************************\"\n end\n end", "def configure\n\t\t\tyield self\n\t\tend", "def configure\n\t\t\tyield self\n\t\tend", "def default_configuration=(_arg0); end", "def configure_manager\n end", "def config\n self\n end", "def configure_and_run(params = [])\n config_file = Configuration::DEFAULT_CONFIG_FILE_NAME\n tmp_config = Configuration.new\n action_wizard = false\n\n parser = OptionParser.new do |opts|\n opts.banner = if ENV['OCRA_EXECUTABLE']\n \"Usage: #{ENV['OCRA_EXECUTABLE'].gsub(\"#{Dir.pwd}/\".gsub('/', '\\\\'), '')} [options]\"\n else\n \"Usage: #{Gem.ruby} #{$PROGRAM_NAME} [options]\"\n end\n\n opts.on('-c', '--config CONFIG_FILE_NAME', 'Specify custom configuration file,'\\\n \" instead of #{Configuration::DEFAULT_CONFIG_FILE_NAME}.\") do |file_name|\n config_file = file_name\n end\n\n opts.on('-r', '--register FILE', 'Register a custom plugin, e.g. your own Datasource implementation') do |plugin|\n require plugin\n end\n\n opts.on('-d', '--debug LEVEL', 'Specify detail level: FATAL, ERROR, WARN, INFO, DEBUG.') do |level|\n tmp_config.set_param('grafana-reporter:debug-level', level)\n end\n\n opts.on('-o', '--output FILE', 'Output filename if only a single file is rendered') do |file|\n tmp_config.set_param('to_file', file)\n end\n\n opts.on('-s', '--set VARIABLE,VALUE', Array, 'Set a variable value, which will be passed to the '\\\n 'rendering') do |list|\n raise ParameterValueError, list.length unless list.length == 2\n\n tmp_config.set_param(\"default-document-attributes:#{list[0]}\", list[1])\n end\n\n opts.on('--ssl-cert FILE', 'Manually specify a SSL cert file for HTTPS connection to grafana. Only '\\\n 'needed if not working properly otherwise.') do |file|\n if File.file?(file)\n tmp_config.set_param('grafana-reporter:ssl-cert', file)\n else\n config.logger.warn(\"SSL certificate file #{file} does not exist. Setting will be ignored.\")\n end\n end\n\n opts.on('--test GRAFANA_INSTANCE', 'test current configuration against given GRAFANA_INSTANCE') do |instance|\n tmp_config.set_param('grafana-reporter:run-mode', 'test')\n tmp_config.set_param('grafana-reporter:test-instance', instance)\n end\n\n opts.on('-t', '--template TEMPLATE', 'Render a single ASCIIDOC template to PDF and exit') do |template|\n tmp_config.set_param('grafana-reporter:run-mode', 'single-render')\n tmp_config.set_param('default-document-attributes:var-template', template)\n end\n\n opts.on('-w', '--wizard', 'Configuration wizard to prepare environment for the reporter.') do\n action_wizard = true\n end\n\n opts.on('-v', '--version', 'Version information') do\n puts GRAFANA_REPORTER_VERSION.join('.')\n return -1\n end\n\n opts.on('-h', '--help', 'Show this message') do\n puts opts\n return -1\n end\n end\n\n begin\n parser.parse!(params)\n return ConsoleConfigurationWizard.new.start_wizard(config_file, tmp_config) if action_wizard\n rescue ApplicationError => e\n puts e.message\n return -1\n end\n\n # abort if config file does not exist\n unless File.file?(config_file)\n puts \"Config file '#{config_file}' does not exist. Consider calling the configuration wizard\"\\\n ' with option \\'-w\\' or use \\'-h\\' to see help message. Aborting.'\n return -1\n end\n\n # merge command line configuration with read config file\n @config.load_config_from_file(config_file)\n @config.merge!(tmp_config)\n\n run\n end", "def configure\n self.configuration ||= AllscriptsApi::Configuration.new\n yield(configuration)\n end", "def set_config(*args); end", "def set_config(*args); end", "def set_config(*args); end", "def set_config(*args); end", "def set_config(*args); end", "def configure_with(params)\r\n\r\n\t\tend", "def config\n configuration\n end", "def configure!(options={})\n self.local_config = options\n end", "def config=(value); end", "def config\n @config ||= {}\n end", "def config\n @config ||= {}\n end" ]
[ "0.76876414", "0.76450205", "0.76450205", "0.76450205", "0.76450205", "0.76450205", "0.7620882", "0.7620882", "0.7620882", "0.7620882", "0.7620882", "0.7620882", "0.7620882", "0.7620882", "0.7620882", "0.7620882", "0.7620882", "0.7620882", "0.7620882", "0.7620882", "0.7620882", "0.7620882", "0.7620882", "0.7620882", "0.7584787", "0.7548429", "0.74134415", "0.7391961", "0.72981966", "0.7195777", "0.7031033", "0.69996446", "0.68596864", "0.6779604", "0.6751152", "0.6751032", "0.6683008", "0.6596582", "0.65855557", "0.6576852", "0.6572669", "0.655423", "0.655423", "0.65498656", "0.65419394", "0.65336734", "0.65330994", "0.6530402", "0.6530402", "0.6523188", "0.6485378", "0.6485378", "0.6485378", "0.6485378", "0.6485378", "0.647692", "0.6476041", "0.64619607", "0.645261", "0.6446314", "0.6445404", "0.6415568", "0.64153475", "0.64140135", "0.64140135", "0.64013535", "0.6396133", "0.63875633", "0.63863254", "0.63704723", "0.63472295", "0.63408625", "0.63348633", "0.6330104", "0.63263434", "0.6318583", "0.63138044", "0.630153", "0.6299962", "0.6283792", "0.62706983", "0.6265741", "0.6238486", "0.6238486", "0.62306577", "0.6219555", "0.621942", "0.6209466", "0.62016433", "0.6195981", "0.6195981", "0.6195981", "0.6195981", "0.6195981", "0.6185854", "0.61857176", "0.6182383", "0.61779237", "0.61567897", "0.61567897" ]
0.61693287
98
Nothing needs to be done on cleanup.
def cleanup super end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def cleanup; end", "def cleanup; end", "def cleanup; end", "def cleanup; end", "def cleanup!; end", "def cleanup!; end", "def cleanup\r\n end", "def cleanup!\n # This method may be left unimplemented if that is applicable\n end", "def cleanup\n end", "def cleanup\n end", "def cleanup\n end", "def cleanup\n end", "def cleanup\n end", "def cleanup\n end", "def cleanup\n end", "def cleanup\n end", "def cleanup\n end", "def cleanup\n\tend", "def cleanup\n\tend", "def cleanup\n true\n end", "def cleanup\n # override and do something appropriate\n end", "def cleanup_hook; end", "def cleanup\n super\n end", "def cleanup\n true\nend", "def finalized; end", "def finalize!; end", "def cleanup_handler\n end", "def teardown; end", "def teardown; end", "def on_cleanup(unit); end", "def finalize\n nil\n end", "def finalize\n end", "def cleanup_called\n @cleanup_called\n end", "def finalize\n end", "def finalize\n end", "def finalize\n end", "def finalize\n end", "def finalize\n end", "def finalize\n end", "def finalize\n end", "def teardown\r\n end", "def tear_down; end", "def finalise\n end", "def finalize\n\n end", "def cleanup_handler\n\tend", "def after_teardown; end", "def teardown\n end", "def teardown\n end", "def teardown\n end", "def teardown\n end", "def teardown\n end", "def teardown\n end", "def teardown\n end", "def teardown\n end", "def teardown\n end", "def teardown\n end", "def teardown\n end", "def teardown\n end", "def teardown\n end", "def teardown\n end", "def teardown\n end", "def teardown\n end", "def teardown\n end", "def teardown\n end", "def teardown\n end", "def teardown\n end", "def teardown\n end", "def teardown\n end", "def teardown\n\t\t\t\t# Do nothing\n\t\tend", "def teardown\n end", "def teardown\n end", "def teardown\n\t\t# Do nothing\n\tend", "def teardown\n\t\t# Do nothing\n\tend", "def teardown\n\t\t# Do nothing\n\tend", "def teardown\n # Empty\n end", "def teardown\n # Empty\n end", "def clean_up\n end", "def clean_up\n end", "def teardown\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend", "def teardown\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend", "def teardown\n # if necessary\n end", "def teardown\n\n end", "def teardown\n\n end", "def teardown\n\n end", "def teardown\n\n end", "def teardown\n\n end", "def teardown\n\n end", "def teardown\n\n end", "def teardown\n\n end", "def teardown\n\n end", "def teardown\n\n end", "def teardown\n\n end", "def teardown\n\n end", "def teardown\n\n end", "def teardown\n\n end", "def teardown\n\n end", "def teardown\n\n end", "def teardown\n\n end", "def teardown\n # No-op\n end", "def teardown\n\tend" ]
[ "0.9077426", "0.9077426", "0.9077426", "0.9077426", "0.8927613", "0.8927613", "0.8764102", "0.87586147", "0.8717561", "0.8717561", "0.8717561", "0.8717561", "0.87075377", "0.87075377", "0.87075377", "0.86842954", "0.86842954", "0.8348282", "0.8348282", "0.82635987", "0.8107503", "0.80933696", "0.8046423", "0.80381376", "0.78013283", "0.7754089", "0.77278626", "0.7712889", "0.7712889", "0.76935256", "0.7676881", "0.7669724", "0.7669134", "0.76475686", "0.76475686", "0.76475686", "0.76475686", "0.76475686", "0.76475686", "0.76475686", "0.7642461", "0.7637188", "0.76368576", "0.76084775", "0.7608428", "0.7463443", "0.746245", "0.746245", "0.746245", "0.746245", "0.746245", "0.746245", "0.746245", "0.746245", "0.74525535", "0.74525535", "0.74525535", "0.74525535", "0.74525535", "0.74525535", "0.74525535", "0.74525535", "0.74525535", "0.74525535", "0.74525535", "0.74525535", "0.74525535", "0.7428907", "0.7424596", "0.741568", "0.741568", "0.740629", "0.740629", "0.740629", "0.740402", "0.740402", "0.7400277", "0.7400277", "0.7382298", "0.7382298", "0.73703885", "0.73661554", "0.73661554", "0.73661554", "0.73661554", "0.73661554", "0.73661554", "0.73661554", "0.73661554", "0.73661554", "0.73661554", "0.73661554", "0.73661554", "0.73661554", "0.73661554", "0.73661554", "0.73661554", "0.73661554", "0.73459536", "0.7333388" ]
0.78892756
24
POST /enrollments POST /enrollments.json
def create @enrollment = @membership.build_enrollment(params[:enrollment]) respond_to do |format| if @enrollment.save format.html { redirect_to business_membership_enrollment_path(@business, @membership, @enrollment), notice: 'Enrollment was successfully created.' } else format.html { render action: "new" } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create\n @enrollments = Enrollment.new(enrollment_params)\n\n respond_to do |format|\n if @enrollments.save\n format.html { redirect_to current_user }\n format.json { render :show, status: :created, location: @enrollments }\n else\n format.html { render :new }\n format.json { render json: @enrollments.errors, status: :unprocessable_entity }\n end\n end\n\n end", "def enrollment(params = {})\n scope 'default'\n post('enrollment/', params)\n end", "def create\n @enroll = Enroll.new(enroll_params)\n\n respond_to do |format|\n if @enroll.save\n format.html { redirect_to @enroll, notice: 'Enroll was successfully created.' }\n format.json { render :show, status: :created, location: @enroll }\n else\n format.html { render :new }\n format.json { render json: @enroll.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @enrollment = Enrollment.new(enrollment_params)\n\n respond_to do |format|\n if @enrollment.save\n format.html { redirect_to @enrollment, notice: 'Enrollment was successfully created.' }\n format.json { render :show, status: :created, location: @enrollment }\n else\n format.html { render :new }\n format.json { render json: @enrollment.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @enrollment = Enrollment.new(enrollment_params)\n\n respond_to do |format|\n if @enrollment.save\n format.html { redirect_to @enrollment, notice: 'Enrollment was successfully created.' }\n format.json { render :show, status: :created, location: @enrollment }\n else\n format.html { render :new }\n format.json { render json: @enrollment.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @course = Course.find(params[:course_id])\n @enrollment = @course.enrollments.create(params[:enrollment])\n\n respond_to do |format|\n if @enrollment.save\n format.html { render :template => 'enrollments/success', notice: 'ya' }\n format.json { render json: @enrollment, status: :created, location: @enrollment }\n else\n format.html { render action: \"new\" }\n format.json { render json: @enrollment.errors, status: :unprocessable_entity }\n end\n format.js\n end\n end", "def create\n @enroll = Enroll.new(params[:enroll])\n @enroll.view =0\n if @enroll.save\n render json: JSON.parse(@enroll.to_json)\n else\n render json: JSON.parse(@enroll.errors.to_json)\n end\n end", "def create\n @enrollment = current_user.enrollments.build(enrollment_params)\n respond_to do |format|\n if @enrollment.save\n format.html { redirect_to user_enrollment_path(current_user, @enrollment), notice: 'We have received your request for enrollment. We\\'ll contact you with further details.' }\n else\n flash[:alert] = @enrollment.errors.full_messages.to_sentence\n format.html { redirect_to request.referrer }\n end\n end\n end", "def create\n @enrollment = Enrollment.new(enrollment_params)\n\n respond_to do |format|\n if @enrollment.save\n format.html { redirect_to [:admin, @enrollment], notice: 'enrollment was successfully created.' }\n format.json { render :show, status: :created, location: @enrollment }\n else\n format.html { render :new }\n format.json { render json: @enrollment.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @enrollment = @parent.enrollments.build enrollment_params\n if @enrollment.save\n render :show, status: :created, location: api_v1_mutant_enrollment_url(@enrollment.mutant_id, @enrollment)\n else\n render json: @enrollment.errors, status: :unprocessable_entity\n end\n end", "def create\n @enrolment = Enrolment.new(enrolment_params)\n\n respond_to do |format|\n if @enrolment.save\n format.html { redirect_to @enrolment, notice: \"Enrolment was successfully created.\" }\n format.json { render :show, status: :created, location: @enrolment }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @enrolment.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\n @enrollment = Enrollment.new(properties_data: enrollment_properties_params)\n #debugger\n #@enrollment = Enrollment.new()\n #render json: request.raw_post(), status: :created\n\n if @enrollment.save\n render json: {:reference_number => @enrollment.reference_number}, status: :created\n else\n render json: @enrollment.errors, status: :unprocessable_entity\n end\n end", "def create\n @enrollment = Enrollment.new(enrollment_params)\n\n respond_to do |format|\n if @enrollment.save\n format.html { redirect_to @enrollment, notice: 'Matrícula criada com sucesso.' }\n format.json { render :show, status: :created, location: @enrollment }\n else\n format.html { render :new }\n format.json { render json: @enrollment.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @enrollment = Enrollment.new(params[:enrollment])\n\n respond_to do |format|\n if @enrollment.save\n flash[:notice] = 'Enrollment was successfully created.'\n format.html { redirect_to(department_lecture_path(@enrollment.lecture.department, @enrollment.lecture)) }\n format.xml { render :xml => @enrollment, :status => :created, :location => @enrollment }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @enrollment.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @enrollment = Enrollment.new(instructor: true)\n @course = Course.new(course_params)\n @course.enrollments << @enrollment\n current_user.enrollments << @enrollment\n\n respond_to do |format|\n if @enrollment.save and @course.save and current_user.save\n format.html { redirect_to root_url, notice: 'Course was successfully created.' }\n format.json { render action: 'show', status: :created, location: @course }\n else\n format.html { render action: 'new' }\n format.json { render json: @course.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_enrollment\n\n end", "def index\n @enrollments = Enrollment.all\n end", "def index\n @enrollments = Enrollment.all\n end", "def index\n @enrollments = Enrollment.all\n end", "def index\n @enrollments = Enrollment.all\n end", "def create\n @enrollment = Enrollment.new(enrollment_params)\n\[email protected]\n respond_to do |format|\n if @enrollment.save\n format.html { redirect_to @enrollment, notice: tr(\"enrollment_created\") }\n else\n format.html { render :new }\n end\n end\n end", "def create\n @enrollment_ta = EnrollmentTa.new(enrollment_ta_params)\n\n respond_to do |format|\n if @enrollment_ta.save\n format.html { redirect_to @enrollment_ta, notice: 'Enrollment ta was successfully created.' }\n format.json { render :show, status: :created, location: @enrollment_ta }\n else\n format.html { render :new }\n format.json { render json: @enrollment_ta.errors, status: :unprocessable_entity }\n end\n end\n end", "def enrollment_params\n params.require(:enrollments).permit(:user_id, :lesson_id)\n end", "def enroll\n\n response = {}\n status_code = 200\n\n begin\n\n # Must be POST request to create course\n return unless request.post?\n\n # Retrieves current user\n user = get_logged_user()\n return unless user\n\n if !user\n status_code = 401\n raise 'Not logged in!'\n end\n\n if !user.is? \"supervisor\"\n status_code = 403\n raise 'Student cannot edit course!'\n end\n\n # If a supervisor\n if user.is? \"supervisor\"\n # Get parameters\n student_id = params[:student_id]\n course_id = params[:course_id]\n\n # Only allowed to enroll students in courses he supervises\n return unless user.courses.find(course_id)\n else\n # If unknown class, do nothing\n return\n end\n\n # Create plan\n plan = Plan.new\n\n group = Group.create!(\n :name => \"Pessoal\",\n :min_credits => nil,\n :min_subjects => nil\n )\n\n # Supervisor only enrolls if student exists\n if Student.find(student_id) != nil\n plan.course = Course.find(course_id)\n plan.student = Student.find(student_id)\n plan.group = group\n\n plan.save\n else\n status_code = 404\n raise 'Student does not exist!'\n end\n\n redirect_back fallback_location: \"/\"\n rescue Exception => e\n response[:status] = 'error'\n response[:error] = \"#{e}\"\n else\n status_code 201\n response[:status] = 'success'\n response[:message] = 'Student was enrolled with success!'\n end\n end", "def create\n @enrolled = Enrolled.new(params[:enrolled])\n \n respond_to do |format|\n if @enrolled.save\n format.html { redirect_to @enrolled, :notice => t('selecao_admin.flash_messages.successfully_created.', :model => @enrolled.class.model_name.human) }\n format.json { render :json => @enrolled, :status => :created, :location => @enrolled }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @enrolled.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @education = Education.new(education_params)\n\n if @education.save\n render json: @education, status: :created, location: @education\n else\n render json: @education.errors, status: :unprocessable_entity\n end\n end", "def create\n @pre_enrollment = PreEnrollment.new(pre_enrollment_params)\n\n respond_to do |format|\n if @pre_enrollment.save\n format.html { redirect_to @pre_enrollment, notice: 'Pre enrollment was successfully created.' }\n format.json { render :show, status: :created, location: @pre_enrollment }\n else\n format.html { render :new }\n format.json { render json: @pre_enrollment.errors, status: :unprocessable_entity }\n end\n end\n end", "def enrollment_params\n params.require(:enrollment).permit(:date, :method, :remarks, :coordinator_id, :registry_id, :participant_id)\n end", "def enroll!(course_id)\n self.enrollments.create!(course_id:course_id)\n end", "def enroll_params\r\n params.require(:enroll).permit(:user_id, :lecture)\r\n end", "def create\n @enrollment = Enrollment.new(enrollment_params)\n @enrollment.student = Student.find(params[:student_for_enrollment])\n @enrollment.subject = Subject.find(params[:subject])\n @enrollment.year = DateTime.now.year\n\n respond_to do |format|\n if @enrollment.save\n format.html { redirect_to '/students', notice: 'La Cursada se creó exitosamente.' }\n format.json { render :show, status: :created, location: @enrollment }\n else\n format.html { render :new }\n format.json { render json: @enrollment.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @enrolled = Enrolled.new(:student_id => current_student.student_id, :course_id => params[:course_id])\n\n respond_to do |format|\n if @enrolled.save\n format.html { redirect_to @enrolled, notice: 'Enrolled was successfully created.' }\n format.json { render json: @enrolled, status: :created, location: @enrolled }\n else\n format.html { render action: \"new\" }\n format.json { render json: @enrolled.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @enrolls = Enroll.all\n @enroll = Enroll.new\n end", "def enroll_params\n params.require(:enroll).permit(:firstname, :lastname, :phone, :email, :childname, :childage, :question, :consent, :startdate, :enddate, :typeofday)\n end", "def enroll_params\n params.require(:enrollment).permit(:course_id, :user_id)\n end", "def create_and_invitation_studant(params = {})\n run(:post, \"/invitations\", [201,422], JSON.dump(params))\n end", "def enroll_params\n params.require(:enroll).permit(:user_id, :course_id)\n end", "def create\n @instructor = Instructor.new(trainer_params)\n if @instructor.save\n render json: @instructor\n else\n render json: @instructor.errors\n end\n end", "def enrollment_params\n params.require(:enrollment).permit(:attended, :user_id, :training_session_id)\n end", "def guardian_create_enrollment_ticket(body)\n raise Auth0::InvalidParameter, 'Must supply a valid body' if body.to_s.empty?\n\n path = \"#{guardian_enrollments_path}/ticket\"\n post(path, body)\n end", "def create\n \n\t# create a new student as well if there is not already a student associated with this user.\n\t#Student.new({:user_id => session[:id], :student_number => params[:enrollment][:student_number]})\n\t\n\t# give correct user id.\n\tparams[:enrollment][:user_number] = session[:user_id]\n @enrollment = Enrollment.new(params[:enrollment])\n\t\n respond_to do |format|\n if @enrollment.save\n format.html { redirect_to @enrollment, notice: 'Enrollment was successfully created.' }\n format.json { render json: @enrollment, status: :created, location: @enrollment }\n else\n format.html { render action: \"new\" }\n format.json { render json: @enrollment.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n # @attendance_record = AttendanceRecord.new(attendance_record_params)\n #\n # respond_to do |format|\n # if @attendance_record.save\n # format.html { redirect_to @attendance_record, notice: 'Attendance record was successfully created.' }\n # format.json { render :show, status: :created, location: @attendance_record }\n # else\n # format.html { render :new }\n # format.json { render json: @attendance_record.errors, status: :unprocessable_entity }\n # end\n # end\n enrollments = Enrollment.where(section_id: params[:section_id])\n enrollments.each do |e|\n if (params[\"ar_p-#{e.student_id}\"])\n primary = params[\"ar_p-#{e.student_id}\"]\n secondary = params[\"ar_s-#{e.student_id}\"] ? params[\"ar_s-#{e.student_id}\"] : nil\n ar_params = {}\n ar_params[:student_id] = e.student_id\n ar_params[:section_id] = params['section_id']\n ar_params[:primary] = primary\n ar_params[:secondary] = secondary\n ar_params[:attendance_date] = Date.today\n AttendanceRecord.create(ar_params)\n end\n end\n end", "def create\n\n @enroll = Enroll.new(enroll_params)\n\n respond_to do |format|\n\n if @enroll.save\n\n format.html { redirect_to promotions_path, notice: 'Test was successfully created.' }\n format.json { render :show, status: :created, location: @promotion }\n\n end\n end\n end", "def index\n @enrolls = Enroll.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @enrolls }\n end\n end", "def enrollment_params\n params.require(:enrollment).permit(:student_id, :course_id)\n end", "def enrollment_params\n params.require(:enrollment).permit(:user_id, :course_id, :approve, :deny, :grade)\n\n end", "def create\n @admitting = Admitting.new(admitting_params)\n\n if @admitting.save\n render json: @admitting, status: :created, location: @admitting\n else\n render json: @admitting.errors, status: :unprocessable_entity\n end\n end", "def create\n #@enrollment = Enrollment.new(params[:enrollment])\n\n respond_to do |format|\n @enrollment = Enrollment.shard_for( params[:enrollment][:classroom_id] ).create!( params[:enrollment] )\n if @enrollment\n format.html { redirect_to @enrollment, notice: 'Enrollment was successfully created.' }\n format.json { render json: @enrollment, status: :created, location: @enrollment }\n else\n format.html { render action: \"new\" }\n format.json { render json: @enrollment.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n admin_only\n @consuming_enrollment = ConsumingEnrollment.new(consuming_enrollment_params)\n\n respond_to do |format|\n if @consuming_enrollment.save\n format.html { redirect_to @consuming_enrollment, notice: 'Consuming enrollment was successfully created.' }\n format.json { render :show, status: :created, location: @consuming_enrollment }\n else\n format.html { render :new }\n format.json { render json: @consuming_enrollment.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @enroll = Enroll.find(params[:id])\n if @enroll.update_attributes(params[:enroll])\n render json: JSON.parse(@enroll.to_json)\n else\n render json: JSON.parse(@enroll.errors.to_json)\n end\n end", "def enroll_params\n params.require(:enroll).permit(:student_id, :course_id, :percentage, :lettergrade)\n end", "def create\n if params[:education][:accomplishment][\"0\"] != \"\"\n @education = Education.new(education_params)\n if @education.save\n params[:education][:accomplishment].each do |i, acc|\n EducationAccomplishment.create(description: acc, education_id: @education.id)\n end\n redirect_to '/'\n else\n redirect_to :back, flash: {alert: @education.errors.full_messages}\n end\n else\n redirect_to :back, flash: {alert: \"Must have at least one accomplishment\"}\n end\n end", "def new\n @enrollment = Enrollment.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @enrollment }\n end\n end", "def new\n @enrollment = Enrollment.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @enrollment }\n end\n end", "def create\n @education_accomplishment = EducationAccomplishment.new(education_accomplishment_params)\n\n respond_to do |format|\n if @education_accomplishment.save\n format.html { redirect_to @education_accomplishment, notice: 'Education accomplishment was successfully created.' }\n format.json { render :show, status: :created, location: @education_accomplishment }\n else\n format.html { render :new }\n format.json { render json: @education_accomplishment.errors, status: :unprocessable_entity }\n end\n end\n end", "def create \n if current_user && current_user.university_id\n begin \n params[:enrollment][:user_id] = current_user.id \n params[:enrollment][:university_id] = current_user.university_id\n @enrollment = Enrollment.renew( params[:enrollment] )\n render :show\n rescue \n render json: {error: \"Enrollment not created.\"}\n end\n else\n render json: {error: \"Enrollment not created.\"}\n end\n end", "def create\n @encouragement = Encouragement.new(encouragement_params)\n\n respond_to do |format|\n if @encouragement.save\n format.html { redirect_to admin_encouragements_path, notice: 'Encouragement was successfully created.' }\n format.json { render :show, status: :created, location: @encouragement }\n else\n format.html { render :new }\n format.json { render json: @encouragement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @enrollment = Enrollment.new(enrollment_params)\n @registry = @enrollment.registry\n @participants = Participant.all - @registry.participants\n @coordinators = @registry.coordinators\n\n respond_to do |format|\n if @enrollment.save\n format.html { redirect_to @enrollment, notice: 'Enrollment was successfully created.' }\n format.json { render :show, status: :created, location: @enrollment }\n else\n format.html { render :new }\n format.json { render json: @enrollment.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n raise SecurityTransgression unless Enrollment.can_be_created_by? current_user\n @enrollment = Enrollment.new(enrollment_params)\n\n if @enrollment.save\n redirect_to welcome_index_path, notice: 'Enrollment was successfully created.'\n else\n render action: 'new'\n end\n end", "def enrollment_params\n params.require(:enrollment).permit(:enrollment_date, :year, :active, :paid, :student_id, :course_id)\n end", "def create\n course = Course.find(params[:course_id])\n student = Student.find_by(dni: params[:student_id])\n @enroll = Enroll.new( student: student, course: course)\n TestCourse.of(course).each do |tc|\n Score.create( student: student, test_id: tc.test_id, value: -2)\n end\n \n respond_to do |format|\n if @enroll.save\n format.html { redirect_to course_enrolls_path(course), notice: 'Enroll was successfully created.' }\n format.json { render :show, status: :created, location: course_enrolls_path(course) }\n else\n format.html { render :new }\n format.json { render json: @enroll.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @entertainment = Entertainment.new(entertainment_params)\n\n respond_to do |format|\n if @entertainment.save\n format.html { redirect_to @entertainment, notice: 'Entertainment was successfully created.' }\n format.json { render :show, status: :created, location: @entertainment }\n else\n format.html { render :new }\n format.json { render json: @entertainment.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @enrolls = Enroll.all\n end", "def enrollment_params\n params.require(:enrollment).permit(:section_id, :student_id)\n end", "def create\n @enrollment = Enrollment.new\n @enrollment.student_id = params[:enrollment][:student]\n @enrollment.course_id = params[:enrollment][:course_id]\n \n if [email protected]_id.nil? and [email protected]_id.nil?\n @enrollment.save\n end\n redirect_to enrollments_index_path(:course_id=>@enrollment.course_id) \n end", "def create_enrollment\n Enrollment.create!([{\n subject_id: 1,\n student_id: 1\n },\n {\n subject_id: 2,\n student_id: 2\n },\n {\n subject_id: 3,\n student_id: 3\n },\n {\n subject_id: 1,\n student_id: 4\n },\n {\n subject_id: 2,\n student_id: 5\n },\n {\n subject_id: 3,\n student_id: 6\n },\n {\n subject_id: 1,\n student_id: 7\n },\n {\n subject_id: 2,\n student_id: 8\n },\n {\n subject_id: 3,\n student_id: 9\n },\n {\n subject_id: 1,\n student_id: 10\n }])\nend", "def enrollment_params\n params.require(:enrollment).permit(:client_id, :service_id, :preferences)\n end", "def enrollment_params\n params.require(:enrollment).permit(:user_id, :course_code)\n end", "def enrollment_params\n params.require(:enrollment).permit(:course_id,:student_id, :grade)\n end", "def enrollment_params\n params.require(:enrollment).permit(:section_id, :user_id)\n end", "def create\n @deed = Deed.create(deed_params)\n\n if @deed.save\n render json: @deed, status: :created, location: @deed\n else\n render json: @deed.errors, status: :unprocessable_entity\n end\n end", "def create\n @enrolled_student = EnrolledStudent.new(params[:enrolled_student])\n\n respond_to do |format|\n if @enrolled_student.save\n format.html { redirect_to @enrolled_student, notice: 'Enrolled student was successfully created.' }\n format.json { render json: @enrolled_student, status: :created, location: @enrolled_student }\n else\n format.html { render action: \"new\" }\n format.json { render json: @enrolled_student.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @entrant = Entrant.new(params[:entrant])\n\n respond_to do |format|\n if @entrant.save\n format.html { redirect_to @entrant, notice: 'Entrant was successfully created.' }\n format.json { render json: @entrant, status: :created, location: @entrant }\n else\n format.html { render action: \"new\" }\n format.json { render json: @entrant.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @desease = Desease.new(desease_params)\n\n if @desease.save\n render json: @desease, status: :ok\n else\n render json: @desease.errors, status: :unprocessable_entity\n end\n end", "def create\n @investment = Investment.new(investment_params)\n\n if @investment.save\n render json: @investment, status: :created\n else\n render json: @investment.errors, status: :unprocessable_entity\n end\n end", "def enrollment\n \n connection =\n HTTParty.post('https://eastus.api.cognitive.microsoft.com/speaker/identification/v2.0/text-independent/profiles',\n :body => JSON.generate(\"locale\": 'en-us'),\n :headers => { 'Content-Type' => 'application/json',\n 'Ocp-Apim-Subscription-Key' => \"3c43bca9ad884fe39518a5cf3925e707\" })\n @parsed = JSON.parse(connection.body)\n create_DB_profile();\n create_profile();\n redirect_to ('/speech')\n end", "def index\n @educations = Education.all\n render json: @educations\n end", "def create\n @instructor = Instructor.new(params[:instructor])\n\n respond_to do |format|\n if @instructor.save\n format.html { redirect_to @instructor, notice: 'Instructor was successfully created.' }\n format.json { render json: @instructor, status: :created, location: @instructor }\n else\n format.html { render action: \"new\" }\n format.json { render json: @instructor.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @education = Education.new(education_params)\n\n respond_to do |format|\n if @education.save\n format.html { redirect_to @education, notice: \"Education was successfully created.\" }\n format.json { render :show, status: :created, location: @education }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @education.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n user_id = @current_user.id\n date = DateTime.strptime(params[:date], '%s')\n schedule_id = params[:id]\n\n e = Enrollment.find_by user_id: user_id, date: date, schedule_id: schedule_id\n\n # avoid duplicating enrollments\n unless e.present?\n\n @enrollment = Enrollment.create(\n user_id: user_id,\n date: date,\n schedule_id: schedule_id\n )\n\n end\n\n redirect_to bookings_path\n\n end", "def index\n @enrollments = Enrollment.all\n\n # Search\n @enrollments = @enrollments.search(params[:q]) if params[:q]\n\n # Filter for group\n #@enrollments = @enrollments.relationship(params[:group]) if params[:group]\n\n # Order by\n @enrollments = @enrollments.order(params[:order].gsub(':', ' ')) if params[:order]\n\n # Pagination\n if (params[:offset] && params[:limit])\n @enrollments = @enrollments.page(1).per(params[:limit]).padding(params[:offset])\n else\n @enrollments = @enrollments.page(1).per(25)\n end\n\n render json: @enrollments if stale?(etag: @enrollments.all, last_modified: @enrollments.maximum(:updated_at))\n end", "def enrollment_params\n params.permit(:course_id, :andrew_id, :active)\n end", "def create\n @referral_enrolment = ReferralEnrolment.new(referral_enrolment_params)\n\n respond_to do |format|\n if @referral_enrolment.save\n format.html { redirect_to @referral_enrolment, notice: 'Referral enrolment was successfully created.' }\n format.json { render :show, status: :created, location: @referral_enrolment }\n else\n format.html { render :new }\n format.json { render json: @referral_enrolment.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @assessment = Assessment.new(params[:assessment])\n\n respond_to do |format|\n if @assessment.save\n format.html { redirect_to @assessment, notice: 'Assessment was successfully created.' }\n format.json { render json: @assessment, status: :created, location: @assessment }\n else\n format.html { render action: \"new\" }\n format.json { render json: @assessment.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @education_level = EducationLevel.new(params[:education_level])\n\n respond_to do |format|\n if @education_level.save\n format.html { redirect_to @education_level, :notice => t('controllermessage.insert') }\n format.json { render :json => @education_level, :status => :created, :location => @education_level }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @education_level.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @enqury = Enqury.new(enqury_params)\n\n respond_to do |format|\n if @enqury.save\n format.html { redirect_to @enqury, notice: 'Enqury was successfully created.' }\n format.json { render :show, status: :created, location: @enqury }\n else\n format.html { render :new }\n format.json { render json: @enqury.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @endorsement = Endorsement.new(endorsement_params)\n\n if @endorsement.save\n render json: @endorsement, status: :created, location: @endorsement\n else\n render json: @endorsement.errors, status: :unprocessable_entity\n end\n end", "def new\n @course = Course.find(params[:course_id])\n @enrollment = Enrollment.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @enrollment }\n end\n end", "def create\n @instructor = Instructor.new(instructor_params)\n\n respond_to do |format|\n if @instructor.save\n format.html { redirect_to @instructor, notice: 'Instructor was successfully created.' }\n format.json { render :show, status: :created, location: @instructor }\n else\n format.html { render :new }\n format.json { render json: @instructor.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @instructor = Instructor.new(instructor_params)\n\n respond_to do |format|\n if @instructor.save\n format.html { redirect_to @instructor, notice: 'Instructor was successfully created.' }\n format.json { render :show, status: :created, location: @instructor }\n else\n format.html { render :new }\n format.json { render json: @instructor.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @instructor = Instructor.new(instructor_params)\n\n respond_to do |format|\n if @instructor.save\n format.html { redirect_to @instructor, notice: 'Instructor was successfully created.' }\n format.json { render :show, status: :created, location: @instructor }\n else\n format.html { render :new }\n format.json { render json: @instructor.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @education_level = EducationLevel.new(education_level_params)\n\n respond_to do |format|\n if @education_level.save\n format.html { redirect_to @education_level, notice: 'Education level was successfully created.' }\n format.json { render :show, status: :created, location: @education_level }\n else\n format.html { render :new }\n format.json { render json: @education_level.errors, status: :unprocessable_entity }\n end\n end\n end", "def enrolment_params\n params.require(:enrolment).permit(:course_id, :student_id)\n end", "def create\n @engagement_attendee = EngagementAttendee.new(engagement_params)\n if @engagement_attendee.save\n render :show, status: :created, location: api_v1_engagement_url(@engagement_attendee)\n else\n render json: @engagement_attendee.errors, status: :unprocessable_entity\n end\n end", "def enrollment_params\n params.require(:enrollment).permit(:event_group_id, :user_id, :coupon_id, :opp_status_id, :guest_id)\n end", "def enroll_params\n params.fetch(:enroll, {})\n end", "def enrollment_params\n params.require(:enrollment).permit(:term_id, :mutant_id)\n end", "def create\n newEssay = params[:essay]\n newEssay[:assignment_id] = params[:assignment_id]\n @essay = Essay.new(newEssay)\n \n respond_to do |format|\n if @essay.save\n format.html { redirect_to assignment_essay_url(@essay.assignment_id, @essay.id), notice: 'Essay was successfully created.' }\n format.json { render json: @essay, status: :created, location: @essay }\n else\n format.html { render action: \"new\" }\n format.json { render json: @essay.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @pre_enrollments = PreEnrollment.all\n end", "def new\n @enrolled = Enrolled.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @enrolled }\n end\n end" ]
[ "0.7454781", "0.7336914", "0.7142115", "0.6823971", "0.6823971", "0.68186426", "0.67857486", "0.67269367", "0.66352534", "0.65869594", "0.6410974", "0.639911", "0.6384636", "0.6376349", "0.63298506", "0.6321295", "0.6297824", "0.6297824", "0.6297824", "0.6297824", "0.62677735", "0.6205036", "0.6204671", "0.61898935", "0.6173724", "0.61534774", "0.61446834", "0.61377686", "0.6126241", "0.6094172", "0.6075239", "0.60739", "0.60639226", "0.60476464", "0.60468847", "0.60109186", "0.60067064", "0.5995347", "0.5993288", "0.59856045", "0.59695363", "0.595117", "0.59486336", "0.5947921", "0.5923624", "0.59146816", "0.5894116", "0.58834565", "0.58815676", "0.58801645", "0.58726424", "0.5868744", "0.5855339", "0.5855339", "0.5854847", "0.58500856", "0.58395094", "0.5835032", "0.58184576", "0.58129853", "0.5794435", "0.5790076", "0.57851255", "0.5783607", "0.57766855", "0.5773194", "0.5772176", "0.57556146", "0.57381725", "0.5721511", "0.57099307", "0.5702688", "0.5690583", "0.5688667", "0.5684183", "0.5677892", "0.5672684", "0.56683445", "0.56579274", "0.5656798", "0.56527096", "0.56449544", "0.5631923", "0.5622251", "0.56027097", "0.55967784", "0.55797756", "0.55766046", "0.5573078", "0.5573078", "0.5573078", "0.5571271", "0.556315", "0.5561415", "0.5559598", "0.5554471", "0.5553736", "0.55497473", "0.5548756", "0.55436724" ]
0.5670478
77
PUT /enrollments/1 PUT /enrollments/1.json
def update respond_to do |format| if @enrollment.update_attributes(params[:enrollment]) format.html { redirect_to business_membership_enrollment_path(@business, @membership, @enrollment), notice: 'Enrollment was successfully updated.' } else format.html { render action: "edit" } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update\n @enroll = Enroll.find(params[:id])\n if @enroll.update_attributes(params[:enroll])\n render json: JSON.parse(@enroll.to_json)\n else\n render json: JSON.parse(@enroll.errors.to_json)\n end\n end", "def update\n respond_to do |format|\n if @enroll.update(enroll_params)\n format.html { redirect_to @enroll, notice: 'Enroll was successfully updated.' }\n format.json { render :show, status: :ok, location: @enroll }\n else\n format.html { render :edit }\n format.json { render json: @enroll.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @enroll.update(enroll_params)\n format.html { redirect_to @enroll, notice: 'Enroll was successfully updated.' }\n format.json { render :show, status: :ok, location: @enroll }\n else\n format.html { render :edit }\n format.json { render json: @enroll.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n #debugger\n if @enrollment.update(update_params)\n head :no_content\n else\n render json: @enrollment.errors, status: :unprocessable_entity\n end\n end", "def update\n @enroll = Enroll.find(params[:id])\n @enroll.tournament = Tournament.find params[:enroll][:tournament_id]\n respond_to do |format|\n if @enroll.update_attributes(params[:enroll])\n format.html { redirect_to @enroll, notice: 'Enroll was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @enroll.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @enroll.update(enroll_params)\n format.html { redirect_to @enroll, notice: 'Test was successfully updated.' }\n format.json { render :show, status: :ok, location: @enroll }\n else\n format.html { render :edit }\n format.json { render json: @enroll.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n \n @enrollment = Enrollment.find(params[:id])\n\t# give correct user id.\n\t\n respond_to do |format|\n if @enrollment.update_attributes(params[:enrollment])\n format.html { redirect_to @enrollment, notice: 'Enrollment was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @enrollment.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_enroll\n @enroll = Enroll.find(params[:id])\n end", "def set_enroll\n @enroll = Enroll.find(params[:id])\n end", "def set_enroll\n @enroll = Enroll.find(params[:id])\n end", "def set_enroll\n @enroll = Enroll.find(params[:id])\n end", "def set_enroll\n @enroll = Enroll.find(params[:id])\n\n end", "def update \n\n if @enrollment && @enrollment.update(enrollment_params)\n render :show\n else\n render json: {error: \"Enrollment not updated.\"}\n end\n end", "def update\n respond_to do |format|\n if @enrollment.update(enrollment_params)\n format.html { redirect_to @enrollment, notice: 'Enrollment was successfully updated.' }\n format.json { render :show, status: :ok, location: @enrollment }\n else\n format.html { render :edit }\n format.json { render json: @enrollment.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @enrollment.update(enrollment_params)\n format.html { redirect_to @enrollment, notice: 'Enrollment was successfully updated.' }\n format.json { render :show, status: :ok, location: @enrollment }\n else\n format.html { render :edit }\n format.json { render json: @enrollment.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @enrollment.update(enrollment_params)\n format.html { redirect_to @enrollment, notice: 'Enrollment was successfully updated.' }\n format.json { render :show, status: :ok, location: @enrollment }\n else\n format.html { render :edit }\n format.json { render json: @enrollment.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @enrollment.update(enrollment_params)\n format.html { redirect_to @enrollment, notice: 'Enrollment was successfully updated.' }\n format.json { render :show, status: :ok, location: @enrollment }\n else\n format.html { render :edit }\n format.json { render json: @enrollment.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @enrollment.update(enrollment_params)\n format.html { redirect_to @enrollment, notice: 'Enrollment was successfully updated.' }\n format.json { render :show, status: :ok, location: @enrollment }\n else\n format.html { render :edit }\n format.json { render json: @enrollment.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @enrollment = Enrollment.find(params[:id])\n if @enrollment.update(enrollment_params)\n redirect_to enrollments_index_path(:course_id=>@enrollment.course_id) \n end\n \n end", "def enrollment(params = {})\n scope 'default'\n post('enrollment/', params)\n end", "def update\n\n @enrollment = Enrollment.shard_for( params[:enrollment][:classroom_id] ).find(params[:id])\n\n respond_to do |format|\n if @enrollment.update_attributes(params[:enrollment])\n format.html { redirect_to @enrollment, notice: 'Enrollment was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @enrollment.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @enrollment = Enrollment.find(params[:id])\n\n respond_to do |format|\n if @enrollment.update_attributes(params[:enrollment])\n flash[:notice] = 'Enrollment was successfully updated.'\n format.html { redirect_to(@enrollment) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @enrollment.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @enrollment.update(enrollment_params)\n format.html { redirect_to @enrollment, notice: 'Matrícula editada com sucesso.' }\n format.json { render :show, status: :ok, location: @enrollment }\n else\n format.html { render :edit }\n format.json { render json: @enrollment.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @pre_enrollment.update(pre_enrollment_params)\n format.html { redirect_to @pre_enrollment, notice: 'Pre enrollment was successfully updated.' }\n format.json { render :show, status: :ok, location: @pre_enrollment }\n else\n format.html { render :edit }\n format.json { render json: @pre_enrollment.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @instructor1 = Instructor1.find(params[:id])\n\n respond_to do |format|\n if @instructor1.update_attributes(params[:instructor1])\n format.html { redirect_to @instructor1, notice: 'Instructor1 was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @instructor1.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n if @instructor.update(instructor_params)\n render json: @instructor\n else\n render json: @instructor.errors\n end\n end", "def update\n respond_to do |format|\n if @enrolment.update(enrolment_params)\n format.html { redirect_to @enrolment, notice: \"Enrolment was successfully updated.\" }\n format.json { render :show, status: :ok, location: @enrolment }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @enrolment.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @enrolled = Enrolled.find(params[:id])\n\n respond_to do |format|\n if @enrolled.update_attributes(params[:enrolled])\n format.html { redirect_to @enrolled, notice: 'Enrolled was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @enrolled.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @instructor = Instructor.find(params[:id])\n\n respond_to do |format|\n if @instructor.update_attributes(params[:instructor])\n format.html { redirect_to @instructor, notice: 'Instructor was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @instructor.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_enrollment\n @enrollment = Enrollment.find(params[:id])\n end", "def set_enrollment\n @enrollment = Enrollment.find(params[:id])\n end", "def update_enrollment(subdomain, course_id, enrollment_id, state)\n canvas_url = \"https://#{subdomain}.instructure.com\"\n token = get_token\n\n canvas_delete(\"#{canvas_url}/api/v1/courses/#{course_id}/enrollments/#{enrollment_id}\",\n token,\n {\n task: state\n }\n )\n end", "def create\n @enrollments = Enrollment.new(enrollment_params)\n\n respond_to do |format|\n if @enrollments.save\n format.html { redirect_to current_user }\n format.json { render :show, status: :created, location: @enrollments }\n else\n format.html { render :new }\n format.json { render json: @enrollments.errors, status: :unprocessable_entity }\n end\n end\n\n end", "def create\n @enroll = Enroll.new(enroll_params)\n\n respond_to do |format|\n if @enroll.save\n format.html { redirect_to @enroll, notice: 'Enroll was successfully created.' }\n format.json { render :show, status: :created, location: @enroll }\n else\n format.html { render :new }\n format.json { render json: @enroll.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @enrollment.student = @student_for_enrollment\n respond_to do |format|\n if @enrollment.update(enrollment_params)\n format.html { redirect_to '/students', notice: 'La Cursada se actualizó exitosamente.' }\n format.json { render :show, status: :ok, location: @enrollment }\n else\n format.html { render :edit }\n format.json { render json: @enrollment.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @enrollment_ta.update(enrollment_ta_params)\n format.html { redirect_to @enrollment_ta, notice: 'Enrollment ta was successfully updated.' }\n format.json { render :show, status: :ok, location: @enrollment_ta }\n else\n format.html { render :edit }\n format.json { render json: @enrollment_ta.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_enrollment\n @enrollment = Enrollment.find(params[:id])\n end", "def set_enrollment\n @enrollment = Enrollment.find(params[:id])\n end", "def set_enrollment\n @enrollment = Enrollment.find(params[:id])\n end", "def set_enrollment\n @enrollment = Enrollment.find(params[:id])\n end", "def set_enrollment\n @enrollment = Enrollment.find(params[:id])\n end", "def set_enrollment\n @enrollment = Enrollment.find(params[:id])\n end", "def set_enrollment\n @enrollment = Enrollment.find(params[:id])\n end", "def set_enrollment\n @enrollment = Enrollment.find(params[:id])\n end", "def set_enrollment\n @enrollment = Enrollment.find(params[:id])\n end", "def set_enrollment\n @enrollment = Enrollment.find(params[:id])\n end", "def set_enrollment\n @enrollment = Enrollment.find(params[:id])\n end", "def update\n\t \n\t @enrollment = Enrollment.find(params[:enrollment_id], :include => :contract)\n\t @meeting = Meeting.find(params[:meeting_id])\n\t if @enrollment\n\t privs = @enrollment.contract.privileges(@user)\n\t render :text => \"You don't have privileges to do this.\", :status=>500 and return unless privs[:edit]\n\t \n\t participant = update_attendance_for_enrollment(@meeting, @enrollment, params)\n\t end\n \n render :json => {:id => participant.id}.to_json\n\tend", "def update\n admin_only\n respond_to do |format|\n if @consuming_enrollment.update(consuming_enrollment_params)\n format.html { redirect_to @consuming_enrollment, notice: 'Consuming enrollment was successfully updated.' }\n format.json { render :show, status: :ok, location: @consuming_enrollment }\n else\n format.html { render :edit }\n format.json { render json: @consuming_enrollment.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n if @education.update(education_params)\n render :show, status: :ok, location: @education\n else\n render json: @education.errors, status: :unprocessable_entity\n end\n end", "def enroll!(course_id)\n self.enrollments.create!(course_id:course_id)\n end", "def update\n @enrolled = Enrolled.find(params[:id])\n \n respond_to do |format|\n if @enrolled.update_attributes(params[:enrolled])\n format.html { redirect_to @enrolled, :notice => t('selecao_admin.flash_messages.successfully_updated.', :model => @enrolled.class.model_name.human) }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @enrolled.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @enroll = Enroll.new(params[:enroll])\n @enroll.view =0\n if @enroll.save\n render json: JSON.parse(@enroll.to_json)\n else\n render json: JSON.parse(@enroll.errors.to_json)\n end\n end", "def enroll\n\n response = {}\n status_code = 200\n\n begin\n\n # Must be POST request to create course\n return unless request.post?\n\n # Retrieves current user\n user = get_logged_user()\n return unless user\n\n if !user\n status_code = 401\n raise 'Not logged in!'\n end\n\n if !user.is? \"supervisor\"\n status_code = 403\n raise 'Student cannot edit course!'\n end\n\n # If a supervisor\n if user.is? \"supervisor\"\n # Get parameters\n student_id = params[:student_id]\n course_id = params[:course_id]\n\n # Only allowed to enroll students in courses he supervises\n return unless user.courses.find(course_id)\n else\n # If unknown class, do nothing\n return\n end\n\n # Create plan\n plan = Plan.new\n\n group = Group.create!(\n :name => \"Pessoal\",\n :min_credits => nil,\n :min_subjects => nil\n )\n\n # Supervisor only enrolls if student exists\n if Student.find(student_id) != nil\n plan.course = Course.find(course_id)\n plan.student = Student.find(student_id)\n plan.group = group\n\n plan.save\n else\n status_code = 404\n raise 'Student does not exist!'\n end\n\n redirect_back fallback_location: \"/\"\n rescue Exception => e\n response[:status] = 'error'\n response[:error] = \"#{e}\"\n else\n status_code 201\n response[:status] = 'success'\n response[:message] = 'Student was enrolled with success!'\n end\n end", "def update\n enrollment.update!(\n selected_location_details: update_params.as_json,\n issuer: current_sp&.issuer,\n )\n add_proofing_component\n\n render json: { success: true }, status: :ok\n end", "def update\n respond_to do |format|\n if @vopportunity_enrolment.save(vopportunity_enrolment_params)\n format.html { redirect_to @vopportunity_enrolment, notice: 'Enrolled! Congratulations!' }\n format.json { render :show, status: :ok, location: @vopportunity_enrolment }\n else\n format.html { render :edit }\n format.json { render json: @vopportunity_enrolment.errors, status: :unprocessable_entity }\n end\n end\n end", "def enroll_params\n params.require(:enrollment).permit(:course_id, :user_id)\n end", "def update\n @assessment = Assessment.find(params[:id])\n\n respond_to do |format|\n if @assessment.update_attributes(params[:assessment])\n format.html { redirect_to :back }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @assessment.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_enrollment\n @enrollment = Participantstudysite.find(params[:id])\n end", "def update\n respond_to do |format|\n if @instructor.update(instructor_params)\n format.html { redirect_to @instructor, notice: 'Instructor was successfully updated.' }\n format.json { render :show, status: :ok, location: @instructor }\n else\n format.html { render :edit }\n format.json { render json: @instructor.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @issuer = Issuer.find(params[:id])\n\n respond_to do |format|\n if @issuer.update_attributes(params[:issuer])\n format.html { redirect_to issuers_path, notice: 'Issuer was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @issuer.errors, status: :unprocessable_entity }\n end\n end\n end", "def enroll_params\n params.require(:enroll).permit(:user_id, :course_id)\n end", "def update\n @manage_instructor = Instructor.find(params[:id])\n\n respond_to do |format|\n if @manage_instructor.update_attributes(params[:manage_instructor])\n format.html { redirect_to @manage_instructor, notice: 'Instructor was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @manage_instructor.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @education_accomplishment.update(education_accomplishment_params)\n format.html { redirect_to @education_accomplishment, notice: 'Education accomplishment was successfully updated.' }\n format.json { render :show, status: :ok, location: @education_accomplishment }\n else\n format.html { render :edit }\n format.json { render json: @education_accomplishment.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @enterprise = Enterprise.find(params[:id])\n\n respond_to do |format|\n if @enterprise.update_attributes(params[:enterprise])\n format.html { redirect_to \"/enterprises\", notice: 'Enterprise was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @enterprise.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @exprience = Exprience.find(params[:id])\n\n respond_to do |format|\n if @exprience.update_attributes(params[:exprience])\n format.html { redirect_to @exprience, notice: 'Exprience was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @exprience.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @enrollement.update(enrollement_params)\n format.html { redirect_to @enrollement, notice: \"Enrollement was successfully updated.\" }\n format.json { render :show, status: :ok, location: @enrollement }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @enrollement.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n raise SecurityTransgression unless current_user.can_update? @enrollment\n if @enrollment.update(enrollment_params)\n redirect_to course_path(@enrollment.course_id), notice: 'Enrollment was successfully updated.'\n else\n render action: 'edit'\n end\n end", "def set_enrolls\r\n @lecture = Lecture.find(params[:lecture_id])\r\n end", "def update\n @services = Service.all\n respond_to do |format|\n if @enrollment.update(enrollment_params)\n format.html { redirect_to [:admin, @enrollment], notice: 'enrollment was successfully updated.' }\n format.json { render :show, status: :ok, location: @enrollment }\n else\n format.html { render :edit }\n format.json { render json: @enrollment.errors, status: :unprocessable_entity }\n end\n end\n end", "def enroll_params\r\n params.require(:enroll).permit(:user_id, :lecture)\r\n end", "def update\n @education = Education.where(:resource_id => current_user.id, :id => params[:id]).first\n\n respond_to do |format|\n if @education.update_attributes(params[:education])\n format.html { redirect_to(@education, :notice => 'Education was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @education.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @enrollment = Enrollment.find(params[:id])\n\n respond_to do |format|\n if @enrollment.update_attributes(params[:enrollment])\n @log_entry = LogEntry.last\n format.html { redirect_to @enrollment, :notice => 'The details of this enrollment have changed.' }\n format.xml { head :ok }\n format.js\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @enrollment.errors, :status => :unprocessable_entity }\n format.js\n end\n end\n end", "def update\n respond_to do |format|\n if @education.update(education_params)\n format.html { redirect_to @education, notice: \"Education was successfully updated.\" }\n format.json { render :show, status: :ok, location: @education }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @education.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @education = Education.find(params[:id])\n if params[:education][:accomplishment][\"0\"] != \"\"\n if @education.update(education_params)\n @education.education_accomplishment.delete_all\n params[:education][:accomplishment].each do |i, acc|\n EducationAccomplishment.create(description: acc, education_id: @education.id)\n end\n redirect_to '/'\n else\n redirect_to :back, flash: {alert: @education.errors.full_messages}\n end\n else\n redirect_to :back, flash: {alert: \"Must have at least one accomplishment\"}\n end\n end", "def update\n @enrolled_student = EnrolledStudent.find(params[:id])\n\n respond_to do |format|\n if @enrolled_student.update_attributes(params[:enrolled_student])\n format.html { redirect_to @enrolled_student, notice: 'Enrolled student was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @enrolled_student.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @roll = Roll.find(params[:id])\n\n respond_to do |format|\n if @roll.update_attributes(params[:roll])\n format.html { redirect_to @roll, notice: 'Roll was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @roll.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @trip_enrollment = TripEnrollment.find(params[:id])\n\n respond_to do |format|\n if @trip_enrollment.update_attributes(params[:trip_enrollment])\n flash[:notice] = 'TripEnrollment was successfully updated.'\n format.html { redirect_to(@trip_enrollment) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @trip_enrollment.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @encouragement.update(encouragement_params)\n format.html { redirect_to admin_encouragements_path, notice: 'Encouragement was successfully updated.' }\n format.json { render :show, status: :ok, location: @encouragement }\n else\n format.html { render :edit }\n format.json { render json: @encouragement.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @employer_liability_insurance.update(employer_liability_insurance_params)\n # format.html { redirect_to @employer_liability_insurance, notice: 'Accident insurance was successfully updated.' }\n format.html { redirect_to insurances_url, notice: 'Insurance was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @employer_liability_insurance.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @entertainment.update(entertainment_params)\n format.html { redirect_to @entertainment, notice: 'Entertainment was successfully updated.' }\n format.json { render :show, status: :ok, location: @entertainment }\n else\n format.html { render :edit }\n format.json { render json: @entertainment.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @enrollment.update(attended: @enrollment.set_attended)\n format.html { redirect_to @enrollment.training_session }\n format.json { render :show, status: :ok, location: @enrollment }\n format.js\n else\n format.html { redirect_to training_sessions_path, notice: @enrollment.errors }\n format.json { render json: @enrollment.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @education_level = EducationLevel.find(params[:id])\n\n respond_to do |format|\n if @education_level.update_attributes(params[:education_level])\n format.html { redirect_to @education_level, :notice => t('controllermessage.update') }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @education_level.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @assessment_course = AssessmentCourse.find(params[:id])\n\n respond_to do |format|\n if @assessment_course.update_attributes(params[:assessment_course])\n format.html { redirect_to @assessment_course, notice: 'Assessment course was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @assessment_course.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @assessment.update(assessment_params)\n format.html { redirect_to @assessment, notice: 'Assessment was successfully updated.' }\n format.json { render :show, status: :ok, location: @assessment }\n else\n format.html { render :edit }\n format.json { render json: @assessment.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @assessment.update(assessment_params)\n format.html { redirect_to @assessment, notice: 'Assessment was successfully updated.' }\n format.json { render :show, status: :ok, location: @assessment }\n else\n format.html { render :edit }\n format.json { render json: @assessment.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @education_entry.update(education_entry_params)\n format.html { redirect_to @education_entry, notice: 'Education entry was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @education_entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def destroy\n @enroll = Enroll.find(params[:id])\n @enroll.destroy\n\n respond_to do |format|\n format.html { redirect_to enrolls_url }\n format.json { head :no_content }\n end\n end", "def create \n if current_user && current_user.university_id\n begin \n params[:enrollment][:user_id] = current_user.id \n params[:enrollment][:university_id] = current_user.university_id\n @enrollment = Enrollment.renew( params[:enrollment] )\n render :show\n rescue \n render json: {error: \"Enrollment not created.\"}\n end\n else\n render json: {error: \"Enrollment not created.\"}\n end\n end", "def update\n @entrant = Entrant.find(params[:id])\n\n respond_to do |format|\n if @entrant.update_attributes(params[:entrant])\n format.html { redirect_to @entrant, notice: 'Entrant was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @entrant.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @api_v1_initiative.update(api_v1_initiative_params)\n format.html { redirect_to @api_v1_initiative, notice: 'Initiative was successfully updated.' }\n format.json { render :show, status: :ok, location: @api_v1_initiative }\n else\n format.html { render :edit }\n format.json { render json: @api_v1_initiative.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @entrant = Entrant.find(params[:id])\n\n respond_to do |format|\n if @entrant.update_attributes(params[:entrant])\n format.html { redirect_to @entrant, notice: 'Entrant was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @entrant.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @enrolled_course.update(enrolled_course_params)\n format.html { redirect_to @enrolled_course, notice: 'Enrolled course was successfully updated.' }\n format.json { render :show, status: :ok, location: @enrolled_course }\n else\n format.html { render :edit }\n format.json { render json: @enrolled_course.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @acquirement = Acquirement.find(params[:id])\n\n respond_to do |format|\n if @acquirement.update_attributes(params[:acquirement])\n format.html { redirect_to @acquirement, notice: 'Acquirement was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @acquirement.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @instructor = Instructor.find(params[:id])\n render :action => :edit unless @instructor.update_attributes(params[:instructor])\n \n end", "def update\n @elector = Elector.find(params[:id])\n\n if @elector.update(elector_params)\n head :no_content\n else\n render json: @elector.errors, status: :unprocessable_entity\n end\n end", "def update\n @employe = Employe.find(params[:id])\n\n respond_to do |format|\n if @employe.update_attributes(params[:employe])\n format.html { redirect_to @employe, notice: 'Employe was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @employe.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @enrollment = Enrollment.new(enrollment_params)\n\n respond_to do |format|\n if @enrollment.save\n format.html { redirect_to [:admin, @enrollment], notice: 'enrollment was successfully created.' }\n format.json { render :show, status: :created, location: @enrollment }\n else\n format.html { render :new }\n format.json { render json: @enrollment.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @enrollment = Enrollment.new(enrollment_params)\n\n respond_to do |format|\n if @enrollment.save\n format.html { redirect_to @enrollment, notice: 'Enrollment was successfully created.' }\n format.json { render :show, status: :created, location: @enrollment }\n else\n format.html { render :new }\n format.json { render json: @enrollment.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @enrollment = Enrollment.new(enrollment_params)\n\n respond_to do |format|\n if @enrollment.save\n format.html { redirect_to @enrollment, notice: 'Enrollment was successfully created.' }\n format.json { render :show, status: :created, location: @enrollment }\n else\n format.html { render :new }\n format.json { render json: @enrollment.errors, status: :unprocessable_entity }\n end\n end\n end" ]
[ "0.7461845", "0.7149237", "0.7149237", "0.6986249", "0.6958556", "0.6883756", "0.6880892", "0.6805591", "0.6805591", "0.6805591", "0.6805591", "0.6759934", "0.6695068", "0.6677743", "0.6677743", "0.6677743", "0.6677743", "0.6677743", "0.6648709", "0.65927005", "0.6553545", "0.6494736", "0.6434392", "0.6399066", "0.6396544", "0.63682234", "0.63491625", "0.63456494", "0.6338043", "0.6306066", "0.6306066", "0.63047206", "0.6301716", "0.6292439", "0.6263483", "0.6257534", "0.6251281", "0.623517", "0.623517", "0.623517", "0.623517", "0.623517", "0.623517", "0.623517", "0.623517", "0.623517", "0.623517", "0.6230471", "0.6198069", "0.6185232", "0.6154529", "0.6149145", "0.61089087", "0.6090357", "0.60864896", "0.6081801", "0.6069259", "0.60631937", "0.60614693", "0.60408926", "0.6034523", "0.6015293", "0.60148257", "0.60087943", "0.59975874", "0.5992146", "0.5975151", "0.5967428", "0.5964855", "0.5950305", "0.5930005", "0.5928843", "0.5925428", "0.5920824", "0.5916692", "0.59104484", "0.59018433", "0.5891914", "0.5890688", "0.58846396", "0.58819944", "0.58790845", "0.58644134", "0.58584696", "0.5855799", "0.5855799", "0.5852521", "0.5850037", "0.5849661", "0.5849491", "0.5842153", "0.5838552", "0.5828247", "0.58273333", "0.58264804", "0.58216584", "0.5811731", "0.58084893", "0.58075064", "0.58075064" ]
0.5955725
69
DELETE /enrollments/1 DELETE /enrollments/1.json
def destroy @enrollment.destroy respond_to do |format| format.html { redirect_to business_membership_url(@business, @membership) } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n @enroll = Enroll.find(params[:id])\n @enroll.destroy\n\n respond_to do |format|\n format.html { redirect_to enrolls_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @enroll = Enroll.find(params[:id])\n @enroll.destroy\n render json: JSON.parse({msg:\"success\"}.to_json)\n end", "def destroy\n @enrollment.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @enrollment = Enrollment.find(params[:id])\n @enrollment.destroy\n\n respond_to do |format|\n format.html { redirect_to enrollments_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @enroll.destroy\n respond_to do |format|\n format.html { redirect_to enrolls_path, notice: 'Test was successfully destroyed.' }\n format.json { head :no_enroll }\n end\n end", "def destroy\n @enroll.destroy\n respond_to do |format|\n format.html { redirect_to enrolls_url, notice: 'Enroll was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @enrollment.destroy\n respond_to do |format|\n format.html { redirect_to enrollments_url, notice: 'Enrollment was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @enrollment.destroy\n respond_to do |format|\n format.html { redirect_to enrollments_url, notice: 'Enrollment was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @enrollment.destroy\n respond_to do |format|\n format.html { redirect_to enrollments_url, notice: 'Enrollment was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @enrollment.destroy\n respond_to do |format|\n format.html { redirect_to enrollments_url, notice: 'Enrollment was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @enrollment.destroy\n respond_to do |format|\n format.html { redirect_to enrollments_url, notice: 'Enrollment was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @enrollment.destroy\n respond_to do |format|\n format.html { redirect_to admin_enrollments_url, notice: 'enrollment was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @enrollment.destroy\n respond_to do |format|\n format.html { redirect_to enrollments_url, notice: 'Matrícula excluída com sucesso.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @enrollment = Enrollment.find(params[:id])\n @enrollment.delete\n end", "def destroy\n @enrollment.destroy\n\n head :no_content\n end", "def destroy \n if @enrollment && @enrollment.destroy \n render json: {success: \"Delete Successfully.\"}, status: 200\n else\n render json: {error: \"Enrollment not deleted.\"}\n end \n end", "def destroy\n admin_only\n @consuming_enrollment.destroy\n respond_to do |format|\n format.html { redirect_to consuming_enrollments_url, notice: 'Consuming enrollment was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @enrollment = Enrollment.find(params[:id])\n @enrollment.destroy\n\n respond_to do |format|\n format.html { redirect_to(enrollment_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @enrollment.destroy\n respond_to do |format|\n format.html { redirect_to '/students', notice: 'La Cursada se borró exitosamente.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @enrollment = Enrollment.shard_for( params[:classroom_id] ).find(params[:id])\n @enrollment.destroy\n\n respond_to do |format|\n format.html { redirect_to enrollments_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @pre_enrollment.destroy\n respond_to do |format|\n format.html { redirect_to pre_enrollments_url, notice: 'Pre enrollment was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @instructor1 = Instructor1.find(params[:id])\n @instructor1.destroy\n\n respond_to do |format|\n format.html { redirect_to instructor1s_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @enrollment_ta.destroy\n respond_to do |format|\n format.html { redirect_to enrollment_tas_url, notice: 'Enrollment ta was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @enrolled = Enrolled.find(params[:id])\n @enrolled.destroy\n\n respond_to do |format|\n format.html { redirect_to enrolleds_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @enrolment.destroy\n respond_to do |format|\n format.html { redirect_to enrolments_url, notice: \"Enrolment was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def delete\n render json: Alien.delete(params[\"id\"])\n end", "def destroy\n @education_level = EducationLevel.find(params[:id])\n @education_level.destroy\n\n respond_to do |format|\n format.html { redirect_to education_levels_url, :notice => t('controllermessage.delete') }\n format.json { head :no_content }\n end\n end", "def destroy\n @lease = Lease.find(params[:id])\n @lease.destroy\n\n respond_to do |format|\n format.html { redirect_to leases_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @education_entry.destroy\n respond_to do |format|\n format.html { redirect_to education_entries_url }\n format.json { head :no_content }\n end\n end", "def destroy\n current_user.enrollments.where(course_id: @course.id).first.destroy\n @course.destroy\n respond_to do |format|\n format.html { redirect_to dashboard_url, :flash => { :success => 'Course was successfully deleted.' } }\n format.json { head :no_content }\n end\n end", "def destroy\n @education_accomplishment.destroy\n respond_to do |format|\n format.html { redirect_to education_accomplishments_url, notice: 'Education accomplishment was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @instructor = Instructor.find(params[:id])\n @instructor.destroy\n\n respond_to do |format|\n format.html { redirect_to instructores_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @education.destroy\n respond_to do |format|\n format.html { redirect_to educations_url, notice: 'Education was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @education.destroy\n respond_to do |format|\n format.html { redirect_to educations_url, notice: 'Education was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @education.destroy\n respond_to do |format|\n format.html { redirect_to educations_url, notice: \"Education was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @exprience = Exprience.find(params[:id])\n @exprience.destroy\n\n respond_to do |format|\n format.html { redirect_to expriences_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @trip_enrollment = TripEnrollment.find(params[:id])\n @trip_enrollment.destroy\n\n respond_to do |format|\n format.html { redirect_to(trip_enrollments_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @instructor = Instructor.find(params[:id])\n @instructor.destroy\n\n respond_to do |format|\n format.html { redirect_to instructors_url }\n format.json { head :ok }\n end\n end", "def destroy\n @referral_enrolment.destroy\n respond_to do |format|\n format.html { redirect_to referral_enrolments_url, notice: 'Referral enrolment was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @education_level.destroy\n respond_to do |format|\n format.html { redirect_to education_levels_url, notice: 'Education level was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @lease.destroy\n respond_to do |format|\n format.html { redirect_to leases_url, notice: 'Lease was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @employer_liability_insurance.destroy\n respond_to do |format|\n format.html { redirect_to employer_liability_insurances_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @assessment.destroy\n respond_to do |format|\n format.html { redirect_to assessments_url, notice: 'Assessment was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @assessment.destroy\n respond_to do |format|\n format.html { redirect_to assessments_url, notice: 'Assessment was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @assessment.destroy\n respond_to do |format|\n format.html { redirect_to assessments_url, notice: 'Assessment was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @admission.destroy\n respond_to do |format|\n format.html { redirect_to admissions_url, notice: 'Admission was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete\n client.delete(\"/#{id}\")\n end", "def destroy\n @assessment = Assessment.find(params[:id])\n @assessment.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 @agreement_renewal.destroy\n respond_to do |format|\n format.html { redirect_to agreement_renewals_url, notice: 'Agreement renewal was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @life_insurance.destroy\n\n respond_to do |format|\n format.html { redirect_to life_insurances_url }\n format.json { head :no_content }\n end\n end", "def destroy\n authorize @lease\n @lease.destroy\n respond_to do |format|\n format.html { redirect_to leases_url, notice: 'Lease was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @ailment.destroy\n respond_to do |format|\n format.html { redirect_to ailments_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @ledger.destroy\n respond_to do |format|\n format.html { redirect_to ledgers_url, notice: 'Ledger was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @ledger.destroy\n respond_to do |format|\n format.html { redirect_to ledgers_url, notice: 'Ledger was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @enrolled_student = EnrolledStudent.find(params[:id])\n @enrolled_student.destroy\n\n respond_to do |format|\n format.html { redirect_to enrolled_students_url }\n format.json { head :ok }\n end\n end", "def destroy\n @enrollement.destroy\n respond_to do |format|\n format.html { redirect_to enrollements_url, notice: \"Enrollement was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @assessment = @department.assessments.find(params[:id])\n @assessment.destroy\n respond_to do |format|\n flash[:notice] = \"Aspek Penilaian berhasil dihapus, #{undo_link(@assessments)}\"\n format.html { redirect_to assessments_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @encouragement.destroy\n respond_to do |format|\n format.html { redirect_to admin_encouragements_url, notice: 'Encouragement was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @life_insurance.destroy\n respond_to do |format|\n format.html { redirect_to life_insurances_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @admission.destroy\n respond_to do |format|\n format.html { redirect_to admissions_url, notice: 'Admission information was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @assessment = Assessment.find(params[:id])\n authorize! :destroy, @assessment\n\n @assessment.destroy\n\n respond_to do |format|\n format.html { redirect_to assessments_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @acquirement = Acquirement.find(params[:id])\n @acquirement.destroy\n\n respond_to do |format|\n format.html { redirect_to acquirements_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @enrollment = Enrollment.find(params[:id])\n student = @enrollment.student\n course_id = @enrollment.course_id\n @enrollment.destroy\n\n respond_to do |format|\n flash[:notice] = student.name_first_last + ' unenrolled'\n format.html { redirect_to course_url(course_id) }\n format.xml { head :ok }\n end\n end", "def destroy\n @oncourse_exercise.destroy\n respond_to do |format|\n format.html { redirect_to oncourse_exercises_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @agreement.destroy\n respond_to do |format|\n format.html { redirect_to agreements_url, notice: 'Agreement was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @enrollment=Enrollment.find(params[:id])\n if @enrollment.present?\n @enrollment.destroy\n end\n redirect_to request.referrer\n end", "def destroy\n @edu_detail = EduDetail.find(params[:id])\n @edu_detail.destroy\n\n respond_to do |format|\n format.html { redirect_to edu_details_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @instructor.destroy\n respond_to do |format|\n format.html { redirect_to instructors_url, notice: 'Instructor was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @instructor.destroy\n respond_to do |format|\n format.html { redirect_to instructors_url, notice: 'Instructor was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @assessment.destroy\n respond_to do |format|\n format.html { redirect_to course_assessments_url(@course), notice: 'Attempt was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @assessment.destroy\n respond_to do |format|\n format.html { redirect_to course_assessments_url(@course), notice: 'Attempt was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @api_v1_exercise.destroy\n respond_to do |format|\n format.html { redirect_to api_v1_exercises_url, notice: 'Exercise was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @education_detail.destroy\n respond_to do |format|\n format.html { redirect_to education_details_url, notice: 'Education detail was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @educate.destroy\n respond_to do |format|\n format.html { redirect_to educates_url, notice: 'Educate was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @first_aid_course = FirstAidCourse.find(params[:id])\n @first_aid_course.destroy\n\n respond_to do |format|\n format.html { redirect_to first_aid_courses_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @employe = Employe.find(params[:id])\n @employe.destroy\n\n respond_to do |format|\n format.html { redirect_to employes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @tenancy_agreement = TenancyAgreement.find(params[:id])\n @tenancy_agreement.destroy\n\n respond_to do |format|\n format.html { redirect_to tenancy_agreements_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @exalt = Exalt.find(params[:id])\n @exalt.destroy\n\n respond_to do |format|\n format.html { redirect_to exalts_url }\n format.json { head :ok }\n end\n end", "def destroy\n begin\n @course = Course.find(params[:id])\n @student = Student.find(params[:student_id])\n\n if Enrollment.where(course_id: @course.id, student_id: @student.id).count == 0\n render json: {\"message\": \"student is not enrolled in the course\"}\n return\n end\n\n @enrollment = Enrollment.find_by(course_id: @course.id, student_id: @student.id)\n \n if @enrollment.destroy\n render json: {\"message\": \"Student de-enrolled successfully\"}\n else\n render json: {\"message\": \"some server issue\"}\n end\n rescue\n render json: {\"message\": \"Course or Student not found\"}\n end\n end", "def delete_course_by_id(org_unit_id)\n path = \"/d2l/api/lp/#{$lp_ver}/courses/#{org_unit_id}\" # setup user path\n # ap path\n _delete(path)\n puts '[+] Course data deleted successfully'.green\nend", "def destroy\n @enterprise = Enterprise.find(params[:id])\n @enterprise.destroy\n\n respond_to do |format|\n format.html { redirect_to enterprises_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @encuestum = Encuestum.find(params[:id])\n @encuestum.destroy\n\n respond_to do |format|\n format.html { redirect_to encuesta_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @climber_education.destroy\n respond_to do |format|\n format.html { redirect_to climber_educations_url, notice: 'Climber education was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @manage_instructor = Instructor.find(params[:id])\n @manage_instructor.destroy\n\n respond_to do |format|\n format.html { redirect_to manage_instructors_url }\n format.json { head :ok }\n end\n end", "def destroy\n @education = @resume.educations.find(params[:id])\n @education.destroy\n\n respond_to do |format|\n format.html { redirect_to(edit_resume_path(@resume)) }\n format.xml { head :ok }\n end\n end", "def destroy\n @itenary.destroy\n respond_to do |format|\n format.html { redirect_to itenaries_url, notice: 'Itenary was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @entrant = Entrant.find(params[:id])\n @entrant.destroy\n\n respond_to do |format|\n format.html { redirect_to entrants_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @annex = Annex.find(params[:id])\n @annex.destroy\n\n respond_to do |format|\n format.html { redirect_to annexes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @educational_level = EducationalLevel.find(params[:id])\n @educational_level.destroy\n\n respond_to do |format|\n format.html { redirect_to educational_levels_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @claimant = Claimant.find(params[:id])\n @claimant.destroy\n\n respond_to do |format|\n format.html { redirect_to claimants_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @entrant = Entrant.find(params[:id])\n @entrant.destroy\n\n respond_to do |format|\n format.html { redirect_to entrants_url }\n format.json { head :ok }\n end\n end", "def destroy\n @enrolled_course.destroy\n respond_to do |format|\n format.html { redirect_to enrolled_courses_url, notice: 'Enrolled course was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete\n\t\trender json: Investor.delete_by_id(params[:id])\n\tend", "def destroy\n @advancement = Advancement.find(params[:id])\n @advancement.destroy\n\n respond_to do |format|\n format.html { redirect_to advancements_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @assessment = Assessment.find(params[:id])\n @assessment.destroy\n \n respond_to do |format|\n format.html { redirect_to(assessments_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @announcement = Announcement.find(params[:id])\n @announcement.destroy\n render json:@announcement\n\n end", "def destroy\n @investigated.destroy\n respond_to do |format| \n format.json { head :no_content }\n end\n end", "def destroy\n @health_insurance.destroy\n respond_to do |format|\n format.html { redirect_to health_insurances_url, notice: 'Health insurance was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @education = Education.where(:resource_id => current_user.id, :id => params[:id]).first\n @education.destory\n\n respond_to do |format|\n format.html { redirect_to(educations_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @employe.destroy\n respond_to do |format|\n format.html { redirect_to employes_path(api_id: @employe.organisme_id), notice: 'Employe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end" ]
[ "0.7878989", "0.7807575", "0.7752044", "0.7749885", "0.75889903", "0.7575885", "0.7510936", "0.7510936", "0.7510936", "0.7510936", "0.7510936", "0.74598867", "0.7427407", "0.7404994", "0.73979115", "0.73262525", "0.72354174", "0.71959776", "0.71811384", "0.7150566", "0.71188104", "0.7000409", "0.6977181", "0.6961701", "0.6939282", "0.6928756", "0.6927809", "0.6927059", "0.69029945", "0.6893816", "0.6867595", "0.6825365", "0.6814122", "0.6814122", "0.68134993", "0.6813345", "0.6804528", "0.6797446", "0.67857385", "0.67800546", "0.67758816", "0.67714214", "0.6765036", "0.6765036", "0.6765036", "0.6744213", "0.6724701", "0.67214566", "0.67133796", "0.6710645", "0.670727", "0.67052513", "0.6704601", "0.6704601", "0.66983503", "0.6696363", "0.66956455", "0.6693005", "0.66929257", "0.66793525", "0.6676006", "0.66750616", "0.66687864", "0.66592205", "0.66589236", "0.6658052", "0.6657369", "0.66548914", "0.66548914", "0.6650513", "0.6650513", "0.6648976", "0.66480505", "0.6642046", "0.6632702", "0.66270596", "0.6623698", "0.66204125", "0.6615374", "0.6607921", "0.65997475", "0.6597963", "0.65979445", "0.65970695", "0.65950286", "0.65922624", "0.65912586", "0.6588447", "0.65863705", "0.65846694", "0.6581338", "0.6568134", "0.65677106", "0.656667", "0.6565455", "0.6559882", "0.6556652", "0.6553735", "0.6553244", "0.65528256" ]
0.672684
46
Function created to help break down multiplication of the roman numeral and divided number(from dividing the key and number being tested)
def mult(x,y) x * y end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def convertToRoman(n)\n #divide by roman num taken out\n #num is remainder \n #repeat\n roman = { 1000 => \"M\", 900 => \"CM\", 500 => \"D\", 400 => \"CD\", 100 => \"C\", 90 => \"XC\", 50 => \"L\", 40 => \"XL\", 10 => \"X\", 9 => \"IX\", 5 => \"V\", 4 => \"IV\", 1 => \"I\" }\n\n ans = \"\"\n roman.keys.each do |divisor|\n quotient, modulus = n.divmod(divisor)\n ans << roman[divisor] * quotient\n n = modulus\n end\n return ans \nend", "def roman_numeral(num)\n digits = [[1000, 500, 100, 50, 10, 5, 1], [0, 0, 0, 0, 0, 0, 0], ['M','D','C','L','X','V','I']]\n answer = ' '\n h = 0\n \n digits[0].each do |z|\n if num / z > 0\n digits[1][h] = (num / z) #Counting the number of 10s, 50s, 100s, etc in num\n num = num % z #Using the remainder as the next value of num\n end\n h += 1\n end\n \n for a in 0..digits[1].size - 1 do #Iterate through array to calculate roman numerals old school style\n answer << digits[2][a] * digits[1][a]\n answer = answer.gsub(\"DCCCC\",\"CM\").gsub(\"CCCC\",\"CD\").gsub(\"LXXXX\",\"XC\").gsub(\"XXXX\",\"XL\").gsub(\"VIIII\",\"IX\").gsub(\"IIII\",\"IV\") #Catching edge cases to update old school roman numeral\n end\n\n answer.strip\nend", "def roman_numerals(number)\n\n puts (\"M\" * (number/1000)).to_s\n if ((number%1000)%500) == 0\n puts (\"D\" * (number%1000/500)).to_s\n if ((number%500)%100) == 0\n puts (\"C\" * (number%500/100)).to_s\n if ((number%100)%50) == 0\n puts (\"L\" * (number%100/50)).to_s\n if ((number%50)%10) == 0\n puts (\"X\" * (number%50/10)).to_s\n if ((number%10)%5) == 0\n puts (\"V\" * (number%10/5)).to_s\n if ((number%5)%1)) == 0\n puts (\"I\" * (number%5/1)).to_s\n end\n end\n end\n end\n end\n end\n\n\nend", "def to_roman2(num)\n result = \"\"\n \n @roman_mapping.each do |pair|\n value = pair[0]\n roman = pair[1]\n division_result = num / value\n result += roman * division_result\n num = num - (value * division_result)\n end\n return result\nend", "def to_roman\n result = ''\n number = self\n ROMAN_NUMERALS.each do |key, value|\n numeral, remainder = number.divmod(value)\n if numeral > 0 \n result += (key * numeral)\n end\n number = remainder\n end\n result\n end", "def old_school_roman_numeral(num)\n arabs_to_romans = [\n ['M', 1000],\n ['D', 500],\n ['C', 100],\n ['L', 50],\n ['X', 10],\n ['V', 5],\n ['I', 1]\n ]\n\n result = ''\n\n arabs_to_romans.each do |arab_to_roman|\n arab = arab_to_roman[1]\n roman = arab_to_roman[0]\n\n if num / arab != 0\n result += roman * (num / arab)\n num = num % arab\n end\n end\n result\nend", "def to_roman2 number\t\r\n\t@roman = ''\r\n\tmarker = ['I','V','X','L','C','D','M']\r\n\t(0..Math.log10(number).to_i).each do |i|\r\n\t\tputs i\r\n\t\t@unit_number = (number % (10^(i+1)))/10^i\r\n\t\tputs @unit_number\t\r\n\t\t@roman = @roman + show_power_of_ten(@unit_number,marker[2*i+2],marker[2*i+1],marker[2*i])\t\r\n\tend\r\n\[email protected]\r\nend", "def roman_numeral num\r\n\r\n\tthous = (num \t\t\t/ 1000)\r\n\thunds = (num \t% 1000 \t/ 100)\r\n\ttens = (num \t% 100 \t/ 10)\r\n\tones = (num \t% \t\t\t10)\r\n\r\n\troman = 'M' * thous\r\n\r\nend", "def numeralise!(num, ans=\"\", mapping = roman_mapping)\n return ans if num == 0\n \n mapping.keys.each do |key_num|\n next unless key_num <= num\n quotient, modulus = num.divmod(key_num)\n ans << (mapping[key_num] * quotient)\n return numeralise!(modulus, ans) if quotient > 0\n end\nend", "def old_roman_numeral num\n working_num = num\n roman_val = ''\n \n numeral_ref = [[1, 'I'],\n [5, 'V'],\n [10, 'X'],\n [50, 'L'],\n [100, 'C'],\n [500, 'D'],\n [1000, 'M']]\n \n (0...numeral_ref.length).reverse_each { |i|\n if working_num >= numeral_ref[i][0]\n mult = working_num/numeral_ref[i][0]\n roman_val += numeral_ref[i][1]*(mult)\n working_num %= numeral_ref[i][0]\n end\n }\n roman_val\nend", "def calculate_multiple(number, decimal)\n # for 522 => number = 5, decimal = 100.\n # number = 2, decimal = 10\n # number = 2, decimal = 1\n\n # below both cases we do not utilize number field\n # 44 is different -> 40, 4 -> XLIV (10 - 50, 1 - 5)\n # 99 is different -> 90, 9 -> XCIX (10 - 90, 1 - 9)\n case number\n when 0\n ''\n when (1..3)\n @roman_hash[decimal] * number\n when 4\n @roman_hash[decimal] + @roman_hash[decimal * 5]\n when 5\n @roman_hash[5 * decimal]\n when 6..8\n @roman_hash[5 * decimal] + (@roman_hash[decimal] * (number - 5))\n when 9\n @roman_hash[decimal] + @roman_hash[decimal * 10]\n else\n 'Quit'\n end\n end", "def solution(number)\n\nm, r_1 = number.divmod(1000)\ncd, r_2 = r_1.divmod(100)\nlx, r_3 = r_2.divmod(10)\nvi, r_4 = r_3.divmod(1)\n\nroman = []\n\nm.times { roman << \"M\" }\n\nif cd <= 3\n\tcd.times { roman << \"C\" }\nelsif cd == 4\n\troman << \"CD\"\nelsif cd == 5\n\troman << \"D\"\nelsif cd > 5 && cd < 9\n\troman << \"D\"\n\t(cd - 5).times { roman << \"C\" }\nelsif cd == 9\n\troman << \"CM\"\nend\n\nif lx <= 3\n\tlx.times { roman << \"X\" }\nelsif lx == 4\n\troman << \"XL\"\nelsif lx == 5\n\troman << \"L\"\nelsif lx > 5 && lx < 9\n\troman << \"L\"\n\t(lx - 5).times { roman << \"X\" }\nelsif lx == 9\n\troman << \"XC\"\nend\n\nif vi <= 3\n\tvi.times { roman << \"I\" }\nelsif vi == 4\n\troman << \"IV\"\nelsif vi == 5\n\troman << \"V\"\nelsif vi > 5 && vi < 9\n\troman << \"V\"\n\t(vi - 5).times { roman << \"I\" }\nelsif vi == 9\n\troman << \"IX\"\nend\n\nroman.join\n\nend", "def old_roman_numeral(num)\n\t@romanNumeral = \"\"\t\n\n\twhile num > 0\n\t\tquotient, modulus = num.divmod(1000)\n\t\t\tif quotient > 0 \t\t\t\t\t\t\t\t\t\t#using a divisor \n\t\t\t@romanNumeral << (\"M\" * quotient) #using divisor again\n\t\t\tnum = modulus\t\t\t\t\t\t\t\t\t\t\t\t#using modulus\n\t\telsif\n\t\t\tnum / 500 > 0\n\t\t\t@romanNumeral << (\"D\" * (num/500))\n\t\t\tnum %= 500\n\t\telsif\n\t\t\tif num / 100 > 0\n\t\t\t\t@romanNumeral << (\"C\" * (num/100))\n\t\t\t\tnum %= 100\n\t\t\telsif \n\t\t\t\tnum / 90 > 0 \n\t\t\t\t@romanNumeral << (\"XC\" * (num/90))\n\t\t\t\tnum %= 90\n\t\t\tend\n\t\telsif\n\t\t\tif num / 50 > 0\n\t\t\t@romanNumeral << (\"L\" * (num/50))\n\t\t\tnum %= 50\n\t\t\telsif \n\t\t\t\tnum / 40 > 0\n\t\t\t\t@romanNumeral << (\"XL\" * (num/40))\n\t\t\t\tnum %= 40 \t\t\t\n\t\t\tend\n\t\telsif\n\t\t\tif num / 10 > 0\n\t\t\t\t@romanNumeral << (\"X\" * (num/10))\n\t\t\t\tnum %= 10\n\t\t\telsif\n\t\t\t\tnum / 9 > 0\n\t\t\t\t@romanNumeral << (\"IX\" * (num/9))\n\t\t\t\tnum %= 9 \n\t\t\tend\n\t\telsif\n\t\t\tnum / 5 > 0\n\t\t\t@romanNumeral << (\"V\" * (num/5))\n\t\t\tnum %= 5\n\t\telse\n\t\t\tif\n\t\t\t\tnum / 4 > 0 \n\t\t\t\t@romanNumeral << (\"I\" * (num/4))\n\t\t\t\tnum %= 4\n\t\t\telse\n\t\t\t\tnum / 1 > 0 \n\t\t\t\t@romanNumeral << (\"I\" * (num/1))\n\t\t\t\tnum %= 1\n\t\t\tend\t\n\t\tend\n\tend\n\n\t@romanNumeral\n\nend", "def roman_numeral num\n\n number1000s = (num / 1000)\n number100s = (num % 1000) / 100\n number10s = (num % 100) / 10\n number1s = (num % 10) / 1\n\n numberDs = (num % 1000) / 500\n numberCs = (num % 500) / 100\n numberLs = (num % 100) / 50\n numberXs = (num % 50) / 10\n numberVs = (num % 10) / 5\n numberIs = (num % 5) / 1\n\n result = \"M\" * number1000s\n\n if number100s == 9\n result = result + \"CM\"\n elsif number100s == 4\n result = result + \"CD\"\n else\n result = result + \"D\" * numberDs\n result = result + \"C\" * numberCs\n end\n\n if number10s == 9\n result = result + \"XC\"\n elsif number10s == 4\n result = result + \"XL\"\n else\n result = result + \"L\" * numberLs\n result = result + \"X\" * numberXs\n end\n\n if number1s == 9\n result = result + \"IX\"\n elsif number1s == 4\n result = result + \"IV\"\n else\n result = result + \"V\" * numberVs\n result = result + \"I\" * numberIs\n end\n\n result\n\nend", "def roman (remainder, digit)\r\n if remainder < digit # ie you do not have any of this roman letter\r\n x = nil.to_i\r\n else\r\n x = remainder / digit\r\n end\r\n\r\n y = remainder % digit\r\n\r\n return [x,y]\r\nend", "def old_school_roman_numerial number\n roman = ''\n\n # 1000\n roman << \"M\" * (number / 1000)\n # 500\n roman << \"D\" * (number % 1000 / 500)\n # 100\n roman << \"C\" * (number % 1000 % 500 / 100)\n # 50\n roman << \"L\" * (number % 1000 % 500 % 100 / 50)\n # 10\n roman << \"X\" * (number % 1000 % 500 % 100 % 50 / 10)\n # 5\n roman << \"V\" * (number % 1000 % 500 % 100 % 50 % 10 / 5)\n # 1\n roman << \"I\" * (number % 1000 % 500 % 100 % 50 % 10 % 5 / 1)\n\n puts roman\nend", "def roman_numeral num\n working_num = num\n roman_val = ''\n \n # [number value, roman value, index of its modifier (if any)]\n numeral_ref = [[1, 'I'], #0\n [5, 'V', 0],\n [10, 'X', 0], #2\n [50, 'L', 2],\n [100, 'C', 2], # 4\n [500, 'D', 4],\n [1000, 'M', 4]] #6\n \n (0...numeral_ref.length).reverse_each { |i|\n \n ref_num = numeral_ref[i][0]\n ref_rom = numeral_ref[i][1]\n ref_mod_i = numeral_ref[i][2]\n ref_mod_num = ref_mod_i ? numeral_ref[ref_mod_i][0] : 0\n ref_mod_rom = ref_mod_i ? numeral_ref[ref_mod_i][1] : ''\n \n if working_num >= ref_num # The 'normal' case\n mult = working_num/ref_num\n roman_val += ref_rom*(mult)\n working_num %= ref_num\n end\n if working_num >= (ref_num - ref_mod_num) # The 'subtraction case'\n roman_val += ref_mod_rom+ref_rom\n working_num -= (ref_num - ref_mod_num)\n end\n \n }\n roman_val\nend", "def new_roman_numeral num\n number = \"\"\n if (num / 1000) > 0\n number = \"M\" * (num / 1000)\n end\n if (num % 1000) >= 900 \n number += \"CM\"\n end\n if (num % 1000) >= 500 && (num % 1000) < 900\n number += \"D\"\n end\n if (num % 1000) >= 400 && (num % 1000) < 500\n number += \"CD\"\n end\n if ((num % 1000) % 500) >= 100 && ((num % 1000) % 500) < 400\n number += \"C\" * (((num % 1000) % 500) / 100)\n end\n if (((num % 1000) % 500) % 100) >= 90\n number += \"XC\"\n end\n if (((num % 1000) % 500) % 100) >= 50 && (((num % 1000) % 500) % 100) < 90\n number += \"L\"\n end\n if (((num % 1000) % 500) % 100) >= 40 && (((num % 1000) % 500) % 100) < 50\n number += \"XL\"\n end\n if (((num % 1000) % 500) % 50) >= 10 && (((num % 1000) % 500) % 50) < 40\n number += \"X\" * ((((num % 1000) % 500) % 50) / 10)\n end\n if ((((num % 1000) % 500) % 50) % 10) == 9\n number += \"IX\"\n end\n if ((((num % 1000) % 500) % 50) % 10) >= 5 && ((((num % 1000) % 500) % 50) % 10) < 9\n number += \"V\" + \"I\" * (((((num % 1000) % 500) % 50) % 10) % 5)\n end\n if ((((num % 1000) % 500) % 50) % 10) == 4\n number += \"IV\"\n end\n if ((((num % 1000) % 500) % 50) % 10) < 4\n number += \"I\" * (((((num % 1000) % 500) % 50) % 10) % 5)\n end\n puts number\nend", "def roman number\n\t\nm_length = 0\nd_length = 0\nc_length = 0\nl_length = 0\nx_length = 0\nv_length = 0\ni_length = 0\n\nif number >= 1000\n\tm_length = number/1000\n\tnumber = number%1000\nend\nif number >= 500\n\td_length = number/500\n\tnumber = number%500\nend\nif number >= 100\n\tc_length = number/100\n\tnumber = number%100\nend\nif number >= 50\n\tl_length = number/50\n\tnumber = number%50\nend\nif number >= 10\n\tx_length = number/10\n\tnumber = number%10\nend\nif number >= 5\n\tv_length = number/5\n\tnumber = number%5\nend\nif number < 5\n\ti_length = number/1\n\tnumber = number%10\nend\n\nputs 'M'*m_length + 'D'*d_length + 'C'*c_length + 'L'*l_length + \"X\"*x_length + \"V\"*v_length + \"I\"*i_length\n\nend", "def new_roman_numeral(number)\n \n roman = \"\"\n\n thousands_place = number/1000\n hundreds_place = (number%1000)/100\n tens_place = (number%100)/10\n ones_place = (number%10)\n\n roman << \"M\"*thousands_place\n\n if hundreds_place == 9\n roman << \"CM\"\n elsif hundreds_place == 4\n roman << \"CD\"\n else\n roman = roman << 'D' * (number%1000 /500)\n roman = roman << 'C' * (number%500 /100)\n end\n\n if tens_place == 9\n roman << \"XC\"\n elsif tens_place == 4\n roman << \"XL\"\n else\n roman = roman << 'L' * (number%100 /50)\n roman = roman << 'X' * (number%50 /10)\n end\n\n\n if ones_place == 9\n roman << \"IX\"\n elsif ones_place == 4\n roman << \"IV\"\n else\n roman = roman << 'V' * (number%10 /5)\n roman = roman << 'I' * (number%5)\n end\n \n\n\nend", "def vol_roman\n dict = { M: 1000, CM: 900, D: 500, CD: 400,\n C: 100, XC: 90, L: 50, XL: 40,\n X: 10 , IX: 9, V: 5, IV: 4,\n I: 1 };\n input, output = vol.to_i, ''\n\n # Descend through the character list.\n dict.each_pair do |r, a|\n # Subtract from the input/add to the output until\n # this character is no longer useful.\n while input >= a { input -= a; output << r.to_s }\n end\n \n output\n end\nend", "def roman_numerals number\n roman_numerals = ''\n\n roman_numerals += 'M' * (number / 1000)\n number %= 1000\n\n roman_numerals += 'D' * (number / 500)\n number %= 500\n\n roman_numerals += 'C' * (number / 100)\n number %= 100\n\n roman_numerals += 'L' * (number / 50)\n number %= 50\n\n roman_numerals += 'X' * (number / 10)\n number %= 10\n\n roman_numerals += 'V' * (number / 5)\n number %= 5\n\n roman_numerals += 'I' * (number / 1)\n number %= 1\n\n roman_numerals\nend", "def roman_numeral num\n \n if num >= 1000\n thousands = 'M' * (num / 1000)\n end\n\n # We now account for cases of 400 and 900 (CD, CM, respectively)\n # CCC=300, CD=400, D=500, DCCC=800, CM=900\n if num >= 100\n temp_hundreds = (num % 1000) / 100\n if temp_hundreds == 9\n hundreds = 'CM'\n elsif (temp_hundreds < 9 && temp_hundreds > 5)\n hundreds = 'D' + 'C' * (temp_hundreds - 5)\n elsif temp_hundreds == 5\n hundreds = 'D'\n elsif temp_hundreds == 4\n hundreds = 'CD'\n else\n hundreds = 'C' * temp_hundreds\n end\n end\n \n # We now account for cases of 40 and 90 (XL, XC, respectively)\n # XXX=30, XL=40, L=50, LXXX=80, XC=90\n if num >= 10\n temp_tens = (num % 100) / 10\n if temp_tens == 9\n tens = 'XC'\n elsif (temp_tens < 9 && temp_tens > 5)\n tens = 'L' + 'X' * (temp_tens - 5)\n elsif temp_tens == 5\n tens = 'L'\n elsif temp_tens == 4\n tens = 'XL'\n else\n tens = 'X' * temp_tens\n end\n end\n \n # We now account for cases of 4 and 9 (IV, IX, respectively)\n # III=3, IV=4, V=5, XIII=8, IX=9\n if num > 0\n temp_ones = num % 10\n if temp_ones == 9\n ones = 'IX'\n elsif (temp_ones < 9 && temp_ones > 5)\n ones = 'V' + 'I' * (temp_ones - 5)\n elsif temp_ones == 5\n ones = 'V'\n elsif temp_ones == 4\n ones = 'IV'\n else\n ones = 'I' * temp_ones\n end\n end\n \n puts \"#{num} in \\\"Modern\\\" Roman numerals is \"+\"#{thousands}\"+\"#{hundreds}\"+\"#{tens}\"+\"#{ones}\"\nend", "def old_roman num\r\n\r\n\taux = num\r\n\troman_num = ''\r\n\t\r\n\twhile true\r\n\t\r\n\t\tif((aux / 1000) >= 1)\r\n\t\t\troman_num = roman_num + 'M'\r\n\t\t\taux = aux - 1000\r\n\t\t\tputs aux\r\n\t\telsif ((aux / 500) >= 1)\r\n\t\t\troman_num = roman_num + 'D'\r\n\t\t\taux = aux - 500\t\t\r\n\t\t\tputs aux\r\n\t\telsif((aux / 100) >= 1)\r\n\t\t\troman_num = roman_num + 'C'\r\n\t\t\taux = aux - 100\r\n\t\t\tputs aux\r\n\t\telsif((aux / 50) >= 1)\r\n\t\t\troman_num = roman_num + 'L'\r\n\t\t\taux = aux - 50\r\n\t\t\tputs aux\r\n\t\telsif((aux / 10) >= 1)\r\n\t\t\troman_num = roman_num + 'X'\r\n\t\t\taux = aux - 10\r\n\t\t\tputs aux\r\n\t\telsif((aux / 5) >= 1)\r\n\t\t\troman_num = roman_num + 'V'\r\n\t\t\taux = aux - 5\r\n\t\t\tputs aux\r\n\t\telsif((aux / 1) >= 1)\r\n\t\t\troman_num = roman_num + 'I'\r\n\t\t\taux = aux - 1\r\n\t\t\tputs aux\r\n\t\telse\r\n\t\t\tbreak\t\t\t\r\n\t\tend\r\n\tend\r\n\t\r\n\troman_num\r\nend", "def modern_roman_numeral(num)\n arabs_to_romans = [\n ['M', 1000],\n ['CM', 900],\n ['D', 500],\n ['CD', 400],\n ['C', 100],\n ['XC', 90],\n ['L', 50],\n ['XL', 40],\n ['X', 10],\n ['IX', 9],\n ['V', 5],\n ['IV', 4],\n ['I', 1]\n ]\n\n result = ''\n\n arabs_to_romans.each do |arab_to_roman|\n arab = arab_to_roman[1]\n roman = arab_to_roman[0]\n\n if num / arab != 0\n result += roman * (num / arab)\n num = num % arab\n end\n end\n result\nend", "def roman_numeral roman\n\tnumerals_hash = {\n\t\t\"i\" => 1, \n\t\t\"iv\"=> 4,\n\t\t\"v\" => 5, \n\t\t\"ix\"=> 9,\n\t\t\"x\" => 10, \n\t\t\"xl\" => 40,\n\t\t\"l\" => 50, \n\t\t\"xc\" => 90,\n\t\t\"c\" => 100, \n\t\t\"cd\" => 400,\n\t\t\"d\" => 500, \n\t\t\"cm\" => 900,\n\t\t\"m\" => 1000,\n\t\t}\n\tnumber_array = []\n\n\troman = roman.downcase\n\tinteger =0\n\n\tif roman == \"iv\"\n\t\tinteger = 4\n\telsif\troman.include? \"iv\" \n\t\tinteger += 4\n\t\troman = roman[0..roman.length-3]\n\t\troman_array = roman.downcase.split(//)\n\t\tstop_at = roman_array.length-2\n\t\t\n\t\troman_array.each do |numeral|\n\t\teach_num = numerals_hash[numeral]\n\t\tnumber_array.push each_num\n\t\tend\n\n\t\tstop_at = number_array.length-1\n\n\t\t(0..stop_at).each do |number|\n\t\tinteger += number_array[number]\n\t\tend\n\telsif roman == \"ix\"\n\t\tinteger = 9\n\telsif roman.include? \"ix\"\n\t\tinteger+=9\n\t\troman = roman[0..roman.length-3]\n\t\troman_array = roman.downcase.split(//)\n\t\tstop_at = roman_array.length-2\n\t\t\n\t\troman_array.each do |numeral|\n\t\teach_num = numerals_hash[numeral]\n\t\tnumber_array.push each_num\n\t\tend\n\n\t\tstop_at = number_array.length-1\n\n\t\t(0..stop_at).each do |number|\n\t\tinteger += number_array[number]\n\t\tend\n\telsif roman == \"xl\"\n\t\tinteger = 40\n\telsif roman.include? \"xl\"\n\t\tinteger+=40\n\t\troman = roman[0..roman.length-3]\n\t\troman_array = roman.downcase.split(//)\n\t\tstop_at = roman_array.length-2\n\t\t\n\t\troman_array.each do |numeral|\n\t\teach_num = numerals_hash[numeral]\n\t\tnumber_array.push each_num\n\t\tend\n\n\t\tstop_at = number_array.length-1\n\n\t\t(0..stop_at).each do |number|\n\t\tinteger += number_array[number]\n\t\tend\n\telsif roman == \"xc\"\n\t\tinteger = 90\n\telsif roman.include? \"xc\"\n\t\tinteger+=90\n\t\troman = roman[0..roman.length-3]\n\t\troman_array = roman.downcase.split(//)\n\t\tstop_at = roman_array.length-2\n\t\t\n\t\troman_array.each do |numeral|\n\t\teach_num = numerals_hash[numeral]\n\t\tnumber_array.push each_num\n\t\tend\n\n\t\tstop_at = number_array.length-1\n\n\t\t(0..stop_at).each do |number|\n\t\tinteger += number_array[number]\n\t\tend\n\telsif roman == \"cd\"\n\t\tinteger = 400\n\telsif roman.include? \"cd\"\n\t\tinteger+=400\n\t\troman = roman[0..roman.length-3]\n\t\troman_array = roman.downcase.split(//)\n\t\tstop_at = roman_array.length-2\n\t\t\n\t\troman_array.each do |numeral|\n\t\teach_num = numerals_hash[numeral]\n\t\tnumber_array.push each_num\n\t\tend\n\n\t\tstop_at = number_array.length-1\n\n\t\t(0..stop_at).each do |number|\n\t\tinteger += number_array[number]\n\t\tend\n\telsif roman == \"cm\"\n\t\tinteger = 900\n\telsif roman.include? \"cm\"\n\t\tinteger+=900\n\t\troman = roman[0..roman.length-3]\n\t\troman_array = roman.downcase.split(//)\n\t\tstop_at = roman_array.length-2\n\t\t\n\t\troman_array.each do |numeral|\n\t\teach_num = numerals_hash[numeral]\n\t\tnumber_array.push each_num\n\t\tend\n\n\t\tstop_at = number_array.length-1\n\n\t\t(0..stop_at).each do |number|\n\t\tinteger += number_array[number]\n\t\tend\n\telse\n\t\troman_array = roman.split(//)\n\t\tstop_at = roman_array.length-2\n\t\t\n\t\troman_array.each do |numeral|\n\t\teach_num = numerals_hash[numeral]\n\t\tnumber_array.push each_num\n\t\tend\n\n\t\tstop_at = number_array.length-1\n\n\t\t(0..stop_at).each do |number|\n\t\tinteger += number_array[number]\n\t\tend\n\tend\n\n\tinteger\n\n\t\n# # Replaces the numeral letters in our array with integers via our hash\n# roman_array.each do |numeral|\n# each_num = numerals_hash[numeral]\n# number_array.push each_num\n# end\n\n# # Creates a new 2d array, filled with smaller arrays representing each pair of \"letters\"\n# \tresult = []\n\n# \t(0..stop_at).each do |i|\n# \t\tresult.push number_array[i..i+1]\n# \tend\n\n=begin\n\t\n our code stops working here. We were trying to compare\n each pair of values in the original array to determine\n if the value should be added or subtracted from a running\n integer total that would total up the value of the \n numeral. \n\t\n\n \t\n \tstop_at_2 = result.length-1\n \tinteger = 0\n \t\n\n \t(0..stop_at_2).each do |i|\n \t\tif result[i][i] >= result[i][i+1]\n \t \t\tinteger += result[i][i]\n \t \telse\n \t \t\tinteger += (result[i][i+1]-result[i][i])\n \t \tend\n \tend\n \t\n integer\nend\n\n\nOur tests don't make much sense at this point. We were\nbuilding smaller problems and small tests to fix them, \nbuilding up to bigger problems with our original method of\ncomparing pairs of numbers against each other.\n\nclass TestNumerals < Minitest::Test\n\t def test_x\n\t \tassert_equal roman_numeral(\"x\"), 10\n\t end\t\n\n\t def test_array_split\n\t \tassert_equal roman_numeral(\"XI\"),[\"X\",\"I\"]\n\t end\n\n\t def test_array2\n\t \tassert_equal roman_numeral(\"XIVXIL\"), [10,1,5,10,1,50]\n\t end\n\n\t def test_integer1\n\t \tassert_equal 60, roman_numeral(\"LX\")\n\t end\n\n\t def test_pair_up\n\t\tassert_equal roman_numeral(\"LXXIV\"), [[50,10],[10,10],[10,1],[1,5]]\n\t end\nend\n=end\nend", "def roman(num, comp = '')\n roman_mapping = {\n 1000 => \"M\",\n 900 => \"CM\",\n 500 => \"D\",\n 400 => \"CD\",\n 100 => \"C\",\n 90 => \"XC\",\n 50 => \"L\",\n 40 => \"XL\",\n 10 => \"X\",\n 9 => \"IX\",\n 5 => \"V\",\n 4 => \"IV\",\n 1 => \"I\"\n}\n \n if num == 0\n p comp \n else\n roman_mapping.each_key do |key|\n result = num - key \n if result >= 0 \n comp += roman_mapping[key]\n roman(result, comp)\n break\n end\n end\n end\nend", "def to_roman3(num)\n result = \"\"\n @roman_mapping.each do |pair|\n value = pair[0]\n binding.pry\n roman = pair[1]\n level_occurance = num / value\n level_occurance.times do |x|\n result << roman\n end\n num = num - value * level_occurance\n end\n return result\nend", "def romanize(input)\n\n raise ArgumentError, 'can not encode negative number' if input < 0\n raise ArgumentError, 'can not encode zero' if input == 0\n\n #Creating a Hash that pointing different numbers to different characters.\n romkeys = {1000 => 'M', 900 => 'CM', 500 => 'D', 400 => 'CD', 100 => 'C', 90 => 'XC', 50 => 'L', 40 => 'XL', 10 => 'X', 9 => 'IX', 5 => 'V', 4 => 'IV' ,1 => 'I'}\n\n #Creating a variable that have the format string, for storing the different characters.\n output = ' '\n\n #Looping until the input is zero.\n until input == 0\n\n #Looping thro the different keys and values of the hash.\n romkeys.each do |key, value|\n if input >= key\n\n #If the input was 5 this will result as 'V' after that the output will save the V and loop thro until it's nothing left.\n output += value\n\n #This subtract the key value to make the loop end.\n input -= key\n\n #This just ending the loop.\n break\n end\n end\n end\n\n #Returning the output string.\n return output\nend", "def to_roman(num)\n roman_sym=[\"M\",\"CM\",\"D\",\"CD\",\"C\",\"XC\",\"L\",\"XL\",\"X\",\"IX\",\"V\",\"IV\",\"I\"]\n roman_val=[1000,900,500,400,100,90,50,40,10,9,5,4,1]\n roman = \"\"\n roman_sym.each_index do |i|\n roman += roman_sym[i] * (num/roman_val[i])\n num = num%roman_val[i]\n end\n return roman\nend", "def roman_numeral num\n thous = (num / 1000)\n hunds = (num % 1000 / 100)\n tens = (num % 100 / 10)\n ones = (num % 10 )\n\n roman = \"M\" * thous\n if hunds == 9\n roman = roman + \"CM\" \n elsif hunds == 4\n roman = roman + \"CD\"\n else\n roman = roman + \"D\" * (num % 1000 / 500)\n roman = roman + \"C\" * (num % 500 / 100)\n end\n\n if tens == 9 \n roman = roman + \"XC\"\n elsif tens == 4\n roman = roman + \"XL\"\n else\n roman = roman + \"L\" * (num % 100 / 50) \n roman = roman + \"X\" * (num % 50 / 10)\n end\n\n if ones == 9 \n roman = roman + \"IX\"\n elsif ones == 4\n roman = roman + \"IV\"\n else\n roman = roman + \"V\" * (num % 10/ 5)\n roman = roman + \"I\" * (num % 5 / 1)\n end\n roman\n end", "def modern_roman_numeral number\n numeral = \"\"\n\n numeral_1 = (number / 1000)\n numeral_2 = (number % 1000/100)\n numeral_3 = (number % 100/ 10) \n numeral_4 = (number % 10) \n \n roman = \"M\" * numeral_1\n\nif numeral_2 == 9\n roman = roman + \"CM\"\nelsif numeral_2 == 4\n roman = roman + \"CD\"\nelse\n roman = roman + \"D\" * (number % 1000 / 500)\n roman = roman + \"C\" *(number % 500/100) \n end\nif numeral_3 == 9\n roman = roman + \"XC\"\nelsif numeral_3 == 4\n roman = roman + \"XL\"\nelse\n roman=roman +\"L\" *(number % 100/ 50)\n roman=roman + \"X\"*(number % 50/ 10) \n end\nif numeral_4 == 9\n roman = roman + \"IX\"\nelsif numeral_4 == 4\n roman = roman + \"IV\"\nelse\n roman = roman + \"V\" * (number % 10/ 5)\n roman = roman + \"I\" * (number % 5/ 1) \nend\n\nroman\n\nend", "def old_roman num\r\n\r\n\taux = num\r\n\troman_num = ''\r\n\t\r\n\twhile true\r\n\t\r\n\t\tif((aux / 1000) >= 1)\r\n\t\t\troman_num = roman_num + 'M'\r\n\t\t\taux = aux - 1000\r\n\t\telsif ((aux / 500) >= 1)\r\n\t\t\tif(aux >= 900)\r\n\t\t\t\troman_num = roman_num + 'CM'\r\n\t\t\t\taux = aux - 900\t\t\t\t\t\r\n\t\t\telse\r\n\t\t\t\troman_num = roman_num + 'D'\r\n\t\t\t\taux = aux - 500\t\t\r\n\t\t\tend\r\n\t\telsif((aux / 100) >= 1)\r\n\t\t\tif(aux >= 400)\r\n\t\t\t\troman_num = roman_num + 'CD'\r\n\t\t\t\taux = aux - 400\t\t\t\t\t\r\n\t\t\telse\r\n\t\t\t\troman_num = roman_num + 'C'\r\n\t\t\t\taux = aux - 100\t\t\r\n\t\t\tend\r\n\t\telsif((aux / 50) >= 1)\r\n\t\t\tif(aux >= 90)\r\n\t\t\t\troman_num = roman_num + 'XC'\r\n\t\t\t\taux = aux - 90\t\t\t\t\t\r\n\t\t\telse\r\n\t\t\t\troman_num = roman_num + 'L'\r\n\t\t\t\taux = aux - 50\t\t\r\n\t\t\tend\r\n\t\telsif((aux / 10) >= 1)\r\n\t\t\tif(aux >= 40)\r\n\t\t\t\troman_num = roman_num + 'XL'\r\n\t\t\t\taux = aux - 40\t\t\t\t\t\r\n\t\t\telse\r\n\t\t\t\troman_num = roman_num + 'X'\r\n\t\t\t\taux = aux - 10\t\t\r\n\t\t\tend\r\n\r\n\t\telsif((aux / 5) >= 1)\r\n\t\t\tif(aux >= 9)\r\n\t\t\t\troman_num = roman_num + 'IX'\r\n\t\t\t\taux = aux - 9\t\t\t\t\t\r\n\t\t\telse\r\n\t\t\t\troman_num = roman_num + 'V'\r\n\t\t\t\taux = aux - 5\t\t\r\n\t\t\tend\r\n\t\telsif((aux / 1) >= 1)\r\n\t\t\tif(aux >= 4)\r\n\t\t\t\troman_num = roman_num + 'IV'\r\n\t\t\t\taux = aux - 4\t\t\t\t\t\r\n\t\t\telse\r\n\t\t\t\troman_num = roman_num + 'I'\r\n\t\t\t\taux = aux - 1\t\r\n\t\t\tend\r\n\t\telse\r\n\t\t\tbreak\t\t\t\r\n\t\tend\r\n\tend\r\n\t\r\n\troman_num\r\nend", "def to_roman\n result = \"\"\n number = self\n roman_mapping.keys.each do |divisor|\n quotient, modulus = number.divmod(divisor)\n result << roman_mapping[divisor] * quotient\n number = modulus\n end\n result\n end", "def old_roman_numberals num\n roman = \"\"\n roman += \"M\" * (num/1000)\n roman += \"D\" * ((num%1000)/500)\n roman += \"C\" * ((num%500)/100)\n roman += \"L\" * ((num%100)/50)\n roman += \"X\" * ((num%50)/10)\n roman += \"V\" * ((num%10)/5)\n roman += \"I\" * ((num%5)/1)\nputs roman\nend", "def solution(number)\n roman_numeral = { 1 => 'I', 4 => 'IV', 5=> 'V', 6 => 'VI', 10=> 'X', 50=> 'L', 100=> 'C', 500=> 'D', 1000=> 'M' }\n numbers = number.digits.map.with_index{ |int, idx| int * 10**idx }\n numbers.map{ |number| roman_numeral[number] }.reverse.join\nend", "def roman_numeral(num)\n thousands = (num / 1000)\n hundreds = (num % 1000 / 100)\n tens = (num % 100 / 10)\n ones = (num % 10)\n\n roman = 'M' * thousands\n\n if hundreds == 9\n roman = roman + 'CM'\n elsif hundreds == 4\n roman = roman + 'CD'\n else\n roman = roman + 'D' * (num % 1000 / 500)\n roman = roman + 'C' * (num % 500 / 100)\n end\n\n if tens == 9\n roman = roman + 'XC'\n elsif tens == 4\n roman = romann + 'XL'\n else\n roman = roman + 'L' * (num % 100 / 50)\n roman = roman + 'X' * (num % 50 / 10)\n end\n\n if ones == 9\n roman = roman + 'IX'\n elsif ones == 4\n roman = roman + 'IV'\n else\n roman = roman + 'V' * (num % 10 / 5)\n roman = roman + 'I' * (num % 5 / 1)\n end\n roman\nend", "def new_roman_numeral number\n digits = []\n i = 4\n while i>0\n digits.push (number%10)\n number = (number/10).to_i\n i -= 1\n end\n thousandth = 'M'*digits[3]\n hundredth = 'D'*(digits[2]/5).to_i+'C'*(digits[2]%5)\n tenth = 'L'*(digits[1]/5).to_i+'X'*(digits[1]%5)\n unit = 'V'*(digits[0]/5).to_i+'I'*(digits[0]%5)\n hundredth = 'CD' if hundredth == 'C'*4\n hundredth = 'CM' if hundredth == 'D'+'C'*4\n tenth = 'XL' if tenth == 'X'*4\n tenth = 'XC' if tenth == 'L'+'X'*4\n unit = 'IV' if unit == 'I'*4\n unit = 'IX' if unit == 'V'+'I'*4\n puts thousandth+hundredth+tenth+unit\nend", "def roman_numeral year\n thou = year/1000\n thou_remain = year%1000\n five_hundreds = thou_remain/500\n hundreds = (thou_remain%500)/100\n fifties = ((thou_remain%500)%100)/50\n tens = (((thou_remain%500)%100)%50)/10\n fives = ((((thou_remain%500)%100)%50)%10)/5\n ones = (((((thou_remain%500)%100)%50)%10)%5)/1\n \n \n #this is just to clear the terminal screen so you only see the result.\n100.times do puts \"\" \n end\n \n #outputs the letters times the number returned.\n puts \"M\" * thou + \"D\" * five_hundreds + \"C\" * hundreds + \"L\" * fifties + \"X\" * tens + \"V\" * fives + \"I\" * ones\nend", "def to_roman(num)\n \n output = ''\n\n if num\n how_many_thousand = (num - num % 1000) / 1000\n num = num - (num - num % 1000)\n\n how_many_hundred = (num - num % 100) / 100\n num = num - (num - num % 100)\n\n how_many_tens = (num - num % 10) / 10\n num = num - (num - num % 10)\n\n how_many_ones = num - (num - num % 10)\n else\n \treturn nil\n end\n\n #adding thousands\n output << 'M' * how_many_thousand\n #adding hundreds\n if how_many_hundred == 9\n \t output << 'CM'\n \telsif how_many_hundred >= 5\n \t output << 'D' + 'C' * (how_many_hundred - 5)\n elsif how_many_hundred == 4\n output << 'CD'\n else\n output << \"C\" * how_many_hundred\n end\n #adding tens\n if how_many_tens == 9\n \t output << 'XC'\n \telsif how_many_tens >= 5 \n \t output << 'L' + 'X' * (how_many_tens - 5)\n elsif how_many_tens == 4\n output << 'XL'\n else\n output << \"X\" * how_many_tens\n end\n #adding ones\n if how_many_ones == 9\n \t output << 'IX'\n \telsif how_many_ones >= 5 \n \t output << 'V' + 'I' * (how_many_ones - 5)\n elsif how_many_ones == 4\n output << 'IV'\n else\n output << \"I\" * how_many_ones\n end\n\n output\n\nend", "def roman_numbers num\n case num\n when 'CM'\n return 900\n when 'CD'\n return 400\n when 'XC'\n return 90\n when 'XL'\n return 40\n when 'IX'\n return 9\n when 'IV'\n return 4\n else\n return false\n end\nend", "def build_roman(digit, exp)\n roman_digits = [\n { 1 => \"I\", 5 => \"V\" },\n { 1 => \"X\", 5 => \"L\" },\n { 1 => \"C\", 5 => \"D\" },\n { 1 => \"M\" }\n ]\n\n if digit == 0\n return \"\"\n elsif digit <= 3\n return roman_digits[exp][1] * digit\n elsif digit == 4\n return roman_digits[exp][1] + roman_digits[exp][5]\n elsif digit == 5\n return roman_digits[exp][5]\n elsif digit <= 8\n return roman_digits[exp][5] + roman_digits[exp][1] * (digit - 5)\n else\n return roman_digits[exp][1] + roman_digits[exp+1][1]\n end\n end", "def prepare_group(integer, roman, group_value, group_letter, lower_value, lower_letter)\n count, integer = integer.divmod(group_value)\n roman += group_letter * count\n if lower_value and integer >= lower_value\n roman += lower_letter\n integer -= lower_value\n end\n return integer, roman\nend", "def to_roman(num)\n place_value_digits = num.to_s.split('').map { |digit| digit.to_i}\n\n if place_value_digits.length == 0 \n return \"\"\n end \n\n if place_value_digits[0] == 0 \n place_value_digits.shift \n return \"\" + to_roman(place_value_digits) if place_value_digits.empty? == false\n return \"\"\n end \n\n if place_value_digits.length == 1 \n digit = place_value_digits.shift\n if digit <= 3\n return \"I\" * digit\n elsif digit == 4\n return \"IV\" \n elsif digit == 5 \n return \"V\" \n elsif digit > 5 && digit < 9\n return \"V\" + (\"I\" * (digit - 5))\n else \n return \"IX\"\n end \n\n elsif place_value_digits.length == 2 \n digit = place_value_digits.shift\n if digit <= 3\n return \"X\" * digit + to_roman(place_value_digits.join.to_i)\n elsif digit == 4\n return \"XL\" + to_roman(place_value_digits.join.to_i)\n elsif digit == 5 \n return \"L\" + to_roman(place_value_digits.join.to_i)\n elsif digit > 5 && digit < 9\n return \"L\" + (\"X\" * (digit - 5)) + to_roman(place_value_digits.join.to_i)\n else \n return \"XC\" + to_roman(place_value_digits.join.to_i)\n end \n\n elsif place_value_digits.length == 3\n digit = place_value_digits.shift\n if digit <= 3\n return \"C\" * digit + to_roman(place_value_digits.join.to_i)\n elsif digit == 4\n return \"CD\" + to_roman(place_value_digits.join.to_i)\n elsif digit == 5 \n return \"D\" + to_roman(place_value_digits.join.to_i)\n elsif digit > 5 && digit < 9\n return \"D\" + (\"C\" * (digit - 5)) + to_roman(place_value_digits.join.to_i)\n else \n return \"CM\" + to_roman(place_value_digits.join.to_i)\n end \n\n elsif place_value_digits.length == 4 \n digit = place_value_digits.shift\n return \"M\" * digit + to_roman(place_value_digits.join.to_i)\n end \n end", "def roman_numeral num_to_convert\n\t\n\tnum_converted = ''\n\n\tthousands = num_to_convert / 1000\n\tnum_converted = 'M'*thousands\n\tremainder = num_to_convert % 1000\n\n\tfivehundreds = remainder / 500\n\tif remainder >= 900\n\t\tnum_converted += 'CM'\n\t\tremainder = remainder % 900\n\telse\n\t\tnum_converted += 'D'*fivehundreds\n\t\tremainder = remainder % 500\n\tend\n\n\tonehundreds = remainder / 100\n\tif onehundreds == 4\n\t\tnum_converted += 'CD'\n\t\tremainder = remainder % 400\n\telse\n\t\tnum_converted += 'C'*onehundreds\n\t\tremainder = remainder % 100\n\tend\n\t\n\n\tfifties = remainder / 50\n\tif remainder >= 90\n\t\tnum_converted += 'XC'\n\t\tremainder = remainder % 90\n\telse\n\t\tnum_converted += 'L'*fifties\n\t\tremainder = remainder % 50\t\n\tend\n\t\n\ttens = remainder / 10\n\tif tens == 4\n\t\tnum_converted += 'XL'\n\t\tremainder = remainder % 40\n\telse\n\t\tnum_converted += 'X'*tens\n\t\tremainder = remainder % 10\n\tend\n\t\n\tfives = remainder / 5\n\tif remainder >= 9\n\t\tnum_converted += 'IX'\n\t\tremainder = remainder % 9\n\telse\n\t\tnum_converted += 'V'*fives\n\t\tremainder = remainder % 5\n\tend\n\n\tones = remainder\n\tif ones == 4\n\t\tnum_converted += 'IV'\n\telse \n\t\tnum_converted += 'I'*ones\n\tend\n\n\tputs num_converted\n\treturn num_converted\nend", "def old_school(num) \n roman = ''\n roman = roman + 'M' * (num / 1000)\n roman = roman + 'D' * (num % 1000/ 500)\n roman = roman + 'C' * (num % 500/ 100)\n roman = roman + 'L' * (num % 100/ 50)\n roman = roman + 'X' * (num % 50/ 10)\n roman = roman + 'V' * (num % 10/ 5)\n roman = roman + 'I' * (num % 5/ 1)\n roman \nend", "def old_roman number\n\tnumerals = []\n\twhile number < 0\n\t\tputs 'please use a whole number => 1 and <= 3000'\n\tend\n\tif number % 1000 > 0\n\t\tthousands = number / 1000\n\t\tm_numerals = 'M' * thousands\n\t\tnumerals.push m_numerals\n\t\tnumber = number - (thousands * 1000)\n\tend\n\tif number % 500 > 0\n\t\tnumerals.push 'D'\n\t\tnumber = number - 500\n\tend\n\tif number % 100 > 0\n\t\thundreds = number / 100\n\t\tc_numerals = 'C' * hundreds\n\t\tnumerals.push c_numerals\n\t\tnumber = number - (hundreds * 100)\n\tend\n\tif number % 50 > 0\n\t\tnumerals.push 'L'\n\t\tnumber = number - 50\n\tend\n\tif number % 10 > 0\n\t\ttens = number / 10\n\t\tx_numerals = 'X' * tens\n\t\tnumerals.push x_numerals\n\t\tnumber = number - (tens * 10)\n\tend\n\tif number % 5 > 0\n\t\tnumerals.push 'V'\n\t\tnumber = number - 5\n\tend\n\n\tones = number\n\ti_numerals = 'I' * ones\n\tnumerals.push i_numerals\n\n\tputs numerals\nend", "def old_r_conv nums\n\troman = ''\n\troman = roman + 'M' * (nums/1000)\n\troman = roman + 'D' * ((nums%1000)/500)\n\troman = roman + 'C' * ((nums%500)/100)\n\troman = roman + 'L' * ((nums%100)/50)\n\troman = roman + 'X' * ((nums%50)/10)\n\troman = roman + 'V' * ((nums%10)/5)\n\troman = roman + 'I' * ((nums%5)/1)\n\n\tputs roman\nend", "def old_roman_numeral number\n digits = []\n i = 4\n while i>0\n digits.push (number%10)\n number = (number/10).to_i\n i -= 1\n end\n thousandth = 'M'*digits[3]\n hundredth = 'D'*(digits[2]/5).to_i+'C'*(digits[2]%5)\n tenth = 'L'*(digits[1]/5).to_i+'X'*(digits[1]%5)\n unit = 'V'*(digits[0]/5).to_i+'I'*(digits[0]%5)\n puts thousandth+hundredth+tenth+unit\nend", "def old_roman_numeral number\n numeral = \"\"\n\n numeral = numeral + \"M\" * (number / 1000)\n numeral = numeral + \"D\" * (number % 1000/500)\n numeral = numeral + \"C\" * (number % 500/ 100) \n numeral = numeral + \"L\" * (number % 100/ 50) \n numeral = numeral + \"X\" * (number % 50/ 10) \n numeral = numeral + \"V\" * (number % 10/ 5) \n numeral = numeral + \"I\" *(number % 5/ 1) \n numeral\nend", "def to_roman(num)\n\toutput = \"\"\n\t@roman_num.each do |key, val|\n\t\tremainder = num%key.to_i\n\t\twhile remainder < num\n\t\t\toutput << val\n\t\t\tnum = num - key.to_i\n\t\tend\n\tend\n\toutput\nend", "def old_roman_numeral num\nnumerals = \"\"\nnumerals << \"M\" * (num / 1000)\nnumerals << \"D\" * (num % 1000 /500)\nnumerals << \"C\" * (num % 500 / 100)\nnumerals << \"L\" * (num % 100 / 50)\nnumerals << \"X\" * (num % 50 / 10)\nnumerals << \"V\" * (num % 10 / 5)\nnumerals << \"I\" * (num % 5 / 1)\nnumerals\nend", "def to_roman(input)\n result = \"\"\n MAPPING.each do |k,v|\n while input%v < input\n result += k\n input -= v\n end\n end\n result\n end", "def iterate_roman_numerals(key, value)\n\t\tcheck_edge_cases(key)\n\t\twhile @num_integer >= key\n\t\t\t@roman_numeral_string += value\n\t\t\t@num_integer -= key\n\t\tend\n\tend", "def converter(x)\n i=x\n roman_num=[]\n while i!=0\n if i/1000>0\n roman_num.push('M'*(i/1000))\n i-=i-i%1000\n elsif i/100>0\n if i/100<4\n roman_num.push('C'*(i/100))\n i-=i-i%100\n elsif i/100==4\n roman_num.push('CD')\n i-=400\n elsif i/100==5\n roman_num.push('D')\n i-=500\n elsif ((i/100)>5 && (i/100)<9)\n roman_num.push('D')\n i-=500\n roman_num.push('C'*(i/100))\n i-=i-i%100\n elsif i/100==9\n roman_num.push('CM')\n i-=900\n end\n elsif i/10>0\n if i/10<4\n roman_num.push('X'*(i/10))\n i-=i-i%10\n elsif i/10==4\n roman_num.push('XL')\n i-=40\n elsif i/10==5\n roman_num.push('L')\n i-=50\n elsif ((i/10)>5 && (i/10)<9)\n roman_num.push('L')\n i-=50\n roman_num.push('X'*(i/10))\n i-=i-i%10\n elsif i/10==9\n roman_num.push('XC')\n i-=90\n end\n else \n if (i>=1 && i<4)\n roman_num.push('I'*i)\n i=0\n elsif i==4\n roman_num.push('IV')\n i=0\n elsif i==5\n roman_num.push('V')\n i=0\n elsif (i>5 && i<9)\n roman_num.push('V')\n i-=5\n roman_num.push('I'*i)\n i=0\n else\n roman_num.push('IX')\n i=0\n end\n end\n end\n return roman_num.join('')\nend", "def ReduceRoman(myroman)\n lesschar = 0;\n newroman = \"\"\n puts \"orig roman = #{myroman}\"\n\n for i in 0...myroman.to_s.length-1 do\n count = 0\n j=i\n basechar = myroman[i]\n \n while ( $numbers[myroman[j]] == $numbers[myroman[j+1]]) do\n count = count + 1\n j = j+1\n end\n \n if(count == 4)\n case basechar\n when 'I'\n \n when 'V'\n \n when 'L'\n \n when 'C'\n \n when 'D'\n\n when 'M'\n \n end\n\n else\n for k in 0..count do\n newroman[k]=basechar\n end\n end\n\n end\n puts \"new roman is #{newroman}\"\n return lesschar\nend", "def roman_to_integer roman \n digit_vals = {'i' => 1,\n 'v' => 5,\n 'x' => 10,\n 'l' => 50,\n 'c' => 100,\n 'd' => 500,\n 'm' => 1000}\n total = 0 \n prev = 0 \n index = roman.length - 1 \n while index >= 0 \n c = roman[index].downcase \n index = index - 1 \n val = digit_vals[c]\n if !val \n puts \"This is not a valud roman numeral\"\n return \n end \n if val < prev\n val = val * -1\n else \n prev = val \n end \n total = total + val \n end \n total \nend", "def old_roman_mod\n old_roman = nil\n i,v,x,l,c,d,ms,request = nil,nil,nil,nil,nil,nil,nil,nil\n ms = 0\n while true \n puts \"enter a number between 1 and 3000 ['q' to quit program]\"\n request = gets.chomp\n break if request.downcase == 'q'\n (puts 'only enter between 1 and 3000';next) if request.to_i < 1 || request.to_i > 3000\n request= request.to_i\n ms = request / 1000\n test = request % 1000\n d = test / 500\n test = test % 500\n c = test / 100\n test = test % 100\n l = test / 50\n test = test % 50\n x = test / 10\n test = test % 10\n v = test / 5\n test = test % 5\n i = test\n puts\n puts \n old_roman = 'M'*ms + 'D'*d + 'C'*c+ 'L'*l + 'X'*x + 'V'*v+ 'I'*i\n puts old_roman\n end\n old_roman\nend", "def first_roman_for( number )\n map = {\n 1 => 'I',\n 5 => 'V',\n 10 => 'X',\n 50 => 'L',\n 100 => 'C',\n 500 => 'D',\n 1000 => 'M'\n }\n \n decimal_place = number.to_s.size - 1 # the number of digits in the number passed\n factor = 10 ** decimal_place # the factor : 1 for one's place , 10 for tens place : the factor for the digit we are working on \n \n #append the roman_representation according to the digit\n return ( map[factor] ) * ( number/(factor) ) if number < 4 * factor \n return ( map[factor] + map[ 5*factor ] ) if number >= 4 * factor && number < 5 * factor\n return ( map[ 5 * factor ] ) if number >= ( 5 * factor ) && number < ( 6 * factor )\n return ( map[ 5 * factor ] + ( map[ factor ] * (( number - 5*factor )/factor) )) if number >= 6 * factor && number < 9 * factor\n return ( map[factor] + map[ 10 * factor ] ) if number >= 9 * factor\n end", "def roman_numeral num\n roman_to_arabic = {\n M: 1_000, CM: 900, D: 500, CD: 400,\n C: 100, XC: 90, L: 50, XL: 40,\n X: 10, IX: 9, V: 5, IV: 4,\n I: 1\n }\n\n return '' if num <= 0\n roman_to_arabic.each { |key, val| return key.to_s + roman_numeral(num - val) if num >= val }\nend", "def calculate_roman_numeral\n remaining_value = value\n roman_string = ''\n while (remaining_value > 0)\n value = biggest_number_that_fits_into(remaining_value)\n roman_string += numbers_to_numerals[value]\n remaining_value -= value\n end\n roman_string\n end", "def roman_to_integer(roman_value)\n digital_vals = {'i'=> 1, 'v'=> 5, 'x'=> 10, 'l'=> 50, \n 'c'=> 100, 'd'=> 500, 'm'=> 1000,}\n\n roman_value.each_char do |char|\n if digital_vals.has_key?(char) == false\n return \"Invalid Entry!\"\n end \n end\n\n \n\n reversed_roman_value = roman_value.reverse\n total_value = 0\n prev_val = 0\n prev_char = ''\n reversed_roman_value.each_char do |char|\n val = digital_vals[char]\n\n val < prev_val ? val *= -1 : prev_val = val\n total_value += val\n\n\n\n=begin \nNote: The commented method below isn't concise and simple as the current implementation\nabove.\nInstead of comparing the alphabets, it's simpler to compare the values\n case \n when ((char == 'i') && (prev_char == 'x')) then total_value -= 1\n when ((char == 'i') && (prev_char == 'v')) then total_value -= 1\n when ((char == 'x') && (prev_char == 'l')) then total_value -= 10\n when ((char == 'x') && (prev_char == 'c')) then total_value -= 10\n when ((char == 'c') && (prev_char == 'd')) then total_value -= 100\n when ((char == 'c') && (prev_char == 'm')) then total_value -= 100\n else \n total_value += digital_vals[char]\n end\n prev_char = char\n\n=end \n\n end\n\n \n\n \n total_value\nend", "def numberise!(numeral, ans=0, mapping = roman_mapping)\n return ans if numeral.empty?\n\n mapping.values.each do |roman_num|\n while numeral[0..roman_num.size-1] == roman_num\n ans += mapping.key(roman_num)\n numeral = numeral[roman_num.size..-1]\n end\n end\n return numberise!(numeral, ans)\nend", "def solution(roman)\n split = roman.split(\"\")\n last_value = 0\n split.reduce(0) do |final, char|\n current = CONVERSION[char.upcase]\n binding.pry\n if current >= last_value\n final += current\n else\n final -= current\n end\n binding.pry\n last_value = current\n final\n end\nend", "def new_roman_numeral num\n roman = ''\n\n roman << 'M' * (num / 1000)\n\n digit_hundred = num % 1000 / 100\n if digit_hundred >= 5\n if digit_hundred == 9\n roman << 'CM'\n else\n roman << 'D'\n roman << 'C' * (digit_hundred % 5)\n end\n else\n if digit_hundred == 4\n roman << 'CD'\n else\n roman << 'C' * digit_hundred\n end\n end\n\n digit_ten = num % 100 / 10\n if digit_ten >= 5\n if digit_ten == 9\n roman << 'XC'\n else\n roman << 'L'\n roman << 'X' * (digit_ten % 5)\n end\n else\n if digit_ten == 4\n roman << 'XL'\n else\n roman << 'X' * digit_ten\n end\n end\n\n digit_one = num % 10\n if digit_one >= 5\n if digit_one == 9\n roman << 'IX'\n else\n roman << 'V'\n roman << 'I' * (digit_one % 5)\n end\n else\n if digit_one == 4\n roman << 'IV'\n else\n roman << 'I' * digit_one\n end\n end\n\n roman\nend", "def old_roman_numeral num\n\t\n\tif num >= 1000\n\t\tthousands = 'M' * (num / 1000)\n\tend\n\n\tif num >= 100\n\t\ttemp_hundreds = (num % 1000) / 100\n\t\tif temp_hundreds > 5\n\t\t\thundreds = 'D' + 'C' * (temp_hundreds - 5)\n\t\telsif temp_hundreds == 5\n\t\t\thundreds = 'D'\n\t\telse\n\t\t\thundreds = 'C' * temp_hundreds\n\t\tend\n\tend\n\t\n\tif num >= 10\n\t\ttemp_tens = (num % 100) / 10\n\t\tif temp_tens > 5\n\t\t\ttens = 'L' + 'X' * (temp_tens - 5)\n\t\telsif temp_tens == 5\n\t\t\ttens = 'L'\n\t\telse\n\t\t\ttens = 'X' * temp_tens\n\t\tend\n\tend\n\t\n\tif num > 0\n\t\ttemp_ones = num % 10\n\t\tif temp_ones > 5\n\t\t\tones = 'V' + 'I' * (temp_ones - 5)\n\t\telsif temp_ones == 5\n\t\t\tones = 'V'\n\t\telse\n\t\t\tones = 'I' * temp_ones\n\t\tend\n\tend\n\t\n\tputs \"#{num} in Roman numerals is \"+\"#{thousands}\"+\"#{hundreds}\"+\"#{tens}\"+\"#{ones}\"\nend", "def Old_Roman_Numerals number #THANKS SATAN, for such a stress inducing exercise.\n m_length = 0\n d_length = 0\n c_length = 0\n l_length = 0\n x_length = 0\n v_length = 0\n i_length = 0\n\n if number >= 1000 #Is this unconventional? Yes. Does it work? Yes.\n m_length = number / 1000\n number = number % 1000\nend\n\n if number >= 500\n d_length = number / 500\n number = number % 500\nend\n\n if number >= 100\n c_length = number / 100\n number = number % 100\nend\n\n if number >= 50\n l_length = number / 50\n number = number % 50\nend\n\n if number >= 10\n x_length = number / 10\n number = number % 10\nend\n\n if number >= 5\n v_length = number / 5\n number = number % 5\nend\n\n if number < 5\n i_length = number / 1\n number = number % 10\nend\n\nputs 'M'*m_length + # Prefer clean order list vs. one long code line.\n 'D'*d_length +\n 'C'*c_length +\n 'L'*l_length +\n 'X'*x_length +\n 'V'*v_length +\n 'I'*i_length\nend", "def solution(number)\n accumulator =\n number.to_s.reverse.each_char.with_index.map do |letter, index|\n character_map(letter.to_i, *@roman_symbols[index * 2, 3])\n end\n accumulator.reverse.join \nend", "def to_roman(n)\n resto = []\n num = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]\n num.each do |element|\n resto.push(n / element)\n n = n % element\n end\n chars = %w[M CM D CD C XC L XL X IX V IV I]\n resto.each_with_index.map do |element, index|\n chars[index] * element\n end.join\nend", "def from_roman(str)\n hash = {}\n str.each_char do |letter|\n hash.default = 0\n hash[rn_to_decimal(letter)] += 1 \n end\n array = []\n hash.each do |k, v|\n array << k*v\n end\n array.reduce(:+)\nend", "def roman_convert(input)\n numerals_string = []\n input_array = input.split('')\n\n until input_array.empty?\n case input_array.length\n when 4\n puts \"#{input_array.first}000 = #{@thousands[input_array.first.to_i]}\"\n numerals_string.push(@thousands[input_array.shift.to_i])\n when 3\n puts \" #{input_array.first}00 = #{@hundreds[input_array.first.to_i]}\"\n numerals_string.push(@hundreds[input_array.shift.to_i])\n when 2\n puts \" #{input_array.first}0 = #{@tens[input_array.first.to_i]}\"\n numerals_string.push(@tens[input_array.shift.to_i])\n when 1\n puts \" #{input_array.first} = #{@units[input_array.first.to_i]}\"\n numerals_string.push(@units[input_array.shift.to_i])\n else\n break\n end\n end\n\n puts ''\n puts 'Your number converted to Roman Numerals is: '\n puts \"#{numerals_string.join}\"\n puts ''\n end", "def roman digit\n\n\trules = [ 'I', 'V', 'X', 'L', 'C', 'D', 'M']\n\tnum = digit[0]\n\tplace = digit[1]\n\n\nromannumeral = []\nif num == 5\n\tromannumeral.push rules[place+1].to_s\n\n\nelse if num > 5\n\tromannumeral.push rules[place+1].to_s\n\tnum = num - 5\n\tnum.times do\n\tromannumeral.push rules[place].to_s\n\tend\n\nelse if num < 5\n\tnum.times do\n\t\tputs 'num<5'\n\tromannumeral.push rules[place].to_s\n\tend\n\n\tend\n\tend\n\tend\n\nreturn romannumeral\nend", "def old_roman_numeral(num)\n return \"Please use a positive integer.\" if num <= 0\n \n roman = \"\"\n \n roman << \"M\" * (num / 1000)\n roman << \"D\" * (num % 1000 / 500)\n roman << \"C\" * (num % 500 / 100)\n roman << \"L\" * (num % 100 / 50)\n roman << \"X\" * (num % 50 / 10)\n roman << \"V\" * (num % 10 / 5)\n roman << \"I\" * (num % 5 / 1)\n \n roman\nend", "def decimal_to_roman decimal\n roman = \"\"\n i = 0\n\n # Greedily append the highest roman numeral that fits\n while i < ROMANS.size\n numeral = ROMANS[i]\n if VALUE[numeral] <= decimal\n roman += numeral\n decimal -= VALUE[numeral]\n else\n i += 1\n end\n end\n\n # Find groups of unnecessary repeated numerals, replace with subtractive \n # pairs.\n for repeat in REPEATS do\n roman = roman.sub(repeat, SUB_PAIRS[repeat])\n end\n\n return roman\nend", "def roman_numeral(arabic_numeral)\n arabic_array = arabic_numeral.to_s.split(//)\n arabic_array_int = arabic_array.map { |int| int.to_i }\n if arabic_array.length >= 8\n puts \">> This feature only supports numbers up to 9,999,999, as the unicode for Roman numerals above 1,000 is not universally displayable. Please enter a positive whole number less than 10,000,000:\"\n arabic_numeral = gets.to_i\n roman_numeral(arabic_numeral)\n loop do\n break if arabic_numeral > 0\n if arabic_numeral <= 0\n puts \">> Make sure that the number you enter is greater than 0:\"\n end\n arabic_numeral = gets.to_i\n end\n end\n# begin millions place\n if arabic_array_int[-7] != nil\n millions = arabic_array_int[-7] * 1000\n millions.times { |mmmmm| print \"M\" }\n end\n# begin hundred thousands place\n if arabic_array_int[-6] != nil\n hundred_thousands = arabic_array_int[-6] * 100\n hundred_thousands.times { |mmm| print \"M\" }\n end\n# begin ten thousands place\n if arabic_array_int[-5] != nil\n ten_thousands = arabic_array_int[-5] * 10\n ten_thousands.times { |mm| print \"M\" }\n end\n# begin thousands place\n if arabic_array_int[-4] != nil\n m = arabic_array_int[-4]\n m.times { |m| print \"M\" }\n end\n# begin hundreds place\n unless arabic_array_int[-3] != true || arabic_array_int[-3] == 9 || arabic_array_int[-3] == 4 || arabic_array_int[-3] >= 5 && arabic_array_int[-3] <= 8\n arabic_array_int[-3].times { |c| print \"C\" }\n end\n if arabic_array_int[-3] == 1\n print \"C\"\n end\n if arabic_array_int[-3] == 2\n print \"CC\"\n end\n if arabic_array_int[-3] == 3\n print \"CCC\"\n end\n if arabic_array_int[-3] == 4\n print \"CD\"\n end\n if arabic_array_int[-3] == 5\n print \"D\"\n elsif arabic_array_int[-3] == 6 \n print \"DC\"\n elsif arabic_array_int[-3] == 7\n print \"DCC\"\n elsif arabic_array_int[-3] == 8\n print \"DCCC\"\n end \n if arabic_array_int[-3] == 9\n print \"CM\"\n end\n \n# begin tens place\n unless arabic_array_int[-2] != true || arabic_array_int[-2] == 9 || arabic_array_int[-2] == 4 || arabic_array_int[-2] >= 5 && arabic_array_int[-2] <= 8\n arabic_array_int[-2].times { |x| print \"X\" }\n end\n if arabic_array_int[-2] == 1\n print \"X\" \n elsif arabic_array_int[-2] == 2\n print \"XX\"\n elsif arabic_array_int[-2] == 3\n print \"XXX\"\n elsif arabic_array_int[-2] == 4\n print \"XL\"\n elsif arabic_array_int[-2] == 5\n print \"L\"\n elsif arabic_array_int[-2] == 6 \n print \"LX\"\n elsif arabic_array_int[-2] == 7\n print \"LXX\"\n elsif arabic_array_int[-2] == 8\n print \"LXXX\"\n elsif arabic_array_int[-2] == 9\n print \"XC\"\n end\n \n# begin ones place\n unless arabic_array_int[-1] == 9 || arabic_array_int[-1] == 4 || arabic_array_int[-1] >= 5 && arabic_array_int[-1] <= 8\n arabic_array_int[-1].times { |ones| print \"I\" }\n end\n if arabic_array_int[-1] == 5\n print \"V\"\n elsif arabic_array_int[-1] == 6 \n print \"VI\"\n elsif arabic_array_int[-1] == 7\n print \"VII\"\n elsif arabic_array_int[-1] == 8\n print \"VIII\"\n end \n if arabic_array_int[-1] == 9\n print \"IX\"\n end\n if arabic_array_int[-1] == 4\n print \"IV\"\n end\n# end line for readability\nprint \"\\n\"\nend", "def roman(decimal)\n bases = ROMANS.keys\n roman = \"\"\n base = bases.pop\n while base > 1 and decimal > 0 do\n y = Math.log(decimal, base).floor \n if y > 0\n roman << ROMANS[base] * y\n decimal -= base ** y\n else\n base = bases.pop\n end\n end\n roman << ROMANS[base] * decimal\n end", "def roman(decimal)\n bases = ROMANS.keys\n roman = \"\"\n base = bases.pop\n while base > 1 and decimal > 0 do\n y = Math.log(decimal, base).floor \n if y > 0\n roman << ROMANS[base] * y\n decimal -= base ** y\n else\n base = bases.pop\n end\n end\n roman << ROMANS[base] * decimal\n end", "def roman_to_integer roman\r\n digit_vals = {'i' => 1,\r\n 'v' => 5,\r\n 'x' => 10,\r\n 'l' => 50,\r\n 'c' => 100,\r\n 'd' => 500,\r\n 'm' => 1000}\r\n total = 0\r\n prev = 0\r\n roman.reverse.each_char do |c_or_C|\r\n c = c_or_C.downcase\r\n val = digit_vals[c]\r\n if !val\r\n puts 'this is not a valid roman numeral!'\r\n return\r\n end\r\n if val < prev\r\n val *= -1\r\n else\r\n prev = val\r\n end\r\n\r\n total += val\r\n end\r\n\r\n total\r\nend", "def to_roman1(num)\n # Your code here\n ans = \"\"\n\n while (num / 1000 > 0)\n ans << 'M'\n num -= 1000\n end\n\n while (num / 500 > 0)\n ans << 'D'\n num -= 500\n end\n\n while (num / 100 > 0)\n ans << 'C'\n num -= 100\n end\n\n while (num / 50 > 0)\n ans << 'L'\n num -= 50\n end\n\n while (num / 10 > 0)\n ans << 'X'\n num -= 10\n end\n\n while (num / 5 > 0)\n ans << 'V'\n num -= 5\n end\n\n while (num > 0)\n ans << 'I'\n num -= 1\n end\n\n ans.gsub!(/DCCCC/, 'CM')\n ans.gsub!(/CCCC/, 'CD')\n ans.gsub!(/LXXXX/, 'XC')\n ans.gsub!(/XXXX/, 'XL')\n ans.gsub!(/VIIII/, 'IX')\n ans.gsub!(/IIII/, 'IV')\n\n ans\nend", "def roman_to_decimal roman \n decimal = 0\n i = 0\n\n while i < roman.size do\n pair = roman[i, 2]\n\n # Single numeral at the end.\n if pair.size == 1\n decimal += VALUE[pair[0,1]] \n i += 1\n\n # Normal pair. \n elsif VALUE[pair[0,1]] >= VALUE[pair[1,1]] then\n decimal += VALUE[pair[0,1]]\n i += 1\n\n # Subtractive pair. Treat as one numeral.\n else\n decimal += VALUE[pair[1,1]] - VALUE[pair[0,1]]\n i += 2 \n end\n end\n return decimal\nend", "def roman_numeral number\n\nend", "def to_num(input)\n result = 0\n #iterate on roman number hash\n MAPPING.each do |k,v|\n while input.index(k) == 0 #if \"CL\".index(\"C\") == 0\n result += v #assign value of current hash key\n input.slice!(0) #remove string \"C\" from input and so on\n end\n end\n result\n end", "def convert_numbers(input_number, result)\n if input_number >= 1000\n input_number -= 1000\n result << \"M\"\n convert_numbers(input_number, result)\n elsif input_number >= 900\n result << \"CM\"\n input_number -= 900\n convert_numbers(input_number, result)\n elsif input_number >= 500\n input_number -= 500\n result << \"D\"\n convert_numbers(input_number, result)\n elsif input_number >= 400\n input_number -= 400\n result << \"CD\"\n convert_numbers(input_number, result) \n elsif input_number >= 100\n input_number -= 100\n result << \"C\"\n convert_numbers(input_number, result)\n elsif input_number >= 90\n input_number -= 90\n result << \"XC\"\n convert_numbers(input_number, result)\n elsif input_number >= 50\n input_number -= 50\n result << \"L\"\n convert_numbers(input_number, result)\n elsif input_number >= 40\n input_number -= 40\n result << \"XL\"\n convert_numbers(input_number, result)\n elsif input_number >= 10\n input_number -= 10\n result << \"X\"\n convert_numbers(input_number, result)\n elsif input_number >= 9\n input_number -= 9\n result << \"IX\"\n convert_numbers(input_number, result)\n elsif input_number >= 5\n input_number -= 5\n result << \"V\"\n convert_numbers(input_number, result)\n elsif input_number >= 4\n input_number -= 4\n result << \"IV\"\n convert_numbers(input_number, result)\n elsif input_number >= 1\n input_number -= 1\n result << \"I\"\n convert_numbers(input_number, result)\n else\n result\n end\nend", "def solution(roman)\n dict = { \"I\" => 1, \"V\" => 5, \"X\" => 10, \"L\" => 50, \"C\" => 100, \"D\" => 500, \"M\" => 1000, \"N\" => 0 }\n return 0 if roman == \"N\"\n arr = roman.split(//)\n \n arr.each do |char| # check if all characters are valid\n if !dict.keys.include?(char)\n raise \"Invalid\"\n end \n end\n \n fre = Hash.new(0)\n arr.each do |char|\n fre[char] += 1\n end\n \n raise \"Invalid\" if fre[\"V\"], fre[\"L\"], fre[\"D\"] == 2 # these characters can't appear twice\n \n fre.each_value do |value| # a character can't repeat more than 3 times\n if value > 3\n raise \"Invalid\"\n end\n end\n \n # translation starts\n\n num = 0\n last = arr.length\n arr<<'N'\n i = 0\n while i < last\n if dict[arr[i]] < dict[arr[i+1]]\n num += (dict[arr[i+1]] - dict[arr[i]])\n i += 2\n else\n num += dict[arr[i]]\n i += 1\n end\n end \n return num \nend\n \n", "def new_roman_numeral num\n roman = \"\"\n if num == 400\n roman = \"CD\"\n elsif num == 40\n roman = \"XL\"\n elsif num == 4\n roman = \"IV\"\n elsif num == 9\n roman == \"IX\"\n elsif num == 90\n roman == \"XC\"\n elsif num == 900\n roman == \"CM\"\n end\n roman += \"M\" * (num/1000)\n roman += \"D\" * ((num%1000)/500)\n roman += \"C\" * ((num%500)/100)\n roman += \"L\" * ((num%100)/50)\n roman += \"X\" * ((num%50)/10)\n roman += \"V\" * ((num%10)/5)\n roman += \"I\" * ((num%5)/1)\n puts roman\n end", "def romanNumerator(romanString)\n charArray = romanString.chars\n romanSum = 0\n\n charArray.each_with_index do |char, index|\n\n nextChar = charArray[index + 1]\n charCombo = []\n charCombo << charArray[index]\n charCombo << charArray[index+1]\n charCombo = charCombo.join.upcase\n\n\n if charCombo == \"IV\" || charCombo == \"IX\" || charCombo == \"XL\" || charCombo == \"XC\" || charCombo == \"CD\" || charCombo == \"CM\"\n if charCombo == \"IV\"\n romanSum += 4\n charArray[index+1] = 0\n elsif charCombo == \"IX\"\n romanSum += 9\n charArray[index+1] = 0\n elsif charCombo == \"XL\"\n romanSum += 40\n charArray[index+1] = 0\n elsif charCombo == \"XC\"\n romanSum += 90\n charArray[index+1] = 0\n elsif charCombo == \"CD\"\n romanSum += 400\n charArray[index+1] = 0\n elsif charCombo == \"CM\"\n romanSum += 900\n charArray[index+1] = 0\n end\n elsif char == \"I\"\n romanSum += 1\n elsif char == \"V\"\n romanSum += 5\n elsif char == \"X\"\n romanSum += 10\n elsif char == \"L\"\n romanSum += 50\n elsif char == \"C\"\n romanSum += 100\n elsif char == \"D\"\n romanSum += 500\n elsif char == \"M\"\n romanSum += 1000\n end\n end\n\n return romanSum\n\nend", "def numeral(number)\n\tnumerals = {:I => 1, :V => 5, :X => 10, :L => 50, \n\t\t:C => 100, :D => 500, :M => 1000}\n\torder = [:M,:D,:C,:L,:X,:V,:I]\n\toutput = \"\"\n\torder.each do |n|\n\t\tif numerals[n] <= number\n\t\t\ttimes = number / numerals[n]\n\t\t\tremainder = number % numerals[n]\n\t\t\toutput += n.to_s * times\n\t\t\tnumber = remainder\n\t\tend\n\tend\n\toutput\nend", "def old_roman_string num\n raise \"Use positive integer\" if num <= 0\n roman_str = ''\nroman_str << 'M' * (num /1000)\nroman_str << 'D' * (num % 1000 / 500)\nroman_str << 'C' * (num % 500 / 100)\nroman_str << 'L' * (num % 100 / 50)\nroman_str << 'X' * (num % 50 / 10)\nroman_str << 'V' * (num % 10 / 5)\nroman_str << 'I' * (num % 5 / 1)\n\n#build up the strings by * H,T,U\nend", "def get_roman()\n num = @number\n answer = \"\"\n# you can also use: If num >= 10 \n\n while num >= 10\n answer += \"X\"\n num -= 10\n end\n if num == 9\n answer += \"IX\"\n num -= 9\n end\n if num >= 5\n answer += \"V\"\n num -= 5\n end\n if num == 4\n answer += \"IV\"\n num -= 4\n end\n answer += \"I\" * num # * @number\n return answer\n end", "def roman_to_integer(roman)\n values = {i: 1, v: 5, x: 10, l: 50, c: 100, d: 500, m: 1000}\n total = 0\n prev = 0\n index = roman.length - 1\n while index >= 0\n c = roman[index].downcase\n c = c.to_sym\n index = index - 1\n value = values[c]\n if !value\n return \"Not a valid roman numeral\"\n end\n if value < prev\n value = value * -1\n else\n prev = value\n end\n total = total + value\n end\n total\nend", "def to_roman\n\n roman = ''\n\n roman = roman + 'M' * (self / 1000)\n roman = roman + 'D' * (self % 1000 / 500)\n roman = roman + 'C' * (self % 500 / 100)\n roman = roman + 'L' * (self % 100 / 50)\n roman = roman + 'X' * (self % 50 / 10)\n roman = roman + 'V' * (self % 10 / 5)\n roman = roman + 'I' * (self % 5 / 1)\n\n roman\n end", "def num_to_roman_numeral num\n \n orig_num = num\n \n # Clear values for all characters before starting\n m = ''\n d = ''\n c = ''\n l = ''\n x = ''\n v = ''\n i = ''\n \n # Get 1000s\n if num/1000 >= 1\n m = 'M'*(num/1000)\n num = num%1000\n end\n \n # Get 500s\n if num/500 >= 1\n if num/100 == 9\n d = ''\n c = 'CM'\n num = num%100\n else\n d = 'D'*(num/500)\n num = num%500\n end\n end\n \n # Get 100s\n if num/100 >= 1\n c = 'C'*(num/100)\n num = num%100\n end\n \n # Get 50s\n if num/50 >= 1\n if num/10 == 9\n l = ''\n x = 'XC'\n num = num%10\n else\n l = 'L'*(num/50)\n num = num%50\n end\n end\n \n # Get 10s\n if num/10 >= 1\n if num/10 == 4\n x = 'XL'\n else\n x = 'X'*(num/10)\n end\n num = num%10\n end\n \n # Get 5s\n if num/5 >= 1\n if num == 9\n v = ''\n i = 'IX'\n num = 0\n else\n v = 'V'*(num/5)\n num = num%5\n end\n end\n \n # Get 1s\n if num >= 1\n if num == 4\n i = 'IV'\n num = 0\n else\n i = 'I'*num\n end\n end\n \n roman_numeral = m + d + c + l + x + v + i\n \n puts orig_num.to_s + ' in old roman numerals is ' + roman_numeral\nend", "def roman\n #old_roman = nil\n #i,v,x,l,c,d,ms,request = nil\n while true \n puts \"enter a number between 1 and 3000 ['q' to quit program]\"\n request = gets.chomp\n break if request.downcase == 'q'\n (puts 'only enter between 1 and 3000';next) if request.to_i < 1 || request.to_i > 3000\n request= request.to_i\n ms = request / 1000\n test = request % 1000\n d = test / 500\n test = test % 500\n c = test / 100\n test = test % 100\n l = test / 50\n test = test % 50\n x = test / 10\n test = test % 10\n v = test / 5\n test = test % 5\n i = test\n puts\n puts \n old_roman = 'M'*ms + 'D'*d + 'C'*c+ 'L'*l + 'X'*x + 'V'*v+ 'I'*i\n puts old_roman\n end\n old_roman\nend", "def roman_numeral num\n\tif num > 999999\n\t\treturn \"number too big for roman numerals\"\n\tend\n\n\trom_digits = ['I','V','X','L','C','D','M','P','Q','R','S','T','A','B','E','F']\n\tnum_of_digits = (num).to_s.length\n\troman_num = ''\n\n\tfor i in 0...num_of_digits\n\t\troman_num = romnum_1_to_9(num,rom_digits[i*2],rom_digits[i*2+1],rom_digits[i*2+2],10**i) + roman_num\n\tend\n\t\n\treturn roman_num.downcase\n\nend", "def old_roman_numeral number\n\n if number >= 1000\n thousands = 'M' * (number / 1000)\n end\n\n if number >= 100\n hundreds = (number % 1000) / 100\n if hundreds >= 5\n hundreds = 'D' + 'C' * (hundreds - 5)\n else\n hundreds = 'C' * ((number % 1000) / 100)\n end\n end\n\n if number >= 10\n tens = (number % 100) / 10\n if tens >= 5\n tens = 'L' + 'X' * (tens - 5)\n else\n tens = 'X' * ((number % 100) / 10)\n end\n end\n\n if number >= 1\n ones = (number % 10) / 1\n if ones >= 5\n ones = 'V' + 'I' * (ones - 5)\n else\n ones = 'I' * ((number % 10) / 1)\n end\n end\n\n puts \"#{number} in old-school Roman numerals is \"+\"#{thousands}\"+\"#{hundreds}\"+\"#{tens}\"+\"#{ones}\"\nend", "def old_roman_numeral num\n\troman = ''\n\n\troman = roman + 'M' * (num / 1000)\n\troman = roman + 'D' * (num % 1000 / 500)\n\troman = roman + 'C' * (num % 500 / 100)\n\troman = roman + 'L' * (num % 100 / 50)\n\troman = roman + 'X' * (num % 50 / 10)\n\troman = roman + 'V' * (num % 10 / 5)\n\troman = roman + 'I' * (num % 5 / 1)\n\n\troman\nend", "def new_numeral_maker(num)\n i = 'I' * ((num % 5) / 1)\n v = 'V' * ((num % 10) / 5)\n x = 'X' * ((num % 50) / 10)\n l = 'L' * ((num % 100) / 50)\n c = 'C' * ((num % 500) / 100)\n\n four_error = 'IIII'\n nine_error = 'VIIII'\n forty_error = 'XXXX'\n ninety_error = 'LXXXX'\n four_hundred_error = 'CCCC'\n\n # hundreds\n if c == four_hundred_error\n print('DC')\n else\n print(c)\n end\n\n # tens\n if l + x == ninety_error\n print('XC')\n elsif x == forty_error\n print('XL')\n else\n print(x)\n end\n\n # ones and teens\n if v + i == nine_error\n print('IX')\n elsif i == four_error\n print('IV')\n else\n print(v + i)\n end\nend", "def english_number original_number\r\n current_number = original_number\r\n exploded_number = []\r\n # Convert number into an array of multiples of base units\r\n CONVERSIONS.each do |base_pair|\r\n if current_number >= base_pair[:number] * 2\r\n # Enter the multiple and the base unit as elements if necessary\r\n exploded_number << current_number / base_pair[:number]\r\n exploded_number << base_pair\r\n current_number %= base_pair[:number]\r\n elsif current_number >= base_pair[:number]\r\n # Enter just the base unit if there's no integer multiple\r\n exploded_number << base_pair\r\n current_number %= base_pair[:number]\r\n end\r\n # Otherwise enter nothing\r\n end\r\n # Eg array [{1000000}, 507, {1000}, 5, 100, 30, 7]\r\n # Reduce array to an English translation\r\n english_result = exploded_number.reduce([\"\",:start]) { |text_string, base_pair|\r\n # Add a space unless it's the start of the string\r\n text_string[0] += ' ' unless text_string[1] == :start\r\n # Convert current number to English if it's a multiple\r\n if base_pair.class == Integer\r\n text_string[0] += english_number(base_pair)\r\n text_string[1] = :multiple\r\n elsif base_pair[:number] >= ONE_PREFIX_BOUNDARY\r\n # Otherwise, if it's >= 100 and preceding unit is not a multiple add 'one'\r\n text_string[0] += 'one ' unless text_string[1] == :multiple\r\n text_string[0] += base_pair[:name]\r\n text_string[1] = :above_boundary\r\n else\r\n # Otherwise, if it's <100 and transitioning from >=100, add 'and'\r\n text_string[0] += 'and ' if text_string[1] == :above_boundary\r\n text_string[0] += base_pair[:name]\r\n text_string[1] = :below_boundary\r\n end\r\n text_string\r\n }[0]\r\n return english_result\r\nend", "def test_covert_one_to_roman\n generic_fn_roman_numerals( '1', 'I' )\n end", "def old_roman\n #old_roman = ''\n while true \n puts \"enter a number between 1 and 3000\"\n request = gets.chomp.to_i\n (puts 'only enter between 1 and 3000';next) if request < 1 || request > 3000\n ms = request / 1000\n test = request - ms*1000\n d = test / 500\n test = test - d*500\n c = test / 100\n test = test - c*100\n l = test / 50\n test = test - l*50\n x = test / 10\n test = test - x*10\n v = test / 5\n test = test - v*5\n i = test\n puts\n puts request\n puts 'M'*ms + 'D'*d + 'C'*c+ 'L'*l + 'X'*x + 'V'*v+ 'I'*i\n end\nend", "def to_modern_roman(number)\n\n\twhile number.to_i <= 3000\n\t\t# split number into an array\n\t\tarray = number.split(//).map { |x| x.to_i }\n\t\tresult =[]\n\t\t# array has length of 4\n\t\tuntil array.length == 4\n\t\tarray.unshift(0)\n\t\tend\n\t\t# 1000s of number\n\t\tif array[-4] < 4 \n\t\t\t\tnum = array[-4]\n\t\t\t\tnum.times { result << \"M\" }\n\t\tend\n\t\t# 100s of number\n\t\tif array[-3] < 4\n\t\t\t\tnum = array[-3]\n\t\t\t\tnum.times { result << \"C\" }\n\t\telsif array[-3] == 4\n\t\t\t\tnum = array[-3]\n\t\t\t\tresult << \"CD\"\n\t\telsif array[-3] == 6\n\t\t\t\tnum = array[-3]\n\t\t\t\tresult << \"DC\"\n\t\telsif array[-3] == 9\n\t\t\t\tnum = array[-3]\n\t\t\t\tresult << \"CM\"\n\t\telse\n\t\t\t\tnum = array[-3]\n\t\t\t\tresult << \"D\" \n\t\t\t\t(num-5).times { result << \"C\" }\n\t\tend\n\t\t# 10s of number\n\t\tif array[-2] < 4\n\t\t\t\tnum = array[-2]\n\t\t\t\tnum.times { result << \"X\" }\n\t\telsif array[-2] == 4\n\t\t\t\tnum = array[-2]\n\t\t\t\tresult << \"XL\"\n\t\telsif array[-2] == 6\n\t\t\t\tnum = array[-2]\n\t\t\t\tresult << \"LX\"\n\t\telsif array[-2] == 9\n\t\t\t\tnum = array[-2]\n\t\t\t\tresult << \"XC\"\n\t\telse\n\t\t\t\tnum = array[-2]\n\t\t\t\tresult << \"L\" \n\t\t\t\t(num-5).times { result << \"X\" }\n\t\tend\n\t\t# single digits of number\n\t\tif array[-1] < 4\n\t\t\t\tnum = array[-1]\n\t\t\t\tnum.times { result << \"I\" }\n\t\telsif array[-1] == 4\n\t\t\t\tnum = array[-1]\n\t\t\t\tresult << \"IV\"\n\t\telsif array[-1] == 6\n\t\t\t\tnum = array[-1]\n\t\t\t\tresult << \"VI\"\n\t\telsif array[-1] == 9\n\t\t\t\tnum = array[-1]\n\t\t\t\tresult << \"IX\"\n\t\telse\n\t\t\t\tnum = array[-1]\n\t\t\t\tresult << \"V\" \n\t\t\t\t(num-5).times { result << \"I\" }\t\n\t\tend\n\t\t# return number in roman numerals\n\t\tputs \"#{number} in New Style Roman Numerals is #{result.join(\"\")}.\"\n\t\texit\n\tend\n\tputs \"Number must be greater than 3000.\"\n\texit\nend" ]
[ "0.7349924", "0.72723097", "0.717049", "0.7079716", "0.70752275", "0.7042755", "0.7030761", "0.70078313", "0.70029527", "0.69749993", "0.69377095", "0.6910887", "0.6896755", "0.68681806", "0.68323076", "0.6802452", "0.6795064", "0.6783195", "0.678287", "0.6765192", "0.6760622", "0.6756336", "0.67382157", "0.6734407", "0.67281234", "0.6724361", "0.6721298", "0.67032915", "0.66994214", "0.6690899", "0.66664284", "0.66633373", "0.66574013", "0.66557163", "0.66437256", "0.6636498", "0.6605198", "0.6602466", "0.65978587", "0.6523226", "0.6510561", "0.65086323", "0.65068483", "0.65017164", "0.6498696", "0.64972526", "0.6484134", "0.6484098", "0.64785486", "0.647784", "0.6470785", "0.6453084", "0.64437705", "0.64322466", "0.64294654", "0.6423078", "0.6416188", "0.64017606", "0.63918996", "0.63901097", "0.6377921", "0.63721764", "0.63625324", "0.6359635", "0.63545096", "0.63466847", "0.63456213", "0.6327578", "0.63195306", "0.6314602", "0.6294185", "0.6292875", "0.6291285", "0.62875146", "0.62849194", "0.62511355", "0.62511355", "0.62501013", "0.62479764", "0.6222833", "0.62204826", "0.62163806", "0.6207349", "0.6186185", "0.61732394", "0.6170704", "0.61604667", "0.61505777", "0.61485165", "0.6138032", "0.61222464", "0.6113228", "0.6106263", "0.61020356", "0.6092119", "0.6085395", "0.60817546", "0.6064081", "0.6063591", "0.6055007", "0.6050615" ]
0.0
-1
Function created to help break down the divisibility of the number to be converted and the keys in the roman hash
def num_converter_update(num_to_convert,key) num_to_convert % key end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def to_num(input)\n result = 0\n #iterate on roman number hash\n MAPPING.each do |k,v|\n while input.index(k) == 0 #if \"CL\".index(\"C\") == 0\n result += v #assign value of current hash key\n input.slice!(0) #remove string \"C\" from input and so on\n end\n end\n result\n end", "def convertToRoman(n)\n #divide by roman num taken out\n #num is remainder \n #repeat\n roman = { 1000 => \"M\", 900 => \"CM\", 500 => \"D\", 400 => \"CD\", 100 => \"C\", 90 => \"XC\", 50 => \"L\", 40 => \"XL\", 10 => \"X\", 9 => \"IX\", 5 => \"V\", 4 => \"IV\", 1 => \"I\" }\n\n ans = \"\"\n roman.keys.each do |divisor|\n quotient, modulus = n.divmod(divisor)\n ans << roman[divisor] * quotient\n n = modulus\n end\n return ans \nend", "def numeralise!(num, ans=\"\", mapping = roman_mapping)\n return ans if num == 0\n \n mapping.keys.each do |key_num|\n next unless key_num <= num\n quotient, modulus = num.divmod(key_num)\n ans << (mapping[key_num] * quotient)\n return numeralise!(modulus, ans) if quotient > 0\n end\nend", "def hash\n num = 0\n self.each do |k,v|\n if k.is_a?(Integer) && v.is_a?(Integer)\n num += k * 26 + v\n elsif k.is_a?(Integer) && !v.is_a?(Integer)\n num += k * 26 + ALPHA_NUMBERS[v.to_s.downcase]\n elsif v.is_a?(Integer) && !k.is_a?(Integer)\n num += v * 26 + ALPHA_NUMBERS[k.to_s.downcase]\n elsif !k.nil? && !v.nil?\n num += ALPHA_NUMBERS[k.to_s.downcase] * ALPHA_NUMBERS[v.to_s.downcase]\n end\n end\n num\n end", "def to_roman2(num)\n result = \"\"\n \n @roman_mapping.each do |pair|\n value = pair[0]\n roman = pair[1]\n division_result = num / value\n result += roman * division_result\n num = num - (value * division_result)\n end\n return result\nend", "def romanize(input)\n\n raise ArgumentError, 'can not encode negative number' if input < 0\n raise ArgumentError, 'can not encode zero' if input == 0\n\n #Creating a Hash that pointing different numbers to different characters.\n romkeys = {1000 => 'M', 900 => 'CM', 500 => 'D', 400 => 'CD', 100 => 'C', 90 => 'XC', 50 => 'L', 40 => 'XL', 10 => 'X', 9 => 'IX', 5 => 'V', 4 => 'IV' ,1 => 'I'}\n\n #Creating a variable that have the format string, for storing the different characters.\n output = ' '\n\n #Looping until the input is zero.\n until input == 0\n\n #Looping thro the different keys and values of the hash.\n romkeys.each do |key, value|\n if input >= key\n\n #If the input was 5 this will result as 'V' after that the output will save the V and loop thro until it's nothing left.\n output += value\n\n #This subtract the key value to make the loop end.\n input -= key\n\n #This just ending the loop.\n break\n end\n end\n end\n\n #Returning the output string.\n return output\nend", "def roman_numeral roman\n\tnumerals_hash = {\n\t\t\"i\" => 1, \n\t\t\"iv\"=> 4,\n\t\t\"v\" => 5, \n\t\t\"ix\"=> 9,\n\t\t\"x\" => 10, \n\t\t\"xl\" => 40,\n\t\t\"l\" => 50, \n\t\t\"xc\" => 90,\n\t\t\"c\" => 100, \n\t\t\"cd\" => 400,\n\t\t\"d\" => 500, \n\t\t\"cm\" => 900,\n\t\t\"m\" => 1000,\n\t\t}\n\tnumber_array = []\n\n\troman = roman.downcase\n\tinteger =0\n\n\tif roman == \"iv\"\n\t\tinteger = 4\n\telsif\troman.include? \"iv\" \n\t\tinteger += 4\n\t\troman = roman[0..roman.length-3]\n\t\troman_array = roman.downcase.split(//)\n\t\tstop_at = roman_array.length-2\n\t\t\n\t\troman_array.each do |numeral|\n\t\teach_num = numerals_hash[numeral]\n\t\tnumber_array.push each_num\n\t\tend\n\n\t\tstop_at = number_array.length-1\n\n\t\t(0..stop_at).each do |number|\n\t\tinteger += number_array[number]\n\t\tend\n\telsif roman == \"ix\"\n\t\tinteger = 9\n\telsif roman.include? \"ix\"\n\t\tinteger+=9\n\t\troman = roman[0..roman.length-3]\n\t\troman_array = roman.downcase.split(//)\n\t\tstop_at = roman_array.length-2\n\t\t\n\t\troman_array.each do |numeral|\n\t\teach_num = numerals_hash[numeral]\n\t\tnumber_array.push each_num\n\t\tend\n\n\t\tstop_at = number_array.length-1\n\n\t\t(0..stop_at).each do |number|\n\t\tinteger += number_array[number]\n\t\tend\n\telsif roman == \"xl\"\n\t\tinteger = 40\n\telsif roman.include? \"xl\"\n\t\tinteger+=40\n\t\troman = roman[0..roman.length-3]\n\t\troman_array = roman.downcase.split(//)\n\t\tstop_at = roman_array.length-2\n\t\t\n\t\troman_array.each do |numeral|\n\t\teach_num = numerals_hash[numeral]\n\t\tnumber_array.push each_num\n\t\tend\n\n\t\tstop_at = number_array.length-1\n\n\t\t(0..stop_at).each do |number|\n\t\tinteger += number_array[number]\n\t\tend\n\telsif roman == \"xc\"\n\t\tinteger = 90\n\telsif roman.include? \"xc\"\n\t\tinteger+=90\n\t\troman = roman[0..roman.length-3]\n\t\troman_array = roman.downcase.split(//)\n\t\tstop_at = roman_array.length-2\n\t\t\n\t\troman_array.each do |numeral|\n\t\teach_num = numerals_hash[numeral]\n\t\tnumber_array.push each_num\n\t\tend\n\n\t\tstop_at = number_array.length-1\n\n\t\t(0..stop_at).each do |number|\n\t\tinteger += number_array[number]\n\t\tend\n\telsif roman == \"cd\"\n\t\tinteger = 400\n\telsif roman.include? \"cd\"\n\t\tinteger+=400\n\t\troman = roman[0..roman.length-3]\n\t\troman_array = roman.downcase.split(//)\n\t\tstop_at = roman_array.length-2\n\t\t\n\t\troman_array.each do |numeral|\n\t\teach_num = numerals_hash[numeral]\n\t\tnumber_array.push each_num\n\t\tend\n\n\t\tstop_at = number_array.length-1\n\n\t\t(0..stop_at).each do |number|\n\t\tinteger += number_array[number]\n\t\tend\n\telsif roman == \"cm\"\n\t\tinteger = 900\n\telsif roman.include? \"cm\"\n\t\tinteger+=900\n\t\troman = roman[0..roman.length-3]\n\t\troman_array = roman.downcase.split(//)\n\t\tstop_at = roman_array.length-2\n\t\t\n\t\troman_array.each do |numeral|\n\t\teach_num = numerals_hash[numeral]\n\t\tnumber_array.push each_num\n\t\tend\n\n\t\tstop_at = number_array.length-1\n\n\t\t(0..stop_at).each do |number|\n\t\tinteger += number_array[number]\n\t\tend\n\telse\n\t\troman_array = roman.split(//)\n\t\tstop_at = roman_array.length-2\n\t\t\n\t\troman_array.each do |numeral|\n\t\teach_num = numerals_hash[numeral]\n\t\tnumber_array.push each_num\n\t\tend\n\n\t\tstop_at = number_array.length-1\n\n\t\t(0..stop_at).each do |number|\n\t\tinteger += number_array[number]\n\t\tend\n\tend\n\n\tinteger\n\n\t\n# # Replaces the numeral letters in our array with integers via our hash\n# roman_array.each do |numeral|\n# each_num = numerals_hash[numeral]\n# number_array.push each_num\n# end\n\n# # Creates a new 2d array, filled with smaller arrays representing each pair of \"letters\"\n# \tresult = []\n\n# \t(0..stop_at).each do |i|\n# \t\tresult.push number_array[i..i+1]\n# \tend\n\n=begin\n\t\n our code stops working here. We were trying to compare\n each pair of values in the original array to determine\n if the value should be added or subtracted from a running\n integer total that would total up the value of the \n numeral. \n\t\n\n \t\n \tstop_at_2 = result.length-1\n \tinteger = 0\n \t\n\n \t(0..stop_at_2).each do |i|\n \t\tif result[i][i] >= result[i][i+1]\n \t \t\tinteger += result[i][i]\n \t \telse\n \t \t\tinteger += (result[i][i+1]-result[i][i])\n \t \tend\n \tend\n \t\n integer\nend\n\n\nOur tests don't make much sense at this point. We were\nbuilding smaller problems and small tests to fix them, \nbuilding up to bigger problems with our original method of\ncomparing pairs of numbers against each other.\n\nclass TestNumerals < Minitest::Test\n\t def test_x\n\t \tassert_equal roman_numeral(\"x\"), 10\n\t end\t\n\n\t def test_array_split\n\t \tassert_equal roman_numeral(\"XI\"),[\"X\",\"I\"]\n\t end\n\n\t def test_array2\n\t \tassert_equal roman_numeral(\"XIVXIL\"), [10,1,5,10,1,50]\n\t end\n\n\t def test_integer1\n\t \tassert_equal 60, roman_numeral(\"LX\")\n\t end\n\n\t def test_pair_up\n\t\tassert_equal roman_numeral(\"LXXIV\"), [[50,10],[10,10],[10,1],[1,5]]\n\t end\nend\n=end\nend", "def solution(roman)\n dict = { \"I\" => 1, \"V\" => 5, \"X\" => 10, \"L\" => 50, \"C\" => 100, \"D\" => 500, \"M\" => 1000, \"N\" => 0 }\n return 0 if roman == \"N\"\n arr = roman.split(//)\n \n arr.each do |char| # check if all characters are valid\n if !dict.keys.include?(char)\n raise \"Invalid\"\n end \n end\n \n fre = Hash.new(0)\n arr.each do |char|\n fre[char] += 1\n end\n \n raise \"Invalid\" if fre[\"V\"], fre[\"L\"], fre[\"D\"] == 2 # these characters can't appear twice\n \n fre.each_value do |value| # a character can't repeat more than 3 times\n if value > 3\n raise \"Invalid\"\n end\n end\n \n # translation starts\n\n num = 0\n last = arr.length\n arr<<'N'\n i = 0\n while i < last\n if dict[arr[i]] < dict[arr[i+1]]\n num += (dict[arr[i+1]] - dict[arr[i]])\n i += 2\n else\n num += dict[arr[i]]\n i += 1\n end\n end \n return num \nend\n \n", "def conversion(number)\n words_hash = {0=>\"zero\",1=>\"one\",2=>\"two\",3=>\"three\",4=>\"four\",5=>\"five\",6=>\"six\",7=>\"seven\",8=>\"eight\",9=>\"nine\",\n 10=>\"ten\",11=>\"eleven\",12=>\"twelve\",13=>\"thirteen\",14=>\"fourteen\",15=>\"fifteen\",16=>\"sixteen\",\n 17=>\"seventeen\", 18=>\"eighteen\",19=>\"nineteen\",\n 20=>\"twenty\",30=>\"thirty\",40=>\"forty\",50=>\"fifty\",60=>\"sixty\",70=>\"seventy\",80=>\"eighty\",90=>\"ninety\"}\n if words_hash.has_key?number\n return words_hash[number] \n else\n num_string = number.to_s.split(//)\n while num_string.size > 0 \n if num_string.size == 2\n return(\"and\")\n return words_hash[(num_string.join.to_i) - (num_string.join.to_i)%10] \n num_string.shift\n end\n if num_string.size > 4\n return(words_hash[(num_string[0,2].join.to_i) - (num_string[0,2].join.to_i) % 10])\n else\n return(words_hash[num_string[0].to_i]) \n end\n return(scale[num_string.size])\n num_string.shift\n end\n end\n\nend", "def solution(number)\n\nm, r_1 = number.divmod(1000)\ncd, r_2 = r_1.divmod(100)\nlx, r_3 = r_2.divmod(10)\nvi, r_4 = r_3.divmod(1)\n\nroman = []\n\nm.times { roman << \"M\" }\n\nif cd <= 3\n\tcd.times { roman << \"C\" }\nelsif cd == 4\n\troman << \"CD\"\nelsif cd == 5\n\troman << \"D\"\nelsif cd > 5 && cd < 9\n\troman << \"D\"\n\t(cd - 5).times { roman << \"C\" }\nelsif cd == 9\n\troman << \"CM\"\nend\n\nif lx <= 3\n\tlx.times { roman << \"X\" }\nelsif lx == 4\n\troman << \"XL\"\nelsif lx == 5\n\troman << \"L\"\nelsif lx > 5 && lx < 9\n\troman << \"L\"\n\t(lx - 5).times { roman << \"X\" }\nelsif lx == 9\n\troman << \"XC\"\nend\n\nif vi <= 3\n\tvi.times { roman << \"I\" }\nelsif vi == 4\n\troman << \"IV\"\nelsif vi == 5\n\troman << \"V\"\nelsif vi > 5 && vi < 9\n\troman << \"V\"\n\t(vi - 5).times { roman << \"I\" }\nelsif vi == 9\n\troman << \"IX\"\nend\n\nroman.join\n\nend", "def roman_to_int(str)\n hash = {\n 'M' => 1000,\n 'D' => 500,\n 'C' => 100,\n 'L' => 50,\n 'X' => 10,\n 'V' => 5,\n 'I' => 1,\n }\n sum = 0\n cur = 0\n\n str.chars.each do |l|\n prev = cur\n cur = hash[l]\n sum += cur\n sum -= (prev * 2) if prev < cur\n end\n\n sum\nend", "def dec_rom_num_map\n {\n 3000 => \"MMM\",\n 2000 => \"MM\",\n 1000 => \"M\",\n 900 => \"DCCCC\",\n 800 => \"DCCC\",\n 700 => \"DCC\",\n 600 => \"DC\",\n 500 => \"D\",\n 400 => \"CCCC\",\n 300 => \"CCC\",\n 200 => \"CC\",\n 100 => \"C\",\n 90 => \"LXXXX\",\n 80 => \"LXXX\",\n 70 => \"LXX\",\n 60 => \"LX\",\n 50 => \"L\",\n 40 => \"XXXX\",\n 30 => \"XXX\",\n 20 => \"XX\",\n 10 => \"X\",\n 9 => \"VIIII\",\n 8 => \"VIII\",\n 7 => \"VII\",\n 6 => \"VI\",\n 5 => \"V\",\n 4 => \"IIII\",\n 3 => \"III\",\n 2 => \"II\",\n 1 => \"I\"\n }\nend", "def number_decoder( input )\n output = \"\"\n \n # build number to letter hash\n translator = Hash.new\n letters = ('A'..'Z').to_a\n letters.each_index{|i| translator [(i+1).to_s] = letters[i] }\n \n input.each(' ') do |nibble|\n\n \n num = nibble.strip.to_i\n if (num == 0 or num.nil?) then output << \" \"\n else\n case (num-1)/26\n when 0 then output << translator[num.to_s]# + ' '\n when 1 then output << translator[(num - 26).to_s]\n end\n end\n end\n \n output\nend", "def to_roman\n result = ''\n number = self\n ROMAN_NUMERALS.each do |key, value|\n numeral, remainder = number.divmod(value)\n if numeral > 0 \n result += (key * numeral)\n end\n number = remainder\n end\n result\n end", "def calculate_multiple(number, decimal)\n # for 522 => number = 5, decimal = 100.\n # number = 2, decimal = 10\n # number = 2, decimal = 1\n\n # below both cases we do not utilize number field\n # 44 is different -> 40, 4 -> XLIV (10 - 50, 1 - 5)\n # 99 is different -> 90, 9 -> XCIX (10 - 90, 1 - 9)\n case number\n when 0\n ''\n when (1..3)\n @roman_hash[decimal] * number\n when 4\n @roman_hash[decimal] + @roman_hash[decimal * 5]\n when 5\n @roman_hash[5 * decimal]\n when 6..8\n @roman_hash[5 * decimal] + (@roman_hash[decimal] * (number - 5))\n when 9\n @roman_hash[decimal] + @roman_hash[decimal * 10]\n else\n 'Quit'\n end\n end", "def vol_roman\n dict = { M: 1000, CM: 900, D: 500, CD: 400,\n C: 100, XC: 90, L: 50, XL: 40,\n X: 10 , IX: 9, V: 5, IV: 4,\n I: 1 };\n input, output = vol.to_i, ''\n\n # Descend through the character list.\n dict.each_pair do |r, a|\n # Subtract from the input/add to the output until\n # this character is no longer useful.\n while input >= a { input -= a; output << r.to_s }\n end\n \n output\n end\nend", "def number_to_words_hash\n num_hash = Hash.new\n num_hash[0] = \"zero\"\n num_hash[1] = \"one\"\n num_hash[2] = \"two\"\n num_hash[3] = \"three\"\n num_hash[4] = \"four\"\n num_hash[5] = \"five\"\n num_hash[6] = \"six\"\n num_hash[7] = \"seven\"\n num_hash[8] = \"eight\"\n num_hash[9] = \"nine\"\n num_hash[10] = \"ten\"\n num_hash[11] = \"eleven\"\n num_hash[12] = \"twelve\"\n num_hash[13] = \"thirteen\"\n num_hash[14] = \"fourteen\"\n num_hash[15] = \"fifteen\"\n num_hash[16] = \"sixteen\"\n num_hash[17] = \"seventeen\"\n num_hash[18] = \"eighteen\"\n num_hash[19] = \"nineteen\"\n num_hash[20] = \"twenty\"\n num_hash[30] = \"thirty\"\n num_hash[40] = \"forty\"\n num_hash[50] = \"fifty\"\n num_hash[60] = \"sixty\"\n num_hash[70] = \"seventy\"\n num_hash[80] = \"eighty\"\n num_hash[90] = \"ninety\"\n \n return num_hash\nend", "def roman_to_integer(roman_value)\n digital_vals = {'i'=> 1, 'v'=> 5, 'x'=> 10, 'l'=> 50, \n 'c'=> 100, 'd'=> 500, 'm'=> 1000,}\n\n roman_value.each_char do |char|\n if digital_vals.has_key?(char) == false\n return \"Invalid Entry!\"\n end \n end\n\n \n\n reversed_roman_value = roman_value.reverse\n total_value = 0\n prev_val = 0\n prev_char = ''\n reversed_roman_value.each_char do |char|\n val = digital_vals[char]\n\n val < prev_val ? val *= -1 : prev_val = val\n total_value += val\n\n\n\n=begin \nNote: The commented method below isn't concise and simple as the current implementation\nabove.\nInstead of comparing the alphabets, it's simpler to compare the values\n case \n when ((char == 'i') && (prev_char == 'x')) then total_value -= 1\n when ((char == 'i') && (prev_char == 'v')) then total_value -= 1\n when ((char == 'x') && (prev_char == 'l')) then total_value -= 10\n when ((char == 'x') && (prev_char == 'c')) then total_value -= 10\n when ((char == 'c') && (prev_char == 'd')) then total_value -= 100\n when ((char == 'c') && (prev_char == 'm')) then total_value -= 100\n else \n total_value += digital_vals[char]\n end\n prev_char = char\n\n=end \n\n end\n\n \n\n \n total_value\nend", "def old_school_roman_numeral(num)\n arabs_to_romans = [\n ['M', 1000],\n ['D', 500],\n ['C', 100],\n ['L', 50],\n ['X', 10],\n ['V', 5],\n ['I', 1]\n ]\n\n result = ''\n\n arabs_to_romans.each do |arab_to_roman|\n arab = arab_to_roman[1]\n roman = arab_to_roman[0]\n\n if num / arab != 0\n result += roman * (num / arab)\n num = num % arab\n end\n end\n result\nend", "def from_roman(str)\n hash = {}\n str.each_char do |letter|\n hash.default = 0\n hash[rn_to_decimal(letter)] += 1 \n end\n array = []\n hash.each do |k, v|\n array << k*v\n end\n array.reduce(:+)\nend", "def decode_metal_value\n\tromanhash = {}\n\tcredithash, codehash = read_input\n\tcredithash.each_pair { |k,v|\n\t\troman_str = get_roman_equiv(k)\n\t\tvalidate_roman(roman_str)\n\t\tromanhash[ roman_str + \" \" + k.split(\" \").last ] = v\n\t\t}\n\treturn romanhash\nend", "def solution(number)\n roman_numeral = { 1 => 'I', 4 => 'IV', 5=> 'V', 6 => 'VI', 10=> 'X', 50=> 'L', 100=> 'C', 500=> 'D', 1000=> 'M' }\n numbers = number.digits.map.with_index{ |int, idx| int * 10**idx }\n numbers.map{ |number| roman_numeral[number] }.reverse.join\nend", "def to_roman\n result = \"\"\n number = self\n roman_mapping.keys.each do |divisor|\n quotient, modulus = number.divmod(divisor)\n result << roman_mapping[divisor] * quotient\n number = modulus\n end\n result\n end", "def numberise!(numeral, ans=0, mapping = roman_mapping)\n return ans if numeral.empty?\n\n mapping.values.each do |roman_num|\n while numeral[0..roman_num.size-1] == roman_num\n ans += mapping.key(roman_num)\n numeral = numeral[roman_num.size..-1]\n end\n end\n return numberise!(numeral, ans)\nend", "def prepare_group(integer, roman, group_value, group_letter, lower_value, lower_letter)\n count, integer = integer.divmod(group_value)\n roman += group_letter * count\n if lower_value and integer >= lower_value\n roman += lower_letter\n integer -= lower_value\n end\n return integer, roman\nend", "def to_roman3(num)\n result = \"\"\n @roman_mapping.each do |pair|\n value = pair[0]\n binding.pry\n roman = pair[1]\n level_occurance = num / value\n level_occurance.times do |x|\n result << roman\n end\n num = num - value * level_occurance\n end\n return result\nend", "def fraction(hash,n)\n result = {}\n result[:n] = (n - hash[:minus]**2)/hash[:n]\n result[:i] = (Math.sqrt(n).to_i + hash[:minus])/result[:n]\n result[:minus] = result[:i]*result[:n]-hash[:minus]\n result\nend", "def old_roman_numeral(num)\n\t@romanNumeral = \"\"\t\n\n\twhile num > 0\n\t\tquotient, modulus = num.divmod(1000)\n\t\t\tif quotient > 0 \t\t\t\t\t\t\t\t\t\t#using a divisor \n\t\t\t@romanNumeral << (\"M\" * quotient) #using divisor again\n\t\t\tnum = modulus\t\t\t\t\t\t\t\t\t\t\t\t#using modulus\n\t\telsif\n\t\t\tnum / 500 > 0\n\t\t\t@romanNumeral << (\"D\" * (num/500))\n\t\t\tnum %= 500\n\t\telsif\n\t\t\tif num / 100 > 0\n\t\t\t\t@romanNumeral << (\"C\" * (num/100))\n\t\t\t\tnum %= 100\n\t\t\telsif \n\t\t\t\tnum / 90 > 0 \n\t\t\t\t@romanNumeral << (\"XC\" * (num/90))\n\t\t\t\tnum %= 90\n\t\t\tend\n\t\telsif\n\t\t\tif num / 50 > 0\n\t\t\t@romanNumeral << (\"L\" * (num/50))\n\t\t\tnum %= 50\n\t\t\telsif \n\t\t\t\tnum / 40 > 0\n\t\t\t\t@romanNumeral << (\"XL\" * (num/40))\n\t\t\t\tnum %= 40 \t\t\t\n\t\t\tend\n\t\telsif\n\t\t\tif num / 10 > 0\n\t\t\t\t@romanNumeral << (\"X\" * (num/10))\n\t\t\t\tnum %= 10\n\t\t\telsif\n\t\t\t\tnum / 9 > 0\n\t\t\t\t@romanNumeral << (\"IX\" * (num/9))\n\t\t\t\tnum %= 9 \n\t\t\tend\n\t\telsif\n\t\t\tnum / 5 > 0\n\t\t\t@romanNumeral << (\"V\" * (num/5))\n\t\t\tnum %= 5\n\t\telse\n\t\t\tif\n\t\t\t\tnum / 4 > 0 \n\t\t\t\t@romanNumeral << (\"I\" * (num/4))\n\t\t\t\tnum %= 4\n\t\t\telse\n\t\t\t\tnum / 1 > 0 \n\t\t\t\t@romanNumeral << (\"I\" * (num/1))\n\t\t\t\tnum %= 1\n\t\t\tend\t\n\t\tend\n\tend\n\n\t@romanNumeral\n\nend", "def to_roman(num)\n\toutput = \"\"\n\t@roman_num.each do |key, val|\n\t\tremainder = num%key.to_i\n\t\twhile remainder < num\n\t\t\toutput << val\n\t\t\tnum = num - key.to_i\n\t\tend\n\tend\n\toutput\nend", "def english_number original_number\r\n current_number = original_number\r\n exploded_number = []\r\n # Convert number into an array of multiples of base units\r\n CONVERSIONS.each do |base_pair|\r\n if current_number >= base_pair[:number] * 2\r\n # Enter the multiple and the base unit as elements if necessary\r\n exploded_number << current_number / base_pair[:number]\r\n exploded_number << base_pair\r\n current_number %= base_pair[:number]\r\n elsif current_number >= base_pair[:number]\r\n # Enter just the base unit if there's no integer multiple\r\n exploded_number << base_pair\r\n current_number %= base_pair[:number]\r\n end\r\n # Otherwise enter nothing\r\n end\r\n # Eg array [{1000000}, 507, {1000}, 5, 100, 30, 7]\r\n # Reduce array to an English translation\r\n english_result = exploded_number.reduce([\"\",:start]) { |text_string, base_pair|\r\n # Add a space unless it's the start of the string\r\n text_string[0] += ' ' unless text_string[1] == :start\r\n # Convert current number to English if it's a multiple\r\n if base_pair.class == Integer\r\n text_string[0] += english_number(base_pair)\r\n text_string[1] = :multiple\r\n elsif base_pair[:number] >= ONE_PREFIX_BOUNDARY\r\n # Otherwise, if it's >= 100 and preceding unit is not a multiple add 'one'\r\n text_string[0] += 'one ' unless text_string[1] == :multiple\r\n text_string[0] += base_pair[:name]\r\n text_string[1] = :above_boundary\r\n else\r\n # Otherwise, if it's <100 and transitioning from >=100, add 'and'\r\n text_string[0] += 'and ' if text_string[1] == :above_boundary\r\n text_string[0] += base_pair[:name]\r\n text_string[1] = :below_boundary\r\n end\r\n text_string\r\n }[0]\r\n return english_result\r\nend", "def numbers_to_numerals\n {\n 1 => \"I\",\n 4 => \"IV\",\n 5 => \"V\",\n 9 => \"IX\",\n 10 => \"X\",\n 40 => \"XL\",\n 50 => \"L\",\n 90 => \"XC\",\n 100 => \"C\",\n 400 => \"CD\",\n 500 => \"D\",\n 900 => \"CM\",\n 1000 => \"M\"\n }\n end", "def problem_108a\n i = 4\n max = 0\n solve = {}\n loop do\n num = 0\n a = Rational(1,i)\n 2.upto(i*2+1) do |j|\n if (a - Rational(1,j)).numerator == 1\n num += 1 \n# puts \"(#{a} - #{Rational(1,j)} == #{a - Rational(1,j)}\"\n end\n end\n\n solve[num] = [] unless solve[num]\n solve[num] << i.factors\n\n if num >= max\n puts \"####################################\"\n solve.each_key.sort.each do |k|\n s = solve[k].map do |v|\n h = {}\n v.each {|a| h[a] = (h[a] || 0) + 1 }\n h.values.sort.flatten\n end.uniq.sort\n puts \"k = #{k} groups: #{s.inspect}\"\n# puts solve[k].inspect\n end\n puts \"#{i} = #{num} #{i.factors} #{i.factors.length + i.divisors.length}\" \n max = num\n end\n break if num > 1000\n i += 1\n end\n i\nend", "def converter(x)\n i=x\n roman_num=[]\n while i!=0\n if i/1000>0\n roman_num.push('M'*(i/1000))\n i-=i-i%1000\n elsif i/100>0\n if i/100<4\n roman_num.push('C'*(i/100))\n i-=i-i%100\n elsif i/100==4\n roman_num.push('CD')\n i-=400\n elsif i/100==5\n roman_num.push('D')\n i-=500\n elsif ((i/100)>5 && (i/100)<9)\n roman_num.push('D')\n i-=500\n roman_num.push('C'*(i/100))\n i-=i-i%100\n elsif i/100==9\n roman_num.push('CM')\n i-=900\n end\n elsif i/10>0\n if i/10<4\n roman_num.push('X'*(i/10))\n i-=i-i%10\n elsif i/10==4\n roman_num.push('XL')\n i-=40\n elsif i/10==5\n roman_num.push('L')\n i-=50\n elsif ((i/10)>5 && (i/10)<9)\n roman_num.push('L')\n i-=50\n roman_num.push('X'*(i/10))\n i-=i-i%10\n elsif i/10==9\n roman_num.push('XC')\n i-=90\n end\n else \n if (i>=1 && i<4)\n roman_num.push('I'*i)\n i=0\n elsif i==4\n roman_num.push('IV')\n i=0\n elsif i==5\n roman_num.push('V')\n i=0\n elsif (i>5 && i<9)\n roman_num.push('V')\n i-=5\n roman_num.push('I'*i)\n i=0\n else\n roman_num.push('IX')\n i=0\n end\n end\n end\n return roman_num.join('')\nend", "def solution(roman)\n split = roman.split(\"\")\n last_value = 0\n split.reduce(0) do |final, char|\n current = CONVERSION[char.upcase]\n binding.pry\n if current >= last_value\n final += current\n else\n final -= current\n end\n binding.pry\n last_value = current\n final\n end\nend", "def roman(num, comp = '')\n roman_mapping = {\n 1000 => \"M\",\n 900 => \"CM\",\n 500 => \"D\",\n 400 => \"CD\",\n 100 => \"C\",\n 90 => \"XC\",\n 50 => \"L\",\n 40 => \"XL\",\n 10 => \"X\",\n 9 => \"IX\",\n 5 => \"V\",\n 4 => \"IV\",\n 1 => \"I\"\n}\n \n if num == 0\n p comp \n else\n roman_mapping.each_key do |key|\n result = num - key \n if result >= 0 \n comp += roman_mapping[key]\n roman(result, comp)\n break\n end\n end\n end\nend", "def decode(numbers, key)\n result = \"\"\n numbers.each_with_index do |n, i|\n result += (n ^ key[i % 3].ord).chr\n end\n result\nend", "def new_roman_numeral num\n number = \"\"\n if (num / 1000) > 0\n number = \"M\" * (num / 1000)\n end\n if (num % 1000) >= 900 \n number += \"CM\"\n end\n if (num % 1000) >= 500 && (num % 1000) < 900\n number += \"D\"\n end\n if (num % 1000) >= 400 && (num % 1000) < 500\n number += \"CD\"\n end\n if ((num % 1000) % 500) >= 100 && ((num % 1000) % 500) < 400\n number += \"C\" * (((num % 1000) % 500) / 100)\n end\n if (((num % 1000) % 500) % 100) >= 90\n number += \"XC\"\n end\n if (((num % 1000) % 500) % 100) >= 50 && (((num % 1000) % 500) % 100) < 90\n number += \"L\"\n end\n if (((num % 1000) % 500) % 100) >= 40 && (((num % 1000) % 500) % 100) < 50\n number += \"XL\"\n end\n if (((num % 1000) % 500) % 50) >= 10 && (((num % 1000) % 500) % 50) < 40\n number += \"X\" * ((((num % 1000) % 500) % 50) / 10)\n end\n if ((((num % 1000) % 500) % 50) % 10) == 9\n number += \"IX\"\n end\n if ((((num % 1000) % 500) % 50) % 10) >= 5 && ((((num % 1000) % 500) % 50) % 10) < 9\n number += \"V\" + \"I\" * (((((num % 1000) % 500) % 50) % 10) % 5)\n end\n if ((((num % 1000) % 500) % 50) % 10) == 4\n number += \"IV\"\n end\n if ((((num % 1000) % 500) % 50) % 10) < 4\n number += \"I\" * (((((num % 1000) % 500) % 50) % 10) % 5)\n end\n puts number\nend", "def roman_numeral(num)\n digits = [[1000, 500, 100, 50, 10, 5, 1], [0, 0, 0, 0, 0, 0, 0], ['M','D','C','L','X','V','I']]\n answer = ' '\n h = 0\n \n digits[0].each do |z|\n if num / z > 0\n digits[1][h] = (num / z) #Counting the number of 10s, 50s, 100s, etc in num\n num = num % z #Using the remainder as the next value of num\n end\n h += 1\n end\n \n for a in 0..digits[1].size - 1 do #Iterate through array to calculate roman numerals old school style\n answer << digits[2][a] * digits[1][a]\n answer = answer.gsub(\"DCCCC\",\"CM\").gsub(\"CCCC\",\"CD\").gsub(\"LXXXX\",\"XC\").gsub(\"XXXX\",\"XL\").gsub(\"VIIII\",\"IX\").gsub(\"IIII\",\"IV\") #Catching edge cases to update old school roman numeral\n end\n\n answer.strip\nend", "def solution(number)\n accumulator =\n number.to_s.reverse.each_char.with_index.map do |letter, index|\n character_map(letter.to_i, *@roman_symbols[index * 2, 3])\n end\n accumulator.reverse.join \nend", "def roman_to_int(s)\n # Declare a variable with converting info from roman to integer\n roman = {\n \"I\" => 1,\n \"V\" => 5,\n \"X\" => 10,\n \"L\" => 50,\n \"C\" => 100,\n \"D\" => 500,\n \"M\" => 1000\n }\n # Declare a count variable for adding up numbers\n counts = 0\n # Iterate each letters in the array\n (0...s.length-1).each do |idx|\n # If the next number is small than the current one, add the number to the counts\n if roman[s[idx]] < roman[s[idx+1]]\n counts -= roman[s[idx]]\n else\n counts += roman[s[idx]] \n # else minus the number from the counts\n end\n # return the counts\n end\n counts += roman[s[-1]]\n\nend", "def convert_numbers(input_number, result)\n if input_number >= 1000\n input_number -= 1000\n result << \"M\"\n convert_numbers(input_number, result)\n elsif input_number >= 900\n result << \"CM\"\n input_number -= 900\n convert_numbers(input_number, result)\n elsif input_number >= 500\n input_number -= 500\n result << \"D\"\n convert_numbers(input_number, result)\n elsif input_number >= 400\n input_number -= 400\n result << \"CD\"\n convert_numbers(input_number, result) \n elsif input_number >= 100\n input_number -= 100\n result << \"C\"\n convert_numbers(input_number, result)\n elsif input_number >= 90\n input_number -= 90\n result << \"XC\"\n convert_numbers(input_number, result)\n elsif input_number >= 50\n input_number -= 50\n result << \"L\"\n convert_numbers(input_number, result)\n elsif input_number >= 40\n input_number -= 40\n result << \"XL\"\n convert_numbers(input_number, result)\n elsif input_number >= 10\n input_number -= 10\n result << \"X\"\n convert_numbers(input_number, result)\n elsif input_number >= 9\n input_number -= 9\n result << \"IX\"\n convert_numbers(input_number, result)\n elsif input_number >= 5\n input_number -= 5\n result << \"V\"\n convert_numbers(input_number, result)\n elsif input_number >= 4\n input_number -= 4\n result << \"IV\"\n convert_numbers(input_number, result)\n elsif input_number >= 1\n input_number -= 1\n result << \"I\"\n convert_numbers(input_number, result)\n else\n result\n end\nend", "def to_roman2 number\t\r\n\t@roman = ''\r\n\tmarker = ['I','V','X','L','C','D','M']\r\n\t(0..Math.log10(number).to_i).each do |i|\r\n\t\tputs i\r\n\t\t@unit_number = (number % (10^(i+1)))/10^i\r\n\t\tputs @unit_number\t\r\n\t\t@roman = @roman + show_power_of_ten(@unit_number,marker[2*i+2],marker[2*i+1],marker[2*i])\t\r\n\tend\r\n\[email protected]\r\nend", "def roman_to_integer roman \n digit_vals = {'i' => 1,\n 'v' => 5,\n 'x' => 10,\n 'l' => 50,\n 'c' => 100,\n 'd' => 500,\n 'm' => 1000}\n total = 0 \n prev = 0 \n index = roman.length - 1 \n while index >= 0 \n c = roman[index].downcase \n index = index - 1 \n val = digit_vals[c]\n if !val \n puts \"This is not a valud roman numeral\"\n return \n end \n if val < prev\n val = val * -1\n else \n prev = val \n end \n total = total + val \n end \n total \nend", "def luhns(a)\n\tb = a.to_s[0..-2].reverse.split(\"\").to_a.map{|v|v.to_i}\n\t(b.each_index{|i|i.even? ? b[i]=b[i]*2>9?b[i]*2-9:b[i]*2:i=i}.inject(:+)+a)%10==0\nend", "def from_roman(roman)\n roman = roman.strip.upcase\n roman_a = roman.chars\n integer = 0\n roman_a.zip(roman_a[1..-1]).each do |ch, nch|\n if CHAR_PRECEDENCE.has_key?(ch) and CHAR_PRECEDENCE[ch].include?(nch)\n integer -= CHAR_VALUES[ch]\n else\n integer += CHAR_VALUES[ch]\n end\n end\n integer\nend", "def roman_to_int(s)\n letters = {'I' => 1, 'V' => 5, 'X' => 10, 'L' => 50, 'C' => 100, 'D' => 500, 'M' => 1000}\n words = s.split(\"\")\n result = words.reduce do |accumulator, current|\n letters[accumulator] + letters[current]\n end \n result\nend", "def roman (remainder, digit)\r\n if remainder < digit # ie you do not have any of this roman letter\r\n x = nil.to_i\r\n else\r\n x = remainder / digit\r\n end\r\n\r\n y = remainder % digit\r\n\r\n return [x,y]\r\nend", "def roman_to_integer(roman)\n values = {i: 1, v: 5, x: 10, l: 50, c: 100, d: 500, m: 1000}\n total = 0\n prev = 0\n index = roman.length - 1\n while index >= 0\n c = roman[index].downcase\n c = c.to_sym\n index = index - 1\n value = values[c]\n if !value\n return \"Not a valid roman numeral\"\n end\n if value < prev\n value = value * -1\n else\n prev = value\n end\n total = total + value\n end\n total\nend", "def get_pal str\n arr = str.split('')\n letters_used = {}\n odd = 0\n\n arr.each do |l|\n if !letters_used[l].nil?\n letters_used[l] = letters_used[l] + 1\n if letters_used[l] % 2 == 0\n odd -= 1\n else\n odd += 1\n end\n else\n letters_used[l] = 1\n odd += 1\n end\n end\n odd <= 1\nend", "def main\n results = {}\n strings = Hash.new(Array.new)\n 0.upto(10000).each do |ind|\n result = Helper.to_power_3(ind)\n results[ind] = result\n key = result.to_s.split(//).sort.join\n strings[key] += [ind]\n if strings[key].size == 5\n puts strings[key][0] \n puts results[strings[key][0]]\n break\n end\n \n end\n\n#puts results[345]\n#puts results[384]\n#puts results[405]\n\n#strings.each do |key,value|\n#pp results[value[0]] if value.length == 5\n#end\n \nend", "def CheckUniqDigits(n)\n\n h1 = Hash.new\n\n arr = n.digits\n\n for onedig in arr\n\n h1.key?(onedig) ? (return 0) : (h1[onedig] = 1)\n\n end\n\n return 1\n\nend", "def modern_roman_numeral(num)\n arabs_to_romans = [\n ['M', 1000],\n ['CM', 900],\n ['D', 500],\n ['CD', 400],\n ['C', 100],\n ['XC', 90],\n ['L', 50],\n ['XL', 40],\n ['X', 10],\n ['IX', 9],\n ['V', 5],\n ['IV', 4],\n ['I', 1]\n ]\n\n result = ''\n\n arabs_to_romans.each do |arab_to_roman|\n arab = arab_to_roman[1]\n roman = arab_to_roman[0]\n\n if num / arab != 0\n result += roman * (num / arab)\n num = num % arab\n end\n end\n result\nend", "def old_roman num\r\n\r\n\taux = num\r\n\troman_num = ''\r\n\t\r\n\twhile true\r\n\t\r\n\t\tif((aux / 1000) >= 1)\r\n\t\t\troman_num = roman_num + 'M'\r\n\t\t\taux = aux - 1000\r\n\t\telsif ((aux / 500) >= 1)\r\n\t\t\tif(aux >= 900)\r\n\t\t\t\troman_num = roman_num + 'CM'\r\n\t\t\t\taux = aux - 900\t\t\t\t\t\r\n\t\t\telse\r\n\t\t\t\troman_num = roman_num + 'D'\r\n\t\t\t\taux = aux - 500\t\t\r\n\t\t\tend\r\n\t\telsif((aux / 100) >= 1)\r\n\t\t\tif(aux >= 400)\r\n\t\t\t\troman_num = roman_num + 'CD'\r\n\t\t\t\taux = aux - 400\t\t\t\t\t\r\n\t\t\telse\r\n\t\t\t\troman_num = roman_num + 'C'\r\n\t\t\t\taux = aux - 100\t\t\r\n\t\t\tend\r\n\t\telsif((aux / 50) >= 1)\r\n\t\t\tif(aux >= 90)\r\n\t\t\t\troman_num = roman_num + 'XC'\r\n\t\t\t\taux = aux - 90\t\t\t\t\t\r\n\t\t\telse\r\n\t\t\t\troman_num = roman_num + 'L'\r\n\t\t\t\taux = aux - 50\t\t\r\n\t\t\tend\r\n\t\telsif((aux / 10) >= 1)\r\n\t\t\tif(aux >= 40)\r\n\t\t\t\troman_num = roman_num + 'XL'\r\n\t\t\t\taux = aux - 40\t\t\t\t\t\r\n\t\t\telse\r\n\t\t\t\troman_num = roman_num + 'X'\r\n\t\t\t\taux = aux - 10\t\t\r\n\t\t\tend\r\n\r\n\t\telsif((aux / 5) >= 1)\r\n\t\t\tif(aux >= 9)\r\n\t\t\t\troman_num = roman_num + 'IX'\r\n\t\t\t\taux = aux - 9\t\t\t\t\t\r\n\t\t\telse\r\n\t\t\t\troman_num = roman_num + 'V'\r\n\t\t\t\taux = aux - 5\t\t\r\n\t\t\tend\r\n\t\telsif((aux / 1) >= 1)\r\n\t\t\tif(aux >= 4)\r\n\t\t\t\troman_num = roman_num + 'IV'\r\n\t\t\t\taux = aux - 4\t\t\t\t\t\r\n\t\t\telse\r\n\t\t\t\troman_num = roman_num + 'I'\r\n\t\t\t\taux = aux - 1\t\r\n\t\t\tend\r\n\t\telse\r\n\t\t\tbreak\t\t\t\r\n\t\tend\r\n\tend\r\n\t\r\n\troman_num\r\nend", "def find_self_dividing(number_strings)\n output = []\n number_strings.each do |num_string|\n number = num_string.join(\"\").to_i\n divisibles_in_array = find_divisibles(number, num_string)\n\n if divisibles_in_array.join(\"\").to_i == number\n output << number\n end\n end\n output\nend", "def ReduceRoman(myroman)\n lesschar = 0;\n newroman = \"\"\n puts \"orig roman = #{myroman}\"\n\n for i in 0...myroman.to_s.length-1 do\n count = 0\n j=i\n basechar = myroman[i]\n \n while ( $numbers[myroman[j]] == $numbers[myroman[j+1]]) do\n count = count + 1\n j = j+1\n end\n \n if(count == 4)\n case basechar\n when 'I'\n \n when 'V'\n \n when 'L'\n \n when 'C'\n \n when 'D'\n\n when 'M'\n \n end\n\n else\n for k in 0..count do\n newroman[k]=basechar\n end\n end\n\n end\n puts \"new roman is #{newroman}\"\n return lesschar\nend", "def triple_digit_breakdown(digits_hash)\n base_nums = {0=>'', 1=>'one', 2=>'two', 3=>'three', 4=>'four', 5=>'five', 6=>'six', 7=>'seven', 8=>'eight', 9=>'nine'}\n ten_to_nineteen = {10=>'ten', 11=>'eleven', 12=>'twelve', 13=>'thirteen', 14=>'fourteen', 15=>'fifteen', 16=>'sixteen', 17=>'seventeen', 18=>'eighteen', 19=>'nineteen'}\n multiples_of_ten = {0=>'', 2=>'twenty ', 3=>'thirty ', 4=>'forty ', 5=>'fifty ', 6=>'sixty ', 7=>'seventy ', 8=>'eighty ', 9=>'ninety '}\n\n ones = digits_hash[1]\n tens = digits_hash[2]\n hundreds = digits_hash[3]\n\n val_str = hundreds > 0 ? \"#{base_nums[hundreds]} hundred \" : \"\"\n val_str += tens == 1 ? ten_to_nineteen[(tens*10)+ones] : multiples_of_ten[tens] + base_nums[ones]\n end", "def numeral(number)\n\tnumerals = {:I => 1, :V => 5, :X => 10, :L => 50, \n\t\t:C => 100, :D => 500, :M => 1000}\n\torder = [:M,:D,:C,:L,:X,:V,:I]\n\toutput = \"\"\n\torder.each do |n|\n\t\tif numerals[n] <= number\n\t\t\ttimes = number / numerals[n]\n\t\t\tremainder = number % numerals[n]\n\t\t\toutput += n.to_s * times\n\t\t\tnumber = remainder\n\t\tend\n\tend\n\toutput\nend", "def roman_numerals(number)\n\n puts (\"M\" * (number/1000)).to_s\n if ((number%1000)%500) == 0\n puts (\"D\" * (number%1000/500)).to_s\n if ((number%500)%100) == 0\n puts (\"C\" * (number%500/100)).to_s\n if ((number%100)%50) == 0\n puts (\"L\" * (number%100/50)).to_s\n if ((number%50)%10) == 0\n puts (\"X\" * (number%50/10)).to_s\n if ((number%10)%5) == 0\n puts (\"V\" * (number%10/5)).to_s\n if ((number%5)%1)) == 0\n puts (\"I\" * (number%5/1)).to_s\n end\n end\n end\n end\n end\n end\n\n\nend", "def number_to_words(number)\n string_number = number.to_s\n p string_number\n\n return 'zero' if number.zero?\n\n single_digit_numbers = {'1'=>\"one\",'2'=>\"two\",'3'=>\"three\",'4'=>\"four\",\n '5'=>\"five\",'6'=>\"six\",'7'=>\"seven\",'8'=>\"eight\",'9'=>\"nine\"}\n double_digit_numbers = {'10'=>\"ten\",'11'=>\"eleven\",'12'=>\"twelve\",'13'=>\"thirteen\",'14'=>\"fourteen\",\n '15'=>\"fifteen\",'16'=>\"sixteen\",'17'=>\"seventeen\", '18'=>\"eighteen\",'19'=>\"nineteen\"}\n\n ten_digits = {'2' => 'twenty', '3' => 'thirty', '4' => 'forty', '5' => 'fifty',\n '6' => 'sixty', '7' => 'seventy', '8' => 'eighty', '9' => 'ninety'}\n\n hundred = 'hundred'\n\n case number\n when 10..19\n return double_digit_numbers[string_number]\n when 20..99\n return ten_digits[string_number[0]] + \"-\" + single_digit_numbers[string_number[1]]\n when 99..999\n if double_digit_numbers.include?(string_number[-2,2])\n return single_digit_numbers[string_number[0]] + \" \" + hundred + \" and \" + double_digit_numbers[string_number[-2,2]]\n # for 3 digit numbers, checking if the last two digits are in the double_digit_numbers hash\n elsif string_number[1] == '0' && string_number[2] == '0'\n return single_digit_numbers[string_number[0]] + \" \" + hundred\n end\n else\n return single_digit_number[string_number]\n end\nend", "def test_hash_correct\n\t\n\t\tString test_array1 = '2|abb2|George>Amina(16):Henry>James(4):Henry>Cyrus(17):Henry>Kublai(4):George>Rana(1):SYSTEM>Wu(100)|1518892051.753197000|c72d'.split('|').map(&:chomp)\n\n\t\tx = test_array1[0].unpack('U*') + test_array1[1].unpack('U*') + test_array1[2].unpack('U*') + test_array1[3].unpack('U*')\n\t\tsum = 0\n\t\t# x.each { |i| puts x[i] }\n\t\t# x.delete(\"\")\n\t\tx.each { |i| sum += ((x[i].to_i ** 2000) * ((x[i].to_i + 2) ** 21) - ((x[i].to_i + 5) ** 3)) }\n\t\thash = (sum % 65536)\n\t\tputs hash.to_s(16)\n\t\t\n\t\ttest_array2 = '3|c72d|SYSTEM>Henry(100)|1518892051.764563000|7419'.split('|').map(&:chomp)\n\t\t\n\t\t# assert_equal test_str[2,2], '0|'\t\n\tend", "def roman_numeral num\n thous = (num / 1000)\n hunds = (num % 1000 / 100)\n tens = (num % 100 / 10)\n ones = (num % 10 )\n\n roman = \"M\" * thous\n if hunds == 9\n roman = roman + \"CM\" \n elsif hunds == 4\n roman = roman + \"CD\"\n else\n roman = roman + \"D\" * (num % 1000 / 500)\n roman = roman + \"C\" * (num % 500 / 100)\n end\n\n if tens == 9 \n roman = roman + \"XC\"\n elsif tens == 4\n roman = roman + \"XL\"\n else\n roman = roman + \"L\" * (num % 100 / 50) \n roman = roman + \"X\" * (num % 50 / 10)\n end\n\n if ones == 9 \n roman = roman + \"IX\"\n elsif ones == 4\n roman = roman + \"IV\"\n else\n roman = roman + \"V\" * (num % 10/ 5)\n roman = roman + \"I\" * (num % 5 / 1)\n end\n roman\n end", "def solution(number)\n str = '' \n\n ROMAN_DIC.each_with_index do |dic, index|\n if number > 5\n if index > 0 && index < ROMAN_DIC.size - 1 && (number > (dic[0] + (ROMAN_DIC[index + 1][0] * 3)))\n str = str + ROMAN_DIC[index + 1][1] + ROMAN_DIC[index - 1][1]\n number = number - (ROMAN_DIC[index - 1][0] - ROMAN_DIC[index + 1][0])\n end \n else\n if index > 0 && index < ROMAN_DIC.size - 1 && (number > (ROMAN_DIC[index + 1][0] * 3))\n str = str + ROMAN_DIC[index + 1][1] + dic[1]\n number = number - (ROMAN_DIC[index + 1][0] + dic[0])\n end\n end \n\n while number >= dic[0]\n str = str + dic[1]\n number = number - dic[0]\n end \n end \n\n str\nend", "def roman_to_int(s)\n arr = s.split(\"\")\n arr_dup = []\n letter_hash = { I: 1, IV: 4, V: 5, IX: 9, X: 10, XL:40,\n L:50, XC: 90, C: 100, CD: 400, D: 500,\n CM: 900, M: 1000 }\n\n 1.upto(arr.length) do\n if (arr[1] != nil) && (letter_hash.key?((arr[0] + arr[1]).to_sym))\n arr_dup << letter_hash[(arr[0] + arr[1]).to_sym]\n arr.delete_at(0)\n arr.delete_at(0)\n next\n end\n\n if arr.length > 0\n if letter_hash.key?((arr[0]).to_sym)\n arr_dup << letter_hash[(arr[0]).to_sym]\n arr.delete_at(0)\n end\n end\n end\n arr_dup.reduce(&:+)\nend", "def roman_to_int(s)\n roman = {\n \"I\" => 1,\n \"V\" => 5,\n \"X\" => 10,\n \"L\" => 50,\n \"C\" => 100,\n \"D\" => 500,\n \"M\" => 1000\n }\n \n sum = 0\n \n i = 0\n while i <= s.length - 1\n j = i + 1\n \n if j == s.length\n sum += roman[s[i]] \n break\n end\n \n if roman[s[i]] < roman[s[j]]\n sum -= roman[s[i]]\n else\n sum += roman[s[i]]\n end\n \n i += 1\n end\n \n sum\nend", "def to_words(n)\n\nwords_hash = {0=>\"zero\",1=>\"one\",2=>\"two\",3=>\"three\",4=>\"four\",5=>\"five\",6=>\"six\",7=>\"seven\",8=>\"eight\",9=>\"nine\",\n 10=>\"ten\",11=>\"eleven\",12=>\"twelve\",13=>\"thirteen\",14=>\"fourteen\",15=>\"fifteen\",16=>\"sixteen\",\n 17=>\"seventeen\", 18=>\"eighteen\",19=>\"nineteen\",\n 20=>\"twenty\",30=>\"thirty\",40=>\"forty\",50=>\"fifty\",60=>\"sixty\",70=>\"seventy\",80=>\"eighty\",90=>\"ninety\"}\n \nif words_hash.has_key?(n)\n return words_hash[n]\nelsif n <= 99\n\n final_string = \"\"\n remainder = (n%10)\n key_value = n - remainder\n final_string = words_hash[key_value] + \" \" + words_hash[remainder]\n return final_string\n\nelse\n return \"one hundred\"\n\nend\nend", "def roman_symbols_to_numeral(roman_string)\n\t\tsum = 0\n\t\tfor key, value in @@valid_substractions_in_order\n\t\t\twhile roman_string.index(key)==0\n\t\t\t\tsum += value\n\t\t\t\troman_string.slice!(key)\n\t\t\tend\n\t\tend\n\t\tsum\n\tend", "def roman_symbols_to_numeral(roman_string)\n\t\tsum = 0\n\t\tfor key, value in @@valid_substractions_in_order\n\t\t\twhile roman_string.index(key)==0\n\t\t\t\tsum += value\n\t\t\t\troman_string.slice!(key)\n\t\t\tend\n\t\tend\n\t\tsum\n\tend", "def fix_numerals\n hash = self.clone\n traverse hash\n hash\n end", "def dv\n split_reversed_rut = @last_rut.to_s.reverse.chars\n seq = [2, 3, 4, 5, 6, 7]\n i = 0\n digit_sum = split_reversed_rut.reduce(0) do |sum, n|\n partial_result = sum.to_i + (n.to_i * seq[i])\n i = i == 5 ? 0 : i + 1\n partial_result\n end\n partial_check_digit = 11 - (digit_sum % 11)\n case partial_check_digit\n when 11\n '0'\n when 10\n 'k'\n else\n partial_check_digit.to_s\n end\n end", "def old_school(num) \n roman = ''\n roman = roman + 'M' * (num / 1000)\n roman = roman + 'D' * (num % 1000/ 500)\n roman = roman + 'C' * (num % 500/ 100)\n roman = roman + 'L' * (num % 100/ 50)\n roman = roman + 'X' * (num % 50/ 10)\n roman = roman + 'V' * (num % 10/ 5)\n roman = roman + 'I' * (num % 5/ 1)\n roman \nend", "def partify key\n nums = key.scan(/[0-9]/).join.to_i\n spaces = key.scan(/ /).size\n \n raise \"Key Error: #{key} has no spaces\" if spaces == 0\n raise \"Key Error: #{key} nums #{nums} is not an integral multiple of #{spaces}\" if (nums % spaces) != 0\n\n [nums / spaces].pack(\"N*\")\n end", "def Old_Roman_Numerals number #THANKS SATAN, for such a stress inducing exercise.\n m_length = 0\n d_length = 0\n c_length = 0\n l_length = 0\n x_length = 0\n v_length = 0\n i_length = 0\n\n if number >= 1000 #Is this unconventional? Yes. Does it work? Yes.\n m_length = number / 1000\n number = number % 1000\nend\n\n if number >= 500\n d_length = number / 500\n number = number % 500\nend\n\n if number >= 100\n c_length = number / 100\n number = number % 100\nend\n\n if number >= 50\n l_length = number / 50\n number = number % 50\nend\n\n if number >= 10\n x_length = number / 10\n number = number % 10\nend\n\n if number >= 5\n v_length = number / 5\n number = number % 5\nend\n\n if number < 5\n i_length = number / 1\n number = number % 10\nend\n\nputs 'M'*m_length + # Prefer clean order list vs. one long code line.\n 'D'*d_length +\n 'C'*c_length +\n 'L'*l_length +\n 'X'*x_length +\n 'V'*v_length +\n 'I'*i_length\nend", "def roman_numeral num\n roman_to_arabic = {\n M: 1_000, CM: 900, D: 500, CD: 400,\n C: 100, XC: 90, L: 50, XL: 40,\n X: 10, IX: 9, V: 5, IV: 4,\n I: 1\n }\n\n return '' if num <= 0\n roman_to_arabic.each { |key, val| return key.to_s + roman_numeral(num - val) if num >= val }\nend", "def scoobydoo(villian, villians)\n letters = ('a'..'z').to_a\n numbers = (0..25).to_a\n letters_to_numbers = letters.zip(numbers).to_h\n numbers_to_letters = numbers.zip(letters).to_h\n\n villians_downcase = villians.map { |v| v.downcase.delete(' ') }\n villians_hash = (villians_downcase).zip(villians).to_h\n\n s = villian.reverse.chars.rotate(5)\n new = []\n (0...s.size).each do |i|\n if i.even?\n new[i] = s[i]\n else\n num = (letters_to_numbers.fetch(s[i]) + 5) % 26\n new[i] = numbers_to_letters.fetch(num)\n end\n end\n\n villians_hash.fetch(new.join)\n\nend", "def roman_numeral num\n \n if num >= 1000\n thousands = 'M' * (num / 1000)\n end\n\n # We now account for cases of 400 and 900 (CD, CM, respectively)\n # CCC=300, CD=400, D=500, DCCC=800, CM=900\n if num >= 100\n temp_hundreds = (num % 1000) / 100\n if temp_hundreds == 9\n hundreds = 'CM'\n elsif (temp_hundreds < 9 && temp_hundreds > 5)\n hundreds = 'D' + 'C' * (temp_hundreds - 5)\n elsif temp_hundreds == 5\n hundreds = 'D'\n elsif temp_hundreds == 4\n hundreds = 'CD'\n else\n hundreds = 'C' * temp_hundreds\n end\n end\n \n # We now account for cases of 40 and 90 (XL, XC, respectively)\n # XXX=30, XL=40, L=50, LXXX=80, XC=90\n if num >= 10\n temp_tens = (num % 100) / 10\n if temp_tens == 9\n tens = 'XC'\n elsif (temp_tens < 9 && temp_tens > 5)\n tens = 'L' + 'X' * (temp_tens - 5)\n elsif temp_tens == 5\n tens = 'L'\n elsif temp_tens == 4\n tens = 'XL'\n else\n tens = 'X' * temp_tens\n end\n end\n \n # We now account for cases of 4 and 9 (IV, IX, respectively)\n # III=3, IV=4, V=5, XIII=8, IX=9\n if num > 0\n temp_ones = num % 10\n if temp_ones == 9\n ones = 'IX'\n elsif (temp_ones < 9 && temp_ones > 5)\n ones = 'V' + 'I' * (temp_ones - 5)\n elsif temp_ones == 5\n ones = 'V'\n elsif temp_ones == 4\n ones = 'IV'\n else\n ones = 'I' * temp_ones\n end\n end\n \n puts \"#{num} in \\\"Modern\\\" Roman numerals is \"+\"#{thousands}\"+\"#{hundreds}\"+\"#{tens}\"+\"#{ones}\"\nend", "def old_r_conv nums\n\troman = ''\n\troman = roman + 'M' * (nums/1000)\n\troman = roman + 'D' * ((nums%1000)/500)\n\troman = roman + 'C' * ((nums%500)/100)\n\troman = roman + 'L' * ((nums%100)/50)\n\troman = roman + 'X' * ((nums%50)/10)\n\troman = roman + 'V' * ((nums%10)/5)\n\troman = roman + 'I' * ((nums%5)/1)\n\n\tputs roman\nend", "def hashify(key)\n array = key.split('')\n count = array.count\n index = array.inject(0) do |object,char|\n object += char.ord ** count\n count -= 1\n object\n end\n index % 89\n end", "def old_roman_numeral num\n working_num = num\n roman_val = ''\n \n numeral_ref = [[1, 'I'],\n [5, 'V'],\n [10, 'X'],\n [50, 'L'],\n [100, 'C'],\n [500, 'D'],\n [1000, 'M']]\n \n (0...numeral_ref.length).reverse_each { |i|\n if working_num >= numeral_ref[i][0]\n mult = working_num/numeral_ref[i][0]\n roman_val += numeral_ref[i][1]*(mult)\n working_num %= numeral_ref[i][0]\n end\n }\n roman_val\nend", "def divisiori( n )\n root = { :number => n, :divisors => [] }\n #\n # la ricorsione o meglio root e' struttura completa se `n` e' un numero primo\n # cioe' non ha divisori. La prima cosa fare e' calcolare i divisori\n for i in 2..n/2\n if n % i == 0 then\n # se arrivo qui, i e' un divisore del numero n\n root[:divisors] << divisiori( i ) ; # divisori(i) restituisce la Hash del\n # \"sottoalbero\" del divisore i\n end\n end\n return root ;\nend", "def part2(line)\n numbers_str = line.chomp.split()\n numbers = numbers_str.map(&:to_i).sort\n\n # Start from the end\n i = numbers.size - 1\n\n while i > 0\n j = 0\n while j < i\n return numbers[i] / numbers[j] if numbers[i] % numbers[j] == 0\n j = j + 1\n end\n i = i - 1\n end\n return 0\nend", "def roman_to_numeral(roman_string)\n\tsum = 0\n\tfor key, value in @roman_map\n\t\twhile roman_string.index(key) == 0\n\t\t\tsum += value\n\t\t\troman_string.slice!(key)\n\t\tend\n\tend\n\tsum\nend", "def to_hundreds(num)\n\tin_words = \"\"\n\tnum_to_words = Hash.new(0)\n\tnum_to_words = { 1=>\"One\",2=>\"Two\",3=>\"Three\",4=>\"Four\",5=>\"Five\",6=>\"Six\",7=>\"Seven\",8=>\"Eight\",9=>\"Nine\",10=>\"Ten\",11=>\"Eleven\",12=>\"Twelve\",13=>\"Thirteen\",14=>\"Fourteen\",15=>\"Fifteen\",16=>\"Sixteen\",17=>\"Seventeen\",18=>\"Eighteen\",19=>\"Nineteen\",20=>\"Twenty\",30=>\"Thirty\",40=>\"Fourty\",50=>\"Fifty\",60=>\"Sixty\",70=>\"Seventy\",80=>\"Eighty\",90=>\"Ninety\" }\n\n\tif num / 100 > 0\n\t\tin_words = num_to_words[num / 100] + \" Hundred \"\n\n\t\tif num % 10 != 0\n\t\t\tin_words = in_words + \"and \"\n\t\tend\n\t\tnum = num % 100\n\tend\n\n\tif num / 10 > 0\n\t\tif num / 10 == 1\n\t\t\tin_words = in_words + num_to_words[num] + \" \"\n\t\telsif num % 10 == 0\n\t\t\tin_words = in_words + num_to_words[num]\n\t\telse\n\t\t\tin_words = in_words + num_to_words[num / 10*10] + \" \" + num_to_words[num % 10]\n\t\tend\n\telsif num == 0\n\t\tin_words\n\telse \n\t\tin_words = in_words + num_to_words[num]\n\tend\n\n\tin_words\nend", "def to_arabic num\n arabic = 0\n ROMAN_NUMBERS.each do |key, value|\n while num.start_with? value\n arabic += key\n num = num.slice(value.size, num.size)\n end\n end\n arabic\nend", "def BasicRomanNumerals(str)\n romans = { 'M' => 1000, 'D' => 500, 'C' => 100, 'L' => 50, 'X' => 10, 'V' => 5, 'I' => 1 }\n \n sum = 0\n str.chars.each_with_index do |char, idx|\n next sum += romans[char] if idx >= str.size - 1\n if romans[str[idx + 1]] > romans[char]\n sum -= romans[char]\n else\n sum += romans[char]\n end\n end\n sum\nend", "def oldrconv number\n\tset = [1,5,10,50,100,500,1000]\n\tx = 0\n\tlen = set.length\n\twhile x < len\n\t\tresult = number/set[x]\n\t\tbreak if result < 1\n\t\tsres = result\n\t\tx = x + 1\n\tend\n\t\n\tbase = set[x -1]\n\t\n\tif (base !=1)\t\n\tfresult = number%base\n\telse\n\tfresult = number%5\n\tend\n\n\tif (base == 1)\n\t\tform = 'I'* sres\n\telsif (base == 5) \n\t\tform = 'V' * sres\n\telsif (base == 10)\n\t\tform = 'X'* sres\n\telsif (base ==50)\n\t\tform = 'L'* sres\n\telsif (base ==100)\n\t\tform = 'C'* sres\n\telsif (base == 500)\n\t\tform = 'D'* sres\n\telsif (base == 1000)\n\t\tform = 'M'* result\n\tend\n\tif (fresult == 0)\n\t\tputs form\n\telsif (fresult != 0 && base != 1)\n\t\tputs form + 'I'*fresult\n\telse\n\t\tputs 'I' * fresult\n\tend\nend", "def roman_numeral num_to_convert\n\t\n\tnum_converted = ''\n\n\tthousands = num_to_convert / 1000\n\tnum_converted = 'M'*thousands\n\tremainder = num_to_convert % 1000\n\n\tfivehundreds = remainder / 500\n\tif remainder >= 900\n\t\tnum_converted += 'CM'\n\t\tremainder = remainder % 900\n\telse\n\t\tnum_converted += 'D'*fivehundreds\n\t\tremainder = remainder % 500\n\tend\n\n\tonehundreds = remainder / 100\n\tif onehundreds == 4\n\t\tnum_converted += 'CD'\n\t\tremainder = remainder % 400\n\telse\n\t\tnum_converted += 'C'*onehundreds\n\t\tremainder = remainder % 100\n\tend\n\t\n\n\tfifties = remainder / 50\n\tif remainder >= 90\n\t\tnum_converted += 'XC'\n\t\tremainder = remainder % 90\n\telse\n\t\tnum_converted += 'L'*fifties\n\t\tremainder = remainder % 50\t\n\tend\n\t\n\ttens = remainder / 10\n\tif tens == 4\n\t\tnum_converted += 'XL'\n\t\tremainder = remainder % 40\n\telse\n\t\tnum_converted += 'X'*tens\n\t\tremainder = remainder % 10\n\tend\n\t\n\tfives = remainder / 5\n\tif remainder >= 9\n\t\tnum_converted += 'IX'\n\t\tremainder = remainder % 9\n\telse\n\t\tnum_converted += 'V'*fives\n\t\tremainder = remainder % 5\n\tend\n\n\tones = remainder\n\tif ones == 4\n\t\tnum_converted += 'IV'\n\telse \n\t\tnum_converted += 'I'*ones\n\tend\n\n\tputs num_converted\n\treturn num_converted\nend", "def valores\n {\n 'a' => 1, 'e' => 1, 'i' => 1, 'o' => 1, 'u' => 1,\n 'l' => 1, 'n' => 1, 'r' => 1, 's' => 1, 't' => 1,\n 'd' => 2, 'g' => 2,\n 'b' => 3, 'c' => 3, 'm' => 3, 'p' => 3,\n 'f' => 4, 'h' => 4, 'v' => 4, 'w' => 4, 'y' => 4,\n 'k' => 5,\n 'j' => 8, 'x' => 8,\n 'q' => 10 , 'z' => 10\n }\n end", "def roman_mappings\n {\n 1000 => 'M',\n 900 => 'CM',\n 500 => 'D',\n 400 => 'CD',\n 100 => 'C',\n 90 => 'XC',\n 50 => 'L',\n 40 => 'XL',\n 10 => 'X',\n 9 => 'IX',\n 5 => 'V',\n 4 => 'IV',\n 1 => 'I',\n }\n end", "def index(key, size)\n #true_index = hash(key) % k\n code = 0\n key.split(%r{\\s*}).each do |letter|\n code += letter.ord \n end\n puts code\n return code % size\n\n end", "def problem_79\n digits = []\n lines = open(\"keylog.txt\").reduce([]) do |a,l|\n a << l.chomp.split(//).map(&:to_i)\n end\n p = lines.transpose\n loop do \n first = (p[0] - p[1]).uniq\n if first.length == 1\n d = first[0]\n digits << d \n puts \"Remove #{d}\"\n # shift off leading 'd' values\n lines.select {|l| l[0] == d}.map {|l| l.shift; l.push nil }\n # Rebuild out first, second, third arrays\n p = lines.transpose\n return digits.map(&:to_s).join if p.flatten.compact.length == 0\n puts \"len = #{p.flatten.compact.length}\"\n else\n raise \"Trouble - 2 candidates : #{first.inspect}, rework algorithm\"\n end\n end\nend", "def roman_to_decimal roman \n decimal = 0\n i = 0\n\n while i < roman.size do\n pair = roman[i, 2]\n\n # Single numeral at the end.\n if pair.size == 1\n decimal += VALUE[pair[0,1]] \n i += 1\n\n # Normal pair. \n elsif VALUE[pair[0,1]] >= VALUE[pair[1,1]] then\n decimal += VALUE[pair[0,1]]\n i += 1\n\n # Subtractive pair. Treat as one numeral.\n else\n decimal += VALUE[pair[1,1]] - VALUE[pair[0,1]]\n i += 2 \n end\n end\n return decimal\nend", "def self_dividing_numbers(left, right)\n result = []\n i = left\n while i <= right #while i is smaller than right bound\n str = i.to_s #converts all int to string\n j = 0\n c = 0\n while j < str.length\n if str[j].to_i == 0\n break\n elsif i % str[j].to_i == 0\n c += 1\n end\n j+= 1\n end\n if c == str.length\n result.push(i)\n end\n i += 1\n end\n return result\nend", "def solution2(a)\n\n counts = Hash.new(0)\n\n a.each do |int|\n counts[int] += 1\n end\n\n non_divisors = []\n\n a.each do |int|\n div_count = 0\n for i in 1..int do\n div_count += counts[i] if int % i == 0\n end\n non_divisors << a.length - div_count\n end\n\n non_divisors\n\nend", "def hiv_protease(aa_array,start_aa=1)\n out_hash = {}\n sdrm = {}\n sdrm[23] = ['L',['I']]\n sdrm[24] = ['L',['I']]\n sdrm[30] = ['D',['N']]\n sdrm[32] = ['V',['I']]\n sdrm[46] = ['M',['I','L','V']]\n sdrm[47] = ['I',['V','A']]\n sdrm[48] = ['G',['V','M']]\n sdrm[50] = ['I',['V','L']]\n sdrm[53] = ['F',['L']]\n sdrm[54] = ['I',['V','L','M','T','A','S']]\n sdrm[73] = ['G',['S','T','C','A']]\n sdrm[76] = ['L',['V']]\n sdrm[82] = ['V',['A','T','S','F','L','C','M']]\n sdrm[83] = ['N',['D']]\n sdrm[84] = ['I',['V','A','C']]\n sdrm[85] = ['I',['V']]\n sdrm[88] = ['N',['D','S']]\n sdrm[90] = ['L',['M']]\n aa_length = aa_array.size\n end_aa = start_aa + aa_length - 1\n (start_aa..end_aa).each do |position|\n array_position = position - start_aa\n if sdrm.keys.include?(position)\n wt_aa = sdrm[position][0]\n test_aa = aa_array[array_position]\n if test_aa.size == 1\n unless wt_aa == test_aa\n if sdrm[position][1].include?(test_aa)\n out_hash[position] = [wt_aa,test_aa]\n end\n end\n else\n test_aa_array = test_aa.split(\"/\")\n if (test_aa_array & sdrm[position][1])\n out_hash[position] = [wt_aa,test_aa]\n end\n end\n end\n end\n return out_hash\nend", "def in_words(num)\n hash = {0=> \"zero\",1=>\"one\",2=> \"two\", 3=> \"three\", 4=> \"four\", 5=> \"five\", 6=>\"six\", 7=>\"seven\", 8=>\"eight\", 9=> \"nine\", 10=> \"ten\", 11=> \"eleven\", 12 => \"twelve\", 13 => \"thirteen\", 14=> \"fourteen\", 15 => \"fifteen\", 16=> \"sixteen\", 17=>\"seventeen\", 18=> \"eighteen\", 19=> \"nineteen\", 20=> \"twenty\", 30=> \"thirty\", 40=> \"fourty\", 50=> \"fifty\", 60=> \"sixty\", 70=> \"seventy\", 80=> \"eighty\", 90=> \"ninety\", 100=> \"hundred\"}\n if hash.has_key?(num)\n hash[num]\n elsif num < 100\n hash[num - num % 10] + \" \" + hash[num % 10]\n else\n raise ArgumentError.new(\"Number not in the specified range\")\n end\n \nend", "def roman_numerals number\n roman_numerals = ''\n\n roman_numerals += 'M' * (number / 1000)\n number %= 1000\n\n roman_numerals += 'D' * (number / 500)\n number %= 500\n\n roman_numerals += 'C' * (number / 100)\n number %= 100\n\n roman_numerals += 'L' * (number / 50)\n number %= 50\n\n roman_numerals += 'X' * (number / 10)\n number %= 10\n\n roman_numerals += 'V' * (number / 5)\n number %= 5\n\n roman_numerals += 'I' * (number / 1)\n number %= 1\n\n roman_numerals\nend", "def roman_numeral num\n working_num = num\n roman_val = ''\n \n # [number value, roman value, index of its modifier (if any)]\n numeral_ref = [[1, 'I'], #0\n [5, 'V', 0],\n [10, 'X', 0], #2\n [50, 'L', 2],\n [100, 'C', 2], # 4\n [500, 'D', 4],\n [1000, 'M', 4]] #6\n \n (0...numeral_ref.length).reverse_each { |i|\n \n ref_num = numeral_ref[i][0]\n ref_rom = numeral_ref[i][1]\n ref_mod_i = numeral_ref[i][2]\n ref_mod_num = ref_mod_i ? numeral_ref[ref_mod_i][0] : 0\n ref_mod_rom = ref_mod_i ? numeral_ref[ref_mod_i][1] : ''\n \n if working_num >= ref_num # The 'normal' case\n mult = working_num/ref_num\n roman_val += ref_rom*(mult)\n working_num %= ref_num\n end\n if working_num >= (ref_num - ref_mod_num) # The 'subtraction case'\n roman_val += ref_mod_rom+ref_rom\n working_num -= (ref_num - ref_mod_num)\n end\n \n }\n roman_val\nend", "def dump_bigram_info_from_hash()\n\n cumulative_bigram_count = 0\n\n $bigram_count.keys.sort.each do |bigram|\n local_lead_word = bigram.split(/\\s/)[0] #shouldn't need to extract this each time\n cumulative_bigram_count += $bigram_count[bigram]\n cumulative_proportion = cumulative_bigram_count.to_f / $lead_word_count[local_lead_word].to_f\n puts sprintf(\"%s\\t%f\", bigram, cumulative_proportion )\n end\n\nend", "def first_roman_for( number )\n map = {\n 1 => 'I',\n 5 => 'V',\n 10 => 'X',\n 50 => 'L',\n 100 => 'C',\n 500 => 'D',\n 1000 => 'M'\n }\n \n decimal_place = number.to_s.size - 1 # the number of digits in the number passed\n factor = 10 ** decimal_place # the factor : 1 for one's place , 10 for tens place : the factor for the digit we are working on \n \n #append the roman_representation according to the digit\n return ( map[factor] ) * ( number/(factor) ) if number < 4 * factor \n return ( map[factor] + map[ 5*factor ] ) if number >= 4 * factor && number < 5 * factor\n return ( map[ 5 * factor ] ) if number >= ( 5 * factor ) && number < ( 6 * factor )\n return ( map[ 5 * factor ] + ( map[ factor ] * (( number - 5*factor )/factor) )) if number >= 6 * factor && number < 9 * factor\n return ( map[factor] + map[ 10 * factor ] ) if number >= 9 * factor\n end", "def to_english(number)\nsingle_digits = {\n 0 => \"zero\",\n 1 => \"one\",\n 2 => \"two\",\n 3 => \"three\",\n 4 => \"four\",\n 5 => \"five\",\n 6 => \"six\",\n 7 => \"seven\",\n 8 => \"eight\",\n 9 => \"nine\"\n }\n teens = {\n \"zero\" => \"ten\",\n \"one\" => \"eleven\",\n \"two\" => \"twelve\",\n \"three\" => \"thirteen\",\n \"four\" => \"fourteen\",\n \"five\" => \"fifteen\",\n \"six\" => \"sixteen\",\n \"seven\" => \"seventeen\",\n \"eight\" => \"eighteen\",\n \"nine\" => \"nineteen\"\n }\n tens = {\n 0 => \"zero\",\n 2 => \"twenty\",\n 3 => \"thirty\",\n 4 => \"forty\",\n 5 => \"fifty\",\n 6 => \"sixty\",\n 7 => \"seventy\",\n 8 => \"eighty\",\n 9 => \"ninety\"\n }\n\nif number.to_i == 0\n puts \"zero\"\nelse\n\neach_number = number.to_s.split(\"\").reverse\n\neach_number.each_with_index do |n, i|\n if i == 0 || i == 2 || i == 3 || i == 5 || i == 6 || i == 8 || i == 9\n each_number[i].replace(single_digits.fetch(each_number[i].to_i))\n elsif i == 1 && n != \"1\"\n each_number[i].replace(tens.fetch(each_number[i].to_i))\n elsif i == 1 && n == \"1\"\n each_number[i - 1].replace(teens.fetch(each_number[i - 1]))\n each_number[i].replace(\"zero\")\n elsif i == 4 && n != \"1\"\n each_number[i].replace(tens.fetch(each_number[i].to_i))\n elsif i == 4 && n == \"1\"\n each_number[i - 1].replace(teens.fetch(each_number[i - 1]))\n each_number[i].replace(\"zero\")\n elsif i == 7 && n != \"1\"\n each_number[i].replace(tens.fetch(each_number[i].to_i))\n elsif i == 7 && n == \"1\"\n each_number[i - 1].replace(teens.fetch(each_number[i - 1]))\n each_number[i].replace(\"zero\")\n end\nend\n\neach_number.each_with_index do |n, i|\n if i == 2\n each_number[i] = n + \" hundred\"\n elsif i == 3\n each_number[i] = n + \" thousand\"\n elsif i == 4 && each_number[i - 1].match?(/zero/)\n each_number[i] = n + \" thousand\"\n elsif i == 5 \n if each_number[i - 1].match?(/zero/) && each_number[i - 2].match?(/zero/)\n each_number[i] = n + \" hundred thousand\"\n else \n each_number[i] = n + \" hundred\"\n end\n elsif i == 6\n each_number[i] = n + \" million\"\n elsif i == 7 && each_number[i - 1].match?(/zero/)\n each_number[i] = n + \" million\"\n elsif i == 8\n if each_number[i - 1].match?(/zero/) && each_number[i - 2].match?(/zero/)\n each_number[i] = n + \" hundred million\"\n else \n each_number[i] = n + \" hundred\"\n end\n elsif i == 9\n each_number[i] = n + \" billion\"\n end\nend\n\ni = 0\nuntil i == each_number.length\n if each_number[i].match?(/zero/)\n each_number.delete_at(i)\n else\n i += 1\n end\nend\n\nputs each_number.reverse.join(\" \")\n\nend\n\nend", "def to_words(number)\n negative = false\n written_out = \"\"\n dictionary = {\n 0 => \"zero\",\n 1 => \"one\",\n 2 => \"two\",\n 3 => \"three\",\n 4 => \"four\",\n 5 => \"five\",\n 6 => \"six\",\n 7 => \"seven\",\n 8 => \"eight\",\n 9 => \"nine\",\n 10 => \"ten\",\n 11 => \"eleven\",\n 12 => \"twelve\",\n 13 => \"thirteen\",\n 14 => \"fourteen\",\n 15 => \"fifteen\",\n 16 => \"sixteen\",\n 17 => \"seventeen\",\n 18 => \"eighteen\",\n 19 => \"nineteen\",\n 20 => \"twenty\",\n 30 => \"thirty\",\n 40 => \"forty\",\n 50 => \"fifty\",\n 60 => \"sixty\",\n 70 => \"seventy\",\n 80 => \"eighty\",\n 90 => \"ninety\",\n 100 => \"hundred\",\n 1_000 => \"thousand\",\n 1_000_000 => \"million\",\n 1_000_000_000 => \"billion\",\n 1_000_000_000_000 => \"trillion\"\n }\n\n if number < 0\n negative = true\n number *= -1\n end\n if number <= 20\n written_out = dictionary[number]\n elsif number < 100\n digits = number.divmod(10)\n written_out = dictionary[digits[0] * 10]\n written_out.concat(digits[1] == 0 ? \"\" : \"-#{to_words(digits[1])}\")\n elsif number < 1_000\n digits = number.divmod(100)\n written_out = \"#{dictionary[digits[0]]} #{dictionary[100]}\"\n written_out.concat(digits[1] == 0 ? \"\" : \" and #{to_words(digits[1])}\")\n elsif number < 1_000_000\n digits = number.divmod(1_000)\n written_out = \"#{to_words(digits[0])} #{dictionary[1_000]}\"\n written_out.concat(digits[1] == 0 ? \"\" : \", #{to_words(digits[1])}\")\n elsif number < 1_000_000_000\n digits = number.divmod(1_000_000)\n written_out = \"#{to_words(digits[0])} #{dictionary[1_000_000]}\"\n written_out.concat(digits[1] == 0 ? \"\" : \", #{to_words(digits[1])}\")\n elsif number < 1_000_000_000_000\n digits = number.divmod(1_000_000_000)\n written_out = \"#{to_words(digits[0])} #{dictionary[1_000_000_000]}\"\n written_out.concat(digits[1] == 0 ? \"\" : \", #{to_words(digits[1])}\")\n else 1_000_000_000_000\n digits = number.divmod(1_000_000_000_000)\n written_out = \"#{to_words(digits[0])} #{dictionary[1_000_000_000_000]}\"\n written_out.concat(digits[1] == 0 ? \"\" : \", #{to_words(digits[1])}\")\n end\n\n if negative\n written_out = \"negative \".concat(written_out)\n end\n\n written_out\nend" ]
[ "0.7081349", "0.6980615", "0.68603635", "0.66427726", "0.6542843", "0.65317106", "0.65279365", "0.64967775", "0.6461748", "0.64551085", "0.64265347", "0.64248174", "0.6414048", "0.64095867", "0.6342532", "0.6299481", "0.62900305", "0.628542", "0.62599796", "0.62340164", "0.62261885", "0.6214307", "0.61996025", "0.6199028", "0.6182383", "0.6153261", "0.61470354", "0.61281705", "0.6106028", "0.6091177", "0.6085964", "0.6076147", "0.60513115", "0.6046036", "0.6034379", "0.6025518", "0.60233814", "0.60113543", "0.6000622", "0.5996681", "0.59933007", "0.59769213", "0.5970213", "0.5969114", "0.5967978", "0.5942666", "0.5936314", "0.59360176", "0.5934295", "0.5931867", "0.59260786", "0.59203875", "0.5904421", "0.5901927", "0.5901637", "0.5898894", "0.5896461", "0.58952326", "0.58843845", "0.5884261", "0.58792084", "0.58754957", "0.58754635", "0.5875234", "0.5872881", "0.58681434", "0.58681434", "0.58660954", "0.5862436", "0.5859224", "0.5857356", "0.5853901", "0.58533823", "0.5851775", "0.5847263", "0.5837841", "0.58348304", "0.58216983", "0.5821679", "0.5815021", "0.5809868", "0.58083725", "0.5805367", "0.57954484", "0.5791968", "0.5788199", "0.57867485", "0.57806647", "0.57803094", "0.57768655", "0.57738614", "0.5769264", "0.57652605", "0.57644963", "0.57630396", "0.5762528", "0.57551956", "0.5749076", "0.5748954", "0.5744723", "0.574408" ]
0.0
-1
put beer name and id together into one variable
def connect_deleted_beer "#{beer_name} [id: #{id}]" end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def by_id\n get_beer\n end", "def id\n\t\tputs \"Hi! My name is #{name} and my gene_gene is #{gene}.\"\n\tend", "def entire_name_with_id\r\n self.entire_full_name + \" (#{self.id})\"\r\n end", "def make_id_to_name\n build_hash('id', 'name')\n end", "def name\n id.to_s\n end", "def to_s\n s = id, name\n end", "def full_name_with_id\n id.to_s + \": \" + first_name + \" \" + last_name\n end", "def make_name_to_id\n build_hash('name', 'id')\n end", "def beer_url(id)\n \"/beer/a/#{id}/\"\n end", "def id2name() end", "def id2name() end", "def generate_name(id)\n return GameData::Item[id].exact_name\n end", "def title\n [id, name].join(' ')\n end", "def id\n name\n end", "def id\n name\n end", "def get_beer\n beer_id = params['id'];\n response = HTTP.get('http://api.brewerydb.com/v2/beer/' + beer_id,\n :params=> {\n :key => ENV[\"BREWERYDB_BEERRATER_KEY\"],\n :withBreweries => \"y\"\n }\n )\n\n body = response.parse\n\n # check for success\n if body[\"status\"] == \"success\"\n data = body[\"data\"]\n unless data.nil?\n render json: {\n status: 200,\n message: \"#{params['id']} found\",\n data: data}\n else\n render json: {\n status: 200,\n message: \"#{params['id']} not found\",\n data: []\n }\n end\n else\n render json: { status: 401, message: body[\"errorMessage\"]}\n end\n end", "def select_random_id\n beer_ids = Beer.pluck(:id)\n index_of_beer = rand(beer_ids.length - 1)\n beer_ids[index_of_beer]\n end", "def id\n name.gsub(':', '-')\n end", "def id\n name && name.gsub(' ', '').downcase\n end", "def name\n # The name must be a string\n id.to_s\n end", "def by_id\n get_brewery\n end", "def whos_that_trainer\n return \"ID #{id} | Name: #{name} | Hometown: #{hometown}\" \n end", "def full_name_with_id\n id.to_s + \": \" + user.first_name + \" \" + user.last_name\n end", "def id_to_name\n @id_to_name ||= build_hash('id', 'name')\n end", "def id\n name\n end", "def ids_names(items)\n\t\titems.reject(&:new_record?).collect {|item| {id: item.id, name: item.name.html_escape}}\n\tend", "def name\n @name ||= parse_name(id.name)\n end", "def name\n text_get(6, @id)\n end", "def name\n id\n end", "def id\n name.gsub /-/, '_'\n end", "def name\n return text_get(0, id)\n end", "def random\n beer_id = select_random_id\n Beer.find(beer_id)\n end", "def name_id\n status_label = active ? \"\" : \"[INACTIVE] \"\n [\"#{status_label}#{name + school_code}\", id]\n end", "def name_to_id\n @name_to_id ||= build_hash('name', 'id')\n end", "def set_beer\n \t\t@beer = Beer.find(params[:id])\n \tend", "def info\n \"#{name} is of breed: #{breed}\"\n end", "def to_s\n \"#{@id} - #{@name}\"\n end", "def to_string\r\n @id.to_s + ': ' + @billcoins.to_s + ' billcoins '\r\n end", "def to_s\n \t\"#{name} #{brewery.name}\"\n end", "def to_s\n\t\t\"#{@name} [#{@id}]\"\n\tend", "def id\n data[:id]\n end", "def show\n @json = Punk::API.one_beer!(params[:id])\n render json: {\n beer: @json\n }\n create(@json)\n end", "def name_as_id\n self.name.downcase.gsub(/\\s/, '-')\n end", "def get_name(conn, id)\n conn.exec_params(\"SELECT name FROM actors WHERE id=$1\",\n [id])[0][\"name\"]\nend", "def name\n \"#{id}-#{company_name}\"\n end", "def get_restaurant \n puts \"Enter a dish and we will tell you a restaurant that offers it\"\n dish_name = gets.chomp \n d = Dish.find_by(name: dish_name).id\n r = RestaurantDish.find_by(dish_id: d).restaurant_id \n to_return = Restaurant.find_by(id: r).name\n pp to_return\n\nend", "def get_info\n puts @name + ' [ID: ' + @id.to_s + ' @ '+ @@company + ']'\n end", "def get_name_and_id(options = {})\n add_default_name_and_id(options)\n options\n end", "def get_name_and_id(options = {})\n add_default_name_and_id(options)\n options\n end", "def get_name_and_id(options = {})\n add_default_name_and_id(options)\n options\n end", "def get_planet_name(id)\n %w[0 Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune][id]\nend", "def id\n raw_data[:HotelID].to_i\n end", "def id\n raw_data[:HotelID].to_i\n end", "def id\n return @playing_girl ? @id_girl : @id_boy\n end", "def bookin_ref\n return self.id.to_s + \"B\" + self.dog.id.to_s + \"D\" + self.created_at.strftime(\"%Y%m%d\")\n end", "def id\n data[:id]\n end", "def restaurant_menu\n puts \"Whose Menu Would You Like to see \"\n rest_name = gets.chomp \n \n r = Restaurant.find_by(name: rest_name).id\n x = RestaurantDish.find_by(restaurant_id: r).dish_id\n to_return = Dish.find_by(id: x).name \n\n pp to_return \n \nend", "def set_item\n @beer = Beer.find(params[:id])\n end", "def get_baker()\n baker = Baker.find(@baker_id)\n return baker\n end", "def manager_id_with_name\n \"[#{manager_id}] #{name.to_s}\"\n end", "def text_id\n \"#{name} (##{id})\"\n end", "def set_beer\n @beer = Beer.find(params[:id])\n end", "def set_beer\n @beer = Beer.find(params[:id])\n end", "def show\n @beer = BreweryDB.beer(params[:id]) \n render json: @beer\n end", "def id\n raise \"Item.id not set\" unless @id\n $stderr.puts \"Item.id >#{@id}<\"\n @id\n end", "def id\n return @artist_data[\"id\"]\n end", "def character_id(*names)\n response = request(:eve, :character_id, :names => names.flatten.join(','))\n result = {}\n [:characters, :corporations, :alliances].each do |field|\n if response.respond_to?(field)\n response.send(field).each { |row| result[row.name] = row.character_id }\n end\n end\n result\n end", "def id() end", "def id2name\n to_s\n end", "def bear_name(name)\n return name\n end", "def name_the_boat(name)\n @name = name\n puts @name\n end", "def item_name\n return if self.item_id.nil?\n\n # TODO: Redundant now\n if self.item_id.present?\n self.item_id\n else\n self.item.name\n end\n end", "def get_planet_name(id)\n name = case id\n when 1 then name = \"Mercury\"\n when 2 then name = \"Venus\"\n when 3 then name = \"Earth\"\n when 4 then name = \"Mars\"\n when 5 then name = \"Jupiter\"\n when 6 then name = \"Saturn\"\n when 7 then name = \"Uranus\" \n when 8 then name = \"Neptune\"\n end\n return name\nend", "def id\n attributes[:id] \n end", "def print_beer(beer)\n puts \" \"\n puts \"#{beer.name} has an ABV of \".light_blue + \"#{beer.abv}.\".light_red\n puts \" \"\n puts \"Description: \".light_blue + \"#{beer.description}\".light_yellow\n puts \" \"\n puts \"#{beer.name} pairs well with the following meals: \".light_blue + \"#{beer.meals}.\".light_yellow\n puts \" \"\n puts \"Have an ingredient from one of the meals above? Try using that in your next search!\"\n puts \" \"\n puts \" \"\n end", "def return_id\n\t\treturn @idStr\n\tend", "def show\n begin\n #Get the beer indicate by params[:id] in Punk API\n url = \"https://api.punkapi.com/v2/beers/#{params[:id]}\"\n response = Faraday.get(url)\n\n #Convert to JSON the response body\n data = JSON.parse(response.body)\n\n #Create the new\n beer = Beer.new\n beer.name = data[0][\"name\"]\n beer.tagline = data[0][\"tagline\"]\n beer.description = data[0][\"description\"]\n beer.abv = data[0][\"abv\"]\n beer.seen_at = DateTime.now\n beer.user_id =@current_user.id\n beer.save!\n\n render json: BeerSerializer.new(beer).data\n rescue StandardError => e\n message = e.message\n end\n end", "def to_s()\n return \"id: \" + @id.to_s() + \"\\nFirst Name: \" + @first_name + \\\n \"\\nLast Name: \" + @last_name + \"\\nGender: \" + @gender + \"\\nAge: \" + @age + \"\\nBirthdate: \" + @birthdate\n end", "def andrew_id\n @andrew_id ||= @data[:cmuAndrewId].last\n end", "def to_s\n\t\t\"Product Id: #{id}, name \"\n\tend", "def id\n @data['id']\n end", "def name\n @name ? @name.to_s : unique_id\n end", "def name\n @name || @id.to_s.capitalize\n end", "def name\n Item.find(item_id).name\n end", "def name\n Item.find(item_id).name\n end", "def to_s\n self.name + \" \" + self.brewery.name\n end", "def base_id\n \"#{firstname} #{lastname}\"\n end", "def id\n (read_property 'Id') || name\n end", "def to_s\n s = id, band_name, album_name, media_type_id, location_id\n end", "def set_beer\n @beer = Beer.find(params[:id])\n end", "def set_beer\n @beer = Beer.find(params[:id])\n end", "def set_beer\n @beer = Beer.find(params[:id])\n end", "def set_beer\n @beer = Beer.find(params[:id])\n end", "def set_beer\n @beer = Beer.find(params[:id])\n end", "def id\n data[:id]\n end", "def id\n object[\"id\"]\n end", "def brand_name\n brand_id ? brand.name : ''\n end", "def brand_name\n brand_id ? brand.name : ''\n end", "def extract_id(object)\n extract_string object, :id\n end", "def ids(things)\n things.map(&:id).join(\",\")\n end" ]
[ "0.6558066", "0.6024858", "0.58939886", "0.5850488", "0.58489627", "0.5783383", "0.576869", "0.5756782", "0.5751613", "0.5729647", "0.5729647", "0.56936455", "0.56769747", "0.5646166", "0.5646166", "0.56071717", "0.56040776", "0.55874234", "0.5560389", "0.554319", "0.5533847", "0.55237323", "0.5522957", "0.54990053", "0.5486164", "0.5484386", "0.54624397", "0.54420084", "0.54387397", "0.5436598", "0.5433124", "0.5413167", "0.5411885", "0.5411811", "0.5393052", "0.53799075", "0.53720605", "0.5370233", "0.5367505", "0.5366418", "0.53529966", "0.53353184", "0.531768", "0.5308189", "0.53027976", "0.53002954", "0.5280365", "0.52764726", "0.52764726", "0.52764726", "0.5257867", "0.5241938", "0.5241938", "0.5238501", "0.52363294", "0.52361125", "0.5235725", "0.5233339", "0.5232941", "0.522902", "0.52279496", "0.52185017", "0.52185017", "0.5215527", "0.5213152", "0.5210889", "0.5208852", "0.5205015", "0.5203785", "0.5194722", "0.5192824", "0.5188096", "0.51825756", "0.51781833", "0.5177786", "0.51702774", "0.5165013", "0.5163113", "0.5160195", "0.51574284", "0.5155076", "0.51521045", "0.5147561", "0.51470447", "0.51470447", "0.5133094", "0.51292026", "0.5119656", "0.5119", "0.51135635", "0.51135635", "0.51135635", "0.51135635", "0.51135635", "0.51117855", "0.51115185", "0.5106843", "0.5106843", "0.51063967", "0.5102859" ]
0.5159198
79
join long maker and drink name together
def join_drink_name if brewery.short_brewery_name.nil? "#{brewery.brewery_name} #{beer_name}" else "#{brewery.short_brewery_name} #{beer_name}" end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def artist_name_and_genre\n \"#{artist_name} - #{genre.name}\"\n end", "def long_name\n [number, title].join(' ')\n end", "def long_name\n [number, title].join(' ')\n end", "def full_name\n \"#{bike_brand.name} #{model}\"\n end", "def build_name\n \"#{manufacturer} #{weight} #{style} #{name}\"\n end", "def full_name\n \"#{brand.name} #{name} (#{vehicle_type.name})\"\n \n end", "def create_multi_name\n base_name = String.new(Faker::Games::ElderScrolls.creature)\n if base_name.split.size == 1\n adjective = Spicy::Proton.adjective.capitalize\n new_name = base_name.split.unshift(adjective)\n new_name.join(' ')\n else\n return base_name\n end\n end", "def merge_info\n num_obs = observations.count\n num_namings = namings.count\n \"#{:NAME.l} ##{id}: #{real_search_name} [o=#{num_obs}, n=#{num_namings}]\"\n end", "def select_name_and_series_subgenres_of_authors\n \"SELECT authors.name, subgenres.name FROM authors INNER JOIN series ON authors.id=series.author_id INNER JOIN subgenres ON series.subgenre_id = subgenres.id; \"\nend", "def whos_that_trainer\n return \"ID #{id} | Name: #{name} | Hometown: #{hometown}\" \n end", "def select_name_and_series_subgenres_of_authors\n \"SELECT authors.name, subgenres.name\n FROM series\n INNER JOIN authors\n ON series.author_id = authors.id\n INNER JOIN subgenres\n ON series.subgenre_id = subgenres.id\"\nend", "def lifter_names_gym\n lifters_gym.map do |lifter|\n lifter.name\n end\n end", "def namejoin\n self.first_name + \" \" + self.last_name\n end", "def full_name\n [vendor, model].join(\" \")\n end", "def construct_supply_item_name(data)\n @supply_item_name = \"#{data[:name01]}\"\n @supply_item_name += \" #{data[:name02]}\" unless data[:name02].blank?\n @supply_item_name += \" (#{data[:name03]})\" unless data[:name03].blank?\n super\n end", "def construct_supply_item_name(data)\n @supply_item_name = \"#{data[:name01]}\"\n @supply_item_name += \" #{data[:name02]}\" unless data[:name02].blank?\n @supply_item_name += \" (#{data[:name03]})\" unless data[:name03].blank?\n super\n end", "def get_full_name\n return nil unless GENUS_AND_SPECIES_RANK_NAMES.include?(self.rank_string) || self.type == 'Combination'\n d = full_name_hash\n elements = []\n eo = '<em>'\n ec = '</em>'\n d.merge!('genus' => [nil, '[GENUS NOT PROVIDED]']) if !d['genus']\n\n elements.push(\"#{eo}#{d['genus'][1]}#{ec}\")\n elements.push ['(', %w{subgenus section subsection series subseries}.collect { |r| d[r] ? [d[r][0], \"#{eo}#{d[r][1]}#{ec}\"] : nil }, ')']\n elements.push ['(', eo, d['superspecies'], ec, ')'] if d['superspecies']\n\n %w{species subspecies variety subvariety form subform}.each do |r|\n elements.push(d[r][0], \"#{eo}#{d[r][1]}#{ec}\") if d[r]\n end\n\n elements.flatten.compact.join(\" \").gsub(/\\(\\s*\\)/, '').gsub(/\\(\\s/, '(').gsub(/\\s\\)/, ')').squish.gsub('</em> <em>', ' ')\n end", "def drink_classifcation(name)\n size = Sizes.select{|s| name.match(s) }.first\n milk = Milks.select{|m| name.match(m) }.first\n [name, size, milk]\nend", "def full_name\n return \"#{make.name} #{name}\"\n end", "def name\n [phone.brand, phone.model].join(\" \")\n end", "def name_and_price\n [name, \"$\" + price.to_s].join \" - \"\n end", "def name_and_relationship\n [first_name, last_name].join(' ') + ': ' + relationship.to_s\n end", "def car2 (make, model)\n return make + ' ' + model\nend", "def reconstituted_name\n reconstituted = ''\n reconstituted << name\n reconstituted << \" (feat. #{featured_artists.join(', ')})\" if featured_artists.size > 0\n reconstituted << \" [#{remix}]\" if remix && remix != ''\n \n reconstituted\n end", "def select_names\n q = make_work\n # binding.pry\n names = []\n names.push(q.collect{|xx| xx[\"drinks\"][0][\"strDrink\"]})\n #names.push(q.collect{|xx| xx[\"drinks\"][0][\"strDrink\"]})\n names.push(q.collect{|xx| xx[\"drinks\"][1][\"strDrink\"]})\n #binding.pry\n #count +=1\n # end\n \n names\n end", "def name_join\n @code_name = @split_name.join('')\n p @code_name\nend", "def name_bill\n \"#{name}:#{endNumber}\"\n end", "def name; termid;end", "def rcpname(id); det.link(:text, \"#{id}\"); end", "def mix_names(girls, boys)\n\tnew_array = girls \n\tindex = 0 \n\n\tboys.length.times do\n\t\tnew_array << boys[index]\n\t\tindex = index + 1 \n\tend \n\n\toutput = new_array\n\treturn output\nend", "def novel_dup_as_maker\n novel_dup('maker',:maker)\n end", "def alias_manager(covert_spy_name)\n\n spy_name = covert_spy_name.downcase.split(' ')\n reversed_spy_name = spy_name.reverse\n first_name = reversed_spy_name.first.to_s\n last_name = reversed_spy_name.last.to_s\n full_name = first_name + \" \" + last_name\n full_name_id = full_name.gsub(/[abcdefghijklmnopqrstuvwxyz]/, 'a' => 'e', 'b' => 'c', 'c' => 'd', 'd' => 'f', 'e' => 'i', 'f' => 'g', 'g' => 'h', 'h' => 'j', 'i' => 'o', 'j' => 'k', 'k' => 'l', 'l' => 'm', 'm' => 'n', 'n' => 'p', 'o' => 'u', 'p' => 'q', 'q' => 'r', 'r' => 's', 's' => 't', 't' => 'v', 'u' => 'a', 'v' => 'w', 'w' => 'x', 'x' => 'y', 'y' => 'z', 'z' => 'b')\n full_name_idx = full_name_id.split.map {|x| x.capitalize}.join(' ')\nend", "def retrieve_names(meal)\n @names = ''\n begin\n if meal == 0\n breakfast_plates = BreakfastPlate.all\n breakfast_plates.each do |plate|\n if plate.request_day == @date\n user = User.where(id: plate.user_id)\n name = Name.new(user[0]['first_name'], user[0]['last_name'])\n @names << name.first_name + ' ' + name.last_name + \" \\n\"\n end\n end\n return @names\n elsif meal == 1\n dinner_plates = DinnerPlate.all\n dinner_plates.each do |plate|\n if plate.request_day == @date\n user = User.where(id: plate.user_id)\n name = Name.new(user[0]['first_name'], user[0]['last_name'])\n @names << name.first_name + ' ' + name.last_name + \" \\n\"\n end\n end\n return @names\n else\n return \"Error, invalid meal\"\n end\n rescue => ex\n return \"Error, #{ex.message}\"\n end\n end", "def favourite_drink name\r\n\tif name == \"Jean-Luc\"\r\n\t\t\"tea, Earl Grey, hot\"\r\n\telsif name == \"Kathryn\"\r\n\t\t\"coffee, black\"\r\n\telse\r\n\t\t\"perhaps...horchata?\"\r\n\tend\r\nend", "def combine_info\n @combine_info = pipe_names + space_names + comma_names \nend", "def to_s\n \t\"#{name} #{brewery.name}\"\n end", "def name_and_full_address\n [name, full_address].join ' - '\n end", "def put_together_name(full_or_part)\n tag = :\"description_#{full_or_part}_title_#{source_type}\"\n user_name = begin\n user.legal_name\n rescue StandardError\n \"?\"\n end\n args = {\n text: source_name,\n user: user_name\n }\n if full_or_part == :full\n args[:object] = parent.format_name\n elsif source_name.present?\n tag = :\"#{tag}_with_text\"\n end\n tag.l(args)\n end", "def mix_names(girls_array, boys_array)\n b_i = 0 \n boys_array.length.times do \n girls_array << boys_array[b_i]\n b_i += 1 \n end \n output = girls_array\n return output\nend", "def other_names\n [artist_name, tag_name].compact.uniq\n end", "def to_s\n self.name + \" \" + self.brewery.name\n end", "def name; nutrdesc; end", "def aliases\n myAliases = \"\"\n if ['Mount ',' Mountain',' Peak'].any? {|word| self.name.include?(word)}\n short = shortname\n myAliases = \"#{short} Mountain, Mount #{short}, Mt. #{short}, Mt #{short}, #{shortname} mt, #{shortname} mtn, #{short} mtn., #{short} Peak\" \n end\n myAliases\n end", "def item_at_bays_more(loc1, loc2, loc3, loc4)\n product_bays_more = WAREHOUSE.select{ |bays| bays[:rack_bay_position] == loc1 || bays[:rack_bay_position] == loc2 || bays[:rack_bay_position] == loc3 || bays[:rack_bay_position] == loc4 }\n product_bays_more.map{ |bays| bays[:product_name] }.join(\", \")\nend", "def entire_name_with_id\r\n self.entire_full_name + \" (#{self.id})\"\r\n end", "def set_full_name\n self.full_name = \"#{manufacturer.name} #{name}\"\n end", "def name\n \tself.marker_synonyms.collect{|ms| ms.name}.join(',')\n end", "def film_producer(film)\n film[\"producer\"].split(', ').join(\" and \")\nend", "def gym_plus_wall_name\n \"#{gym.name} - #{name}\"\n end", "def join_name(name)\r\n\tnew_alias = name.join('')\r\n\tif new_alias.include?('!')\r\n\t\tnew_alias.gsub!('!', ' ')\r\n\tend\r\n\tnew_alias_ary = new_alias.split(' ')\r\nend", "def join_name(name)\r\n\tnew_alias = name.join('')\r\n\tif new_alias.include?('!')\r\n\t\tnew_alias.gsub!('!', ' ')\r\n\tend\r\n\tnew_alias_ary = new_alias.split(' ')\r\nend", "def secondary_instrument_names\n #instruments.map{|i|i.display_name}.join(\"~\")\n \"\"\n end", "def display_source_identifiers # :yields: String identifying the lot or specimen the extract came from\n specimen_id && (return Specimen.find(specimen_id).display_name(:type => :identifiers))\n return Lot.find(lot_id).display_name(:type => :identifiers)\n end", "def to_s\n \"#{self.artist.name} - #{self.name} - #{self.genre.name}\"\n end", "def get_name\n \"#{@manufacturer} #{@model}\"\n end", "def full_name_and_title\n result = String.new\n result += \"#{self.primary_title.name} \" unless self.primary_title.nil?\n result += \"#{self.first_name} #{self.family_name}\".squeeze(\" \").strip\n end", "def attach_to_name(name)\n if preferred_form == Prefix\n s= [prefix,name].compact.join(\" \")\n else\n s = [name,suffix].compact.join(\" \")\n end\n s.strip\n end", "def combined_name\n self.FirstName + \" \" + self.LastName + \" \" + self.Company\nend", "def full_name(delim = ', ')\n n = name\n n += \"#{delim}#{borough}\" if !borough.nil?\n n\n end", "def create_dn_by_mid(bibid, response)\n\t dn_by_mid = {}\n\t if response[bibid] and response[bibid][bibid] and response[bibid][bibid][:records]\n\t response[bibid][bibid][:records].each do |record|\n\t\tif record[:bibid].to_s == bibid\n\t\t record[:holdings].each do |holding|\n\t\t dn_by_mid[holding[:MFHD_ID].to_s] = holding[:TEMP_LOCATION_DISPLAY_NAME].nil? ? holding[:PERM_LOCATION_DISPLAY_NAME]:holding[:TEMP_LOCATION_DISPLAY_NAME]\n\t\t end\n\t\tend\n\t end\n\t end\n\t dn_by_mid\n\t end", "def minors_list(show_full_names = false, join_string = \", \")\n minors.collect { |m| m.minor_abbr.strip }.join(join_string)\n end", "def long_name\n if @description\n @name + ' ' + @description\n else\n @name\n end\n end", "def reformat_twofaced_names(card)\n end", "def breed(a, b)\n\toffspring = crossover_gene_matrices(a.to_genes, b.to_genes)\n\t[birth(offspring[0]), birth(offspring[1])]\nend", "def name\n \"Lord Admiral #{@name}\"\n end", "def full_name(patient)\n return unless patient\n\n if patient.family_name.blank? && patient.animal_type.present?\n return [patient.given_name,\n patient.middle_name,\n \"(#{animal_species_name(patient.animal_type)})\"].join(' ').squish\n end\n\n [patient.given_name,\n patient.middle_name,\n patient.family_name,\n patient.family_name2,\n patient.partner_name].join(' ').squish\n end", "def full_name\n\t\ts = title\n\t\ts = \"#{artist.name} - #{s}\" if artist\n\t\treturn s\n\tend", "def chop_listings(listings, keys)\n\tlistings.map{|lst| lst[\"title\"].downcase.sub(/#{keys.join('.*|\\ ')}.*/, \"\").strip.concat(\" \" + lst[\"manufacturer\"]).downcase.strip}\nend", "def mothers_name\n\t\tmothersname = mothers_names.delete_if(&:blank?).join(' ')\n\t\t( mothersname.blank? ) ? '[name not available]' : mothersname\n\tend", "def other_party(person)\n person == starter ? listing.author : starter\n end", "def names\n \n # COMBINE split names into composite names for these rows\n composites = [\n {:row => :sa, :version => /^[6-8]/, :field => [:contributor, :donor_candidate]},\n {:row => :sb, :version => /^[6-8]/, :field => [:payee, :beneficiary_candidate]},\n {:row => :sc, :version => /^[6-8]/, :field => [:lender, :lender_candidate]},\n {:row => :sc1, :version => /^[6-8]/, :field => [:treasurer, :authorized]},\n {:row => :sc2, :version => /^[6-8]/, :field => :guarantor},\n {:row => :sd, :version => /^[6-8]/, :field => :creditor},\n {:row => :se, :version => /^[6-8]/, :field => [:payee, :candidate]},\n {:row => :sf, :version => /^[6-8]/, :field => [:payee, :payee_candidate]},\n {:row => :f3p, :version => /^[6-8]/, :field => :treasurer},\n {:row => :f3p31, :version => /^[6-8]/, :field => :contributor},\n ]\n # SPLIT composite names into component parts for these rows\n components = [\n {:row => :sa, :version => /^3|(5.0)/, :field => :contributor},\n {:row => :sa, :version => /^[3-5]/, :field => :donor_candidate},\n {:row => :sb, :version => /^3|(5.0)/, :field => :payee},\n {:row => :sb, :version => /^[3-5]/, :field => :beneficiary_candidate},\n {:row => :sc, :version => /^[3-5]/, :field => [:lender, :lender_candidate]},\n {:row => :sc1, :version => /^[3-5]/, :field => [:treasurer, :authorized]},\n {:row => :sc2, :version => /^[3-5]/, :field => :guarantor},\n {:row => :sd, :version => /^[3-5]/, :field => :creditor},\n {:row => :se, :version => /^[3-5]/, :field => [:payee, :candidate]},\n {:row => :sf, :version => /^[3-5]/, :field => [:payee, :payee_candidate]},\n {:row => :f3p, :version => /^[3-5]/, :field => :treasurer},\n {:row => :f3p31, :version => /^[3-5]/, :field => :contributor},\n ]\n \n composites.each { |c| combine_components_into_name(c) }\n components.each { |c| split_name_into_components(c) }\n \n end", "def get_full_name\n \"#{number} (#{swimmer ? swimmer.get_full_name : '?'})\"\n end", "def modif_town_hall_name(all_town_hall)\n i = 0\n while i != all_town_hall.length\n all_town_hall[i] = all_town_hall[i].downcase!.split.join('-')\n i += 1\n end\n return all_town_hall\nend", "def insured_name\n id, qual = eob.member_id_and_qualifier\n sub_name_ele = []\n sub_name_ele << 'NM1'\n sub_name_ele << 'IL'\n sub_name_ele << '1'\n sub_name_ele << eob.subscriber_last_name\n sub_name_ele << eob.subscriber_first_name\n sub_name_ele << eob.subscriber_middle_initial\n sub_name_ele << ''\n sub_name_ele << eob.subscriber_suffix\n sub_name_ele << qual\n sub_name_ele << id\n sub_name_ele = Output835.trim_segment(sub_name_ele)\n sub_name_ele.join(@element_seperator)\n end", "def car(brand, model)\n brand + ' ' + model\nend", "def lifter_names\n gym_lifters.map(&:name)\n end", "def name\n if has_dupes?\n \"#{firstname} #{lastname} (#{serial_number})\"\n else\n \"#{firstname} #{lastname}\"\n end\n end", "def name_merge hsh\n str = \"\"\n @log.debug \"name merge for #{hsh}\"\n str += hsh[:name].strip.force_encoding(\"UTF-8\") if hsh[:name]\n str += \"\\n#{hsh[:description].strip.force_encoding(\"UTF-8\")}\" if hsh[:description]\n str\n end", "def to_s\n \"#{@name} (#{@party})\"\n end", "def linked_mods_genres(genres)\n genres.map do |subject|\n mods_genre_field(subject) do |subject_text, buffer|\n link_to(\n subject_text,\n search_catalog_path(\n q: \"\\\"#{[buffer, subject_text.strip].flatten.join(' ')}\\\"\",\n search_field: 'subject_terms'\n )\n )\n end\n end.join('').html_safe\n end", "def concat_names(contribs)\n contribs.map do |p|\n if p.name.surname\n \"#{p.name.surname}, #{p.name.forename.map(&:to_s).join(' ')}\"\n else\n p.name.completename.to_s\n end\n end.join(\" and \")\n end", "def join(details)\n joinchar = self.joiner\n\n fields.collect { |field|\n # If the field is marked absent, use the appropriate replacement\n if details[field] == :absent or details[field] == [:absent] or details[field].nil?\n if self.optional.include?(field)\n self.absent\n else\n raise ArgumentError, \"Field '#{field}' is required\"\n end\n else\n details[field].to_s\n end\n }.reject { |c| c.nil?}.join(joinchar)\n end", "def combine_names(first, last)\n first + ' ' + last\nend", "def brand_name\n brand_id ? brand.name : ''\n end", "def brand_name\n brand_id ? brand.name : ''\n end", "def print_owners_heros (fwt, last_name)\n\n\ttemp = fwt.execute(\"SELECT heros.name, ratings.rating, ratings.descripton FROM acquisitions JOIN owners ON acquisitions.owners_id = owners.id JOIN heros ON acquisitions.heros_id = heros.id JOIN ratings ON acquisitions.ratings_id = ratings.id WHERE owners.last_name = ? ORDER BY first_name, last_name\",[last_name])\n\n\tputs \"\\n\\n#{last_name} owns the following heros:\"\n\t\n\ttemp.each do |hero_name,ratings, descripton|\n\t\tputs \"Hero's Name:#{hero_name} Rating:#{ratings} Description:#{descripton}\"\n\tend\nend", "def price_name_and_description\n desc = ' ('+ description + ')' unless description.blank?\n \"#{name}#{desc}\"\n end", "def proper_name #returns lastname, firstname\n \treturn self.last_name + ', ' + self.first\n end", "def modeler_description\n return 'Adds either: (1) hot water boiler and electric chiller with variable-speed pumps to two plant loops, along with coil heating/cooling water objects on zone hvac four pipe fan coil objects, or (2) an electric chiller with variable-speed pump to a single plant loop, along with coil cooling water objects on cooling-only zone hvac four pipe fan coil objects.'\n end", "def lot_name\n lot.name\n end", "def long_association_name(join_table, left_key, left_table, right_key)\n left_key_qualifier = \"_#{left_key}\" if left_table != parent_table_for(left_key)\n \"#{singularize(join_table)}#{left_key_qualifier}_#{plural_association_name(right_key)}\"\n end", "def artist_names #return array of the names of all artists that have a painting in a gallery\n artists.name #pull array from artists method and call reader to get their name\n end", "def lifters_name \n lifters.map do |lifter|\n lifter.name\n end\n end", "def to_s\n \"#{self.name} (#{self.brewery.name})\"\n end", "def link_to_ird_strains!(noisy = false)\n cutoff_year = Time.now.year % 100\n \n parts = strain_name.split(/\\//)\n part_synonyms = parts.each_with_index.map do |part, i|\n part.gsub! /^\\s+|\\s+$/, ''\n synonyms = case\n when i == 0\n # First part, the type of the influenza virus, we'll leave alone\n [part]\n when (i == parts.size - 1 and part =~ /^(\\d{2}?)(\\d{2})$/)\n # Try two digit AND four digit date, assuming that two digit dates past this year's are in the 1900's\n if $1.size > 0 then [part, $2] else [part, \"#{$2.to_i > cutoff_year ? 19 : 20}#{$2}\"] end\n when part =~ /^0*(\\d+)$/\n # Allow some flexibility in leading zeros for middle segments containing numbers\n [$1, \"0#{$1}\", \"00#{$1}\", \"000#{$1}\"]\n when synonym_dict[part]\n synonym_dict[part].to_a\n else\n [part]\n end\n # Now add more possibilities: hyphens removed, underscores vs. spaces\n synonyms.map do |syn|\n more_syns = [syn]\n more_syns << syn.gsub(/-/, '') if syn =~ /-/\n more_syns << syn.gsub(/ /, '_') if syn =~ /_/\n more_syns << syn.gsub(/_/, ' ') if syn =~ / /\n more_syns\n end.flatten\n end\n \n part_synonyms.first.product(*part_synonyms.drop(1)).each do |parts|\n name = parts.join('/').gsub('_', '\\\\_').gsub('%', '\\\\%')\n IrdStrain.where(\"strain_name LIKE ?\", name).find_each do |ird_strain|\n puts \"#{strain_name} linked to IRD strain #{ird_strain.id}, name #{ird_strain.strain_name}.\" if noisy\n ird_strains << ird_strain unless ird_strains.include? ird_strain\n end\n end\n \n ird_strains.size > 0\n end", "def combine_names(first_name, last_name)\n first_name + \" \" + last_name\nend", "def format(maker_breaker)\n index = breaker.guess\n index = maker.code if maker_breaker.type == 'code'\n \"#{@pegs[index[0]]} #{@pegs[index[1]]} #{@pegs[index[2]]} #{@pegs[index[3]]}\"\n end", "def clothing\n @clothing.join(\", \")\n end", "def belongs_to\n return self.property.name if self.renter_id == 0\n return self.renter.full_name2 if (self.renter_id != 0) \n end", "def food_and_drink; end" ]
[ "0.5533941", "0.5518208", "0.5518208", "0.54684293", "0.5456652", "0.54524815", "0.539281", "0.5366308", "0.533506", "0.53204626", "0.5264557", "0.52471876", "0.5244372", "0.52410257", "0.52200073", "0.52200073", "0.5195274", "0.51899457", "0.516247", "0.514659", "0.51452863", "0.51316607", "0.5089738", "0.5082628", "0.5080432", "0.5074972", "0.50608796", "0.5053142", "0.5052032", "0.5050719", "0.5034772", "0.50270575", "0.50268775", "0.50116074", "0.5001489", "0.49893412", "0.4986552", "0.4985252", "0.4984212", "0.49747917", "0.49747562", "0.49706817", "0.49649504", "0.49644715", "0.49578217", "0.49566016", "0.49548498", "0.4954598", "0.49534053", "0.49397245", "0.49397245", "0.49395114", "0.49331218", "0.49311525", "0.49210858", "0.49131876", "0.49117905", "0.4895568", "0.48812342", "0.48753905", "0.48702446", "0.4857035", "0.48560476", "0.48552558", "0.4853446", "0.48496428", "0.48490706", "0.48484734", "0.48197007", "0.48146152", "0.4810852", "0.47929758", "0.4791684", "0.47914216", "0.4791003", "0.47903368", "0.47887236", "0.47864118", "0.4781708", "0.47816917", "0.47780624", "0.47776034", "0.47773507", "0.47770992", "0.47770992", "0.47713766", "0.477089", "0.4768169", "0.4768039", "0.47669715", "0.47578678", "0.47481304", "0.474232", "0.4740204", "0.4737863", "0.47361583", "0.47292957", "0.47286758", "0.4728216", "0.47280058" ]
0.6993197
0
get unique beer descriptors
def top_drink_descriptors(how_many) # create empty array to hold top descriptors list for beer being rated @this_beer_descriptors = Array.new # find all descriptors for this drink @this_beer_all_descriptors = self.descriptors # Rails.logger.debug("this beer's descriptors: #{@this_beer_all_descriptors.inspect}") @this_beer_all_descriptors.each do |descriptor| @descriptor = descriptor["name"] @this_beer_descriptors << @descriptor end # attach count to each descriptor type to find the drink's most common descriptors @this_beer_descriptor_count = @this_beer_descriptors.each_with_object(Hash.new(0)) { |word,counts| counts[word] += 1 } # put descriptors in descending order of importance @this_beer_descriptor_count = Hash[@this_beer_descriptor_count.sort_by{ |_, v| -v }] # grab top 5 of most common descriptors for this drink @this_beer_descriptor_count.first(how_many) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def drink_type_descriptors\n # get related drinks\n @associated_drinks = Beer.where(beer_type_id: self.id)\n # create array to hold descriptors\n @descriptors_holder = Array.new\n # find all descriptors for this drink type\n @associated_drinks.each do |drink|\n @this_drink_type_all_descriptors = drink.descriptors\n @this_drink_type_all_descriptors.each do |descriptor|\n @descriptor = descriptor[\"name\"]\n @descriptors_holder << @descriptor\n end\n end\n # attach count to each descriptor type to find the drink type's most common descriptors\n @this_drink_descriptor_count = @descriptors_holder.each_with_object(Hash.new(0)) { |word,counts| counts[word] += 1 }\n #Rails.logger.debug(\"Descriptors by count-1 #{@this_drink_descriptor_count.inspect}\")\n # put descriptors in descending order of importance\n @this_drink_descriptor_count = Hash[@this_drink_descriptor_count.sort_by{ |_, v| -v }]\n #Rails.logger.debug(\"Descriptors by count-2 #{@this_drink_descriptor_count.inspect}\")\n \n @this_drink_top_descriptors = Array.new\n # fill array descriptors only, in descending order\n @this_drink_descriptor_count.each do |key, value|\n @this_drink_top_descriptors << key\n end\n #Rails.logger.debug(\"Final Descriptors: #{@this_drink_top_descriptors.inspect}\")\n \n # get all descriptors associated to drink type by user, if they exist\n @user_drink_type_descriptors = self.descriptors_from(@user)\n # get final list, minus the descriptors the user already has chosen, if exist\n @this_drink_top_descriptors = @this_drink_top_descriptors - @user_drink_type_descriptors\n end", "def descriptors\n @descriptors ||= (attributes + parameters)\n end", "def many name\n send(name).uniq(&:id)\n end", "def descriptors\n @descriptions ||= (attributes + parameters)\n end", "def animal_species\n Animal.all.map do |animal|\n animal.specie\n end.uniq\n end", "def pseudo_chalkler_bookings\n \n h = Hash.new {|h, c| h[c] = @booking_set.bookings.select{|b| b.pseudo_chalkler_email == c } }\n @booking_set.bookings.collect(&:pseudo_chalkler_email).uniq.compact.map {|c| h[c] }\n h\n end", "def allergens\n ingredients_array=[]\n ingredients.each do |ingredient|\n # binding.pry\n if ingredient.allergens\n # binding.pry\n ingredients_array << ingredient.allergens\n end\n end\n arr= ingredients_array.flatten.map do |allergen|\n allergen.ingredient\n end\n arr.uniq\n end", "def ingredient_recipes\n self.doses.map { |d| d.recipe }.uniq\n end", "def allergens\n self.allergy.map do |allergen|\n allergen.ingredient\n end.uniq\n end", "def chalkler_bookings\n h = Hash.new {|h, c| h[c] = @booking_set.bookings.select{|b| b.chalkler == c } }\n @booking_set.bookings.collect(&:chalkler).uniq.compact.map {|c| h[c] }\n h\n end", "def generate_digest_set(letter = nil)\n get_digest_recipients\n get_updated_reflections\n get_vote_activities\n get_petition_related_activities\n get_updated_contributions\n get_updated_conversations\n get_recipient_subscriptions\n group_activities_by_conversation\n end", "def unique_senders\n return @unique_senders\n end", "def assigned_keys; @assigned_factories.keys; end", "def animal_species\n animal_arr = self.animals.map do |animal|\n animal.species\n end.uniq\n end", "def actors \n characters.map { | characters | characters.actor}.uniq\n end", "def species\n self.waters.map{|water| water.species.map{|s| s.name } }.flatten.uniq.sort\n end", "def animal_species\n Animals.uniq.select { |animal| animal.species }\n end", "def weaker\n descendants\n end", "def animal_species\n animals.map { |animal| animal.species}.uniq\n end", "def names\n $LEDGER.keys\n end", "def descriptors(arg = nil)\n if arg.nil?\n storage.map { |_, (descriptor, _)| descriptor }\n else\n with_interest(arg).map { |_, descriptor, _| descriptor }\n end\n end", "def all_chips\n chips.values.flatten\n end", "def unique_tag\n\n\t\t##collect transforms given array into the new array abbr\n\t\tabbr = self.author.split(\" \").collect do |sub_string|\n\t\t\tsub_string[0] #puts first letter of each substring into intials array\n\t\tend\n\n\t\treturn abbr.join + '#' + self.id.to_s ##join concatenates an array into a string\n\tend", "def species\n species = Array.new\n\n mobs.each do |mob|\n species << mob.specie\n end\n\n return species.uniq\n end", "def describe()\n return \"d\" + @faces.to_s()\n end", "def derived_receive_keys\n receive_depth.times.map{|i|derive_key(0,i)}\n end", "def animal_species()\n self.animals().map() { | animal | animal.species() }.uniq\n end", "def generate_digest_set(letter = nil)\n get_digest_recipients\n get_updated_contributions\n get_updated_conversations\n get_recipient_subscriptions\n group_contributions_by_conversation\n end", "def allergens\n self.ingredients.map do |ingredient|\n Allergen.all.map do |allergen|\n ingredient if allergen.ingredient_O == ingredient\n end.compact\n end.flatten.uniq\n end", "def find_max_descriptors(max_descripors)\n i = max_descripors\n max_size = 1024\n while i != max_size && i > 1024\n max_size = EM.set_descriptor_table_size i\n i /= 2 if max_size < i\n end\n max_size\nend", "def responder_ids\n capacities.keys\n end", "def data\n beers.map do |beer|\n [\n ##link to is a ruby function, the second argument is the path\n ##in this case the path leads to a beer id\n link_to(beer.title, beer),\n beer.rating,\n beer.country,\n beer.state_or_province,\n (beer.votes.where(:up=>true).count - beer.votes.where(:up => false).count),\n link_to('Add Comment',beer),\n ##when this code below is removed it works fine without an up/down vote option\n\t\tupvotelnk(beer) + \" \" + downvotelnk(beer)\n ]\n end\n end", "def desserts\n self.dessert_ingredients.map {|di| di.dessert}\n end", "def all_animal_species\n #binding.pry\n all_animals.select{|species|species.zoo == self }.uniq\n end", "def bond_actors(array)\n #the variable actors is equal to a new array that only has the key actors in each of the movies\n actors = array.map {|movie| movie[:actor]}\n #outputs only the unique actors so no duplicates will be shown\n puts actors.uniq\nend", "def generate_hash\n @tags.group_by do |x|\n x[:name]\n x.delete(:name)\n end\n end", "def common_weakness_enumeration_ids\n return @common_weakness_enumeration_ids\n end", "def get_allergy_names\n allergies.map {|a| a.name}\n end", "def allergens\n unique_allergen_ingredients = Allergen.all.map do |allergen|\n allergen.ingredient\n end.uniq\n\n (self.ingredients & unique_allergen_ingredients)\n end", "def waiters\n waiters_array = []\n meals.each do |meal|\n waiters_array << meal.waiter \n end \n return waiters_array\n end", "def desserts\n dis = DesertIngredient.all.select {|di| di.ingredient == self}\n dis.map {|di| di.dessert}.uniq\n end", "def distinct_devices\n Device.distinct.pluck(:description)\n end", "def breed_group\n return data.breed_groupes\n end", "def bakeries\n dessert.map do |dessert|\n dessert.bakery\n end\n \n end", "def drivers\n full_attributes.map(&:driver).uniq.reject(&:nil?)\n end", "def chair_hiwi\n contracts.collect(&:chair).uniq\n end", "def distractors_list\n self.distractors.map { |distractor| distractor.value }.join(', ')\n end", "def derived_receive_keys\n (receive_depth + 1).times.map{|i|derive_key(0,i)}\n end", "def collocutors\n comments.map(&:reader).uniq\n end", "def fandoms\r\n @fandoms.keys\r\n end", "def waiters\n self.meals.map {|meal| meal.waiter}\n end", "def get_habitats()\n\n all_habitats = []\n\n @raw.raw_habitats.each do |habitat|\n all_habitats.push(habitat.keys)\n end\n\n @habitats = all_habitats.flatten.uniq.sort_by(&:downcase)\n\n end", "def find_hash_tags\n self.scan(/#[\\w-]+/).flatten.uniq\n end", "def get_name_hash_tags\n description.to_s.scan(/#\\w+/).map{|name| name.gsub('#', '') }\n end", "def list_all_received_ingredients\n ingredient_count_hash = {}\n self.owned_ingredients.each do |owned_ingredient|\n ingredient_count_hash[owned_ingredient.ingredient_id] = owned_ingredient.received_count\n end\n ingredient_count_hash\n end", "def passenger_names\n self.rides.map { |ride| ride.passenger }.uniq\n end", "def agentes_serial\n Representante.find(self.agente_ids_serial).map(&:nombre)\n end", "def all_edges\n\t\[email protected]\n\tend", "def get_recipe_names\n users_recipes.map {|ur| ur.recipe.name}\n end", "def find_related\n # Skip any descriptors that are used internally to relate an Identifier to its Identifiable\n @dmp.identifiers.reject { |id| %w[is_identified_by is_funded_by].include?(id.descriptor) }\n end", "def my_backers\n self.pledges.collect do |pledge|\n pledge.user\n end.uniq\n end", "def brands\n beers.collect{ |b| b.brand }\n end", "def edbid\n\t\t\t\t\twhere(:reference_name => \"edb-id\").select('DISTINCT value')\n\t\t\t\tend", "def unique\n self['unique']\n end", "def drivers\n self.rides.map { |ride| ride.driver }.uniq\n end", "def recipe_instances\n recipe_ingredients.map { |ri| ri.recipe }\n end", "def descriminator\n @obj['descriminator']\n end", "def diversity\n color_count.keys\n end", "def test_unique_advertiser_id\n winners = Auctioneer.auction(\n creatives: @creatives,\n number_of_winners: @unique_advertises_count\n )\n\n advertisers = winners.map{ |c| c['advertiser_id'] }\n assert { advertisers.count == advertisers.uniq.count }\n end", "def rating_descriptions\n raters.map { |rater| rater.description }\n end", "def display_superheroes(*heroes)\n \n heroes.flatten.uniq.each do |hero|\n \n #hero.each_pair do |name, value|\n # puts \" --< #{name} = #{value} >--\"\n #end\n #puts \"#{hero.name}\"\n \n puts hero\n \n end\nend", "def passenger_names\n names = rides.collect do |ride|\n ride.passenger.name\n end\n names.uniq\n #we want to\n end", "def bakeries\n self.desserts.select {|dessert| dessert.bakery}\n end", "def chosen\n the_set = []\n self.itemlist.each { |k,v| the_set << self.object(k).chosen }\n the_set\n end", "def allergens\n allergy_for_this_recipe = Allergy.all.select do |allergy|\n ingredients.include?(allergy.ingredient)\n end\n allergy_for_this_recipe.map do |allergy|\n allergy.ingredient\n end.uniq\n end", "def get_animals()\n\n @animals = @raw.raw_animals.keys.uniq.sort_by(&:downcase)\n\n end", "def find_daughters(person)\n find_children(person)\n .map(&:female_child)\n .compact\n .map(&:name)\n end", "def waiters\r\n meals.map do |meal|\r\n meal.waiter \r\n end\r\n end", "def list_all_giveable_ingredients\n ingredient_count_hash = {}\n self.owned_ingredients.each do |owned_ingredient|\n ingredient_count_hash[owned_ingredient.ingredient_id] = owned_ingredient.giveable_count\n end\n ingredient_count_hash\n end", "def lifters\n # binding.pry\n memberships.map { |membership| membership.lifter }.uniq\n end", "def descendant_ids\n descendants.map(&:id)\n end", "def uniq\n return :responses\n end", "def sellers\n line_items.map { |lineitem| lineitem.item.user.id }.uniq\n end", "def get_herb_list\n # Herb http://www.wowdb.com/search.aspx?browse=5.-2\n if @@herbs.length == 0\n herbs = search_list(\"5.-2\")\n herbs.each do |h|\n if not h[:skill].nil? and h[:skill] > 0\n @@herbs[h[:name]] = h[:id]\n end\n end \n end\n return @@herbs\n end", "def digesters\n @digesters\n end", "def descriptors( &block )\n\t\t\tif @log_file && @message_descriptors.empty?\n\t\t\t\tif @descriptor_cache && @descriptor_cache.exist?\n\t\t\t\t\t@message_descriptors = @descriptor_cache.read_descriptors\n\t\t\t\telse\n\t\t\t\t\t@message_descriptors = LogFile::read_descriptors( @log_file, @descriptor_cache, &block )\n\t\t\t\tend\n\n\t\t\t\t@message_descriptors[ FORMAT_MESSAGE.type ] = FORMAT_MESSAGE\n\t\t\tend\n\n\t\t\treturn @message_descriptors\n\t\tend", "def get_number_of_differentiators\n find_elements(DIFFERENTIATORS_TITLES).size\n end", "def avaiable_decks\n Deck.all.map { |d| [d.name, d.id] }\n end", "def beers\n @beers ||= fetch_beers\n end", "def tool_tags\n data.tools.map(&:tags).flatten.uniq\n end", "def tool_tags\n data.tools.map(&:tags).flatten.uniq\n end", "def challenger_tuple(i)\n {:people => i, :algorithm => \"chal#{i}\", :creation_time => Time.now}\n end", "def disponibles\n total = []\n heros.each do |h|\n next unless h.tesoro\n next unless h.tesoro[item + 's']\n h.tesoro[item + 's'].each do |e|\n (total << h.id) if e == id\n end\n end\n total\n end", "def get_all_uuids\n ble_uuids = Hardware.all_ble_uuids.map { |hw| hw.identifier }\n \n render :status => 200, :json => { :uuids => ble_uuids }\n end", "def random\n beer_id = select_random_id\n Beer.find(beer_id)\n end", "def migratoryBirds(ar)\n birds = ar.group_by {|v| v}\n most_repeated_birds = birds.sort_by{|key,value| value.length}\n most_repeated_birds.last.first\nend", "def get_providers\n @weights.map{|k,v|v.keys}.flatten.uniq\n end", "def random_hugs\n huglist_sample = []\n 5.times { huglist_sample.push(Huglist.all.sample[:id]) }\n return huglist_sample.uniq\nend", "def entry_names\n @pairs.keys\n end", "def keys\n lock { @blurbs.keys }\n end" ]
[ "0.5957836", "0.5727464", "0.543534", "0.53549594", "0.52713406", "0.526261", "0.5239569", "0.5232444", "0.5219096", "0.5171344", "0.51576805", "0.51488894", "0.5147665", "0.513588", "0.51348037", "0.51212865", "0.510564", "0.5104553", "0.5081027", "0.50544775", "0.502555", "0.5022852", "0.50193614", "0.50065297", "0.5003735", "0.4993222", "0.49912435", "0.49820468", "0.49706545", "0.495788", "0.49572703", "0.49414104", "0.49313706", "0.49198002", "0.49193025", "0.49120238", "0.49033442", "0.49004674", "0.48887792", "0.4883496", "0.4882817", "0.488189", "0.4876112", "0.48758826", "0.4867249", "0.48590818", "0.48538417", "0.48498854", "0.48465517", "0.48380813", "0.48342022", "0.48291585", "0.48228166", "0.48173797", "0.48165634", "0.48128802", "0.4812273", "0.48113397", "0.48066497", "0.4805843", "0.4803303", "0.48001683", "0.47971332", "0.47911856", "0.47867018", "0.4773079", "0.47720954", "0.4770057", "0.47672632", "0.4765101", "0.47630456", "0.476213", "0.4756527", "0.47512022", "0.4750174", "0.47462147", "0.4741405", "0.47377875", "0.47341856", "0.47289285", "0.47269523", "0.47267374", "0.47233507", "0.47223437", "0.47213548", "0.47190306", "0.47190154", "0.47147453", "0.47087917", "0.47029042", "0.47029042", "0.47020257", "0.47007126", "0.4697732", "0.46958485", "0.46901217", "0.46891364", "0.46864185", "0.46827286", "0.4676728" ]
0.5609657
2
save actual tags without quotes
def descriptor_list_tokens=(tokens) self.descriptor_list = tokens.gsub("'", "") end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def save_tag(tag_vals)\n # strip first line\n # strip last line\n # save to file tag_vals[0]\nend", "def tags_text\n\t\tself.tags.join(', ') #convertir el arreglo en una cadena de texto separado por ,\n\tend", "def after_save\n save_tags\n end", "def tags_raw=(values)\n self.tags = []\n self.tags = values.split(\"\\n\").map(&:strip)\n end", "def tags_raw=(values)\n self.tags = []\n self.tags = values.split(\"\\n\").map { |w| w.strip }\n end", "def tags=(value)\n\t\t#Rails.logger.info(\">>>TAGS===: #{value}\")\n\t\twrite_attribute(:tags, value.split(/\\W+/))\n\tend", "def write_tags(tags)\n\n\t\treturn if tags.empty?\n\n\t\ttags.each do |f|\n \traw(\"<li><a href=\\\"#\\\">\")\n \tf[\"title\"] \n \traw(\"</a><div class=\\\"delcir\\\" onclick=\\\"delTag(this)\\\">x</div></li>\")\n end\n\n\t\t# <% @tags[0].each do |f| %>\n\t\t# <li>\n\t\t# <a href=\"#\"><%= f[\"title\"] %></a>\n\t\t# <div class=\"delcir\" onclick=\"delTag(this)\">x</div>\n\t\t# </li>\n\t\t# <% end %>\n\n\tend", "def tags_raw\n self.tags.join(\"\\n\") unless self.tags.nil?\n end", "def assign_tags\n if self.text\n self.tag_s = self.text.scan(/\\s+\\#\\S+/).join(' ')\n save\n end\n true\n end", "def save_tags\n Tag.transaction do\n taggings.delete_all\n\n scope = nil\n scope = send(self.class.taggable_options[:scope]) if self.class.taggable_options[:scope]\n\n parsed_tags(tagged_with).each do |tag_name|\n tag = Tag.find_or_create_by_name(tag_name)\n self.taggings.create(:tag => tag, :scope => scope)\n end\n end\n end", "def save_tags(delete_old_tags = true)\n #delete all old tags\n if (delete_old_tags)\n PostTag.delete_all(post_id: @post.id)\n end\n #save new tags\n if (params[:tags].length > 0)\n tags = params[:tags].split(',').uniq\n tags.each do |tag_name|\n tag_name = tag_name.downcase.strip\n tag = Tag.find_or_initialize_by(title: tag_name, for: Tag::TYPE_POST)\n if (tag.save)\n #save linked table\n postTag = PostTag.create(post_id: @post.id, tag_id: tag.id)\n postTag.save\n end\n end\n end\n end", "def tags_raw\n tags.join(\"\\n\") unless tags.nil?\n end", "def add_tags_to_verses(document, text)\n html = text.to_str\n html.gsub!(/data-srcid\\s?=\\s?['\"](.*?)['\"]/) do |match|\n tagid = DmKnowledge::Document.tagcontext_from_srcid($1)\n tag_list = document.tag_list_on(tagid)\n unless tag_list.empty?\n \"#{match} data-tags='#{tag_list.to_json}' data-tagid='#{tagid}'\"\n else\n match\n end\n end\n html.html_safe\n end", "def tags\n Array(@options[:tags]).map { |tag| CGI.escape(tag) }\n end", "def tags=(value)\n value = value.split(',') if value.is_a?(String)\n\n write_attribute(:tags, Taggable.sanitize_tag_list(Array(value)))\n end", "def attr_writer_tag(text); end", "def save_tag(sent_tags)\n current_tags = self.tags.pluck(:tag_name) unless self.tags.nil?\n old_tags = current_tags - sent_tags\n new_tags = sent_tags - current_tags\n\n old_tags.each do |old|\n self.tags.delete PostTag.find_by(tag_name: old)\n end\n\n new_tags.each do |new|\n new_tag = Tag.find_or_create_by(tag_name: new)\n self.tags << new_tag\n end\n end", "def tag_attributes_string\n tag_attributes.map{|k, v| \"#{k}=\\\"#{v}\\\"\"}.join(' ')\n end", "def selected_tags=(data)\n self.tags.clear\n data.split('tag').each { |id| self.tags << Tag.find(id) if id.length > 0 }\n end", "def tag_list_tokens=(tokens)\n self.tag_list = tokens.gsub(\"'\", \"\")\n end", "def sanitized_allowed_tags=(tags); end", "def sanitized_allowed_tags=(tags); end", "def smart_quote_entity(el); end", "def save_new_tag_to_tag_table(tag_attributes)\n\n tag_attributes.split(\",\").each do |value|\n value=value.strip\n available_tag = Tag.where('tagname = ?', value).first #checking if added tag is available in the list/not.\n new_tag = Tag.create(:tagname => value) if available_tag.blank? #If it's a new tag then create and Add it to Tag list.\n available_tag.blank? ? self.insert_ids_to_post_tags(new_tag.id) : self.insert_ids_to_post_tags(available_tag.id) #Depending on tag available or it's a new tag, updating post_tags tag.\n end\n\n end", "def tag_text=(value)\n self.tag=(value)\n end", "def tagstring\n\tself.taglist.join ', '\n end", "def tags\n\t\tt = read_attribute(:tags)\n\t\tt.nil? ? \"\" : t.join(', ')\n\tend", "def tagpane=(str)\n ou = Nokogiri::HTML str\n newtags = []\n oldtags = self.tag_ids\n ou.css(\".name\").each { |child|\n str = child.content.to_s\n # Look up the tag and/or create it\n tag = Tag.strmatch(str, self.current_user || User.guest_id, :Food, true)\n newtags << tag.id unless oldtags.include? tag.id\n x=2\n }\n if newtags.length\n self.tag_ids= oldtags + newtags\n self.save\n end\n super\n end", "def raw_tags_plist=(value)\n obj = value.to_s.from_plist\n self.raw_tags = obj\n end", "def tags=(tag_string)\n # tag_array = tag_string.split(/,\\s*/)\n # story.add_tags(tag_array)\n story.set_tag_string(tag_string)\n end", "def save_tags\n tagging_contexts.each do |context|\n tag_list = tag_list_on(context)\n\n ActsAsTaggableSimple::Tag.find_or_create_all_tags(tag_list)\n\n existing_tags = taggings_on(context).collect do |tagging|\n tagging.tag.name\n end\n new_tags = tag_list - existing_tags\n old_tags = existing_tags - tag_list\n\n destroyed_taggings = []\n taggings_on(context).each do |tagging|\n if old_tags.include? tagging.tag.name\n tagging.destroy\n destroyed_taggings << tagging\n end\n end\n\n self.taggings -= destroyed_taggings\n\n new_tags = ActsAsTaggableSimple::Tag.find_by_names(new_tags)\n new_tags.each do |tag|\n taggings.create! tag: tag, context: context\n end\n end\n end", "def tags=(tags)\n @tags = \n case tags\n when String\n tags\n when Array\n tags.map(&:to_s).join(',')\n end\n @tags\n end", "def tags_string\n tags.map(&:name).join(\" \")\n end", "def handle_tag_as_text\n self[:is_tag] = false\n self[:closing_tag] = false\n self[:text] = self[:complete_match]\n end", "def tag_list\n tags.map { |tag| tag.name.include?(\" \") ? '\"' +\"#{tag.name}\" + '\"' : tag.name }.join(\" \")\n end", "def save\n response = Intercom.post(\"/v1/tags\", to_wire)\n self.from_hash(response)\n displayable_self\n end", "def tags_string=(titles)\n self.tags = titles.split(',').map do |title|\n Tag.find_or_create_by(title: title, user: user)\n end\n end", "def complete_tags\n\n end", "def cleanup_image_tags\n self.tags = self.tags.strip\n unless self.tags.empty?\n tags = self.tags.split(\",\")\n tags_new = []\n tags.each do |item|\n tags_new.push(item.strip)\n end\n self.tags = tags_new.join(\",\")\n end\n end", "def convert_tags(text)\n tags = ['path', 'include', 'stylesheet', 'javascript',\n 'todo', 'placeholder', 'react_component']\n regexp = /^(\\s*)=\\s*(#{tags.join('|')})\\s+([^\\n]+)/\n text.gsub(regexp) do\n space = Regexp.last_match[1]\n tag = Regexp.last_match[2]\n argument = Regexp.last_match[3].gsub(/[\\'\\\"]/, '').strip\n \"#{space}<!-- @#{tag} #{argument} -->\"\n end\n end", "def auto_create_tag\n\t\n\tget_tags.each do |tag|\n\t\t@items << Nanoc3::Item.new(\n\t\t\"<%= render 'tag', :tag => '#{tag}' %>\",\n\t { :title => \"Category: #{tag}\", :is_hidden => true, :tag => \"#{tag}\"}, # do not include in sitemap.xml\n\t \"/tags/#{tag}/\", # identifier\n\t :binary => false\n\t)\n\n\tend\n\tnil\nend", "def tag_list_fixed\n\t\ttag_list.to_s\n\tend", "def spaced_tags=(value)\n self.tag_list = value.to_s.split(' ')\n end", "def to_s\n \"<#{tag_name}>#{content}</#{tag_name}>\"\n end", "def tag_list= value\n self.tags = value.split(',').map(&:strip)\n end", "def tag_list= value\n self.tags = value.split(',').map(&:strip)\n end", "def cache_tag_list\n set_cached_tag_list\n save\n end", "def save\n ConsoleGlitter.escape(\"s\")\n end", "def save\n puts \"Rewriting ogg tags of #{File.basename(@file)}\"\n \n options = [\n '-w',\n \"-t artist=#{@data['artist'].shellescape}\",\n \"-t year=#{@data['year'].shellescape}\",\n \"-t album=#{@data['album'].shellescape}\",\n \"-t tracknumber=#{@data['index'].shellescape}\",\n \"-t title=#{@data['title'].shellescape}\",\n ]\n options << \"-t discnumber=#{@data['cd']}\" if @data['cd'] != ''\n # Adding genre if predefined one\n options << \"-t genre=Podcast\" if @data['type'] == \"podcasts\"\n options << \"-t genre=Soundtrack\" if @data['type'] == \"soundtracks\"\n\n %x[vorbiscomment #{options.join(' ')} #{@file.shellescape}]\n\n end", "def tags\n normal[:tags] = Array(normal[:tags])\n normal[:tags]\n end", "def tag_text()\n return self.tag(true)\n end", "def write_tags\n open 'TAGS', 'w' do |io|\n io.write <<-INFO\n!_TAG_FILE_FORMAT\\t2\\t/extended format/\n!_TAG_FILE_SORTED\\t1\\t/sorted/\n!_TAG_PROGRAM_AUTHOR\\tEric Hodel\\t/[email protected]/\n!_TAG_PROGRAM_NAME\\trdoc-tags\\t//\n!_TAG_PROGRAM_URL\\thttps://github.com/rdoc/rdoc-tags\\t//\n!_TAG_PROGRAM_VERSION\\t#{VERSION}\\t//\n INFO\n\n @tags.sort.each do |name, definitions|\n definitions.uniq.each do |(file, address, *field)|\n io.write \"#{name}\\t#{file}\\t#{address};\\\"\\t#{field.join \"\\t\"}\\n\"\n end\n end\n end\n end", "def relation_save_hash_tags(text)\n return if !text || text == nil || text.length = 0\n text.scan(/#[a-zA-Z]+/i).each do |tag|\n relation_add(Note::RELATION_TAG,tag[1..-1])\n end\n end", "def strip_tags\n %w(name description allowed_values).each do |a|\n next if send(a).blank?\n self.send \"#{a}=\", send(a).gsub(/\\<.*?\\>/, '')\n end\n true\n end", "def strip_tags\n %w(name description allowed_values).each do |a|\n next if send(a).blank?\n self.send \"#{a}=\", send(a).gsub(/\\<.*?\\>/, '')\n end\n true\n end", "def strip_tags\n %w(name description allowed_values).each do |a|\n next if send(a).blank?\n self.send \"#{a}=\", send(a).gsub(/\\<.*?\\>/, '')\n end\n true\n end", "def tagging_raw_handle\n name\n end", "def tagging_raw_handle\n name\n end", "def convert_ref_tags; end", "def all_tags=(names)\n self.tags = names.split(\",\").map do |name|\n name.gsub!(/[!@%&\"']/,'')\n name.downcase!\n Tag.where(name: name.strip).first_or_create!\n end\n end", "def tag(tags)\n tags.each do |key, value|\n @tags[key.to_s] = value\n end\n end", "def add_tags chars\n # TODO: write your code here\nend", "def tag_article article\n tags = article.gsub(/'/,'').split(/\\W+/).join(', ')\n tags\n end", "def tag_article article\n tags = article.gsub(/'/,'').split(/\\W+/).join(', ')\n tags\n end", "def tokenize\n super.merge(:tags => tags.taggify(\" \", \" \"))\n end", "def tag_content\n return @tag_content\n end", "def write_tag(tag,value)\n @io << \"<value><#{tag}>#{text(value)}</#{tag}></value>\"\n end", "def cleaned_tags\n @product.tags.split(',').reject{ |c| c.empty? or c == \" \" }.uniq.join(',')\n end", "def tag(new_tag); end", "def escaped_output_tags open, close\n @map[:escaped_output_open][:orig] = open\n @map[:escaped_output_close][:orig] = close\n end", "def tags=(list)\n tags.clear\n for id in list\n tags << Tag.find(id) if !id.empty?\n end\n end", "def test_that_sanitize_does_not_mangle_ref_tags_and_such\n text = \"Hi <ref id=\\\"\\\">2007</ref> ho <ref id=\\\"12345\\\">Bar 2006</ref> fum<ref id=\\\"\\\"> Foo</ref>.\"\n content = contents(:cons1)\n otu = Otu.new(:name => 'foo')\n ct = ContentType.new(:name => 'bar')\n content.update_attributes!(:text => text, :otu => otu, :content_type => ct)\n content.reload\n assert_equal(text, content.text)\n end", "def linked_tags_with_commas(tags)\r\n tags.dup.map { |tag|\r\n tag_link(tag.name)\r\n }.join(', ')\r\n end", "def tags_string=(commastring)\n self.tags.clear\n \n if (commastring.length > 0)\n tagsArr = commastring.split(',');\n tagsArr.each do |tagname|\n # remove white space\n tagname = tagname.strip\n \n if (Tag.find_by_name(tagname))\n aTag = Tag.find_by_name(tagname)\n else\n aTag = Tag.new(:name => tagname)\n aTag.save\n end\n \n self.tags << aTag\n end\n end\n \n Tag.clear_unused\n end", "def sanitize_tags(tags)\n Array(tags).flatten.map(&:to_s)\n end", "def append_tags\n self.text += (\" \"+self.tag_string) if !self.tag_string.blank?\n true\n end", "def append_tags\n self.text += (\" \"+self.tag_string) if !self.tag_string.blank?\n true\n end", "def tag_list\n #tags sie bierze z asocjacji\n tags.map { |t| t.name }.join(\",\")\n end", "def assign_tags\n if self.text\n self.tag_s = self.text.scan(/\\s+\\#\\S+/).join(' ')\n end\n true\n end", "def tags\n article_tags = data.tags || data.tag\n \n if article_tags.is_a? String\n article_tags.split(',').map(&:strip)\n else\n Array(article_tags).map(&:to_s)\n end \n end", "def encode_by(tag, string)\n Tags[tag][0][1] = string\n end", "def reverse_html_tags\n self.gsub('&lt;', \"<\").gsub('&gt;', \">\")\n end", "def set_tags(tags = Array.new)\n\n if tags.is_a?(String) and tags.downcase == 'all'\n @@default_tags.each do |value|\n @@edit_tags[value] = ''\n end\n elsif tags.is_a?(Array)\n tags.each do |value|\n @@edit_tags[value] = ''\n end\n elsif tags.is_a?(Hash)\n # NOTE: might need some adjustment here\n # Not sure this is used at all\n @@edit_tags = tags\n else\n\n\n # Try to match tags\n if tags.is_a?(String)\n\n @@edit_tags = {}\n tagsForEditing = tags.split(',')\n tagsForEditing.each do |value|\n\n # Matchin for seperator\n separator = @@edit_separator\n if value.match(/#{separator}/)\n\n self.log('debug', 'Found tag value assignment.')\n tagmatching = value.split(separator)\n\n # Check date for validity\n if tagmatching[0] == 'createdate'\n validatedDate = validateDate(tagmatching[1])\n if !validatedDate\n self.log('error',\"Date not recognized: '#{tagmatching[1]}'.\")\n abort 'Date format not recognized. Abort.'\n else\n self.log('debug',\"Identified date: #{validatedDate} \")\n @@edit_tags[tagmatching[0]] = validatedDate\n end\n else\n self.log('debug', \"Identified key #{tagmatching[0]} with value '#{tagmatching[1]}'.\")\n @@edit_tags[tagmatching[0]] = tagmatching[1]\n end\n else\n @@edit_tags[value] = ''\n end\n\n end\n\n end\n\n end\n\n\n end", "def tag(string); end", "def set_tag(key, value)\n sanitized_value = valid_tag_value?(value) ? value : value.to_s\n @tags = @tags.merge(key.to_s => sanitized_value)\n end", "def convert_img_tags!(log)\n log[:files_open] += 1\n file_marked = false\n @doc.xpath(\"//img\").each do |img|\n file_marked = true\n log[:tags] += 1\n\n original = img.to_html.gsub(\"\\\">\", \"\\\" />\").gsub(\"\\\" >\", \"\\\" />\").delete(\"\\\\\")\n original2 = img.to_html.gsub(\"\\\">\", \"\\\"/>\").gsub(\"\\\" >\", \"\\\" />\").delete(\"\\\\\")\n original3 = img.to_html.gsub(\"\\\">\", \"\\\">\").gsub(\"\\\" >\", \"\\\" />\").delete(\"\\\\\")\n image_tag = RailsImageTag.new(img).to_erb\n\n @content.gsub!(original, image_tag)\n @content.gsub!(original2, image_tag)\n @content.gsub!(original3, image_tag)\n puts image_tag\n end\n\n write_file(log) if file_marked\n end", "def type_of_tag=(new_type_of_tag)\n super new_type_of_tag.to_s\n end", "def type_of_tag=(new_type_of_tag)\n super new_type_of_tag.to_s\n end", "def text\n text = @tag_data[:text]\n # convert_newlines_to_br\n text.gsub!(\"\\r\\n\", \"\\n\")\n text.gsub!(\"\\n\", \"\\n\")\n text\n end", "def test_values_with_apostrophes\n doc = Document.new(%q#<tag h1=\"1'2'\" h2='1\"2'/>#)\n s = doc.to_s\n assert(s =~ /h1='1&apos;2&apos;'/)\n assert(s =~ /h2='1\"2'/)\n end", "def tags=(list)\n tag(self.class.name)\n tag(*list)\n end", "def crearStringTag\n\t\ti = 0 #contador\n\t\tlistaTag=getTag\n\t\tstringTag = \"\" #Se almacena la cadena de texto\n\t\twhile listaTag.length != i\n\t\t\tstringTag += listaTag[i]\n\t\t\ti +=1\n\t\tend\n\t\treturn stringTag\n\tend", "def html_safe_value\n sanitize(@values.join(' '), tags: %w[sub sup i em])\n end", "def tag_list(obj)\n str = \"\"\n\n obj.tag_list.each do |tag|\n str += \"<span class='label label-info'>#{tag}</span> &nbsp;\"\n end\n\n str.html_safe\n end", "def write_tag\n file.seek(tag_start, IO::SEEK_SET)\n file.write(raw)\n file.truncate(file.pos)\n @has_tag = true\n end", "def snippet_tagged\n tags = {\"testing\" => true, \"yayness\" => false,\n \"both\" => false, \"bothtrue\" => true, \"define\" => true}\n\n tags.each do |tag, retval|\n assert_file(\"/tmp/tagged#{tag}#{retval.to_s}\")\n end\n end", "def page_tags(objectTags, allTagsUrl, locale = 'en')\r\n %{\r\n <div id=\"tags\"></div>\r\n <script type=\"text/javascript\">\r\n $(document).ready(function(){\r\n $(\"#tags\").tagit({\r\n objectTags: #{objectTags.to_json},\r\n allTags : \"#{allTagsUrl}\",\r\n locale : \"#{locale}\"\r\n });\r\n });\r\n </script>\r\n }.html_safe\r\n end", "def formated_tagline_for(game)\n return \"\" if game.nil? || game.tagline.nil?\n return \"\\\"#{game.tagline}\\\"\"\n end", "def write_tag(name, file)\n if $tags.nil?\n $tags = File.new(\"#{$datadir}/commitinfo-tags\", File::WRONLY|File::CREAT|File::APPEND);\n return if $tags.nil?\n end\n $tags.puts(\"#{name}\\t#{file}\")\nend", "def tags\n self.new_record? ? '' : Tag.get_friendly_tags(self)\n end", "def permitted_html_tags=(_arg0); end" ]
[ "0.72315115", "0.64633924", "0.64312917", "0.6400584", "0.6329529", "0.6313223", "0.6284215", "0.62534887", "0.6241067", "0.6107823", "0.6064638", "0.59806883", "0.59617513", "0.591178", "0.5908289", "0.5862886", "0.5861477", "0.584789", "0.5844181", "0.5834414", "0.5821497", "0.5821497", "0.58012563", "0.5796987", "0.57588327", "0.57574457", "0.574348", "0.57343864", "0.5729708", "0.5702601", "0.5698556", "0.56971157", "0.56970114", "0.5695427", "0.5678688", "0.5665621", "0.56504184", "0.5645089", "0.5628937", "0.5625492", "0.560456", "0.55826855", "0.5581056", "0.5564877", "0.55344737", "0.55344737", "0.55046254", "0.5489962", "0.5488539", "0.54850185", "0.5480403", "0.5478348", "0.54776275", "0.5477351", "0.5477351", "0.5477351", "0.54735106", "0.54735106", "0.5472388", "0.5467434", "0.54657555", "0.5453212", "0.54250175", "0.54250175", "0.5412085", "0.5406954", "0.5399701", "0.53960586", "0.5390113", "0.5389347", "0.5389043", "0.53817946", "0.53795606", "0.53787357", "0.5377332", "0.5375104", "0.5375104", "0.5373408", "0.5370331", "0.5367198", "0.5366334", "0.5365486", "0.53646344", "0.53533435", "0.53486794", "0.5345749", "0.53441143", "0.53441143", "0.5342909", "0.5338219", "0.53322613", "0.5331263", "0.53302747", "0.532541", "0.53243715", "0.5318636", "0.5311614", "0.5311367", "0.5310825", "0.53014386", "0.53001595" ]
0.0
-1
aggregate total number of beer ratings
def number_ratings if number_ratings_one.nil? && number_ratings_two.nil? && number_ratings_three.nil? 0 # else, combine the public ratings according to algorithm below else if number_ratings_one && number_ratings_two && number_ratings_three (number_ratings_one + number_ratings_two + number_ratings_three) elsif number_ratings_one && number_ratings_two (number_ratings_one + number_ratings_two) elsif number_ratings_one && number_ratings_three (number_ratings_one + number_ratings_three) elsif number_ratings_two && number_ratings_three (number_ratings_two + number_ratings_three) elsif number_ratings_one number_ratings_one elsif number_ratings_two number_ratings_two else number_ratings_three end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ratings_count\n ratings.count\n end", "def num_ratings\n ratings.count\nend", "def ratings\n if self.reviews.any?\n avg_rating = 0\n self.reviews.each do |review|\n avg_rating += review.rating\n end\n avg_rating = (avg_rating/self.reviews.length).ceil\n return avg_rating\n end\n end", "def count_ratings\n\t\tself.ratings.all.count\n\tend", "def rate\n votes = answers.inject(0) do |sum, a| \n sum + a.votes.count \n end\n \n # Return a count of votes and answers\n answers.count + votes\n end", "def rating\n reviews.any? ? reviews.sum(&:rating) / reviews.count : 0\n end", "def calculate(ratings)\n histogram_data = ratings.group(:int_value).count\n 5.times { |i| histogram_data[i+1] = 0 if !histogram_data[i+1] }\n histogram_data.to_a.sort.to_s\n end", "def num_ratings \n 5\n end", "def rating_count\n search_by_itemprop('ratingCount').to_i\n end", "def avg_rating\n movie_recs = self.given_movie_recommendations\n book_recs = self.given_book_recommendations\n ratings = (movie_recs + book_recs).map(&:recommendee_rating).compact\n return 0 if ratings.empty?\n (ratings.sum.to_f / ratings.size.to_f).round(1)\n end", "def average_ratings\n movies.reduce(0) do |sum, movie|\n sum + movie.rating\n end / movies.length\n end", "def baserunning_total\n self.rating_15 + \n self.rating_16 +\n self.rating_17 +\n self.rating_18\n end", "def rating_sum(wastes)\n wastes.inject(0) { |sum, v| sum + v.rating }\n end", "def rating\n average = 0.0\n ratings.each { |r|\n average = average + r.rating\n }\n if ratings.size != 0\n average = average / ratings.size\n end\n average\n end", "def ratings_count\n rating && rating.ratings_count || 0\n end", "def average_rating\n ratings.inject(0.0) {|sum, num| sum +=num} / ratings.length\n end", "def average_rating\n self.ratings.reduce(0.0) { |sum, score| sum += score } / self.ratings.length\n end", "def each_review_rating\n keys = []\n values = []\n @item.reviews.each do |review|\n review.properties.each do |k,v|\n keys << k\n values << v.to_i\n end\n return (values.sum.to_f / keys.uniq.size).round(1)\n end\n end", "def count_ratings\n self.reviews.all.count\n end", "def average_rating\n sum = 0\n self.ratings.each do |rating|\n sum += rating.score\n end\n avg = sum/self.ratings.length\n avg.to_f\n end", "def sum_ratings\n @sum_ratings ||= @user_ratings.map(&:rating).inject(&:+).to_f\n end", "def average_rating\n average = 0\n count = 0 \n self.trips.each do |trip|\n average += trip.rating.to_i\n count += 1\n end\n return average / count\n end", "def average_rating\n \ttotal_score = 0\n \tnum_of_ratings = self.ratings.count\n \tself.ratings.each do |rating|\n \t\ttotal_score += rating.overall_rating\n \tend\n \tif num_of_ratings > 0\n \t\treturn total_score / num_of_ratings\n \telse\n \t\treturn 0\n \tend\n end", "def calculate_average_rating\n weighted_drinks_ratings.sum.to_f / weighted_drinks_ratings.count\n end", "def average_ratings\n ratings = 0\n self.ratings.each {|r| ratings += r.score}\n avg = votes == 0 ? 0 : ratings.to_f/votes.to_f\n \"%.1f\" % avg\n end", "def average_ratings\n ratings = 0\n self.ratings.each {|r| ratings += r.score}\n avg = votes == 0 ? 0 : ratings.to_f/votes.to_f\n \"%.1f\" % avg\n end", "def hitting_total\n self.rating_19 +\n self.rating_20 +\n self.rating_21 +\n self.rating_22 +\n self.rating_23 +\n self.rating_24 +\n self.rating_25 +\n self.rating_26 +\n self.rating_27\n end", "def rating\n if self.rating_sum > 0 && self.rating_count > 0\n (self.rating_sum / self.rating_count).round(2)\n end\n end", "def average_rating\n\n all_ratings = self.reviews.to_a.map do |review|\n review.rating\n end\n\n return 0 unless all_ratings.length > 0\n\n all_ratings.sum / all_ratings.length\n end", "def get_review_ratings\n ratings = {\n prof: 0,\n enjoy: 0,\n difficulty: 0,\n recommend: 0\n }\n\n @reviews.each do |r|\n ratings[:prof] += r.professor_rating\n ratings[:enjoy] += r.enjoyability\n ratings[:difficulty] += r.difficulty\n ratings[:recommend] += r.recommend\n end\n\n ratings[:overall] = (ratings[:prof] + ratings[:enjoy] + ratings[:recommend]) / 3\n\n num_reviews = @reviews.length\n\n ratings.each_with_object({}) { |(k, v), h|\n h[k] = (v / num_reviews).round(2)\n }\n end", "def rating\n return nil if ratings.empty?\n ratings.reduce(&:+) / ratings.length.to_f\n end", "def throwing_total\n self.rating_1 +\n self.rating_2 +\n self.rating_3 +\n self.rating_4 +\n self.rating_5\n end", "def getAvgUserNumberRating(u)\n @count = 0\n @allR = getUserReviews(u)\n @allR.each do |r|\n @count += r.rating\n end\n return (@allR.count == 0) ? \"None\" : @count/@allR.count \n end", "def average_rating\n return 0 if self.ratings.empty?\n (self.ratings.inject(0){|total, rating| total += rating.score }.to_f / self.ratings.size )\n end", "def average_rating\n total = 0\n self.reviews.each do |review|\n total += review.rating\n end\n average = total.to_f / self.reviews.count\n end", "def avg_rating\n stars_array = []\n ratings.each do |rating|\n stars_array << rating.stars\n end\n return stars_array.inject{ |sum, el| sum + el }.to_f / stars_array.size\n end", "def average_rating\n if ratings != []\n ratings.sum(:stars) / ratings.size\n else\n 0\n end\n end", "def total_num_team_reviews\n team_review_counts.inject(:+)\n end", "def average_rating\n (ratings.sum(:rating).to_f / num_ratings).round(1)\nend", "def rating\n\t\tif review.any?\n\t\t\trating = review.map {|review| review.rating}\n\t\t\ttotal = rating.reduce(0) {|total, rating| total += rating}\n\t\t\ttotal = review.reduce(0) {|total, review| total += review.rating}\n\n\t\t#return nil if reviews.empty?\n\t\tend\n\t\t#(reviews.map(&:rating).reduce(&:+).to_f / reviews.length).round(2)\n\t\t#llama a un array de metodo raiting de todos los review; (reduce el array a uno) \n\tend", "def all_ratings_calculated_ratio\n\t\tif number_of_ratings > 0\n\t\t\tratio = mean_calculated_ratio\n\t\telse\n\t\t\tratio = chapter.mean_calculated_ratio\n\t\tend\n\t\treturn ratio\n\tend", "def average_rating\n rating_sum = 0\n if @trips.length > 0\n @trips.each.map do |trip|\n rating_sum += trip.rating\n end\n total_rating = (rating_sum.to_f / trips.length.to_f)\n total_rating = total_rating.to_f\n puts total_rating\n return total_rating\n elsif @trips == []\n return 0\n end \n end", "def average_ratings\n ratings.average(:int_value)\n end", "def count_getted_like\n user = User.find_by id: self.id\n reviews = user.reviews\n total = 0\n reviews.each do |review|\n total += review.count_like\n end\n return total\n end", "def ratings\n\t\tself.reviews.map{|review| review.rating}\n\tend", "def average_out(ratings)\n ratings.sum(&:score).to_f / ratings.count\n end", "def overall_rating\n\t\ttotal_score = 0\n\t\ttotal_score += self.setting \n\t\ttotal_score += self.hotness\n\t\ttotal_score += self.originality\n\t\ttotal_score += self.style\n\t\ttotal_score += self.attitude\n\t\treturn total_score / 5\n\tend", "def rating\n rating_calculator.rate(raters)\n end", "def average_rating\n return 'n/a' if reviews.empty?\n #return 0 if reviews.empty?\n (reviews.pluck(:rating).sum / reviews.count.to_f).round(2)\n end", "def average_rating(driver)\n sum = 0.0\n \n driver.each do |find_rating|\n driver_rating = find_rating[:rating]\n sum += driver_rating\n end\n\n average = sum / driver.length\n\n return average\nend", "def ratings_sum\nend", "def rating_calculation\n ratings_collection = Rating.where(user_id: self.id)\n average = -1\n if !ratings_collection.empty?\n sum = 0\n ratings_collection.each do |r|\n sum += r.rating\n end\n average = (sum.to_f / ratings_collection.count).round\n end\n average\n end", "def rating\n return 0 if total_votes == 0\n (100 * self.yeses) / total_votes\n end", "def rating\n if reviews.size ==0\n return nil\n end\n rating=0\n reviews.each do |review|\n rating+=review.rating\n end\n return (rating*1.0/reviews.size).round(2)\n end", "def average(ratings)\n ratings.inject(0.0) { |sum, el| sum + el.to_f } / ratings.size\n end", "def average_rating(book_id)\n all_ratings = Rating.where(\"book_id = ?\",book_id)\n count = 0\n total = 0\n all_ratings.each do |rating|\n count += 1\n total += rating.stars;\n end\n if count == 0\n return 0\n end\n total/count\n end", "def average_rating\n sum = self.queue_items.map {|item| item.rating}.reduce(:+)\n length = self.queue_items.length\n sum / length\n end", "def average_rating\n\t\t\t\t\treturn 0 if rates.empty?\n\t\t\t\t\t( rates.inject(0){|total, rate| total += rate.score }.to_f / rates.size )\n\t\t\t\tend", "def imdb_rating_count\n doc.search('div.block_2 div:eq(2)').text.gsub(/.*\\(/, '').gsub(/[ ()]/, '').to_i\n end", "def average_rating\n self.reviews.sum(:score) / reviews.size\n rescue ZeroDivisionError\n 0\n end", "def rating\n reviews.average(:rating)\n end", "def get_ratings\n return @trips.inject(0) do |sum, trip|\n trip.is_in_progress? ? sum + 0 : sum + trip.rating\n end\n end", "def total_review_character_count\n review_character_counts.inject(:+)\n end", "def average_rating\n guest_reviews.count == 0 ? 0 : guest_reviews.average(:star).round(2).to_i\n end", "def avg\n array = []\n# this DO-loop will put all the star ratings into an array\n @reviews.each do |count|\n array.push(count.star.to_i)\n end\n# this line will calculate the actual average of all the star ratings\n outavg = array.inject(0.0) { |sum, el| sum + el } / array.size\n end", "def rating\n (get_upvotes.size + 2)/(get_downvotes.size + 2)\n end", "def getAvgRating(e)\n @count = 0\n @rs = Event.find_by(id: e).reviews\n if @rs.count == 0\n return \"None\"\n else\n @rs.each do |r|\n @count += r.rating\n end\n return @count/@rs.count\n end\n end", "def review_points\n self.reviews.map { |review| review.vote_count }.inject(:+)\n end", "def total_birds\n birds.count\n end", "def average_rating\n if reviews.count > 0\n ratings = reviews.map { |review| review.rating }\n sum = ratings.reduce(:+)\n if sum > 0\n average = sum / ratings.count\n average.round(1)\n else\n return 0\n end\n else\n return 0\n end\n end", "def total_votes\n votes.sum(:weight)\n end", "def average_rating\n if ratings.where(\"score > 0\").size != 0\n\t\tratings.where(\"score > 0\").sum(:score) / ratings.where(\"score > 0\").size\n\telse\n\t\t0\n\tend\n end", "def rating\n average_rating = (trips.collect {|trip| trip.rating.to_f}.sum)/trips.length\n ## Code below functions the same as the code in line 28\n ## Was unsure which design was preferred, so left both in\n # total_rating = 0.0\n # trips.each do |trip|\n # total_rating += trip.rating\n # end\n # average_rating = total_rating/trips.length\n return average_rating.round(1)\n end", "def likes_count\n Recommendable.config.ratable_classes.inject(0) do |sum, klass|\n sum + liked_count_for(klass)\n end\n end", "def average_rating()\n total_ratings = 0\n total_trips = 0\n average_rating = 0\n #self.trips = Trip.where(driver_id:self.id)\n self.trips.each do |trip|\n # if trip cost is not nil, the trip is complete\n if trip.cost != nil \n total_ratings += trip.rating\n total_trips += 1\n end\n end\n if total_trips > 0 \n average_rating = total_ratings.to_f / total_trips\n end\n return average_rating\n end", "def average_rating(&block)\n total = 0\n countable_ratings = block ? ratings.select(&block) : ratings\n countable_ratings.each do |rating|\n total += rating.rating\n end\n average_rating = countable_ratings.empty? ? 0 : (0.0 + total) / countable_ratings.size\n # only 1 decimal.\n [(0.0 + (average_rating * 10).round) / 10, countable_ratings.size]\n end", "def overall_weighted_rating\n @ratings.group_by(&:evaluation_criteria_id).sum do |criteria_group|\n criteria = EvaluationCriteriaRepository.new.find(criteria_group[0])\n calc = Calculator.new(ratings_for(criteria_group), criteria)\n calc.weighted_avg_all_users\n end\n end", "def calculate_average_ratings\n total_reviews = self.reviews.count\n\n quality_total = 0\n study_total = 0\n laptop_total = 0\n hipster_total = 0\n\n self.reviews.each { |review| quality_total += review.qualityRating }\n self.reviews.each { |review| study_total += review.studyRating }\n self.reviews.each { |review| laptop_total += review.laptopRating }\n self.reviews.each { |review| hipster_total += review.hipsterRating }\n\n if total_reviews > 0\n self.average_hipster = hipster_total / total_reviews\n self.average_study = study_total / total_reviews\n self.average_laptop = laptop_total / total_reviews\n self.average_quality = quality_total / total_reviews\n self.overall_average = (average_hipster + average_study + average_laptop + average_quality)/4\n end\n self.save\n end", "def rating\n 0\n end", "def user_reputation\n tally = []\n answers.each do |answer|\n tally.push(answer.answer_votes_total)\n end\n questions.each do |question|\n tally.push(question.question_votes_total)\n end\n tally = tally.inject(:+)\n return tally\n end", "def average_rating\n ratings = book_reviews.pluck(:rating)\n ratings.size.zero? ? nil : (ratings.sum / ratings.size.to_f).round(1)\n end", "def fielding_total\n self.rating_6 +\n self.rating_7 +\n self.rating_8 +\n self.rating_9 +\n self.rating_10 +\n self.rating_11 +\n self.rating_12 +\n self.rating_13 +\n self.rating_14\n end", "def get_avg_rating(rides)\n total_rating = 0\n rides.each do |ride|\n total_rating += ride[:rating]\n end\n return total_rating.to_f / get_num_rides(rides)\nend", "def votes\n self.ratings.length\n end", "def votes\n self.ratings.length\n end", "def rating_of(category, item)\n ratings_of = ratings.select{ |r| r.beer.send(category) == item }\n ratings_of.map(&:score).inject(&:+) / ratings_of.count.to_f\n end", "def number_of_calories\n self.ingredients.sum(\"calories\")\n end", "def average_rating\n # check if there is any review (.size is used to effectively count elements - do not use .length in this example)\n if self.reviews.size > 0\n # counting average from rating column\n self.reviews.average(:rating)\n else\n 'this product does not have any rating yet'\n end\n end", "def average_rating\n reviews.average(:rating)\n end", "def average_rating(rideshare)\n # set variables for total rating and total sum\n total_rating = {}\n sum = 0\n # loop through\n rideshare.each do |driver, trips|\n trips.each do |trip|\n # calculate total rating \n sum += trip[:rating]\n avg_rating = sum / trips.length.to_f\n total_rating[driver] = avg_rating\n end \n sum = 0\n end\n return total_rating\nend", "def rate(rating)\n @nb_ratings += 1\n @sum_ratings += rating\n @average_rating = @sum_ratings / @nb_ratings\n end", "def not_answered_ratings\n self.ratings.not_answered.count\n end", "def average_rating\n driver_id = id\n trips_array = RideShare::Trip.find_by_driver(driver_id)\n trips_array.collect! { |trip| trip.rating.to_f }\n trips_array.reject! { |trip| trip < 1 }\n total = trips_array.reduce(:+)/trips_array.length\n total.round(2)\n end", "def get_avg_rating(movie_ratings)\n sum = 0\n movie_ratings.each { |b| sum += b }\n @average_movie_rating = (sum.to_f / @movie_ratings.count.to_f).round(1)\n end", "def average_rating\n ratings.present? ? (ratings.map(&:score).sum.to_f) / ratings.count : nil\n end", "def calculate_average_rating\n self.average_rating = ((self.content_rating.to_f + self.recommend_rating.to_f) / 2).round(1)\n end", "def average_reviews\n numerator = 0\n denominator = 0\n total = 0\n n = 0\n self.trainings.each do |training|\n unless training.average_reviews.nil?\n n += training.average_reviews[:number]\n numerator += training.average_reviews[:average_score] * training.average_reviews[:number]\n denominator += training.average_reviews[:number]\n end\n end\n if denominator != 0\n (total = numerator / denominator)\n total\n else\n \"No reviews\"\n end\n end", "def avg_rating\n\t\tcount = reviews.count\n\t\tcount > 0 ? '%.2f' % (reviews.reduce(0) {|sum,x| sum + x.rating }.to_f / count) : '0.00'\n\tend", "def item_average_rating\n item_rating / count_properties_names rescue 0\n end", "def average_rating\n\t\tall_ratings = self.reviews.map{|review| review.rating}\n\t\taverage_rating = all_ratings.reduce(0){|sum, rating| sum + rating} / all_ratings.count.to_f\n\t\t'%.1f' % average_rating \n\tend", "def average_rating\n ratings.average(:value).to_f\n end" ]
[ "0.7571546", "0.7411842", "0.7285324", "0.7215017", "0.7129826", "0.7057436", "0.704326", "0.7041887", "0.70111257", "0.6943283", "0.6941667", "0.69359475", "0.6933854", "0.6933302", "0.6933089", "0.6908444", "0.689924", "0.6891107", "0.688944", "0.6888895", "0.6866801", "0.68427175", "0.68241054", "0.6808472", "0.6808052", "0.6808052", "0.68024814", "0.6773634", "0.67729205", "0.6768252", "0.6760906", "0.6750192", "0.6738636", "0.6725901", "0.67139167", "0.67076457", "0.6681376", "0.66730773", "0.6672478", "0.664982", "0.6637688", "0.6630113", "0.6624269", "0.66173315", "0.6615864", "0.6609901", "0.66095304", "0.6605584", "0.6601004", "0.6578272", "0.6566718", "0.6565366", "0.65629923", "0.6546928", "0.6544002", "0.65419334", "0.65387374", "0.6532364", "0.65163916", "0.65123093", "0.65121645", "0.6508692", "0.6506828", "0.65059626", "0.65058094", "0.6505178", "0.6502093", "0.65006554", "0.64993465", "0.64898396", "0.64884204", "0.6483723", "0.6468883", "0.6460561", "0.6459767", "0.6457215", "0.64318997", "0.6422821", "0.6421327", "0.6409646", "0.6405731", "0.640286", "0.6402638", "0.6395439", "0.6395439", "0.638814", "0.6387013", "0.63844794", "0.6383755", "0.63815016", "0.6381137", "0.6367011", "0.63650644", "0.63622427", "0.63589925", "0.63434476", "0.6341714", "0.63358736", "0.63313997", "0.6324988", "0.632273" ]
0.0
-1
create beer rating algorithm
def beer_rating # if all three public rating sources are nil, provide a "zero" rating for this beer if beer_rating_one.blank? && beer_rating_two.blank? && beer_rating_three.blank? (3.25*2).round(2) # else, combine the public ratings according to algorithm below else # determine if a large number of people have provided ratings on this beer if number_ratings_one first_ratings = number_ratings_one else first_ratings = 0 end if number_ratings_two second_ratings = number_ratings_two else second_ratings = 0 end if number_ratings_three third_ratings = number_ratings_three else third_ratings = 0 end # calculate total number of ratings number_of_ratings = (first_ratings + second_ratings + third_ratings) # if a significant number (>500) have rated this beer, don't discount the rating if number_of_ratings >= 500 if beer_rating_one && beer_rating_two && beer_rating_three (((((beer_rating_one * number_ratings_one) + (beer_rating_two * number_ratings_two) + (beer_rating_three * number_ratings_three)) / (number_of_ratings))*1)*2).round(2) elsif beer_rating_one && beer_rating_two (((((beer_rating_one * number_ratings_one) + (beer_rating_two * number_ratings_two)) / (number_ratings_one + number_ratings_two))*1)*2).round(2) elsif beer_rating_one && beer_rating_three (((((beer_rating_one * number_ratings_one) + (beer_rating_three * number_ratings_three)) / (number_ratings_one + number_ratings_three))*1)*2).round(2) elsif beer_rating_two && beer_rating_three (((((beer_rating_two * number_ratings_two) + (beer_rating_three * number_ratings_three)) / (number_ratings_two + number_ratings_three))*1)*2).round(2) elsif beer_rating_one ((((beer_rating_one * number_ratings_one) / (number_ratings_one))*1)*2).round(2) elsif beer_rating_two ((((beer_rating_two * number_ratings_two) / (number_ratings_two))*1)*2).round(2) else ((((beer_rating_three * number_ratings_three) / (number_ratings_three))*1)*2).round(2) end else # if a non-significant number (<500) have rated this beer, discount the rating by 10% if beer_rating_one && beer_rating_two && beer_rating_three (((((beer_rating_one * number_ratings_one) + (beer_rating_two * number_ratings_two) + (beer_rating_three * number_ratings_three)) / (number_of_ratings))*0.9)*2).round(2) elsif beer_rating_one && beer_rating_two (((((beer_rating_one * number_ratings_one) + (beer_rating_two * number_ratings_two)) / (number_ratings_one + number_ratings_two))*0.9)*2).round(2) elsif beer_rating_one && beer_rating_three (((((beer_rating_one * number_ratings_one) + (beer_rating_three * number_ratings_three)) / (number_ratings_one + number_ratings_three))*0.9)*2).round(2) elsif beer_rating_two && beer_rating_three (((((beer_rating_two * number_ratings_two) + (beer_rating_three * number_ratings_three)) / (number_ratings_two + number_ratings_three))*0.9)*2).round(2) elsif beer_rating_one ((((beer_rating_one * number_ratings_one) / (number_ratings_one))*0.9)*2).round(2) elsif beer_rating_two ((((beer_rating_two * number_ratings_two) / (number_ratings_two))*0.9)*2).round(2) else ((((beer_rating_three * number_ratings_three) / (number_ratings_three))*0.9)*2).round(2) end end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def rating\n rating_calculator.rate(raters)\n end", "def rating_of(category, item)\n ratings_of = ratings.select{ |r| r.beer.send(category) == item }\n ratings_of.map(&:score).inject(&:+) / ratings_of.count.to_f\n end", "def bayesian_rating(options = { })\n entity = Rating.find(:first, :select => \"rateable_id, (SUM(rating * weight) / SUM(weight)) AS average_rating\", \n :conditions => rateable_conditions)\n\n counts = Rating.count(:id, :group => 'rateable_id')\n avg_rating = Rating.average(:rating).to_f \n \n avg_num_votes = (counts.values.sum / counts.size).to_f\n\n this_rating = entity.average_rating.to_f\n this_num_votes = counts[entity.rateable_id]\n\n @acts_as_rateable_bayesian_rating = ( (avg_num_votes * avg_rating) + (this_num_votes * this_rating) ) / (avg_num_votes + this_num_votes)\n end", "def users_pattern_rating(base_prediction, modified_prediction, movie_id, user_id)\n user_rating_avg = 0.0 \n movies = @user_hash[user_id]\n movies.each do |hash|\n user_rating_avg += hash[hash.keys[0]].to_i\n end\n user_rating_avg = user_rating_avg / @user_hash[user_id].length\n if base_prediction > user_rating_avg\n modified_prediction -= 0.5 *(base_prediction - user_rating_avg).abs \n elsif base_prediction < user_rating_avg\n modified_prediction += 0.5 * (base_prediction - user_rating_avg).abs\n end\n return modified_prediction\n end", "def boost\n 1.0 #self.rating / 2.0\n end", "def rating\n return 0 if total_votes == 0\n (100 * self.yeses) / total_votes\n end", "def calculate_rating(rating, input, i=0)\n # Base case - single number (return decimal version of number)\n return input.first.to_i(2) if input.size == 1\n\n grouped = input.group_by { |n| n[i] }\n num0s = (grouped[\"0\"] || []).size\n num1s = (grouped[\"1\"] || []).size\n #binding.pry\n winning_group = case rating\n when :oxygen_generator\n num1s >= num0s ? grouped[\"1\"] : grouped[\"0\"]\n when :co2_scrubber\n num0s <= num1s ? grouped[\"0\"] : grouped[\"1\"]\n end\n\n # Recursive call to check next digit\n calculate_rating(rating, winning_group, i+1)\nend", "def rating_factor\n\t\tcase reviews.length\n\t\t\twhen 0..5\n\t\t\t\t0.35\n\t\t\twhen 6..10\n\t\t\t\t0.50\n\t\t\twhen 11..20\n\t\t\t\t0.75\n\t\t\twhen 21..40\n\t\t\t\t0.90\n\t\t\telse\n\t\t\t\t1\n\t\tend\n\tend", "def create_beers_with_ratings(scores, user, brewery = FactoryGirl.create(:brewery), style = FactoryGirl.create(:style))\n \t\tscores.each do |score|\n \t\t\tcreate_beer_with_rating(score, user, brewery, style)\n \t\tend\n \tend", "def candy(ratings)\n candies = Array.new(ratings.size) { 1 }\n 1.upto(ratings.size - 1).each { |i|\n if ratings[i] > ratings[i - 1] && candies[i] <= candies[i - 1]\n candies[i] = candies[i - 1] + 1\n end\n }\n \n (ratings.size - 2).downto(0).each { |i|\n if ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]\n candies[i] = candies[i + 1] + 1\n end\n }\n \n candies.inject(:+)\nend", "def rating; \"Д/379 (stub)\"; end", "def get_beer_hash(doc, beer_list, sub_style)\n beer_list\n doc.css(\"tr\").drop(3).each do |info|\n unless info.css(\"td a b\").text == \"\"\n ratings = info.css(\"td b\").collect {|child| child.text.gsub(\",\",\"\") if child == info.css(\"td b\")[1]}.join.to_i\n if ratings > 99\n beer_list << {\n :name => info.css(\"td a b\").text,\n :url => info.css(\"td a\").attribute('href').value,\n :parent_style => sub_style.parent_style,\n :sub_style => sub_style,\n :ratings => ratings,\n :score => info.css(\"td b\").collect {|child| child.text if child == info.css(\"td b\")[2]}.join.to_f,\n :abv => info.css(\"td span\").text.to_f\n }\n end\n end\n end\n beer_list\n end", "def convertRatings(rating)\n if rating == 10\n return 5\n elsif rating >= 7\n return 4\n elsif rating >= 5\n return 3\n elsif rating >= 2\n return 2\n elsif rating == 1\n return 1\n end\nend", "def calculate_tip(amount, rating)\n# A good use of a key/value hash (e.g. key == 'terrible' and value == 0) to minimize \n# repetition of code\n tips = { 'terrible' => 0, 'poor' => 0.05, 'good' => 0.1, 'great' => 0.15, 'excellent' => 0.2 }\n return 'Rating not recognised' unless tips.keys.include? rating.downcase\n# In this line the calculation is written only once using the keys/values of the hash 'tips'\n (amount * tips[rating.downcase]).ceil\nend", "def num_ratings \n 5\n end", "def rating_css(rating)\n if rating>9\n \"ruby\"\n elsif rating>7.5\n \"gold\"\n elsif rating>6\n \"silver\"\n else\n \"bronze\"\n end\nend", "def rating\n rand(40..140).to_s\n end", "def rateBoringness\n distanceToUnseen = boringnesses[:unseen] || LargeFiniteNumber\n distanceToFood = boringnesses[:food] || LargeFiniteNumber\n distanceToEnemy = boringnesses[:enemyHill] || LargeFiniteNumber\n # Apply a sub-linear function to each distance so that\n # farther away distances have less influence than close.\n # Food is more important than unexplored spaces.\n # Enemy nests are even more important(?).\n # Using a continuous function (rather than e.g. if distanceToFood < 6)\n # makes it easier to write a function that can fairly compare any\n # two locations we're considering moving to, even when the two\n # locations fall on different sides of that threshold.\n result = Math.sqrt(distanceToUnseen * ExploreWeight) +\n Math.sqrt(distanceToFood * FoodWeight) +\n Math.sqrt(distanceToEnemy * HillWeight)\n #log \"#{@col},#{@row} boringness: #{distanceToUnseen}, #{distanceToFood}, #{distanceToEnemy} ==> #{result}\"\n return result\n end", "def baserunning_total\n self.rating_15 + \n self.rating_16 +\n self.rating_17 +\n self.rating_18\n end", "def rating\n 0\n end", "def rate(rating)\n @nb_ratings += 1\n @sum_ratings += rating\n @average_rating = @sum_ratings / @nb_ratings\n end", "def average_rating(driver)\n sum = 0.0\n \n driver.each do |find_rating|\n driver_rating = find_rating[:rating]\n sum += driver_rating\n end\n\n average = sum / driver.length\n\n return average\nend", "def get_random_rating\n ratings = [\n ['Low Unsatisfactory', 2], \n ['High Unsatisfactory', 3], \n ['Low Satisfactory', 10], \n ['Mid Satisfactory', 15], \n ['High Satisfactory', 20], \n ['Low Advanced', 25], \n ['High Advanced', 25]\n ]\n wChooseUsingRand(@rand, ratings)\n end", "def final_val\n \tid = 1\n \tv = 0\n \ta = 0\n final_rating = 0\n \tlast_id = Rating.last.id\n\n for i in 1..10 # i loops n(number of restaurants) times\n recordn = Rating.get(id).business_id\t\t\t\t # n is 10 here\n \t recordall = Rating.all(:business_id => recordn)\n \t\t \n \t\t recordall.each do |e|\n\t \t v += e.useful\n\t \t a += e.usefulval \n\t \t final_rating = a/v\n end\n\n x = final_rating\n\n if x > -4 and x < -3.5\n\t \trating_integer = 1\n\t elsif x > -3.5 and x < -2.5\n\t \trating_integer = 1.5\n\t elsif x > -2.5 and x < -1.5\n\t \trating_integer = 2\n\t elsif x > -1.5 and x < 0.5\n\t \trating_integer = 2.5\n\t elsif x > 0.5 and x < 1.5\n\t \trating_integer = 3\n\t elsif x > 1.5 and x < 2.5\n\t \trating_integer = 3.5\n\t elsif x > 2.5 and x < 3.5\n\t \trating_integer = 4\n\t elsif x > 3.5 and x < 4.5\n\t \trating_integer = 4.5\n\t else\n\t \trating_integer = 5\n\t end\n\n\t z = final_rating % 1\n\t \n\t if z != 0\n\t decimal_val = z * 10\n\t decimal_scaled = (decimal_val % 10)/10\n\t integer_scaled = final_rating - decimal_val\n\t rating_decimal = (decimal_scaled/2)\n\t rating = rating_integer + rating_decimal\n\t end\n\n\t \t new_rating = Business.new\n\t \t new_rating.business_id = recordn\n\t \t new_rating.final_rating = rating\n\t \t new_rating.save\n\t \t \n\t \t last_business_id = recordn\n\t \t last_id_of_group = recordall.last.id\n\t \t id = last_id_of_group + 1 \t \n\t \t puts \"id -> #{id}\"\n\tend\t \n\t \t\t\n end", "def candy(ratings)\n length = ratings.length\n rewards = Array.new(length, 1)\n (1..length - 1).each do |i|\n rewards[i] = rewards[i - 1] + 1 if ratings[i] > ratings[i - 1]\n end\n\n (length - 2).downto(0).each do |j|\n if ratings[j] > ratings[j + 1]\n rewards[j] = [rewards[j + 1] + 1, rewards[j]].max\n end\n end\n\n rewards.sum\nend", "def bakery_num( num_of_people, fav_food ) # defines a method called bakery_num that takes two parameters, num_of_peope, fav_food\n serving_sizes = { \"pie\" => 8, \"cake\" => 6, \"cookie\" => 1 } # Hash of available foods and associated counts\n food_quantities = { \"fav_food\" => 0, \"pie\" => 0, \"cake\" => 0, \"cookie\" => 0 } # Hash of food quantities\n\n # Raise error if serving sizes doesn't contain food\n raise ArgumentError.new(\"You can't make that food\") if !serving_sizes.has_key? (fav_food)\n\n # Returns the necessary number of food items needed to satisfy each serving if the \n # number of people attending is evenly divisible by the quantity of the passed favorite food.\n return \"You need to make #{num_of_people / serving_sizes[fav_food]} #{fav_food}(s).\" if num_of_people % serving_sizes[fav_food] == 0\n\n # Loop through each key in food_quantities to determine how many of each food item is needed.\n food_quantities.each do |key, value|\n if key == \"fav_food\" \n food_quantities[key] = num_of_people / serving_sizes[fav_food] # Setting \"fav_food\" property for future use in food_quantities\n food_quantities[fav_food] = food_quantities[key]\n num_of_people = num_of_people % serving_sizes[fav_food] # Setting remaining amount of people left after fav_food is determined.\n elsif num_of_people / serving_sizes[key] > 0 # key is not fav_food and number of remaining people divided by the next food item serving size is greater than zero\n food_quantities[key] = num_of_people / serving_sizes[key] # Setting count for additional food items needed for remaining people\n num_of_people = num_of_people % serving_sizes[key] # Setting number of remaining people after the additional food item\n end # Ending conditional\n end # Ending .each loop\n\n return \"You need to make #{food_quantities[\"pie\"]} pie(s), #{food_quantities[\"cake\"]} cake(s), and #{food_quantities[\"cookie\"]} cookie(s).\"\nend", "def rating(participant = nil)\n fact_rating = 1\n assignments.each { |a| fact_rating += a.fact.rating(participant) }\n fact_rating * assignment_rating(participant) * feeling(participant)\n end", "def rating_text(rating)\n base = \" Level Opportunity\"\n if rating>9\n \"Ruby\"+base\n elsif rating>7.5\n \"Gold\"+base\n elsif rating>6\n \"Silver\"+base\n else\n \"Bronze\"+base\n end\nend", "def bayesian_rank\n\n #this is an ad hoc value, which basically represents the minimum number of \n #votes we think an Idea should have before it's even considered relevant. \n #eventually this value will come from the admin screen\n @magic_number_of_votes = 0.5\n\n @return_value = ((@magic_number_of_votes*Idea.average_rank_of_all_ideas.to_f)+(self.count_of_users_ranked*self.average_rank.to_f))/(@magic_number_of_votes+self.count_of_users_ranked)\n\n if @return_value == 0\n return 10\n else\n return @return_value.round(2)\n end\n\nend", "def create_ratyrate\n\t\tself.rate(self.rating, self.user, \"rating\", false)\n\tend", "def rating\n average_rating = (trips.collect {|trip| trip.rating.to_f}.sum)/trips.length\n ## Code below functions the same as the code in line 28\n ## Was unsure which design was preferred, so left both in\n # total_rating = 0.0\n # trips.each do |trip|\n # total_rating += trip.rating\n # end\n # average_rating = total_rating/trips.length\n return average_rating.round(1)\n end", "def rating_formula\n time = Time.new\n age = ((time - self.created_at)/60/60/24).to_i\n if upvotes != nil\n rating = upvotes + age * (-0.5)\n else \n rating = age * (-0.5)\n end\n rating\n end", "def corrected_rating\n [(weighted_rating + 2) * 1.6666666666666667, 5.0].min\n end", "def feedback_score\n average_rating = self.average_rating\n if average_rating > 0 and average_rating <= 2.5\n average_rating = 1\n elsif average_rating > 2.5 and average_rating <= 5.0\n average_rating = 2\n elsif average_rating > 5.0 and average_rating <= 7.5\n average_rating = 3\n elsif average_rating > 7.5 and average_rating <= 10.0\n average_rating = 4\n end\n end", "def get_review_ratings\n ratings = {\n prof: 0,\n enjoy: 0,\n difficulty: 0,\n recommend: 0\n }\n\n @reviews.each do |r|\n ratings[:prof] += r.professor_rating\n ratings[:enjoy] += r.enjoyability\n ratings[:difficulty] += r.difficulty\n ratings[:recommend] += r.recommend\n end\n\n ratings[:overall] = (ratings[:prof] + ratings[:enjoy] + ratings[:recommend]) / 3\n\n num_reviews = @reviews.length\n\n ratings.each_with_object({}) { |(k, v), h|\n h[k] = (v / num_reviews).round(2)\n }\n end", "def score\n\t\treviews.length > 1 ? 5 + (avg_rating-2.5)*2*rating_factor : -1\n\tend", "def rating\n if self.rating_sum > 0 && self.rating_count > 0\n (self.rating_sum / self.rating_count).round(2)\n end\n end", "def weight; end", "def set_rating\n food_reviews = self.food_reviews\n if self.has_rating\n totrating = 0\n food_reviews.each do |food_review|\n totrating = totrating + food_review.rating\n end\n avg_rating = totrating.to_f/food_reviews.length\n @food_rating = avg_rating.round(2)\n return\n end\n @food_rating = 0.0\n end", "def rating_convert\n self.rating.each do |trip|\n trip.rating = * 0.01 * ('%.2f' % trip.rating)\n return trip.rating\n end\n end", "def calc_ratings\n # Changes players' ratings\n x = 1\n @players.each do |player|\n puts \"Starting calcs for #{player.name}\"\n player.scores[self.id] = @scores[player]\n puts \"#{player.name}'s score added to personal score list\"\n \n if player.provisional == true\n if @scores[player] == 10\n puts \"#{player.name} won this provisional game.\"\n rating_change = $PROVK * (players.length - 1)\n player.rating += rating_change\n else\n puts \"#{player.name} lost this provisional game.\"\n proportion = @scores[player].to_f / (self.sum_scores - 10)\n puts \"Proportion: #{proportion}\"\n # The (-2 * $PROVK) part essentially inverses a player's\n # rating_change. Higher proportion -> lower rating loss.\n rating_change = (-2 * $PROVK) + (proportion * ($PROVK * (players.length - 1)))\n puts \"Rating change: #{rating_change}\"\n player.rating += rating_change\n end\n else\n if player == @players[-1]\n break\n end\n @players[x..-1].each do |opponent| # Compares to each following player in array\n puts \"versus #{opponent.name}\"\n expected_score = [((@old_ratings[player] + $BETA) / (@old_ratings[opponent] + $BETA) * @scores[opponent]), 2].max\n \n rating_change = [(@scores[player]/expected_score), (expected_score/@scores[player])].min - 1\n \n if @scores[player] > expected_score\n rating_change = -rating_change\n end\n \n rating_change = rating_change * $REGK\n \n if @scores[player] > @scores[opponent]\n rating_change += $WINLOSS\n \n player.rating += rating_change\n opponent.rating -= rating_change\n \n end\n end\n end\n x += 1\n \n\n end\n \n for player in players\n @new_ratings[player] = player.rating\n puts \"Added #{player.name} to @new_ratings\"\n player.old_rating = player.rating\n puts \"old_rating set equal to rating in preparation for future games\"\n end\n return @new_ratings\n end", "def rating\n if reviews.size ==0\n return nil\n end\n rating=0\n reviews.each do |review|\n rating+=review.rating\n end\n return (rating*1.0/reviews.size).round(2)\n end", "def calculate_rating(query)\n @rating = 0 #initialize page rating\n count = 0\n q_keyword_weight = 0\n p_keyword_weight = 0\n query.keywords.each do |q_keyword|\n q_keyword_weight = MAX_NUM_KEYWORDS - count\n count += 1\n @keywords.each do |p_keyword|\n if p_keyword.downcase == q_keyword.downcase\n p_keyword_weight = MAX_NUM_KEYWORDS - @keywords.index(p_keyword)\n @rating += (q_keyword_weight * p_keyword_weight )\n end\n end\n end\n end", "def score(class_id, dab, from_id)\n retain = @classes[class_id].map { |x| x.to_a}.flatten\n values = BookmarkColorer.color(from_id, @alpha, 0.0000001, retain) do |article|\n edges = (@out_links[article] || \"\").split(/\\t/)\n edges.delete(dab)\n [edges, Array.new(edges.length, 1)]\n end\n #p values\n if @bayes\n text = @wiki.get_full_link(@full_links, from_id, dab)\n #@classes[dab].map { |vs| vs.map { |v| (values[v] || 0) * @wiki.get_in_link_count(@in_link_counts, v, text) / (@wiki.get_in_link_count(@in_link_counts,v, \"\").to_f) }.max}\n res = @classes[class_id].map do |vs| \n (vs.map do |v|\n if text\n val = values[v] || 0\n #p [v, val, text]\n text_contrib = @wiki.get_in_link_count(@in_link_counts, v, text)\n total = @wiki.get_in_link_count(@in_link_counts, v, \"\").to_f\n total = 1 if total == 0\n #p [val, text_contrib, total]\n val * text_contrib / total\n else\n 0\n end\n end).max\n end\n res\n elsif @radius\n @classes[class_id].pmap do |vs| \n (vs.map do |v|\n other_values = BookmarkColorer.color(v, @alpha, 0.0001) do |article|\n edges =(@out_links[article] || \"\").split(/\\t/)\n edges.delete(dab)\n [edges, Array.new(edges.length, 1)]\n end\n\n avg_values = Hash.new { |h,k| h[k] = 0}\n [values, other_values].each do |h|\n h.keys.each do |k|\n avg_values[k] += h[k] / 2\n end\n end\n\n -(kl(values, avg_values) + kl(other_values, avg_values)) / 2\n end).max\n end\n else\n res = @classes[class_id].map { |vs| vs.map { |v| values[v] || 0 }.max}\n #p res\n res\n end\n end", "def calculate_tip(amount, rating)\n amount = amount.to_i\n if rating == \"Terrible\"\n return (amount * 0).to_i\n elsif rating == \"Poor\"\n return (amount * 0.05).to_i\n elsif rating == \"Good\"\n return (amount * 0.10).to_i\n elsif rating == \"Great\"\n return (amount * 0.15).to_i\n elsif rating == \"Excellent\"\n return (amount * 0.20).to_i\n else \n return \"rating not recognized.\"\n end \nend", "def set_rating\n all_ratings = []\n self.reviews.each { |review| all_ratings << review.overall_rating }\n self.rating = all_ratings.reduce(:+) / (all_ratings.length * 1.0)\n self.save\n end", "def calculate_rating(user_id,movie_id)\n #user_similarity: {\"user1\"=>{\"user2\"=>similarity, \"user3\" => similarity}, \"user2\"....}\n count = 0;\n rating = 0.0\n user_similarity[user_id.to_i].each do |u,s|\n if (tmp = rating(u.to_i,movie_id.to_i)) != 0\n count += 1\n end\n rating += (tmp * 1.0 * s).round(4)\n end\n return count, rating\n end", "def hitting_total\n self.rating_19 +\n self.rating_20 +\n self.rating_21 +\n self.rating_22 +\n self.rating_23 +\n self.rating_24 +\n self.rating_25 +\n self.rating_26 +\n self.rating_27\n end", "def add_rating(rating)\n if @count < TRAINING_SET_SIZE\n add_movie(rating)\n add_user(rating)\n @count += 1\n else\n @test_set << rating\n end\n end", "def rating factorization\n num_items = factorization.num_items\n num_users = factorization.num_users\n\n\n feature_dim = factorization.getItemFeatures(factorization.get_item_id_mappings.iterator.next.get_key.long_value).length\n\n vektor = factorization.getItemFeatures(factorization.get_item_id_mappings.iterator.next.get_key.long_value)\n\n item_matrix = factorization.get_item_id_mappings.iterator.inject([]) do |item_matrix, item_map| \n item_row = item_map.get_value\n item_vector = factorization.getItemFeatures(item_map.get_key.long_value).to_a\n item_matrix << item_vector\n item_matrix\n end\n\n user_matrix = factorization.get_user_id_mappings.iterator.inject([]) do |user_matrix, user_map| \n user_row = user_map.get_value\n user_matrix << factorization.getUserFeatures(user_map.get_key.long_value).to_a\n user_matrix\n end\n\n user_matrix = Matrix.rows(user_matrix)\n item_matrix = Matrix.rows(item_matrix)\n \n rating_matrix = item_matrix * user_matrix.transpose\n \n\n dense_matrix = DenseMatrix.new(num_users, num_items)\n\n rating_matrix.each_with_index{|num, row, col|\n dense_matrix.set_quick(col, row, num) \n }\n\n dense_matrix\n\n# factorization.get_item_id_mappings.iterator.each do |item_map| \n# item_row = item_map.get_value\n# item_matrix = Matrix[factorization.getItemFeatures(item_map.get_key.long_value).to_a]\n# factorization.get_user_id_mappings.iterator.each do |user_map| \n# user_row = user_map.get_value\n# user_matrix = Matrix[factorization.getUserFeatures(user_map.get_key.long_value).to_a]\n# rating = item_matrix*user_matrix.transpose\n# rating_matrix.set_quick(user_row,item_row,rating[0,0])\n# end\n# end\n\n \n #TODO: multiply the vectors and put it into the matrix \n end", "def bakery_num(num_of_people, fav_food)\n # Hash to show the serving zise of each food item \n my_list = {\"pie\" => 8, \"cake\" => 6, \"cookie\" => 1}\n # Raise an error if fav_food is not one of my_list\n raise ArgumentError.new(\"You can't make that food\") if my_list[fav_food].nil?\n # Initialize each quantity at zero\n supplies = { \"pie\" => 0,\n \"cake\" => 0,\n \"cookie\" => 0}\n \n left_over = num_of_people % my_list[fav_food]\n supplies[fav_food] = num_of_people/my_list[fav_food]\n if left_over == 0\n \"You need to make #{supplies[fav_food]} #{fav_food}(s).\"\n else \n my_list.each do |k, v|\n if left_over >= v \n supplies[k] = left_over / v\n left_over = left_over % v\n end\n end\n return \"You need to make #{supplies['pie']} pie(s), #{supplies['cake']} cake(s), and #{supplies['cookie']} cookie(s).\"\n end\nend", "def candy_1(ratings)\n rewards = Array.new(ratings.length, 1)\n (1..ratings.length - 1).each do |i|\n j = i - 1\n # increment rewards if ratings are increasing\n if ratings[i] > ratings[j]\n rewards[i] = 1 + rewards[j]\n else\n # Go back till ratings are increasing\n while (j >= 0) && (ratings[j] > ratings[j + 1])\n # max out of current value and 1+ previous value (we are going back)\n rewards[j] = [rewards[j], rewards[j + 1] + 1].max\n j -= 1\n end\n end\n end\n rewards.sum\nend", "def bakery_num(num_of_people, fav_food)\n # Hash to show the serving zise of each food item \n my_list = {\"pie\" => 8, \"cake\" => 6, \"cookie\" => 1}\n # Raise an error if fav_food is not one of my_list\n raise ArgumentError.new(\"You can't make that food\") if my_list[fav_food].nil?\n # Initialize each quantity at zero\n supplies = { \"pie\" => 0,\n \t\t\t \"cake\" => 0,\n \t\t\t \"cookie\" => 0 }\n \n left_over = num_of_people % my_list[fav_food]\n supplies[fav_food] = num_of_people/my_list[fav_food]\n if left_over == 0\n \"You need to make #{supplies[fav_food]} #{fav_food}(s).\"\n else \n my_list.each do |k, v|\n if left_over >= v \n supplies[k] = left_over / v\n left_over = left_over % v\n end\n end\n return \"You need to make #{supplies['pie']} pie(s), #{supplies['cake']} cake(s), and #{supplies['cookie']} cookie(s).\"\n end\nend", "def calculate_average_rating\n weighted_drinks_ratings.sum.to_f / weighted_drinks_ratings.count\n end", "def calculate(ratings)\n histogram_data = ratings.group(:int_value).count\n 5.times { |i| histogram_data[i+1] = 0 if !histogram_data[i+1] }\n histogram_data.to_a.sort.to_s\n end", "def convert_by_flour_weight(ingredients)\n puts \"Please input a number for the amount of grams of flour to be used\"\n input = get_user_integer # validates integer for use in formula\n total_weight = 0\n flour = 0.0\n # parses ingredients array for a hash containing flour and uses its value. flour in recipe check is handled by conversion option selection method.\n ingredients.each do |parse_ingredients|\n if parse_ingredients.key?(\"flour\")\n flour = parse_ingredients[\"flour\"]\n end\n end\n # divides flour weight by its percentage (represented as a decimal) to find total weight of recipe and uses that value to find values of other ingredients in grams from percentage value. \n total = input / flour\n ascii_heading(\"Conversions\")\n ingredients.each do | ingredient |\n ingredient.each do | i,p |\n puts \"#{i}: #{(total*p).to_i}grams\" # iterator formats recipe list and handles value conversion.\n total_weight += (total*p).to_i # updates total weight with each iteration to print total eight\n end\n end\n puts \"Total Recipe weight = #{total_weight} grams\"\nend", "def calculate_tip(amount, rating)\n rating = rating.downcase\n case\n when rating == \"terrible\"\n return 0\n when rating == \"poor\"\n return (amount * 0.05).ceil\n when rating == \"good\"\n return (amount * 0.10).ceil\n when rating == \"great\"\n return (amount * 0.15).ceil\n when rating == \"excellent\"\n return (amount * 0.20).ceil\n else\n \"Rating not recognised\"\n end\nend", "def each_review_rating\n keys = []\n values = []\n @item.reviews.each do |review|\n review.properties.each do |k,v|\n keys << k\n values << v.to_i\n end\n return (values.sum.to_f / keys.uniq.size).round(1)\n end\n end", "def find_suitable_adapter_for(joltage)\n # Create a range of suitable adapters that would work\n suitable_range = (joltage..joltage + 3).to_a\n\n # Look in the bag for adapters we have and see if any of them match our suitable range\n suitable_range.each do |searching_joltage|\n suitable_adapter = @adapters.find { |n| n[:rating] == searching_joltage && !n[:has_been_used] }\n\n if suitable_adapter\n # Find difference between joltage and suitable adapter\n joltage_difference = suitable_adapter[:rating] - joltage\n\n # We've used this now...\n suitable_adapter[:has_been_used] = true\n\n puts suitable_adapter\n # Keep track of difference\n @difference << joltage_difference\n return suitable_adapter[:rating]\n else\n next\n end\n end\nend", "def y_star(items, already_sorted = false)\n items = sort_items_by_profitability!(items.clone) unless already_sorted\n i1, i2 = items[0], items[1]\n c1, c2, a1, a2 = i1[:p], i2[:p], i1[:w], i2[:w]\n \n (Rational(c1)/(Rational(c1, a1) - Rational(c2, a2))).ceil\nend", "def tbs_tactic_rate\n tactic = GTBS_Tactics::All_AI_Tactics[ (battler.ai_tactic or 'default') ]\n value = 0\n if @effect_preview.keys.size == 0\n self.rating = value\n return\n end\n \n for target, effect in @effect_preview\n hit_chance, dmg_eval, mp, rate_states, rate_counter = effect\n damage, ref, ally = dmg_eval\n damage_frac = damage / ref.to_f\n dmg_rate = (mp ? tactic.mp_damage : tactic.hp_damage) \n target_rate = [0.01, ((subject.view_range.to_f/$game_map.distance(subject, target)) * target.tgr)].max\n \n if ally\n pained_ally = (target.hp / target.mhp.to_f < 0.33) ? 1.0 + tactic.team_rate : 1.0\n death_unlike = (damage_frac > 0.83) ? [damage_frac*(1.0+tactic.team_rate), 1.0].max : 1.0\n dmg_rate = tactic.hp_heal if damage < 0\n value -= (hit_chance / 100.0) * damage_frac * dmg_rate * death_unlike * pained_ally * target_rate\n value += rate_states * tactic.state * tactic.team_rate * pained_ally * target_rate\n else\n n_ally = 1.0\n #if tactic team enabled, add value if target can be attacked by other allies\n if tactic.team\n for bat in subject.friends\n if @other_bat_attack[bat] & target.positions != []\n n_ally += tactic.team_rate\n end\n end\n end\n if tactic.force_approach\n value += 10\n end\n \n #check 83% because variance add 20%\n death_like = (damage_frac > 0.83) ? [damage_frac*tactic.death_like, 1.0].max : 1.0\n value += n_ally * (hit_chance / 100.0 * damage / ref.to_f * dmg_rate) * death_like * target_rate\n value += rate_states * tactic.state * target_rate\n #don't care of counter if unit will die\n rate_counter *= (1.0 - damage_frac) / 0.17 if (damage_frac > 0.83)\n end\n value -= rate_counter * tactic.counter\n value -= tactic.mp_save * battler.skill_mp_cost(item) / [battler.mmp.to_f, 1.0].max if skill?\n end\n \n #modify rating\n if value > 0\n unless tactic.team \n value += (@move_pos == battler.pos) ? tactic.position : -tactic.position / 4 * rate_pos_safe\n end\n value = (value * ai_rating)\n self.rating += (value * tactic.predictable / 100).to_i\n else\n self.rating = 0\n end\n end", "def rating\n reviews.any? ? reviews.sum(&:rating) / reviews.count : 0\n end", "def bakery_num(servings, favorite_food)\n raise ArgumentError, \"You can't make that food\" unless TREAT_SERVINGS.key?(favorite_food)\n\n #instead of initializing them individually, we cna put it into a hash and easily associate with the servings hash\n order_quantity = {\"pie\" => 0, \"cake\" => 0, \"cookie\" => 0}\n fave_food_servings = TREAT_SERVINGS[favorite_food]\n\n if servings % fave_food_servings == 0\n return \"You need to make #{servings/fave_food_servings} #{favorite_food}(s).\"\n end\n\n # we know that we'll only have to fill the order with foods that have serving sizes of \n # equal to or less than favorite_food. so, if the constant TREAT_SERVINGS is always in \n # order by most servings : least_servings, this should return\n # an array of the treats that will potentially be part of the order\n foods = TREAT_SERVINGS.keys.drop_while {|food| food != favorite_food}\n\n # take_while will continue iterating until it evaluates to false or nil\n # so the last line in the block is asking if servings still have to be allocated\n foods.take_while do |food|\n order_quantity[food] = servings / TREAT_SERVINGS[food]\n servings %= TREAT_SERVINGS[food]\n end\n\n \"You need to make #{order_quantity[\"pie\"]} pie(s), #{order_quantity[\"cake\"]} cake(s), and #{order_quantity[\"cookie\"]} cookie(s).\"\nend", "def rating\n return nil unless ratings.length > 0\n (ratings.average(:value) / 0.25).round * 0.25\n end", "def bakery_num(num_of_people, fav_food) #defining method bakery_num, which takes 2 arguments\n my_list = {\"pie\" => 8, \"cake\" => 6, \"cookie\" => 1, \"pudding\" => 2, \"bunt cake\" => 4, \"mega-cupcakes\" => 3} #creates hash my_list, key is food, value is number\n pie_qty = cake_qty = cookie_qty = has_fave = 0 \n \n\n my_list.each_key do |k| #iterating through array my_list\n if k == fav_food #tests if each item in array my_list = fav_food\n has_fave = 1 #if test above passes, set has_fave to true\n # fav_food = k #if test above passes, set fav_food to k\n end\n end\n \n if has_fave == 0 #if fav_food is not a key, end program\n raise ArgumentError.new(\"You can't make that food\")\n else #if fav_food is a key\n fav_food_qty = my_list.values_at(fav_food)[0] #set fav_food_qty equal to the value of fav_food\n if num_of_people % fav_food_qty == 0 \n num_of_food = num_of_people / fav_food_qty #if num_of_people is evenly divisible by fav_food_qty\n return \"You need to make #{num_of_food} #{fav_food}(s).\"\n \n #num_of_food = num_of_people / fav_food_qty #then perform division by integer\n #return \"You need to make #{num_of_food} #{fav_food}(s).\" #return \"You need to make (num_of_food) (fav_food)s\"\n else num_of_people % fav_food_qty != 0 #redundant else\n while num_of_people > 0 #while num_of_people is greater than 0\n if num_of_people / my_list[\"pie\"] > 0 #if num_of_people divided by value of pie is greater than 0\n pie_qty = num_of_people / my_list[\"pie\"] #set pie_qty equal to num_of_people divided by value of pie in hash\n num_of_people = num_of_people % my_list[\"pie\"] #set num_of_people equal to the remainder of num_of_people divided by value of pie in hash\n elsif num_of_people / my_list[\"cake\"] > 0 #if num_of_people divided by hash value of cake is greater than 0\n cake_qty = num_of_people / my_list[\"cake\"] #set cake_qty equal to num_of_people divided by hash value of cake\n num_of_people = num_of_people % my_list[\"cake\"] #set num_of_people equal to the remainder of num_of_people divided by value of cake in hash\n else\n cookie_qty = num_of_people #set cookie_qty equal to num_of_people\n num_of_people = 0 #set num_of_people equal to 0\n end\n end\n return \"You need to make #{pie_qty} pie(s), #{cake_qty} cake(s), and #{cookie_qty} cookie(s).\" #print out\n end\n end\n \nend", "def bet(chips)\n\n end", "def fleiss(matrix)\n debug = true\n\n # n Number of rating per subjects (number of human raters)\n n = checkEachLineCount(matrix) # PRE : every line count must be equal to n\n i_N = matrix.size\n k = matrix[0].size\n\n if debug\n puts \"#{n} raters.\"\n puts \"#{i_N} subjects.\"\n puts \"#{k} categories.\"\n end\n\n # Computing p[]\n p = [0.0] * k\n (0...k).each do |j|\n p[j] = 0.0\n (0...i_N).each {|i| p[j] += matrix[i][j] } \n p[j] /= i_N*n \n end\n\n puts \"p = #{p.join(',')}\" if debug\n\n # Computing f_P[] \n f_P = [0.0] * i_N\n\n (0...i_N).each do |i|\n f_P[i] = 0.0\n (0...k).each {|j| f_P[i] += matrix[i][j] * matrix[i][j] } \n f_P[i] = (f_P[i] - n) / (n * (n - 1)) \n end \n\n puts \"f_P = #{f_P.join(',')}\" if debug\n\n # Computing Pbar\n f_Pbar = sum(f_P) / i_N\n puts \"f_Pbar = #{f_Pbar}\" if debug\n\n # Computing f_PbarE\n f_PbarE = p.inject(0.0) { |acc,el| acc + el**2 }\n\n puts \"f_PbarE = #{f_PbarE}\" if debug \n\n kappa = (f_Pbar - f_PbarE) / (1 - f_PbarE)\n puts \"kappa = #{kappa}\" if debug \n\n kappa \nend", "def average_rating(rideshare)\n # set variables for total rating and total sum\n total_rating = {}\n sum = 0\n # loop through\n rideshare.each do |driver, trips|\n trips.each do |trip|\n # calculate total rating \n sum += trip[:rating]\n avg_rating = sum / trips.length.to_f\n total_rating[driver] = avg_rating\n end \n sum = 0\n end\n return total_rating\nend", "def rate; end", "def rate; end", "def rating\n r = 0\n if self[:power_rating]\n r = self[:power_rating].to_f\n else\n r = PHASES.inject(0) {|sum, ph| sum += (self[\"power#{ph}_rating\".to_sym] || 0).to_f}\n end\n raise \"Can't find a rating for #{self[:name]}\" if r == 0\n r\n end", "def overall_rating\n\t\ttotal_score = 0\n\t\ttotal_score += self.setting \n\t\ttotal_score += self.hotness\n\t\ttotal_score += self.originality\n\t\ttotal_score += self.style\n\t\ttotal_score += self.attitude\n\t\treturn total_score / 5\n\tend", "def calculate_tip(amount, rating)\n return (amount * 0.00).ceil if rating.downcase == \"terrible\"\n return (amount * 0.05).ceil if rating.downcase == \"poor\"\n return (amount * 0.10).ceil if rating.downcase == \"good\"\n return (amount * 0.15).ceil if rating.downcase == \"great\"\n return (amount * 0.20).ceil if rating.downcase == \"excellent\"\n 'Rating not recognised'\nend", "def runoff(voters)\n\n def find_winner(voters, tallies=nil)\n if tallies\n min = tallies.values.min\n tallies.keep_if { |candidate, v| v == min }\n voters.each { |voter| voter.reject! {|vote| tallies.include? vote }}\n return nil if voters.length == 0\n end\n new_tallies = Hash.new(0)\n voters[0].each {|candidate| new_tallies[candidate] = 0 }\n voters.each_with_object(new_tallies) { |voter, nt| nt[voter[0]] += 1 }\n total_votes = new_tallies.values.reduce(:+);\n new_tallies.each { |candidate, v|\n return candidate if v / total_votes.to_f > 0.5\n }\n return find_winner(voters, new_tallies)\n end\n\n find_winner(voters)\n\nend", "def rating _args\n \"rating _args;\" \n end", "def breed(players)\n (0..4).each do |i|\n players[i].successor(0, players[(i + 1) % 5])\n players[i].successor(1, players[(i - 1) % 5])\n players[i].successor(2, players[(i + 2) % 5])\n end\n end", "def random_reviews_hash\n\t\t[{title: \"Pretty decent, could have been better\", stars: 4, summary: \"This chair arrived well-packaged and protected with a lot of foam insulation around the wheels and metal components. Assembly was quick and simple, as I didn't even need the instructions. All you have to do is put the air lift on the base and place the seat on the air lift, then it's ready to go. The chair has great lumbar support and reaches all the way up to my head, allowing me to rest entirely against it. It's also fairly comfortable, having a few inches of padding, while not being too compliant so as to lack support, making for a pretty good balance that I particularly like. The air lift lever (for raising/lowering the height of the chair) is designed so that when pushed in the chair cannot recline, but if you pull it out slightly, it releases a mechanical lock and allows the chair to recline back about 20-30 degrees.\"},\n\t\t{title: \"Got exactly what I needed and more!\", stars: 5, summary: \"Customer Service: We often encounter a customer service rep who has had a bad day or just does not care or any of the negative phrases that make us some reps. This is absolutely NOT the case with the folks at BOSS. After opening the box and putting it together (a feat accomplished by anyone who can lift a sack of potatoes) I could not get the gas cylinder to raise the seat level. One of us is 5'6\\\" and the other is 6'3\\\" and the seat is either too high or too low unless the gas cylinder works. It did not. \n\n\t\t\t\tIt was too late to call and it was Thanksgiving eve. Even if anyone had been home I would have waited until Frantic Friday to call. So I emailed my concern and expected no reply until today or maybe tomorrow. On Friday, the 26th, the height adjustment absence was just too much to endure. A call was placed to BOSS and a woman told me exactly what to do and I did. Closed case. Wow! I did suggest that the instructions would benefit from her advice in future iterations. Regardless, my problem was settled in seconds and when I finally got to reviewing my email I saw a response from BOSS saying the same thing. Let's all give a big shout to BOSS for fantastic service.\"\n\t\t},\n\t\t{title: \"Quick, Easy, and Fast!\", stars: 4, summary: \"The chair leans back which is nice. Doesn't seem to have too much lean which i don't really like but it's enough to put my feet up on my sub woofer. The leather is very nice quality and it has a built-in lumbar support which feels nice. My only issue with the chair was the first chair i sat in it and a bolt sheered off. But i told amazon and they had my new chair their the next day (same as what i paid for to ship it originally) and they had a ups man there the next day to pick up the broken chair. After that the chair has been flawless and very comfortable. The leather feels less cheap then the leather on my old chair.\"\n\t\t\t},\n\t\t\t{title: \"Bad Overall Experience\", stars: 2 , summary: \"This chair is nicely built. It looks elegant and cool. It is easy to clean.\n\t\t\t\tThe problem for me is that this is too big.\n\t\t\t\tI am male, 170 cm, 56 kg, that is about 5 foot 7 inches and 123 pounds. I don't feel very comfortable in this chair especially due to the armrest. The armrest is just a few centimeters too high, it pushes my elbow up, and that's annoying.\n\t\t\t\tThe part where you sit on is very large, and I seem to \\\"sink\\\" inside it, which worsens the armrest problem.\n\t\t\t\tBut I think if you are taller, this should be good. It will be even better if you are both taller and fatter. Maybe if I were 180cm(5 foot 11 inches) 85kg(188 pounds), this chair would be perfect.\" },\n\t\t\t\t\t\t\t{title: \"Worse Lender In Dojo!\", stars: 1, summary: \"First the positives:\n\n\t\t\t\t* This is the easiest chair I've ever put together. Simply unfold the chair back and the seat, which come pre-attached along with the arms, until they lock together. Next, place the gas cylinder firmly into the chair base and snap the 5 wheels onto the bottom. Finally, slide the gas cylinder/base into the seat bottom. It's completely tool-less and takes minutes.\n\n\t\t\t\t* The chair itself is pretty comfortable. It fit my back perfectly and was firm enough to give support while being soft enough to sit for extended periods.\n\n\t\t\t\t* Contrary to what other reviewers say, this chair can lean back. Just slide the height adjustment lever in towards the chair to lock the back in place, or slide it out to allow the chair to lean backwards.\"\n\t\t},\n\t\t{title: \"The Best Lender In the Dojo!\", stars: 5, summary: \"Purchased this chair once before on July 26, 2012. Was happy with the chair and the material that was used. This time the material was totally different. Very Cheap, so called Leather Plus..................... Very Cheap. In the description it does say Leather Plus but in the details as this is how it is described, below. I copied and pasted the information. It is not Leather............. Don't be fooled and it feels and looks very cheap. This material is totally different from the purchase in the past. If it were the same as the first chair I bought, I would have been happy. It was discribe to be the exact same and was not............ I don't write many reviews and I shop a lot with Amazon and this time I am a very unhappy shopper. Beware of this cheap chair...........................................\"\n\t\t},\n\t\t{title: \"Very good experience\", stars: 4, summary: \"This chair was packed sufficiently, arrived quickly, and was easy to assemble (5mins, no tools). The chair is comfortable, but I'll have to either turn my A/C colder or wear a shirt (I work at home) because this material either makes me sweat a lot more, or it just shows up more.\"\n\t\t},\n\t\t{title: \"Experienced teach, but always late\", stars: 2, summary: \"Update: after less that 1 year of use, this chair's piston is giving out. It rises on it's own, and I have to lower the chair every time I sit in it. It even rises slowly while I am in it, causing me to have to constantly lower it again. CHEAP CRAP!!!\"\n\t\t}].sample\n\tend", "def candy_2(ratings)\n rewards = Array.new(ratings.length, 1)\n local_mins(ratings).each do |min|\n expand_from_local_min(min, ratings, rewards)\n end\n # puts rewards.to_s\n rewards.sum\nend", "def get_rating\n more_than_five_late_deliveries ? 2 : 1\nend", "def score(user_id, order, question_id, limit, adj=true)\n joins = \"INNER JOIN users ON items.user_id=#{user_id}\"\n joins += \" INNER JOIN items_questions ON (items_questions.question_id=#{question_id} AND items_questions.item_id=items.id)\" if question_id.to_i > 0\n conditions = {\n :joins => joins,\n :group => 'items.id'\n }\n items = Item.find(:all, conditions)\n\n conditions = {\n :conditions => { :active => false },\n :order => 'prompts.created_at',\n :include => [:items, :votes],\n :group => 'prompts.id'\n }\n conditions[:conditions].merge!(:question_id => question_id) if question_id > 0\n prompts = Prompt.all(conditions)\n\n elo = {}\n items.each { |item| elo[item] = START_RATING }\n @adj = adj\n prompts.each do |prompt|\n prompt.votes.each do |vote|\n # elo values static during update\n old_elo = elo.clone\n # if vote has items it has winner(s)\n unless vote.items.empty?\n vote.items.each do |item|\n lost_items = prompt.items - vote.items\n lost_items.each do |loser|\n elo[item] += adjust_elo(WIN_SCORE, old_elo[item], elo[loser])\n elo[loser] += adjust_elo(LOSS_SCORE, elo[loser], old_elo[item])\n end\n end\n else\n # otherwise consider as draw between all prompt items\n prompt.items.each do |item|\n (prompt.items - [item]).each do |other|\n elo[item] += adjust_elo(DRAW_SCORE, elo[item], old_elo[other])\n end\n end # item_ids each\n end # else\n end # votes each\n end # prompts each\n elo = (order == \"asc\") ? elo.sort_by { |k, v| v } : elo.sort_by { |k, v| -v }\n elo = elo.first(limit) if limit > 0\n elo.transpose\n end", "def weighted_combined_score\n return 0.0/0.0 if review_committee_score.nil? || interview_committee_score.nil?\n ratio = offering.final_decision_weight_ratio\n r = review_committee_score * ratio\n i = interview_committee_score * (1 - ratio)\n r + i\n end", "def runoff(voters)\n ballot= Hash.new\n # populate the hash with 0's\n voters.each do |votes|\n votes.each do |v|\n ballot[v] = 0;\n end\n end\n while voters.size/2 >= ballot.values.max && ballot.size > 1\n # reset ballot totals to zero at beginning of each round\n ballot.each { |k,v| ballot[k] = 0 }\n # tally votes for this round\n voters.each do |vote|\n votee = vote.select { |x| ballot.include?(x)}.first\n ballot[votee] += 1\n end\n ballot = ballot.select { |k,v| v > ballot.values.min }\n return nil if ballot.empty?\n end\n ballot.select { |k,v| v == ballot.values.max }.keys[0]\nend", "def average_rating\n ratings.inject(0.0) {|sum, num| sum +=num} / ratings.length\n end", "def weightPolls()\n\n end", "def calculate_rank(gravity=1.8)\n item_hour_age = (Time.now - created_at) / 3600 \n return (vote_score - 1) / (item_hour_age+2) ** gravity\n end", "def rating\n (get_upvotes.size + 2)/(get_downvotes.size + 2)\n end", "def rating_to_type_json(rating)\n rating_json = Hash.new\n rating_json[:throwing] = Hash.new\n rating_json[:fielding] = Hash.new\n rating_json[:baserunning] = Hash.new\n rating_json[:hitting] = Hash.new\n # throwing\n rating_json[:throwing][1] = rating[:rating_1]\n rating_json[:throwing][2] = rating[:rating_2]\n rating_json[:throwing][3] = rating[:rating_3]\n rating_json[:throwing][4] = rating[:rating_4]\n rating_json[:throwing][5] = rating[:rating_5]\n # fielding\n rating_json[:fielding][6] = rating[:rating_6]\n rating_json[:fielding][7] = rating[:rating_7]\n rating_json[:fielding][8] = rating[:rating_8]\n rating_json[:fielding][9] = rating[:rating_9]\n rating_json[:fielding][10] = rating[:rating_10]\n rating_json[:fielding][11] = rating[:rating_11]\n rating_json[:fielding][12] = rating[:rating_12]\n rating_json[:fielding][13] = rating[:rating_13]\n rating_json[:fielding][14] = rating[:rating_14]\n # baserunning\n rating_json[:baserunning][15] = rating[:rating_15]\n rating_json[:baserunning][16] = rating[:rating_16]\n rating_json[:baserunning][17] = rating[:rating_17]\n rating_json[:baserunning][18] = rating[:rating_18]\n # hitting\n rating_json[:hitting][19] = rating[:rating_19]\n rating_json[:hitting][20] = rating[:rating_20]\n rating_json[:hitting][21] = rating[:rating_21]\n rating_json[:hitting][22] = rating[:rating_22]\n rating_json[:hitting][23] = rating[:rating_23]\n rating_json[:hitting][24] = rating[:rating_24]\n rating_json[:hitting][25] = rating[:rating_25]\n rating_json[:hitting][26] = rating[:rating_26]\n rating_json[:hitting][27] = rating[:rating_27]\n rating_json\n end", "def throwing_total\n self.rating_1 +\n self.rating_2 +\n self.rating_3 +\n self.rating_4 +\n self.rating_5\n end", "def save_rating_by(reviewer, rating)\n common_tags = find_common_tags(reviewer)\n common_tags.each do |tag|\n relevance = relevances.where(tag_id: tag.id).first\n relevance.modify_strength(rating, reviewer.proficiency(tag))\n relevance.save\n user.save_rating(tag, reviewer, rating)\n end\n end", "def score\n result = 0\n tiro_index = 0\n rellenar_vector\n\n 10.times do\n if strike?(tiro_index)\n result += strike_Score(tiro_index)\n tiro_index += 1\n elsif spare?(tiro_index)\n\n result += spare_score(tiro_index)\n tiro_index += 2\n else\n result += cuadro_score(tiro_index)\n tiro_index += 2\n end\n end\n result\n end", "def average_rating(blue)\n average_array = []\n names1_array = []\n blue.each do |key,value|\n sum = 0\n value.each do |hash|\n sum += hash.fetch(:\"rating\")\n end\n converted = sum.to_f\n puts \"Driver #{key} has an average rating of #{(converted/value.length).round(3)}.\"\n average_array << (converted/value.length).round(3)\n names1_array << key\n end\n s = average_array.max\n winner2 = names1_array[average_array.find_index(s)]\n return winner2\nputs\nend", "def ratings_sum\nend", "def data\n beers.map do |beer|\n [\n ##link to is a ruby function, the second argument is the path\n ##in this case the path leads to a beer id\n link_to(beer.title, beer),\n beer.rating,\n beer.country,\n beer.state_or_province,\n (beer.votes.where(:up=>true).count - beer.votes.where(:up => false).count),\n link_to('Add Comment',beer),\n ##when this code below is removed it works fine without an up/down vote option\n\t\tupvotelnk(beer) + \" \" + downvotelnk(beer)\n ]\n end\n end", "def rating_sum(wastes)\n wastes.inject(0) { |sum, v| sum + v.rating }\n end", "def beers\n # calculate our answer\n # ask the Beer class a question\n # What fridge are you in? Is it me?\n Beer.all.select do |beer|\n beer.fridge == self # are you in me?\n end\n end", "def rating\n average = 0.0\n ratings.each { |r|\n average = average + r.rating\n }\n if ratings.size != 0\n average = average / ratings.size\n end\n average\n end", "def rating\n\t\tif review.any?\n\t\t\trating = review.map {|review| review.rating}\n\t\t\ttotal = rating.reduce(0) {|total, rating| total += rating}\n\t\t\ttotal = review.reduce(0) {|total, review| total += review.rating}\n\n\t\t#return nil if reviews.empty?\n\t\tend\n\t\t#(reviews.map(&:rating).reduce(&:+).to_f / reviews.length).round(2)\n\t\t#llama a un array de metodo raiting de todos los review; (reduce el array a uno) \n\tend", "def allocate_rewards(score)\n \n # Power allocated for this round\n total_users = User.all.count\n total_feeds = Feed.all.count\n power = (total_users * 5).to_f / (total_feeds * 1000).to_f\n\n # Index values with related ids\n indexes = []\n total = 0.0\n val = 1\n \n # Sort each rating by update date\n ratings.order! 'updated_at ASC'\n ratings.each do |rating|\n user = User.find(rating.user_id)\n difference = rating.score - score \n consistency = 0.99 * user.consistency + 0.01 * difference \n index = Math.exp(-(val**1.5/total_users)) / \n (difference**2 + (consistency - difference)**2 + 1.0)\n indexes.append([user.id, index])\n total = total + index\n val = val + 1\n user.consistency = consistency\n user.save!\n end\n\n # Add respective new voting power\n indexes.each do |element|\n user = User.find(element[0])\n user.voting_power = user.voting_power + (element[1] / total) * power\n user.save!\n end\n\n # Normalize the voting power\n max = 0.0\n User.all.each do |user|\n max = max + user.voting_power\n end \n \n norm_factor = (5 * total_users) / max\n User.all.each do |user|\n user.voting_power = user.voting_power * norm_factor\n user.save!\n end\n \n end", "def highest_average_rating(rideshare)\n highest_rating = 0.0\n best_driver = \"\"\n # call the method from #3\n average_rating(rideshare).map do |driver, rating|\n if rating > highest_rating\n highest_rating = rating\n best_driver = driver\n end\n end\n return best_driver\nend", "def average_rating(var)\n rtngs = ratings.select{ |r| r.beer.var == var }\n rtngs.inject(0.0){|sum, r| sum + r.score } / rtngs.count\n end" ]
[ "0.67777103", "0.6221486", "0.6170849", "0.6123548", "0.60644686", "0.60255337", "0.5953071", "0.5950244", "0.59494865", "0.5943388", "0.5940363", "0.5918166", "0.5913563", "0.5862407", "0.5851387", "0.5818734", "0.5811374", "0.58102465", "0.58041066", "0.5795505", "0.5789432", "0.57877713", "0.57820326", "0.5766352", "0.57540286", "0.5748375", "0.5734375", "0.5725844", "0.57230026", "0.5713095", "0.57082367", "0.57018065", "0.5691296", "0.5687505", "0.56664157", "0.56651914", "0.5659682", "0.564593", "0.562439", "0.56188035", "0.56105036", "0.5595273", "0.55798477", "0.55755", "0.5575031", "0.55683446", "0.5546269", "0.55462635", "0.5545067", "0.55441576", "0.5541228", "0.5537088", "0.5534502", "0.55304193", "0.5524059", "0.5520272", "0.55145067", "0.55123675", "0.55119663", "0.54994667", "0.549369", "0.5486883", "0.5486171", "0.54853904", "0.5484974", "0.5484815", "0.54737777", "0.54727435", "0.54709136", "0.54709136", "0.547038", "0.54668856", "0.5460001", "0.54590553", "0.54582745", "0.54447484", "0.54414916", "0.54394376", "0.5436661", "0.5432448", "0.54318833", "0.542776", "0.5424947", "0.54221827", "0.5421247", "0.5420075", "0.5420062", "0.5419529", "0.5419103", "0.541125", "0.54091376", "0.540873", "0.54082644", "0.5402467", "0.5397605", "0.5388175", "0.53852165", "0.53841066", "0.5383299", "0.537841" ]
0.76755834
0
GET /fish GET /fish.json
def index @fish = Fish.all end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def show\n @fishing_method = FishingMethod.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @fishing_method }\n end\n end", "def show\n @fish_type = FishType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @fish_type }\n end\n end", "def show\n @favorite_flyer = FavoriteFlyer.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @favorite_flyer }\n end\n end", "def show\n @favourite_food = FavouriteFood.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @favourite_food }\n end\n end", "def show\n\n @food = Food.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @food }\n end\n end", "def show\n @food = Food.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @food }\n end\n end", "def show\n json_response(@fav)\n end", "def show\n @foodhamper = Foodhamper.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @foodhamper }\n end\n end", "def show\n @golfer = Golfer.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @golfer }\n end\n end", "def new\n @fishing_method = FishingMethod.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @fishing_method }\n end\n end", "def show\n begin\n @fucker = Fucker.find(params[:id])\n respond_to do |format|\n format.json { render json: @fucker }\n end\n rescue => err\n $log.warn(err)\n respond_to do |format|\n format.json { render json: err, status: :internal_server_error }\n end\n end\n end", "def show\n @family = get_family(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @family }\n end\n end", "def show\n json_response(@food_item)\n end", "def show\n @foam = Foam.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @foam }\n end\n end", "def show\n @spoofer = Spoofer.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @spoofer }\n end\n end", "def show\n\n respond_to do |format|\n format.html { # show.html.erb\n @flyer_info = FlyerInfo.find(params[:id])\n }\n format.json {\n render json: getflyer(params[:id])\n }\n end\n\n end", "def show\n @fav = Fav.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @fav }\n end\n end", "def show\n @foil = Foil.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @foil }\n end\n end", "def show\n @fortune = Fortune.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @fortune }\n end\n end", "def show\n @dish = Dish.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @dish }\n end\n end", "def show\n @fridge = Fridge.find(params[:id])\n @items = @fridge.fridge_items # for _item_list.html.erb\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @fridge }\n end\n end", "def show\n render json: @favorite\n end", "def show\n @restaurant_dish = Restaurant::Dish.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @restaurant_dish }\n end\n end", "def favorite_foods\n get(\"/user/#{@user_id}/foods/log/favorite.json\")\n end", "def show\n render json: @favorite_route\n end", "def show\n @favourite_listing = get_favourite_listing(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @favourite_listing }\n end\n end", "def show\n @family = Family.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @family }\n end\n end", "def show\n @flavor = compute.get_flavor(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @flavor }\n end\n end", "def show\n @flaw = Flaw.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @flaw }\n end\n end", "def show\n render json: @pizza\n end", "def show\n @fooditem = Fooditem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @fooditem }\n end\n end", "def show\n @gig = Gig.find(params[:id])\n\n respond_to do |format|\n format.html {render json: @gig, status: :ok}\n format.json { render json: @gig, status: :ok }\n end\n end", "def create\n @fish = Fish.new(fish_params)\n\n respond_to do |format|\n if @fish.save\n format.html { redirect_to @fish, notice: 'Fish was successfully created.' }\n format.json { render :show, status: :created, location: @fish }\n else\n format.html { render :new }\n format.json { render json: @fish.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @fish = Fish.new(fish_params)\n\n respond_to do |format|\n if @fish.save\n format.html { redirect_to @fish, notice: 'Fish was successfully created.' }\n format.json { render :show, status: :created, location: @fish }\n else\n format.html { render :new }\n format.json { render json: @fish.errors, status: :unprocessable_entity }\n end\n end\n end", "def show\n @kf_course_user_fav = Kf::CourseUserFav.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @kf_course_user_fav }\n end\n end", "def show\n @frais_hebergement = FraisHebergement.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @frais_hebergement }\n end\n end", "def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @dish }\n end\n end", "def show\n @fred = Fred.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @fred }\n end\n end", "def show\n @favorite = Favorite.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n #format.json { render json: @favorite }\n end\n end", "def show\n @forest = Forest.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @forest }\n end\n end", "def create\n @fish = Fish.new(fish_params)\n\n respond_to do |format|\n if @fish.save\n format.html { redirect_to @fish, notice: \"Fish was successfully created.\" }\n format.json { render :show, status: :created, location: @fish }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @fish.errors, status: :unprocessable_entity }\n end\n end\n end", "def food_info(food_id)\n get(\"/foods/#{food_id}.json\")\n end", "def show\n @butterfly = Butterfly.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @butterfly }\n end\n end", "def show\n @glass = Glass.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @glass }\n end\n end", "def new\n @favorite_flyer = FavoriteFlyer.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @favorite_flyer }\n end\n end", "def show\n @frete = Frete.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @frete }\n end\n end", "def flavors()\n return get_request(address(\"/flavors/detail\"), @token)\t\n end", "def show\n family = current_family\n p current_family\n render json: family.as_json\n end", "def show\n @family = Family.find(params[:id])\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @family }\n end\n end", "def index\n @fretes = Frete.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @fretes }\n end\n end", "def show\n @food_recipe = FoodRecipe.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @food_recipe }\n end\n end", "def new\n @fish_type = FishType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @fish_type }\n end\n end", "def show\n @foiltype = Foiltype.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @foiltype }\n end\n end", "def index\n\t @fares = Fare.all\n\n\t respond_to do |format|\n\t\tformat.html # index.html.erb\n\t\tformat.json { render json: @fares }\n\t end\n\tend", "def show\n @fiction = Fiction.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @fiction }\n end\n end", "def show\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @meal }\n end\n end", "def show\n @food = Food.find(params[:id])\n respond_with(@food)\n end", "def show\n @faction = Faction.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @faction }\n end\n end", "def find_food(query)\n get(\"/foods/search.json?query=#{URI.escape(query)}\")\n end", "def consulta\n fiesta = Fiesta.all\n render json: fiesta\n end", "def show\n @kf_diary = Kf::Diary.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @kf_diary }\n end\n end", "def show\n @gpath = Gpath.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gpath }\n end\n end", "def show\n @familium = Familium.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @familium }\n end\n end", "def show\n render json: @food_product\n end", "def show\n @fulcliente = Fulcliente.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @fulcliente }\n end\n end", "def show\n @filial = Filial.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @filial }\n end\n end", "def show\n @favorito = Favorito.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @favorito }\n end\n end", "def index\n @foodhampers = Foodhamper.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @foodhampers }\n end\n end", "def show\n @shunfengch = Shunfengche.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @shunfengch }\n end\n end", "def show\n @gethotel = Gethotel.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gethotel }\n end\n end", "def show\n\t @fare = Fare.find(params[:id])\n\n\t respond_to do |format|\n\t\tformat.html # show.html.erb\n\t\tformat.json { render json: @fare }\n\t end\n\tend", "def update\n respond_to do |format|\n if @fish.update(fish_params)\n format.html { redirect_to @fish, notice: \"Fish was successfully updated.\" }\n format.json { render :show, status: :ok, location: @fish }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @fish.errors, status: :unprocessable_entity }\n end\n end\n end", "def show\n respond_to do |format|\n format.html { render :show }\n format.json { render json: @meal }\n end\n end", "def show\n @heli_kit = HeliKit.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @heli_kit }\n end\n end", "def show\n @gift = Gift.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gift }\n end\n end", "def show\n @father = Father.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @father }\n end\n end", "def show\n if ingredient\n render json: ingredient\n else \n render json: {message: 'Ingredient not found'}\n end\n end", "def show\n @favor = Favor.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @favor }\n end\n end", "def show\n @favor = Favor.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @favor }\n end\n end", "def index\n @glasses = Glass.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @glasses }\n end\n end", "def update\n respond_to do |format|\n if @fish.update(fish_params)\n format.html { redirect_to @fish, notice: 'Fish was successfully updated.' }\n format.json { render :show, status: :ok, location: @fish }\n else\n format.html { render :edit }\n format.json { render json: @fish.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @fish.update(fish_params)\n format.html { redirect_to @fish, notice: 'Fish was successfully updated.' }\n format.json { render :show, status: :ok, location: @fish }\n else\n format.html { render :edit }\n format.json { render json: @fish.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @fish.update(fish_params)\n format.html { redirect_to @fish, notice: 'Fish was successfully updated.' }\n format.json { render :show, status: :ok, location: @fish }\n else\n format.html { render :edit }\n format.json { render json: @fish.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @fish.update(fish_params)\n format.html { redirect_to @fish, notice: 'Fish was successfully updated.' }\n format.json { render :show, status: :ok, location: @fish }\n else\n format.html { render :edit }\n format.json { render json: @fish.errors, status: :unprocessable_entity }\n end\n end\n end", "def show\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @funeral }\n end\n end", "def show\n render json: Festival.build_for(params[:id]).to_json\n end", "def show\n @star_fact = Star::Fact.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @star_fact }\n end\n end", "def show\n require 'net/http'\n require 'json'\n\n response = Net::HTTP.get_response( URI.parse( \"http://freeshit.firebaseio.com/items/%s.json\" % [ params[:id] ] ) );\n\n begin\n @fb_item = JSON.parse(response.body)\n rescue\n render :status => 404, :text => 'Item not found.'\n return\n end\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @fb_item }\n end\n end", "def index\n @spoofers = Spoofer.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @spoofers }\n end\n end", "def show\n @family_crest = FamilyCrest.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @family_crest }\n end\n end", "def show\n @cherup = Cherup.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @cherup }\n end\n end", "def show\n @feeling = Feeling.find(params[:id])\n @sake = Sake.find(params[:sake_id])\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @feeling }\n end\n end", "def index\n render json: @fiestas\n end", "def show\n @cheer = Cheer.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @cheer }\n end\n end", "def show\n @foodlog = Foodlog.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @foodlog }\n end\n end", "def show\n @food_form = FoodForm.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @food_form }\n end\n end", "def set_fish\n @fish = Fish.find(params[:id])\n end" ]
[ "0.7247589", "0.6956957", "0.6747203", "0.66758305", "0.6594654", "0.65888816", "0.65587527", "0.65428066", "0.6526046", "0.6475164", "0.6471221", "0.6466248", "0.64371705", "0.6397099", "0.6332353", "0.6330123", "0.63223624", "0.63073725", "0.6291055", "0.62750745", "0.6267836", "0.6255417", "0.6238218", "0.62329876", "0.622571", "0.62105846", "0.6192817", "0.61836755", "0.61646837", "0.6162067", "0.61614424", "0.61562914", "0.6153278", "0.6153278", "0.6135508", "0.6134618", "0.61337906", "0.61275506", "0.6124549", "0.6120533", "0.6119619", "0.61061436", "0.6105895", "0.6104704", "0.6100813", "0.6093345", "0.6086557", "0.6076056", "0.60725844", "0.6063398", "0.60536677", "0.60517055", "0.6051682", "0.6049435", "0.6045934", "0.60293305", "0.6025778", "0.60234416", "0.6018067", "0.6007027", "0.6003578", "0.5989228", "0.5986717", "0.59802043", "0.5973156", "0.59684813", "0.59613687", "0.5960862", "0.595806", "0.59490883", "0.5939825", "0.5938268", "0.5929331", "0.5922815", "0.591706", "0.59082884", "0.5907846", "0.59078306", "0.59078306", "0.59059656", "0.5897187", "0.5897187", "0.5897187", "0.5897187", "0.5896843", "0.58901507", "0.58896995", "0.5887675", "0.5887425", "0.5886304", "0.5885621", "0.58746624", "0.58737284", "0.5856656", "0.58563924", "0.585005", "0.5843596" ]
0.64805937
11
GET /fish/1 GET /fish/1.json
def show end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def show\n @fishing_method = FishingMethod.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @fishing_method }\n end\n end", "def show\n @fish_type = FishType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @fish_type }\n end\n end", "def show\n @favorite_flyer = FavoriteFlyer.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @favorite_flyer }\n end\n end", "def show\n\n @food = Food.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @food }\n end\n end", "def show\n @food = Food.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @food }\n end\n end", "def show\n @favourite_food = FavouriteFood.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @favourite_food }\n end\n end", "def show\n @golfer = Golfer.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @golfer }\n end\n end", "def show\n begin\n @fucker = Fucker.find(params[:id])\n respond_to do |format|\n format.json { render json: @fucker }\n end\n rescue => err\n $log.warn(err)\n respond_to do |format|\n format.json { render json: err, status: :internal_server_error }\n end\n end\n end", "def show\n @foodhamper = Foodhamper.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @foodhamper }\n end\n end", "def show\n @foam = Foam.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @foam }\n end\n end", "def show\n @family = get_family(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @family }\n end\n end", "def show\n @foil = Foil.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @foil }\n end\n end", "def show\n @dish = Dish.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @dish }\n end\n end", "def show\n @fav = Fav.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @fav }\n end\n end", "def show\n\n respond_to do |format|\n format.html { # show.html.erb\n @flyer_info = FlyerInfo.find(params[:id])\n }\n format.json {\n render json: getflyer(params[:id])\n }\n end\n\n end", "def index\n @fish = Fish.all\n end", "def index\n @fish = Fish.all\n end", "def index\n @fish = Fish.all\n end", "def index\n @fish = Fish.all\n end", "def show\n @gig = Gig.find(params[:id])\n\n respond_to do |format|\n format.html {render json: @gig, status: :ok}\n format.json { render json: @gig, status: :ok }\n end\n end", "def show\n @spoofer = Spoofer.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @spoofer }\n end\n end", "def show\n @fred = Fred.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @fred }\n end\n end", "def show\n @fortune = Fortune.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @fortune }\n end\n end", "def show\n @fooditem = Fooditem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @fooditem }\n end\n end", "def show\n json_response(@fav)\n end", "def show\n @fiction = Fiction.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @fiction }\n end\n end", "def new\n @fishing_method = FishingMethod.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @fishing_method }\n end\n end", "def show\n @restaurant_dish = Restaurant::Dish.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @restaurant_dish }\n end\n end", "def show\n @forest = Forest.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @forest }\n end\n end", "def show\n @foiltype = Foiltype.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @foiltype }\n end\n end", "def show\n @familium = Familium.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @familium }\n end\n end", "def show\n @fridge = Fridge.find(params[:id])\n @items = @fridge.fridge_items # for _item_list.html.erb\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @fridge }\n end\n end", "def show\n @family = Family.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @family }\n end\n end", "def show\n @food_recipe = FoodRecipe.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @food_recipe }\n end\n end", "def show\n @flaw = Flaw.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @flaw }\n end\n end", "def show\n render json: Festival.build_for(params[:id]).to_json\n end", "def show\n json_response(@food_item)\n end", "def show\n @glass = Glass.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @glass }\n end\n end", "def show\n @favourite_listing = get_favourite_listing(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @favourite_listing }\n end\n end", "def show\n @favorite = Favorite.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n #format.json { render json: @favorite }\n end\n end", "def show\n @flavor = compute.get_flavor(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @flavor }\n end\n end", "def show\n @butterfly = Butterfly.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @butterfly }\n end\n end", "def food_info(food_id)\n get(\"/foods/#{food_id}.json\")\n end", "def show\n render json: @favorite_route\n end", "def favorite_foods\n get(\"/user/#{@user_id}/foods/log/favorite.json\")\n end", "def show\n @gpath = Gpath.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gpath }\n end\n end", "def show\n @frete = Frete.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @frete }\n end\n end", "def show\n @filial = Filial.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @filial }\n end\n end", "def show\n render json: @favorite\n end", "def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @dish }\n end\n end", "def show\n @food = Food.find(params[:id])\n respond_with(@food)\n end", "def show\n @frais_hebergement = FraisHebergement.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @frais_hebergement }\n end\n end", "def show\n params.require(%i[id])\n render json: Ingredient.find_by!(id: params[:id])\n end", "def show\n @father = Father.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @father }\n end\n end", "def show\n @family = Family.find(params[:id])\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @family }\n end\n end", "def show\n @favorito = Favorito.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @favorito }\n end\n end", "def show\n @shunfengch = Shunfengche.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @shunfengch }\n end\n end", "def show\n render json: @pizza\n end", "def show\n @fulcliente = Fulcliente.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @fulcliente }\n end\n end", "def show\n @heli_kit = HeliKit.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @heli_kit }\n end\n end", "def show\n @faction = Faction.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @faction }\n end\n end", "def show\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @meal }\n end\n end", "def show\n @phile = File.read(params[:id].gsub('DOTDOT','.').gsub('SLASHSLASH','/'))\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: {content: @phile} }\n end\n end", "def show\n @koti = Koti.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @koti }\n end\n end", "def show\n @favor = Favor.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @favor }\n end\n end", "def show\n @favor = Favor.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @favor }\n end\n end", "def show\n @feeling = Feeling.find(params[:id])\n @sake = Sake.find(params[:sake_id])\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @feeling }\n end\n end", "def show\n @shichoson = Shichoson.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @shichoson }\n end\n end", "def show\n params.require(%i[id])\n render json: Beverage.find_by!(id: params[:id])\n end", "def show\n @foto = Foto.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @foto }\n end\n end", "def show\n @cherup = Cherup.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @cherup }\n end\n end", "def show\n @cheer = Cheer.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @cheer }\n end\n end", "def new\n @fish_type = FishType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @fish_type }\n end\n end", "def show\n @squish = Squish.find(params[:id])\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @squish }\n end\n end", "def show\n @fabric = Fabric.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @fabric }\n end\n end", "def new\n @favorite_flyer = FavoriteFlyer.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @favorite_flyer }\n end\n end", "def get\n @dish = Dish.find_by_id(params[:id]) || Dish.find_or_create_by_name(params[:name])\n respond_to do |format|\n format.json { render json: @dish.id }\n end\n end", "def show\n @gift = Gift.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gift }\n end\n end", "def index\n @foodhampers = Foodhamper.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @foodhampers }\n end\n end", "def show\n @hive = Hive.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @hive }\n end\n end", "def show\n @foodlog = Foodlog.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @foodlog }\n end\n end", "def show\n @star_fact = Star::Fact.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @star_fact }\n end\n end", "def show\n @nfer = Nfer.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @nfer }\n end\n end", "def show\n @hetong = Hetong.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @hetong }\n end\n end", "def index\n @fretes = Frete.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @fretes }\n end\n end", "def show\n @favorite_bundle = FavoriteBundle.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @favorite_bundle }\n end\n end", "def show\n respond_to do |format|\n format.html { render :show }\n format.json { render json: @meal }\n end\n end", "def show\n @flight = Flight.find(params[:id])\n render json: @flight\n end", "def show\n @book_shelf = BookShelf.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @book_shelf }\n end\n end", "def show\n @kf_diary = Kf::Diary.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @kf_diary }\n end\n end", "def show\n @galeria = Galeria.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @galeria }\n end\n end", "def show\n @gig_request = GigRequest.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gig_request }\n end\n end", "def index\n @glasses = Glass.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @glasses }\n end\n end", "def show\n @wish = Wish.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @wish }\n end\n end", "def show\n recipe = Recipe.find(params[:id])\n # recipes = Recipe.find_by(params[:id])\n # render json: recipe\n render json: recipe\n end", "def show\n @foto_galeri = FotoGaleri.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @foto_galeri }\n end\n end", "def index\n @spoofers = Spoofer.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @spoofers }\n end\n end", "def index\n\t @fares = Fare.all\n\n\t respond_to do |format|\n\t\tformat.html # index.html.erb\n\t\tformat.json { render json: @fares }\n\t end\n\tend", "def create\n @fish = Fish.new(fish_params)\n\n respond_to do |format|\n if @fish.save\n format.html { redirect_to @fish, notice: 'Fish was successfully created.' }\n format.json { render :show, status: :created, location: @fish }\n else\n format.html { render :new }\n format.json { render json: @fish.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @fish = Fish.new(fish_params)\n\n respond_to do |format|\n if @fish.save\n format.html { redirect_to @fish, notice: 'Fish was successfully created.' }\n format.json { render :show, status: :created, location: @fish }\n else\n format.html { render :new }\n format.json { render json: @fish.errors, status: :unprocessable_entity }\n end\n end\n end", "def show\n family = current_family\n p current_family\n render json: family.as_json\n end" ]
[ "0.72222954", "0.70915884", "0.679114", "0.6745848", "0.6732362", "0.6686373", "0.66577846", "0.6630204", "0.66273814", "0.6578545", "0.6541784", "0.6512644", "0.6469412", "0.64474076", "0.6445051", "0.64307207", "0.64307207", "0.64307207", "0.64307207", "0.6417912", "0.64058846", "0.63798344", "0.6375485", "0.63656795", "0.6347229", "0.63444966", "0.63409245", "0.6339422", "0.63122565", "0.630351", "0.6301632", "0.6300391", "0.6299677", "0.6298005", "0.62856865", "0.6282498", "0.6281437", "0.62790984", "0.62682176", "0.6264372", "0.62511635", "0.6249293", "0.624881", "0.6227547", "0.6223229", "0.6187932", "0.6181868", "0.61683166", "0.61665523", "0.6150884", "0.61475974", "0.61461675", "0.6142307", "0.61420774", "0.6134731", "0.61303306", "0.61280185", "0.6125818", "0.61243236", "0.61159134", "0.6113445", "0.6099383", "0.6099317", "0.6099154", "0.6095957", "0.6095957", "0.6091782", "0.6083782", "0.6079445", "0.60789317", "0.60747105", "0.60722524", "0.6072027", "0.60676694", "0.6064793", "0.60618365", "0.6061184", "0.6059742", "0.6059733", "0.6055814", "0.60512334", "0.60470784", "0.60402447", "0.6032897", "0.6031297", "0.60268646", "0.60262483", "0.60250837", "0.601979", "0.60184985", "0.6010639", "0.6006027", "0.60052633", "0.6004545", "0.59967023", "0.5996209", "0.5993874", "0.59927875", "0.5992681", "0.5992681", "0.59906584" ]
0.0
-1
POST /fish POST /fish.json
def create @fish = Fish.new(fish_params) respond_to do |format| if @fish.save format.html { redirect_to @fish, notice: 'Fish was successfully created.' } format.json { render :show, status: :created, location: @fish } else format.html { render :new } format.json { render json: @fish.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create\n @fish = Fish.new(fish_params)\n\n respond_to do |format|\n if @fish.save\n format.html { redirect_to @fish, notice: \"Fish was successfully created.\" }\n format.json { render :show, status: :created, location: @fish }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @fish.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @fish = Fish.new(fish_params)\n @fish.user_id = current_user.id\n\n respond_to do |format|\n if @fish.save\n format.html { redirect_to @fish, notice: 'Fish was successfully created.' }\n format.json { render :show, status: :created, location: @fish }\n else\n format.html { render :new }\n format.json { render json: @fish.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @fishing_method = FishingMethod.new(params[:fishing_method])\n\n respond_to do |format|\n if @fishing_method.save\n format.html { redirect_to @fishing_method, notice: 'Fishing method was successfully created.' }\n format.json { render json: @fishing_method, status: :created, location: @fishing_method }\n else\n format.html { render action: \"new\" }\n format.json { render json: @fishing_method.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @fish = Fish.new(fish_params)\n\t\t@user = User.find_by email: params[:user][:email]\n\t\[email protected]_id = @user.id\n\t\tif @fish.save\n\t\t\[email protected]_photo = \"fish#{@fish.id}.jpeg\"\n\t\t\[email protected]\n\t\t\timage_convert(@fish.id)\n \t@weather = @fish.weathers.create(weather_params)\n \trespond_to do |format|\n \tif @weather.save\n \tformat.html { redirect_to @fish, notice: 'Fish was successfully created.' }\n \tformat.json { render action: 'show', status: :created, location: @fish }\n \telse\n \tformat.html { render action: 'new' }\n \tformat.json { render json: @fish.errors, status: :unprocessable_entity }\n \tend\n \tend\n\t\tend\n end", "def fish_params\n params.require(:fish).permit(:name, :description, :sex, :is_neuter)\n end", "def create\n @fishery = @country.fisheries.build(fishery_params)\n\n respond_to do |format|\n if @fishery.save\n format.html { redirect_to country_fisheries_path(@country), notice: \"Fishery was successfully created.\" }\n format.json { render :show, status: :created, location: @fishery }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @fishery.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @fish_type = FishType.new(params[:fish_type])\n\n respond_to do |format|\n if @fish_type.save\n format.html { redirect_to @fish_type, notice: 'Fish type was successfully created.' }\n format.json { render json: @fish_type, status: :created, location: @fish_type }\n else\n format.html { render action: \"new\" }\n format.json { render json: @fish_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def fish_params\n params.require(:fish).permit(:user_id, :fish_type, :fish_length, :fish_weight, :caught_on, :longitude, :latitude, :caught_date, :fish_photo)\n end", "def fish_params\n params.require(:fish).permit(:name, :description, :price, :user_id)\n end", "def fish_params\n params.require(:fish).permit(:name, :age, :enjoys, :species)\n end", "def create\n @fish_poly = FishPoly.new(fish_poly_params)\n\n respond_to do |format|\n if @fish_poly.save\n format.html { redirect_to @fish_poly, notice: 'Fish poly was successfully created.' }\n format.json { render :show, status: :created, location: @fish_poly }\n else\n format.html { render :new }\n format.json { render json: @fish_poly.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n if params[:tournament_id].present?\n @tournament = Tournament.find(params[:tournament_id])\n @fish = @tournament.fish.new(fish_params)\n else\n @fish = Fish.new(fish_params)\n end\n @fish.member = @current_member\n respond_to do |format|\n if @fish.save\n format.html { redirect_to @fish.tournament, notice: 'Fish was successfully created.' }\n format.json { render :show, status: :created, location: @fish }\n else\n format.html { render :new }\n format.json { render json: @fish.errors, status: :unprocessable_entity }\n end\n end\n end", "def fish_params\n params.require(:fish).permit(:name, :latin_name, :description)\n end", "def create\n @fish_product = FishProduct.new(fish_product_params)\n\n respond_to do |format|\n if @fish_product.save\n format.html { redirect_to @fish_product, notice: 'Fish product was successfully created.' }\n format.json { render :show, status: :created, location: @fish_product }\n else\n format.html { render :new }\n format.json { render json: @fish_product.errors, status: :unprocessable_entity }\n end\n end\n end", "def process_post\n service.sign_up_fisherman(\n JSON.parse(request.body.to_s).symbolize_keys\n ).on(\n fishing_application_succeeded: ->(result) {\n response.headers['Content-Type'] = \"application/json\"\n response.body = result.to_json\n true\n },\n fishing_application_conflicts: ->(result) {\n render_json_error_response(\n error: \"command_failed_validation\", message: result.fetch(:message)\n )\n 409\n },\n fishing_application_invalid: ->(result) {\n render_json_error_response(\n error: \"command_failed_validation\", message: result.fetch(:message)\n )\n 422\n }\n )\n end", "def new\n @fishing_method = FishingMethod.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @fishing_method }\n end\n end", "def fish_params\n params.require(:fish).permit(:color_id, :weight, :over_28, :tournament_id, :member_id, :returned, :image, :remove_image)\n end", "def create\n @frosting_flavor = FrostingFlavor.new(frosting_flavor_params)\n\n respond_to do |format|\n if @frosting_flavor.save\n format.html { redirect_to @frosting_flavor, notice: 'Frosting flavor was successfully created.' }\n format.json { render :show, status: :created, location: @frosting_flavor }\n else\n format.html { render :new }\n format.json { render json: @frosting_flavor.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @favorite_flyer = FavoriteFlyer.new(params[:favorite_flyer])\n\n respond_to do |format|\n if @favorite_flyer.save\n format.html { redirect_to @favorite_flyer, notice: 'Favorite flyer was successfully created.' }\n format.json { render json: @favorite_flyer, status: :created, location: @favorite_flyer }\n else\n format.html { render action: \"new\" }\n format.json { render json: @favorite_flyer.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n redirect_to root_url\n\n # @fluke = Fluke.new(fluke_params)\n\n # respond_to do |format|\n # if @fluke.save\n # format.html { redirect_to @fluke, notice: 'Fluke was successfully created.' }\n # format.json { render :show, status: :created, location: @fluke }\n # else\n # format.html { render :new }\n # format.json { render json: @fluke.errors, status: :unprocessable_entity }\n # end\n # end\n end", "def update\n respond_to do |format|\n if @fish.update(fish_params)\n format.html { redirect_to @fish, notice: \"Fish was successfully updated.\" }\n format.json { render :show, status: :ok, location: @fish }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @fish.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @fast_food = FastFood.new(fast_food_params)\n\n respond_to do |format|\n if @fast_food.save\n format.html { redirect_to @fast_food, notice: 'Fast food was successfully created.' }\n format.json { render :show, status: :created, location: @fast_food }\n else\n format.html { render :new }\n format.json { render json: @fast_food.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @funkce = Funkce.new(funkce_params)\n\n respond_to do |format|\n if @funkce.save\n format.html { redirect_to @funkce, notice: 'Funkce was successfully created.' }\n format.json { render action: 'show', status: :created, location: @funkce }\n else\n format.html { render action: 'new' }\n format.json { render json: @funkce.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @fish_type = FishType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @fish_type }\n end\n end", "def create\n @fokey = Fokey.new(fokey_params)\n\n respond_to do |format|\n if @fokey.save\n format.html { redirect_to @fokey, notice: 'Fokey was successfully created.' }\n format.json { render :show, status: :created, location: @fokey }\n else\n format.html { render :new }\n format.json { render json: @fokey.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @fish.update(fish_params)\n format.html { redirect_to @fish, notice: 'Fish was successfully updated.' }\n format.json { render :show, status: :ok, location: @fish }\n else\n format.html { render :edit }\n format.json { render json: @fish.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @fish.update(fish_params)\n format.html { redirect_to @fish, notice: 'Fish was successfully updated.' }\n format.json { render :show, status: :ok, location: @fish }\n else\n format.html { render :edit }\n format.json { render json: @fish.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @fish.update(fish_params)\n format.html { redirect_to @fish, notice: 'Fish was successfully updated.' }\n format.json { render :show, status: :ok, location: @fish }\n else\n format.html { render :edit }\n format.json { render json: @fish.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @fish.update(fish_params)\n format.html { redirect_to @fish, notice: 'Fish was successfully updated.' }\n format.json { render :show, status: :ok, location: @fish }\n else\n format.html { render :edit }\n format.json { render json: @fish.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_fish\n @fish = Fish.find(params[:id])\n end", "def set_fish\n @fish = Fish.find(params[:id])\n end", "def set_fish\n @fish = Fish.find(params[:id])\n end", "def set_fish\n @fish = Fish.find(params[:id])\n end", "def set_fish\n @fish = Fish.find(params[:id])\n end", "def set_fish\n @fish = Fish.find(params[:id])\n end", "def create\n @food = @fridge.foods.create(food_params)\n respond_with @food, location: -> { kitchen_board_path }\n end", "def create\n render json: Dish.create(dish_params)\n end", "def create\n @favourite_food = FavouriteFood.new(params[:favourite_food])\n\n respond_to do |format|\n if @favourite_food.save\n format.html { redirect_to @favourite_food, notice: 'Favourite food was successfully created.' }\n format.json { render json: @favourite_food, status: :created, location: @favourite_food }\n else\n format.html { render action: \"new\" }\n format.json { render json: @favourite_food.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @foodhamper = Foodhamper.new(params[:foodhamper])\n\n respond_to do |format|\n if @foodhamper.save\n format.html { redirect_to @foodhamper, notice: 'Foodhamper was successfully created.' }\n format.json { render json: @foodhamper, status: :created, location: @foodhamper }\n else\n format.html { render action: \"new\" }\n format.json { render json: @foodhamper.errors, status: :unprocessable_entity }\n end\n end\n end", "def fish_params\n params.require(:fish).permit(:genus, :commonname, :description, :thumbnail,files:[])\n end", "def create\n @flower = Flower.new(params[:flower])\n\n respond_to do |format|\n if @flower.save\n format.html { redirect_to @flower, notice: 'Flower was successfully created.' }\n format.json { render json: @flower, status: :created, location: @flower }\n else\n format.html { render action: \"new\" }\n format.json { render json: @flower.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @favorite_dish = FavoriteDish.new(favorite_dish_params)\n\n respond_to do |format|\n if @favorite_dish.save\n format.html { redirect_to @favorite_dish, notice: 'Favorite dish was successfully created.' }\n format.json { render :show, status: :created, location: @favorite_dish }\n else\n format.html { render :new }\n format.json { render json: @favorite_dish.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @flower = Flower.new(flower_params)\n\n respond_to do |format|\n if @flower.save\n format.html { redirect_to @flower, notice: 'Flower was successfully created.' }\n format.json { render :show, status: :created, location: @flower }\n else\n format.html { render :new }\n format.json { render json: @flower.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @satish = Satish.new(satish_params)\n\n respond_to do |format|\n if @satish.save\n format.html { redirect_to @satish, notice: 'Satish was successfully created.' }\n format.json { render :show, status: :created, location: @satish }\n else\n format.html { render :new }\n format.json { render json: @satish.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @fishing_area = FishingArea.new(fishing_area_params)\n @fishing_area.user = current_user\n\n respond_to do |format|\n if @fishing_area.save\n format.html { redirect_to @fishing_area, notice: \"Fishing area was successfully created.\" }\n format.json { render :show, status: :created, location: @fishing_area }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @fishing_area.errors, status: :unprocessable_entity }\n end\n end\n end", "def fishery_params\n params.require(:fishery).permit(:name, :description, :country_id, :licence_issuer_id)\n end", "def create\n @fridge = Fridge.new(params[:fridge])\n\n respond_to do |format|\n if @fridge.save\n format.html { redirect_to @fridge, notice: 'Fridge was successfully created.' }\n format.json { render json: @fridge, status: :created, location: @fridge }\n else\n format.html { render action: \"new\" }\n format.json { render json: @fridge.errors, status: :unprocessable_entity }\n end\n end\n end", "def buy_fish(fish_name)\n fish = Fish.new(fish_name)\n self.pets[:fishes] << fish\n end", "def new\n @fish.Fish.new\n end", "def create\n @fact = @cat.facts.create!({ fact: api_request })\n if @fact.save\n render json: @fact\n else\n render error: { message: \"Não foi possível criar esse fato para este gatinho! :(\" }, status: 400\n end\n end", "def create\n @fat = Fat.new(fat_params)\n\n respond_to do |format|\n if @fat.save\n format.html { redirect_to @fat, notice: 'Fat was successfully created.' }\n format.json { render :show, status: :created, location: @fat }\n else\n format.html { render :new }\n format.json { render json: @fat.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @fip = Fip.new(fip_params)\n\n respond_to do |format|\n if @fip.save\n format.html { redirect_to @fip, notice: 'Fip was successfully created.' }\n format.json { render :show, status: :created, location: @fip }\n else\n format.html { render :new }\n format.json { render json: @fip.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @favorite = Favorite.new(favorite_params)\n if @favorite.save\n render json: FavoriteSerializer.new(@favorite), status: :created\n else\n render json: @favorite.errors.full_messages.to_sentence, status: :unprocessable_entity\n end\n end", "def create\n @food = Food.new(params[:food])\n\n respond_to do |format|\n if @food.save\n format.html { redirect_to @food, notice: \"Piatto creato correttamente.\" }\n format.json { render json: @food, status: :created, location: @food }\n else\n format.html { render action: \"new\" }\n format.json { render json: @food.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @fish.update(fish_params)\n format.html { redirect_to @fish, notice: 'Fish was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @fish.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @falta = Falta.new(falta_params)\n\n respond_to do |format|\n if @falta.save\n format.html { redirect_to @falta, notice: \"Falta was successfully created.\" }\n format.json { render :show, status: :created, location: @falta }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @falta.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @faktury = Faktury.new(faktury_params)\n\n respond_to do |format|\n if @faktury.save\n format.html { redirect_to @faktury, notice: 'Faktury was successfully created.' }\n format.json { render :show, status: :created, location: @faktury }\n else\n format.html { render :new }\n format.json { render json: @faktury.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @flavor = Flavor.new(flavor_params)\n\n respond_to do |format|\n if @flavor.save\n format.html { redirect_to @flavor, notice: 'Flavor was successfully created.' }\n format.json { render :show, status: :created, location: @flavor }\n else\n format.html { render :new }\n format.json { render json: @flavor.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @fridge_food = FridgeFood.new(params[:fridge_food])\n\n respond_to do |format|\n if @fridge_food.save\n format.html { redirect_to(@fridge_food, :notice => 'Fridge food was successfully created.') }\n format.xml { render :xml => @fridge_food, :status => :created, :location => @fridge_food }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @fridge_food.errors, :status => :unprocessable_entity }\n end\n end\n end", "def show\n @fishing_method = FishingMethod.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @fishing_method }\n end\n end", "def create\n @dish = Dish.new(params[:dish])\n\n respond_to do |format|\n if @dish.save\n format.html { redirect_to @dish, notice: 'Dish was successfully created.' }\n format.json { render json: @dish, status: :created, location: @dish }\n else\n format.html { render action: \"new\" }\n format.json { render json: @dish.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @dish = Dish.new(params[:dish])\n\n respond_to do |format|\n if @dish.save\n format.html { redirect_to @dish, notice: 'Dish was successfully created.' }\n format.json { render json: @dish, status: :created, location: @dish }\n else\n format.html { render action: \"new\" }\n format.json { render json: @dish.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n # {\"vcpus\": 1, \"disk\": 1, \"name\": \"test\", \"rxtx_factor\": 1, \"OS-FLV-EXT-DATA:ephemeral\": 1, \"ram\": 512, \"id\": 6, \"swap\": 1}}'\n @flavor = compute.create_flavor(\"rxtx_factor\"=>1,\"OS-FLV-EXT-DATA:ephemeral\"=>params[:ephemeral],:vcpus=>params[:vcpus],:disk=>params[:disk],:name=>params[:name],:ram=>params[:ram],:id=>params[:id],:swap=>params[:swap])\n\n respond_to do |format|\n format.html { redirect_to flavors_path, :notice => 'Flavor was successfully created.' }\n format.json { render :json => @flavor, :status => :created, :location => @flavor }\n end\n end", "def create\n @food = Food.new(food_params)\n respond_to do |format|\n if @food.save\n format.html { redirect_to @food, notice: 'Food was successfully created.' }\n format.json { render :show, status: :created, location: @food }\n else\n format.html { render :new }\n format.json { render json: @food.errors, status: :unprocessable_entity }\n end\n end\n end", "def creacion\n fiesta = Fiesta.new (params[:id])\n if Fiesta.save\n puts \"su fiesta a sido registrada\"\n else \n puts \"su fiesta no a sido registrada\"\n end\n render = json: fiesta \n end", "def create\n @dish = Dish.new(dish_params)\n\n respond_to do |format|\n if @dish.save\n format.html { redirect_to @dish, notice: 'Блюдо создано.' }\n format.json { render :show, status: :created, location: @dish }\n else\n format.html { render :new }\n format.json { render json: @dish.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @dish = @cafeteria.dishes.new(dish_params)\n\n respond_to do |format|\n if @dish.save\n format.html { redirect_to @cafeteria, notice: 'El plato se ha creado.' }\n format.json { render :show, status: :created, location: @dish }\n else\n format.html { redirect_to @cafeteria, alert: 'No se pudo crear el plato.' }\n format.json { render json: @dish.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @favorite_flyer = FavoriteFlyer.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @favorite_flyer }\n end\n end", "def create\n @fooddiary = @food.fooddiaries.new(fooddiary_params)\n @fooddiary.user_id = current_user.id\n @fooddiary.name = @food.name\n @fooddiary.eiweiß = @food.eiweiß\n @fooddiary.fett = @food.fett\n @fooddiary.kohlenhydrate = @food.kohlenhydrate\n @fooddiary.kalorien = @food.kalorien\n respond_to do |format|\n if @fooddiary.save\n format.html { redirect_to foods_path }\n format.json { render :show, status: :created, location: @fooddiary }\n else\n format.html { render :new }\n format.json { render json: @fooddiary.errors, status: :unprocessable_entity }\n end\n end\n end", "def buy_fish(name)\n#knows about its fishes\n pets[:fishes] << Fish.new(name)\n end", "def create\n @dish = Dish.new(dish_params)\n\n respond_to do |format|\n if @dish.save\n format.html { redirect_to @dish, notice: 'Dish was successfully created.' }\n format.json { render :show, status: :created, location: @dish }\n else\n format.html { render :new }\n format.json { render json: @dish.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @featuring = Featuring.new(featuring_params)\n\n respond_to do |format|\n if @featuring.save\n format.html { redirect_to @featuring, notice: 'Featuring was successfully created.' }\n format.json { render :show, status: :created, location: @featuring }\n else\n format.html { render :new }\n format.json { render json: @featuring.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @hefan = Hefan.new(hefan_params)\n\n respond_to do |format|\n if @hefan.save\n format.html { redirect_to @hefan, notice: 'Hefan was successfully created.' }\n format.json { render action: 'show', status: :created, location: @hefan }\n else\n format.html { render action: 'new' }\n format.json { render json: @hefan.errors, status: :unprocessable_entity }\n end\n end\n end", "def buy_fish(name)\n fish = Fish.new(name)\n @pets[:fishes] << fish\n end", "def buy_fish(name)\n fish = Fish.new(name)\n @pets[:fishes] << fish\n end", "def create\n @user_food = UserFood.new(user_food_params)\n\n respond_to do |format|\n if @user_food.save\n format.html { redirect_to @user_food, notice: 'User food was successfully created.' }\n format.json { render :show, status: :created, location: @user_food }\n else\n format.html { render :new }\n format.json { render json: @user_food.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @garnish = Garnish.new(garnish_params)\n\n respond_to do |format|\n if @garnish.save\n format.html { redirect_to garnishes_url, notice: 'Garnish was successfully created.' }\n format.json { render :show, status: :created, location: @garnish }\n else\n format.html { render :new }\n format.json { render json: @garnish.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @fondo = Fondo.new(fondo_params)\n\n respond_to do |format|\n if @fondo.save\n format.html { redirect_to @fondo, notice: 'Fondo was successfully created.' }\n format.json { render :show, status: :created, location: @fondo }\n else\n format.html { render :new }\n format.json { render json: @fondo.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @spoofer = Spoofer.new\n\n\n\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @spoofer }\n end\n end", "def start_fishing\n api_post(@current_resource.body.links[\"start_fishing\"][\"href\"], \"foo\")\n end", "def create\n @foam = Foam.new(params[:foam])\n\n respond_to do |format|\n if @foam.save\n format.html { redirect_to @foam, notice: 'Foam was successfully created.' }\n format.json { render json: @foam, status: :created, location: @foam }\n else\n format.html { render action: \"new\" }\n format.json { render json: @foam.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\n\n\n @kefu = Kefu.new(kefu_params)\n respond_to do |format|\n if @kefu.save\n format.html { redirect_to adminkefus_path, notice: 'Test was successfully created.' }\n format.json { render :show, status: :created, location: @adminkefu }\n else\n format.html { render :new }\n format.json { render json: @adminkefu.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @dish_feature = @store.dish_features.build(dish_feature_params)\n\n respond_to do |format|\n if @dish_feature.save\n format.html { redirect_to store_dish_features_url(@store), notice: 'Dish feature was successfully created.' }\n format.json { render action: 'show', status: :created, location: @dish_feature }\n else\n format.html { render action: 'new' }\n format.json { render json: @dish_feature.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @restaurant_dish = Restaurant::Dish.new(params[:restaurant_dish])\n\n respond_to do |format|\n if @restaurant_dish.save\n format.html { redirect_to @restaurant_dish, notice: 'Dish was successfully created.' }\n format.json { render json: @restaurant_dish, status: :created, location: @restaurant_dish }\n else\n format.html { render action: \"new\" }\n format.json { render json: @restaurant_dish.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @fase = Fase.new(fase_params)\n\n respond_to do |format|\n if @fase.save\n format.html { redirect_to @fase, notice: 'Fase was successfully created.' }\n format.json { render :show, status: :created, location: @fase }\n else\n format.html { render :new }\n format.json { render json: @fase.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n megam_rest.post_promos(to_hash) #WONT BE USED AS OF NOW\n end", "def create\n @frat = Frat.new(frat_params)\n\n respond_to do |format|\n if @frat.save\n format.html { redirect_to @frat, notice: 'Frat was successfully created.' }\n format.json { render action: 'show', status: :created, location: @frat }\n else\n format.html { render action: 'new' }\n format.json { render json: @frat.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @flower = current_user.flowers.build(flower_params)\n\n respond_to do |format|\n if @flower.save\n format.html { redirect_to @flower, notice: 'Flower was successfully created.' }\n format.json { render :show, status: :created, location: @flower }\n else\n format.html { render :new }\n format.json { render json: @flower.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @inchicken_dish = InchickenDish.new(inchicken_dish_params)\n\n respond_to do |format|\n if @inchicken_dish.save\n format.html { redirect_to @inchicken_dish, notice: 'Inchicken dish was successfully created.' }\n format.json { render :show, status: :created, location: @inchicken_dish }\n else\n format.html { render :new }\n format.json { render json: @inchicken_dish.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n megam_rest.post_appdefn(to_hash)\n end", "def create\n @stinsfo = Stinsfo.new(stinsfo_params)\n\n respond_to do |format|\n if @stinsfo.save\n format.html { redirect_to @stinsfo, notice: 'Stinsfo was successfully created.' }\n format.json { render :show, status: :created, location: @stinsfo }\n else\n format.html { render :new }\n format.json { render json: @stinsfo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @beef = Beef.new(beef_params)\n\n respond_to do |format|\n if @beef.save\n format.html { redirect_to @beef, notice: 'Beef was successfully created.' }\n format.json { render :show, status: :created, location: @beef }\n else\n format.html { render :new }\n format.json { render json: @beef.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @favour = Favour.new(favour_params)\n\n respond_to do |format|\n if @favour.save\n format.html { redirect_to @favour, notice: 'Favour was successfully created.' }\n format.json { render :show, status: :created, location: @favour }\n else\n format.html { render :new }\n format.json { render json: @favour.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @fiestum = Fiestum.new(fiestum_params)\n\n respond_to do |format|\n if @fiestum.save\n format.html { redirect_to @fiestum, notice: 'Fiestum was successfully created.' }\n format.json { render :show, status: :created, location: @fiestum }\n else\n format.html { render :new }\n format.json { render json: @fiestum.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @frais_hebergement = FraisHebergement.new(params[:frais_hebergement])\n\n respond_to do |format|\n if @frais_hebergement.save\n format.html { redirect_to @frais_hebergement, :notice => 'Le frais d\\'hébergement a bien été créé' }\n format.json { render :json => @frais_hebergement, :status => :created, :location => @frais_hebergement }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @frais_hebergement.errors, :status => :unprocessable_entity }\n end\n end\n end", "def buy_fish(name)\n @pets[:fishes] << Fish.new(name)\n end", "def create\n @feild = Feild.new(feild_params)\n\n respond_to do |format|\n if @feild.save\n format.html { redirect_to @feild, notice: 'Feild was successfully created.' }\n format.json { render :show, status: :created, location: @feild }\n else\n format.html { render :new }\n format.json { render json: @feild.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @animal_food = AnimalFood.new(animal_food_params)\n\n respond_to do |format|\n if @animal_food.save\n format.html { redirect_to @animal_food, notice: \"Animal food was successfully created.\" }\n format.json { render :show, status: :created, location: @animal_food }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @animal_food.errors, status: :unprocessable_entity }\n end\n end\n end", "def fish_product_params\n params.require(:fish_product).permit(:code, :name, :fish_category_id, :fish_unit_id, :stock, :purchase_price, :sale_price, :picture, :is_valid)\n end" ]
[ "0.75316876", "0.72104937", "0.6981267", "0.69333696", "0.6887857", "0.68178904", "0.6796484", "0.674556", "0.67100996", "0.6703341", "0.6666068", "0.6626096", "0.6478269", "0.6465013", "0.63797915", "0.63763463", "0.63742584", "0.62729216", "0.6198163", "0.6152941", "0.6139421", "0.6104439", "0.60507077", "0.603692", "0.6019841", "0.601276", "0.601276", "0.601276", "0.601276", "0.59635925", "0.59635925", "0.59635925", "0.59635925", "0.59635925", "0.59635925", "0.59410226", "0.59359634", "0.5922676", "0.58820623", "0.5879874", "0.58702594", "0.5844675", "0.582325", "0.58226955", "0.5820064", "0.5817381", "0.5813672", "0.58133423", "0.58073527", "0.5775171", "0.5774655", "0.5772379", "0.5763998", "0.5728093", "0.57249343", "0.5718882", "0.57174283", "0.56892514", "0.5686213", "0.56811816", "0.56803554", "0.56803554", "0.5666646", "0.564223", "0.5629126", "0.5621263", "0.5618797", "0.56117135", "0.560735", "0.5603135", "0.55981934", "0.5592863", "0.55910337", "0.5584962", "0.5584962", "0.55835027", "0.5579834", "0.557958", "0.55781895", "0.5576379", "0.5573748", "0.55543774", "0.555319", "0.55513173", "0.5551141", "0.5541044", "0.55406445", "0.5538227", "0.5536844", "0.5536419", "0.5532939", "0.5532743", "0.55136514", "0.55043745", "0.5492761", "0.5486875", "0.5484056", "0.5472502", "0.54700845" ]
0.7525397
1
PATCH/PUT /fish/1 PATCH/PUT /fish/1.json
def update respond_to do |format| if @fish.update(fish_params) format.html { redirect_to @fish, notice: 'Fish was successfully updated.' } format.json { render :show, status: :ok, location: @fish } else format.html { render :edit } format.json { render json: @fish.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update\n respond_to do |format|\n if @fish.update(fish_params)\n format.html { redirect_to @fish, notice: 'Fish was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @fish.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @fish.update(fish_params)\n format.html { redirect_to @fish, notice: \"Fish was successfully updated.\" }\n format.json { render :show, status: :ok, location: @fish }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @fish.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @spoofer = Spoofer.find(params[:id])\n\n respond_to do |format|\n if @spoofer.update_attributes(params[:spoofer])\n format.html { redirect_to @spoofer, notice: 'Spoofer was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @spoofer.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @fishing_method = FishingMethod.find(params[:id])\n\n respond_to do |format|\n if @fishing_method.update_attributes(params[:fishing_method])\n format.html { redirect_to @fishing_method, notice: 'Fishing method was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @fishing_method.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @fucker = Fucker.find(params[:id])\n\n respond_to do |format|\n if @fucker.update_attributes(params[:fucker])\n format.json { head :no_content }\n else\n format.json { render json: @fucker.errors, status: :internal_server_error }\n end\n end\n end", "def patch!\n request! :patch\n end", "def put!\n request! :put\n end", "def api_patch(path, data = {})\n api_request(:patch, path, :data => data)\n end", "def update\n @fish_type = FishType.find(params[:id])\n\n respond_to do |format|\n if @fish_type.update_attributes(params[:fish_type])\n format.html { redirect_to @fish_type, notice: 'Fish type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @fish_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @fish_poly.update(fish_poly_params)\n format.html { redirect_to @fish_poly, notice: 'Fish poly was successfully updated.' }\n format.json { render :show, status: :ok, location: @fish_poly }\n else\n format.html { render :edit }\n format.json { render json: @fish_poly.errors, status: :unprocessable_entity }\n end\n end\n end", "def update # PATCH\n raise NotImplementedError\n end", "def patch\n headers = {\"If-Match\" => @version}\n response = @context.request :patch, \"#{@path}/#{@id}\", @data.to_json, headers\n @version += 1\n response\n # 'X-HTTP-Method-Override' => 'PATCH'\n end", "def update\n respond_to do |format|\n if @fokey.update(fokey_params)\n format.html { redirect_to @fokey, notice: 'Fokey was successfully updated.' }\n format.json { render :show, status: :ok, location: @fokey }\n else\n format.html { render :edit }\n format.json { render json: @fokey.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @frosting_flavor.update(frosting_flavor_params)\n format.html { redirect_to @frosting_flavor, notice: 'Frosting flavor was successfully updated.' }\n format.json { render :show, status: :ok, location: @frosting_flavor }\n else\n format.html { render :edit }\n format.json { render json: @frosting_flavor.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @fridge = Fridge.find(params[:id])\n\n respond_to do |format|\n if @fridge.update_attributes(params[:fridge])\n format.html { redirect_to @fridge, notice: 'Fridge was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @fridge.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n redirect_to root_url\n\n # respond_to do |format|\n # if @fluke.update(fluke_params)\n # format.html { redirect_to @fluke, notice: 'Fluke was successfully updated.' }\n # format.json { render :show, status: :ok, location: @fluke }\n # else\n # format.html { render :edit }\n # format.json { render json: @fluke.errors, status: :unprocessable_entity }\n # end\n # end\n end", "def update\n @foam = Foam.find(params[:id])\n\n respond_to do |format|\n if @foam.update_attributes(params[:foam])\n format.html { redirect_to @foam, notice: 'Foam was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @foam.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @golfer = Golfer.find(params[:id])\n\n respond_to do |format|\n if @golfer.update_attributes(params[:golfer])\n format.html { redirect_to @golfer, notice: 'Golfer was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @golfer.errors, status: :unprocessable_entity }\n end\n end\n end", "def patch(path, data)\n request 'PATCH', path, body: data.to_json\n end", "def update\n respond_to do |format|\n if @fat.update(fat_params)\n format.html { redirect_to @fat, notice: 'Fat was successfully updated.' }\n format.json { render :show, status: :ok, location: @fat }\n else\n format.html { render :edit }\n format.json { render json: @fat.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @fred = Fred.find(params[:id])\n\n respond_to do |format|\n if @fred.update_attributes(params[:fred])\n format.html { redirect_to @fred, notice: 'Fred was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @fred.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @food = Food.find(params[:id])\n\n respond_to do |format|\n if @food.update_attributes(params[:food])\n format.html { redirect_to foods_path(), notice: 'Food was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @food.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @fishery.update(fishery_params)\n format.html { redirect_to country_fishery_path(@country), notice: \"Fishery was successfully updated.\" }\n format.json { render :show, status: :ok, location: @fishery }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @fishery.errors, status: :unprocessable_entity }\n end\n end\n end", "def update(url, data)\n RestClient.put url, data, :content_type => :json\nend", "def update\n respond_to do |format|\n if @beef.update(beef_params)\n format.html { redirect_to @beef, notice: 'Beef was successfully updated.' }\n format.json { render :show, status: :ok, location: @beef }\n else\n format.html { render :edit }\n format.json { render json: @beef.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @patch.update(patch_params)\n format.html { redirect_to @patch, notice: 'Patch was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @patch.errors, status: :unprocessable_entity }\n end\n end\n end", "def update(&block)\n validate_request()\n\n # Params includes all of the PATCH data at the top level along with other\n # other Rails-injected params like 'id', 'action', 'controller'. These\n # are harmless given no namespace collision and we're only interested in\n # the 'Operations' key for the actual patch data.\n #\n render(json: yield(self.safe_params()[:id], self.safe_params().to_hash()))\n end", "def update\n authorize! :manage, @flock\n\n respond_to do |format|\n if @flock.update(flock_params)\n format.html { redirect_to @flock, notice: \"Flock was successfully updated.\" }\n format.json { render :show, status: :ok, location: @flock }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @flock.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @fast_food.update(fast_food_params)\n format.html { redirect_to @fast_food, notice: 'Fast food was successfully updated.' }\n format.json { render :show, status: :ok, location: @fast_food }\n else\n format.html { render :edit }\n format.json { render json: @fast_food.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @flower = Flower.find(params[:id])\n\n respond_to do |format|\n if @flower.update_attributes(params[:flower])\n format.html { redirect_to @flower, notice: 'Flower was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @flower.errors, status: :unprocessable_entity }\n end\n end\n end", "def update options={}\n client.put(\"/#{id}\", options)\n end", "def update\n @patch = Patch.find(params[:id])\n\n respond_to do |format|\n if @patch.update_attributes(params[:patch])\n format.html { redirect_to @patch, notice: 'Patch was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @patch.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\n @foaf.interests.clear\n\n if(foaf_params.has_key?(:interests_attributes))\n interest_ids = foaf_params[:interests_attributes].split(\",\").map { |s| s.to_i }\n interest_ids.each do |i|\n @foaf.interests << Interest.find(i)\n #@foaf.update(Interest.find(i))\n end\n \n end\n\n respond_to do |format|\n if @foaf.update(name: foaf_params[:name], work: foaf_params[:work], \n slug: foaf_params[:slug], birthday: foaf_params[:birthday])\n format.html { redirect_to @foaf, notice: 'FOAF was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @foaf.errors, status: :unprocessable_entity }\n end\n end\n end", "def update!(params)\n res = @client.put(path, nil, params, \"Content-Type\" => \"application/json\")\n @attributes = res.json if res.status == 201\n res\n end", "def update\n respond_to do |format|\n if @family.update(family_params)\n format.html { redirect_to @family, notice: 'Family was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @family.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\n @foaf.interests.clear\n\n if(foaf_params.has_key?(:interests_attributes))\n interest_ids = foaf_params[:interests_attributes].split(\",\").map { |s| s.to_i }\n interest_ids.each do |i|\n @foaf.interests << Interest.find(i)\n #@foaf.update(Interest.find(i))\n end\n \n end\n\n respond_to do |format|\n if @foaf.update(name: foaf_params[:name], work: foaf_params[:work], \n slug: foaf_params[:slug], birthday: foaf_params[:birthday])\n format.html { redirect_to @foaf, notice: 'Foaf was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @foaf.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @chef.update(chef_params)\n format.html { redirect_to [:admin, @chef], notice: t('messages.updated', model:Chef.model_name.human) }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @chef.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @fascicle.update(fascicle_params)\n format.html { redirect_to @fascicle, notice: 'Fascicle was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @fascicle.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @fish_product.update(fish_product_params)\n format.html { redirect_to @fish_product, notice: 'Fish product was successfully updated.' }\n format.json { render :show, status: :ok, location: @fish_product }\n else\n format.html { render :edit }\n format.json { render json: @fish_product.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @food = Food.find(params[:id])\n\n respond_to do |format|\n if @food.update_attributes(params[:food])\n format.html { redirect_to @food, notice: \"Piatto aggiornato correttamente.\" }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @food.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @favorite_flyer = FavoriteFlyer.find(params[:id])\n\n respond_to do |format|\n if @favorite_flyer.update_attributes(params[:favorite_flyer])\n format.html { redirect_to @favorite_flyer, notice: 'Favorite flyer was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @favorite_flyer.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @six.update(six_params)\n format.html { redirect_to @six, notice: 'Six was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @six.errors, status: :unprocessable_entity }\n end\n end\n end", "def patch(path, params = {})\n request(:patch, path, params)\n end", "def patch(path, params = {})\n request(:patch, path, params)\n end", "def update\n respond_to do |format|\n if @falta.update(falta_params)\n format.html { redirect_to @falta, notice: \"Falta was successfully updated.\" }\n format.json { render :show, status: :ok, location: @falta }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @falta.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n put :update\n end", "def update\n respond_to do |format|\n if @sheep.update(sheep_params)\n format.html { redirect_to @sheep, notice: 'Sau ble oppdatert.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @sheep.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @flavor = Flavor.find(params[:id])\n\n respond_to do |format|\n if @flavor.update_attributes(params[:flavor])\n format.html { redirect_to @flavor, :notice => 'Flavor was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @flavor.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @foo56.update(foo56_params)\n format.html { redirect_to @foo56, notice: \"Foo56 was successfully updated.\" }\n format.json { render :show, status: :ok, location: @foo56 }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @foo56.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @flavor.update(flavor_params)\n format.html { redirect_to @flavor, notice: 'Flavor was successfully updated.' }\n format.json { render :show, status: :ok, location: @flavor }\n else\n format.html { render :edit }\n format.json { render json: @flavor.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @rest.update(rest_params)\n format.html { redirect_to @rest, notice: 'Rest was successfully updated.' }\n format.json { render :show, status: :ok, location: @rest }\n else\n format.html { render :edit }\n format.json { render json: @rest.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @golf.update(golf_params)\n format.html { redirect_to @golf, notice: 'Golf was successfully updated.' }\n format.json { render :show, status: :ok, location: @golf }\n else\n format.html { render :edit }\n format.json { render json: @golf.errors, status: :unprocessable_entity }\n end\n end\n end", "def patch options\n rest_request({ method: :patch }.merge(options))\n end", "def patch options\n rest_request({ method: :patch }.merge(options))\n end", "def update\n respond_to do |format|\n if @coffeeshop.update(coffeeshop_params)\n format.html { redirect_to @coffeeshop, notice: 'Coffeeshop was successfully updated.' }\n format.json { render :show, status: :ok, location: @coffeeshop }\n else\n format.html { render :edit }\n format.json { render json: @coffeeshop.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @food.update(food_params)\n format.html { redirect_to @food, notice: 'Food was successfully updated.' }\n format.json { render :show, status: :ok, location: @food }\n else\n format.html { render :edit }\n format.json { render json: @food.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @foodhamper = Foodhamper.find(params[:id])\n\n respond_to do |format|\n if @foodhamper.update_attributes(params[:foodhamper])\n format.html { redirect_to @foodhamper, notice: 'Foodhamper was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @foodhamper.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n ingredient.update(ingredient_params)\n render json: ingredient\n end", "def update\n respond_to do |format|\n if @funkce.update(funkce_params)\n format.html { redirect_to @funkce, notice: 'Funkce was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @funkce.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @fisier.update(fisier_params)\n format.html { redirect_to root_path, notice: 'Fisier was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @fisier.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n # if food is passed, won't check it again.\n if @food.state == 1\n state = 1 \n else\n state = 0\n end\n\n if @food.update(food_params.merge state: state) # 1 means valid\n format.html { redirect_to @food, notice: 'Food was successfully updated.' }\n format.json { render :show, status: :ok, location: @food }\n else\n format.html { render :edit }\n format.json { render json: @food.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @feature_request.update(feature_request_params)\n format.html { redirect_to @feature_request, notice: 'Feature request was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @feature_request.errors, status: :unprocessable_entity }\n end\n end\n end", "def patch(path, **args); end", "def update\n @foil = Foil.find(params[:id])\n\n respond_to do |format|\n if @foil.update_attributes(params[:foil])\n format.html { redirect_to @foil, notice: 'Foil was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @foil.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @flower.update(flower_params)\n format.html { redirect_to @flower, notice: 'Flower was successfully updated.' }\n format.json { render :show, status: :ok, location: @flower }\n else\n format.html { render :edit }\n format.json { render json: @flower.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @flower.update(flower_params)\n format.html { redirect_to @flower, notice: 'Flower was successfully updated.' }\n format.json { render :show, status: :ok, location: @flower }\n else\n format.html { render :edit }\n format.json { render json: @flower.errors, status: :unprocessable_entity }\n end\n end\n end", "def patch(path, params)\n time(\"PATCH #{path}\") { Cloudflarer.new.patch(path, params) }\n end", "def update\n respond_to do |format|\n if @foo1.update(foo1_params)\n format.html { redirect_to @foo1, notice: \"Foo1 was successfully updated.\" }\n format.json { render :show, status: :ok, location: @foo1 }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @foo1.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @shelf = Shelf.find(params[:id])\n\n respond_to do |format|\n if @shelf.update_attributes(params[:shelf])\n flash[:notice] = 'Shelf was successfully updated.'\n format.html { redirect_to(@shelf) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @shelf.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n @family.slug=nil\n if @family.update(family_params)\n format.html { redirect_to @family, notice: 'La familia fue actualizada exitosamente.' }\n format.json { render :show, status: :ok, location: @family }\n else\n format.html { render :edit }\n format.json { render json: @family.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @patch.update(patch_params)\n format.html { redirect_to @patch, notice: 'Patch was successfully updated.' }\n format.json { render :show, status: :ok, location: @patch }\n else\n format.html { render :edit }\n format.json { render json: @patch.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @foo7.update(foo7_params)\n format.html { redirect_to @foo7, notice: \"Foo7 was successfully updated.\" }\n format.json { render :show, status: :ok, location: @foo7 }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @foo7.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @foo8.update(foo8_params)\n format.html { redirect_to @foo8, notice: \"Foo8 was successfully updated.\" }\n format.json { render :show, status: :ok, location: @foo8 }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @foo8.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @star_fact = Star::Fact.find(params[:id])\n\n respond_to do |format|\n if @star_fact.update_attributes(params[:star_fact])\n format.html { redirect_to @star_fact, notice: 'Fact was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @star_fact.errors, status: :unprocessable_entity }\n end\n end\n end", "def partial_update(klass, id, patchset, options = {}, format = nil)\n headers = {}\n headers[:accept] = \"#{format}\" if format\n format ||= @default_format\n options = { resource: klass, id: id, format: format}.merge options\n if [FHIR::Formats::ResourceFormat::RESOURCE_XML, FHIR::Formats::ResourceFormat::RESOURCE_XML_DSTU2].include?(format)\n options[:format] = FHIR::Formats::PatchFormat::PATCH_XML\n headers[:content_type] = \"#{FHIR::Formats::PatchFormat::PATCH_XML}\"\n elsif [FHIR::Formats::ResourceFormat::RESOURCE_JSON, FHIR::Formats::ResourceFormat::RESOURCE_JSON_DSTU2].include?(format)\n options[:format] = FHIR::Formats::PatchFormat::PATCH_JSON\n headers[:content_type] = \"#{FHIR::Formats::PatchFormat::PATCH_JSON}\"\n end\n headers[:prefer] = @return_preference if @use_return_preference\n reply = patch resource_url(options), patchset, fhir_headers(headers)\n reply.resource = parse_reply(klass, format, reply)\n reply.resource_class = klass\n reply\n end", "def update\n respond_to do |format|\n if @fabrica.update(fabrica_params)\n format.html { redirect_to @fabrica, notice: 'Fabrica was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @fabrica.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @fabric = Fabric.find(params[:id])\n\n respond_to do |format|\n if @fabric.update_attributes(params[:fabric])\n format.html { redirect_to @fabric, notice: 'Fabric was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @fabric.errors, status: :unprocessable_entity }\n end\n end\n end", "def rest_edit(path, options={}, &blk)\n callback = Proc.new { |*args|\n @object = yield(*args) or pass\n rest_params.each { |k, v| @object.send :\"#{k}=\", v unless k == 'id' }\n\n return 400, @object.errors.to_json unless @object.valid?\n\n @object.save\n rest_respond @object\n }\n\n # Make it work with `Backbone.emulateHTTP` on.\n put path, &callback\n post path, &callback\n end", "def rest_edit(path, options={}, &blk)\n callback = Proc.new { |*args|\n @object = yield(*args) or pass\n rest_params.each { |k, v| @object.send :\"#{k}=\", v unless k == 'id' }\n\n return 400, @object.errors.to_json unless @object.valid?\n\n @object.save\n rest_respond @object\n }\n\n # Make it work with `Backbone.emulateHTTP` on.\n put path, &callback\n post path, &callback\n end", "def update\n @f = F.find(params[:id])\n\n respond_to do |format|\n if @f.update_attributes(params[:f])\n format.html { redirect_to software_package_fs_path(@software, @package) }\n format.js\n format.json { head :ok }\n else\n format.html { redirect_to software_package_fs_path(@software, @package) }\n format.js\n format.json { render json: @package.errors, status: :unprocessable_entity }\n end\n end\n \n end", "def patch(path, opts = {})\n request(:patch, path, opts).body\n end", "def update\n respond_to do |format|\n if @fip.update(fip_params)\n format.html { redirect_to @fip, notice: 'Fip was successfully updated.' }\n format.json { render :show, status: :ok, location: @fip }\n else\n format.html { render :edit }\n format.json { render json: @fip.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @stuff = Stuff.find(params[:id])\n\n respond_to do |format|\n if @stuff.update_attributes(params[:stuff])\n format.html { redirect_to @stuff, :notice => 'Stuff was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @stuff.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @glass = Glass.find(params[:id])\n\n respond_to do |format|\n if @glass.update_attributes(params[:glass])\n format.html { redirect_to @glass, notice: 'Glass was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @glass.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @wing.update(wing_params)\n @wing.floors.each { |f| f.touch }\n format.html { redirect_to @wing, notice: t('.update_ok', item: @wing.name) }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @wing.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @feild.update(feild_params)\n format.html { redirect_to @feild, notice: 'Feild was successfully updated.' }\n format.json { render :show, status: :ok, location: @feild }\n else\n format.html { render :edit }\n format.json { render json: @feild.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @fulcliente = Fulcliente.find(params[:id])\n\n respond_to do |format|\n if @fulcliente.update_attributes(params[:fulcliente])\n format.html { redirect_to @fulcliente, notice: 'Fulcliente was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @fulcliente.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @favoritepizza.update(favoritepizza_params)\n format.html { redirect_to @favoritepizza, notice: 'Favoritepizza was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @favoritepizza.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @food.update(food_params)\n respond_with @food, location: -> { kitchen_board_path }\n end", "def update\n @foo = Foo.find(params[:id])\n\n respond_to do |format|\n if @foo.update_attributes(params[:foo])\n format.html { redirect_to @foo, notice: 'Foo was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @foo.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @foo78.update(foo78_params)\n format.html { redirect_to @foo78, notice: \"Foo78 was successfully updated.\" }\n format.json { render :show, status: :ok, location: @foo78 }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @foo78.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @fast.update(fast_params)\n format.html { redirect_to @fast, notice: 'Fast was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @fast.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @stalkee.update(stalkee_params)\n format.html { redirect_to @stalkee, notice: 'Stalkee was successfully updated.' }\n format.json { render :show, status: :ok, location: @stalkee }\n else\n format.html { render :edit }\n format.json { render json: @stalkee.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\n respond_to do |format|\n if @fishing_area.update(fishing_area_params)\n format.html { redirect_to @fishing_area, notice: \"Fishing area was successfully updated.\" }\n format.json { render :show, status: :ok, location: @fishing_area }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @fishing_area.errors, status: :unprocessable_entity }\n end\n end\n\n end", "def patch(type, info)\n path, info = type_info(type, :path), force_case(info)\n ida = type == :client ? 'client_id' : 'id'\n raise ArgumentError, \"info must include #{ida}\" unless id = info[ida]\n hdrs = headers\n if info && info['meta'] && (etag = info['meta']['version'])\n hdrs.merge!('if-match' => etag)\n end\n reply = json_parse_reply(@key_style,\n *json_patch(@target, \"#{path}/#{Addressable::URI.encode(id)}\", info, hdrs))\n\n # hide client endpoints that are not quite scim compatible\n type == :client && !reply ? get(type, info['client_id']): reply\n end", "def update\n # @recipe = Recipe.find(params[:id])\n #\n update! do |success, failure|\n # success.html { redirect_to @recipe, notice: 'Recipe was successfully updated.' }\n # success.json { head :ok }\n # failure.html { render action: \"edit\" }\n # failure.json { render json: @recipe.errors, status: :unprocessable_entity }\n end\n end", "def http_put(path, data, content_type = 'application/json')\n http_methods(path, :put, data, content_type)\n end" ]
[ "0.7068595", "0.6915725", "0.68295753", "0.6707333", "0.6575412", "0.6520344", "0.64568204", "0.64408624", "0.642989", "0.64050674", "0.6347398", "0.63256425", "0.63119215", "0.63097984", "0.6238832", "0.62318236", "0.6227714", "0.6219472", "0.62190235", "0.6204084", "0.61915255", "0.61875457", "0.61422616", "0.61383766", "0.61214477", "0.6099988", "0.60955626", "0.6088367", "0.6086548", "0.60794026", "0.60653776", "0.6064029", "0.6059569", "0.60585356", "0.60433626", "0.603113", "0.60293", "0.60269356", "0.60208374", "0.6014601", "0.6013366", "0.60007507", "0.5992972", "0.5992972", "0.59927535", "0.5990145", "0.5987881", "0.59846884", "0.59838337", "0.59788525", "0.5963552", "0.5961642", "0.5958828", "0.5958828", "0.5956735", "0.5945532", "0.59418035", "0.5941514", "0.59367144", "0.593467", "0.5934246", "0.5934211", "0.59303266", "0.591987", "0.59195", "0.59195", "0.5919474", "0.5917381", "0.59167254", "0.5915585", "0.5915434", "0.590743", "0.5906745", "0.5903377", "0.5895432", "0.58886665", "0.58859015", "0.5879992", "0.5879992", "0.58771825", "0.58769566", "0.5874004", "0.58718646", "0.5867663", "0.58554596", "0.5854968", "0.5853375", "0.58527136", "0.5850147", "0.5846406", "0.5845042", "0.5841726", "0.5840364", "0.5836762", "0.58297515", "0.58279926", "0.58276886" ]
0.6933296
2
DELETE /fish/1 DELETE /fish/1.json
def destroy @fish.destroy respond_to do |format| format.html { redirect_to fish_index_url, notice: 'Fish was successfully destroyed.' } format.json { head :no_content } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n @fish.destroy\n respond_to do |format|\n format.html { redirect_to fish_index_url }\n format.json { head :no_content }\n end\n end", "def delete\n client.delete(\"/#{id}\")\n end", "def destroy\n @fish.destroy\n respond_to do |format|\n format.html { redirect_to fish_index_url, notice: \"Fish was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def deletef\n url = prefix + \"deletef\" + id_param\n return response(url)\n end", "def delete(path)\n RestClient.delete request_base+path\n end", "def destroy\n Fish.find(params[:id]).destroy\n render nothing: true\n end", "def delete path\n make_request(path, \"delete\", {})\n end", "def destroy\n @fishing_method = FishingMethod.find(params[:id])\n @fishing_method.destroy\n\n respond_to do |format|\n format.html { redirect_to fishing_methods_url }\n format.json { head :ok }\n end\n end", "def destroy\n @fish_type = FishType.find(params[:id])\n @fish_type.destroy\n\n respond_to do |format|\n format.html { redirect_to fish_types_url }\n format.json { head :no_content }\n end\n end", "def delete(path)\n request 'DELETE', path\n end", "def delete\n render :json => @fiestas.delete_at(params[:id].to_i)\n end", "def destroy\n @dish = Dish.find(params[:id])\n @dish.destroy\n\n respond_to do |format|\n format.html { redirect_to dishes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @dish = Dish.find(params[:id])\n @dish.destroy\n\n respond_to do |format|\n format.html { redirect_to dishes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @fokey.destroy\n respond_to do |format|\n format.html { redirect_to fokeys_url, notice: 'Fokey was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @food = Food.find(params[:id])\n @food.destroy\n\n respond_to do |format|\n format.html { redirect_to foods_url }\n format.json { head :ok }\n end\n end", "def destroy\n @food = Food.find(params[:id])\n @food.destroy\n\n respond_to do |format|\n format.html { redirect_to foods_url }\n format.json { head :ok }\n end\n end", "def destroy\n @dish = Dish.find(params[:id])\n @dish.destroy\n\n respond_to do |format|\n format.html { redirect_to my_page_path }\n format.json { head :no_content }\n end\n end", "def delete!\n request! :delete\n end", "def delete\n request(:delete)\n end", "def delete(path)\n request(:delete, path)\n end", "def destroy\n @fish_poly.destroy\n respond_to do |format|\n format.html { redirect_to fish_polies_url, notice: 'Fish poly was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete(path)\n\t\trequest(path, :delete)\n\tend", "def destroy\n @foaf.destroy\n\n respond_to do |format|\n format.html { redirect_to foafs_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @foaf.destroy\n\n respond_to do |format|\n format.html { redirect_to foafs_url }\n format.json { head :no_content }\n end\n end", "def delete\n url = prefix + \"delete\"\n return response(url)\n end", "def delete\n url = prefix + \"delete\"\n return response(url)\n end", "def destroy\n @restaurant_dish = Restaurant::Dish.find(params[:id])\n @restaurant_dish.destroy\n\n respond_to do |format|\n format.html { redirect_to restaurant_dishes_url }\n format.json { head :ok }\n end\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def destroy\n @kota_stone.destroy\n respond_to do |format|\n format.html { redirect_to kota_stones_url }\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 delete\n client.delete(url)\n @deleted = true\nend", "def destroy\n @six.destroy\n respond_to do |format|\n format.html { redirect_to sixes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @foam = Foam.find(params[:id])\n @foam.destroy\n\n respond_to do |format|\n format.html { redirect_to foams_url }\n format.json { head :ok }\n end\n end", "def destroy\n @uginuce.sheep.update status:'na farmi'\n @uginuce.destroy\n respond_to do |format|\n format.html { redirect_to uginuces_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @favorite_flyer = FavoriteFlyer.find(params[:id])\n @favorite_flyer.destroy\n\n respond_to do |format|\n format.html { redirect_to favorite_flyers_url }\n format.json { head :no_content }\n end\n end", "def delete(path)\n request(:delete, path)\n end", "def destroy\n @fridge = Fridge.find(params[:id])\n @fridge.destroy\n\n respond_to do |format|\n format.html { redirect_to fridges_url }\n format.json { head :no_content }\n end\n end", "def delete\n render json: Alien.delete(params[\"id\"])\n end", "def destroy\n @dish.destroy\n respond_to do |format|\n format.html { redirect_to dishes_url, notice: 'El plato se ha eliminado.' }\n format.json { head :no_content }\n end\n end", "def delete_json(path)\n url = [base_url, path].join\n resp = HTTParty.delete(url, headers: standard_headers)\n parse_json(url, resp)\n end", "def destroy\n @foodhamper = Foodhamper.find(params[:id])\n @foodhamper.destroy\n\n respond_to do |format|\n format.html { redirect_to foodhampers_url }\n format.json { head :no_content }\n end\n end", "def api_delete(path, data = {})\n api_request(:delete, path, :data => data)\n end", "def destroy\n @fascicle.destroy\n respond_to do |format|\n format.html { redirect_to fascicles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n redirect_to root_url\n \n # @fluke.destroy\n # respond_to do |format|\n # format.html { redirect_to flukes_url, notice: 'Fluke was successfully destroyed.' }\n # format.json { head :no_content }\n # end\n end", "def destroy\n compute.delete_flavor(params[:id])\n \n\n respond_to do |format|\n format.html { redirect_to flavors_path }\n format.json { head :ok }\n end\n end", "def delete\n render json: Item.delete(params[\"id\"])\n end", "def destroy\n @shelf.destroy\n\n respond_to do |format|\n format.html { redirect_to shelves_url }\n format.json { head :no_content }\n end\n end", "def delete(path)\n path = relativize_path path\n\n Precog.connect self do |http|\n uri = Addressable::URI.new\n uri.query_values = { :apiKey => api_key }\n\n http.delete \"/ingest/v#{VERSION}/fs/#{path}?#{uri.query}\"\n end\n end", "def destroy\n @dish.destroy\n respond_to do |format|\n format.html { redirect_to restaurant_dishes_path, notice: 'Dish was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @golfer = Golfer.find(params[:id])\n @golfer.destroy\n\n respond_to do |format|\n format.html { redirect_to golfers_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @fishery.destroy\n respond_to do |format|\n format.html { redirect_to country_fisheries_path(@country), notice: \"Fishery was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def delete\n render json: Post.delete(params[\"id\"])\n end", "def destroy\n @fast_food.destroy\n respond_to do |format|\n format.html { redirect_to fast_foods_url, notice: 'Fast food was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @dish.destroy\n respond_to do |format|\n format.html { redirect_to dishes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @dish.destroy\n respond_to do |format|\n format.html { redirect_to dishes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @shelf.destroy\n respond_to do |format|\n format.html { redirect_to shelves_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @shelf = Shelf.find(params[:id])\n @shelf.destroy\n\n respond_to do |format|\n format.html { redirect_to(shelves_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n animal = Animal.find(params[:id])\n animal.destroy\n head 204\n end", "def destroy\n @fulcliente = Fulcliente.find(params[:id])\n @fulcliente.destroy\n\n respond_to do |format|\n format.html { redirect_to fulclientes_url }\n format.json { head :ok }\n end\n end", "def destroy\n @spoofer = Spoofer.find(params[:id])\n @spoofer.destroy\n\n respond_to do |format|\n format.html { redirect_to spoofers_url }\n format.json { head :ok }\n end\n end", "def delete(path, params = {})\n post(path, params.merge(\"_method\" => \"delete\"))\n end", "def delete!( opts = {} )\n http_action :delete, nil, opts\n end", "def destroy\n @foo = Foo.find(params[:id])\n @foo.destroy\n\n respond_to do |format|\n format.html { redirect_to foos_url }\n format.json { head :ok }\n end\n end", "def destroy\n @fridge_food = FridgeFood.find(params[:id])\n @fridge_food.destroy\n\n respond_to do |format|\n format.html { redirect_to(fridge_foods_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @fisier.destroy\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 @dish.destroy\n respond_to do |format|\n format.html { redirect_to dishes_url, notice: 'Dish was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete\n api(\"Delete\")\n end", "def delete(*rest) end", "def destroy\n @flower = Flower.find(params[:id])\n @flower.destroy\n\n respond_to do |format|\n format.html { redirect_to flowers_url }\n format.json { head :ok }\n end\n end", "def destroy\n @fat.destroy\n respond_to do |format|\n format.html { redirect_to fats_url, notice: 'Fat was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @fooditem = Fooditem.find(params[:id])\n @fooditem.destroy\n\n respond_to do |format|\n format.html { redirect_to fooditems_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @fast.destroy\n respond_to do |format|\n format.html { redirect_to fasts_url }\n format.json { head :no_content }\n end\n end", "def destroy\n client=Client.find_by_id(params[:id])\n if client != nil\n if client.destroy\n head 204\n end\n else\n head 404\n end\n end", "def destroy\n @foo1.destroy\n respond_to do |format|\n format.html { redirect_to foo1s_url, notice: \"Foo1 was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @beef.destroy\n respond_to do |format|\n format.html { redirect_to beefs_url, notice: 'Beef was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @familium = Familium.find(params[:id])\n @familium.destroy\n\n respond_to do |format|\n format.html { redirect_to familia_url }\n format.json { head :no_content }\n end\n end", "def delete\n start { |connection| connection.request http :Delete }\n end", "def destroy\n @baz1.destroy\n respond_to do |format|\n format.html { redirect_to baz1s_url, notice: \"Baz1 was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @hoge = Hoge.find(params[:id])\n @hoge.destroy\n\n respond_to do |format|\n format.html { redirect_to hoges_url }\n format.json { head :ok }\n end\n end", "def delete(*args)\n request(:delete, *args)\n end", "def delete\n url = prefix + \"delete\"\n return response(url)\n end", "def delete\n url = prefix + \"delete\"\n return response(url)\n end", "def destroy\n @one = One.find(params[:id])\n @one.destroy\n\n respond_to do |format|\n format.html { redirect_to ones_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @dish.destroy\n respond_to do |format|\n format.html { redirect_to dishes_url, notice: 'Блюдо уничтожено.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @favourite_food = FavouriteFood.find(params[:id])\n @favourite_food.destroy\n\n respond_to do |format|\n format.html { redirect_to favourite_foods_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @baz72.destroy\n respond_to do |format|\n format.html { redirect_to baz72s_url, notice: \"Baz72 was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @food.destroy\n respond_to do |format|\n format.html { redirect_to foods_url, notice: 'Food was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @food.destroy\n respond_to do |format|\n format.html { redirect_to foods_url, notice: 'Food was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @food.destroy\n respond_to do |format|\n format.html { redirect_to foods_url, notice: 'Food was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @funkce.destroy\n respond_to do |format|\n format.html { redirect_to funkces_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @foo56.destroy\n respond_to do |format|\n format.html { redirect_to foo56s_url, notice: \"Foo56 was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @foil = Foil.find(params[:id])\n @foil.destroy\n\n respond_to do |format|\n format.html { redirect_to foils_url }\n format.json { head :ok }\n end\n end", "def destroy\n @father = Father.find(params[:id])\n @father.destroy\n\n respond_to do |format|\n format.html { redirect_to fathers_url }\n format.json { head :no_content }\n end\n end", "def delete(*args)\n prepare_request(:delete, args)\n @@client.add(:delete, @path, *args)\n end" ]
[ "0.7452039", "0.72269714", "0.72077584", "0.7131434", "0.7102592", "0.7047345", "0.7047036", "0.7023634", "0.69605815", "0.6874034", "0.6853095", "0.68523306", "0.68523306", "0.68480194", "0.684692", "0.684692", "0.684555", "0.6819591", "0.68119234", "0.6796409", "0.67907494", "0.6772039", "0.6761252", "0.6761252", "0.6749762", "0.6749762", "0.6724855", "0.6720812", "0.6720812", "0.6720812", "0.6720812", "0.6709087", "0.67014575", "0.6693241", "0.669259", "0.669173", "0.6688122", "0.6672038", "0.667036", "0.66702205", "0.66695225", "0.66672736", "0.66638994", "0.66606957", "0.66606927", "0.66475296", "0.6645101", "0.66443443", "0.6640751", "0.6640488", "0.663622", "0.66270524", "0.6626568", "0.6624086", "0.6623192", "0.6622536", "0.6619789", "0.6619789", "0.6619692", "0.66103524", "0.6605679", "0.660254", "0.6601004", "0.6599457", "0.6591201", "0.65887314", "0.6588722", "0.6585703", "0.6585305", "0.65757436", "0.6575365", "0.65661544", "0.6565075", "0.6562719", "0.6560488", "0.65567565", "0.6554553", "0.65525967", "0.6550384", "0.6547427", "0.65442204", "0.65441847", "0.6541729", "0.65395856", "0.65395856", "0.6533282", "0.65324557", "0.65305096", "0.6527473", "0.6526256", "0.6526256", "0.6526256", "0.65224725", "0.6521791", "0.65179986", "0.6516182", "0.6512939" ]
0.72058713
4
Use callbacks to share common setup or constraints between actions.
def set_fish @fish = Fish.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 fish_params params.require(:fish).permit(:name, :description, :sex, :is_neuter) 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 user_params\n params.permit(:name, :phoneNumber, :address, :postalCode, :local, :link, :counter, :latitude, :longitude) \n end", "def valid_params_request?; 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 strong_params\n params.require(:metric_change).permit(param_whitelist)\n end", "def safe_params\n params.require(:user).permit(:name)\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 url_params\n params.require(:url).permit(:short_url, :original_url, :clicks, :ip_addresses)\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 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 active_code_params\n params[:active_code].permit\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 ip_address_params\n\t\t\tparams.require(:ip_address).permit!\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 reserved_params\n params.require(:reserved).permit(:name, :email, :pax, :address, :KTP, :title)\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 list_params\n params.permit(:name)\n end", "def filter_parameters; end", "def filter_parameters; 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 url_whitelist; end", "def admin_social_network_params\n params.require(:social_network).permit!\n end", "def filter_params\n params.require(:filters).permit(:letters)\n end", "def origin_params\n params.permit(:country, :state, :city, :postal_code, :address, :description)\n end", "def valid_params(params)\n params.permit(:login, :first_name, :last_name, \n :password, :password_confirmation)\n end", "def sensitive_params=(params)\n @sensitive_params = params\n end", "def permit_request_params\n params.permit(:address)\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 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 user_params\n params.permit(:name, :age, :username, :display_photo, :password)\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.69792545", "0.6781151", "0.67419964", "0.674013", "0.6734356", "0.6591046", "0.6502396", "0.6496313", "0.6480641", "0.6477825", "0.64565", "0.6438387", "0.63791263", "0.63740575", "0.6364131", "0.63192815", "0.62991166", "0.62978333", "0.6292148", "0.6290449", "0.6290076", "0.62894756", "0.6283177", "0.6242471", "0.62382483", "0.6217549", "0.6214457", "0.6209053", "0.6193042", "0.6177802", "0.6174604", "0.61714715", "0.6161512", "0.6151757", "0.6150663", "0.61461", "0.61213595", "0.611406", "0.6106206", "0.6105114", "0.6089039", "0.6081015", "0.6071004", "0.60620916", "0.6019971", "0.601788", "0.6011056", "0.6010898", "0.6005122", "0.6005122", "0.6001556", "0.6001049", "0.59943926", "0.5992201", "0.59909594", "0.5990628", "0.5980841", "0.59669393", "0.59589154", "0.5958826", "0.5957911", "0.5957385", "0.5953072", "0.59526145", "0.5943361", "0.59386164", "0.59375334", "0.59375334", "0.5933856", "0.59292704", "0.59254247", "0.5924164", "0.59167904", "0.59088355", "0.5907542", "0.59064597", "0.5906243", "0.5898226", "0.589687", "0.5896091", "0.5894501", "0.5894289", "0.5891739", "0.58860534", "0.5882406", "0.587974", "0.58738774", "0.5869024", "0.58679986", "0.5867561", "0.5865932", "0.5864461", "0.58639693", "0.58617616", "0.5861436", "0.5860451", "0.58602303", "0.5854586", "0.58537364", "0.5850427", "0.5850199" ]
0.0
-1
DELETE /locations/1 locations are only destroyed when a user destroys their account
def destroy @location.destroy end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n @user_location.destroy\n\n respond_to do |format|\n format.html { redirect_to user_locations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @location = current_user.locations.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to(locations_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @loc = current_user.locs.find(params[:id])\n @loc.destroy\n\n respond_to do |format|\n format.html { redirect_to locs_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @location = apply_scopes(Location).find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_locations_url(:site => current_site.id) }\n format.json { head :no_content }\n end\n end", "def destroy\n @location = $User.get_location(params[:id])\n @location.kill\n GlobalData.reload(:locations)\n respond_to do |format|\n format.html { redirect_to('/locations') }\n format.xml { head :ok }\n end\n end", "def destroy\n puts \"\\nDESTROY: #{@location.inspect}\"\n @location.destroy\n respond_to do |format|\n format.html { redirect_to locations_url, notice: \"Location was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n authorize @location\n @location.destroy\n redirect_to location_path\n end", "def destroy\n @user=User.find_by_id(params[:user_id])\n @location = Location.find_by_id(params[:id])\n @location.destroy\n respond_to do |format|\n format.html { redirect_to user_locations_path }\n format.json { head :no_content }\n end\n end", "def destroy\n return unless admin?\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to locations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n set_location.destroy\n respond_to do |format|\n format.html { redirect_to locations_url, flash: {success: \"Successfully deleted #{@location.name} location!\" }}\n format.json { head :no_content }\n end\n end", "def destroy\n @user_location = UserLocation.find(params[:id])\n @user_location.destroy\n\n respond_to do |format|\n format.html { redirect_to(user_locations_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @location.destroy\n respond_to do |format|\n format.html { redirect_to '/admin/locations', notice: 'Location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @locations = Location.paginate(:page => params[:page], :per_page => 30).order('updated_at DESC')\n @location = Location.find(params[:id])\n begin\n @location.destroy\n rescue ActiveRecord::DeleteRestrictionError => e\n @error = e.message\n end\n end", "def destroy\n @location = current_user.locations.find_by_slug(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to(locations_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @location.destroy\n render :json => { status: :deleted, head: :no_content }\n end", "def destroy\n @location.destroy\n respond_to do |format|\n format.html { redirect_to trip_locations_path, notice: 'Location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to geolocation_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @specific_location.destroy\n respond_to do |format|\n format.html { redirect_to specific_locations_url, notice: 'Specific location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @admin_location.destroy\n respond_to do |format|\n format.html { redirect_to admin_locations_url, notice: 'Location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n if !is_admin\n flash[:danger] = \"Not authorized\"\n redirect_to root_path\n else\n @location.destroy\n flash[:success] = \"Location is successfully deleted\"\n redirect_to admin_location_edit_path\n end\n end", "def destroy\n @location.destroy\n respond_to do |format|\n format.html { redirect_to locations_url, notice: 'Location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @location.destroy\n respond_to do |format|\n format.html { redirect_to locations_url, notice: 'Location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @location.destroy\n respond_to do |format|\n format.html { redirect_to locations_url, notice: 'Location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @location.destroy\n respond_to do |format|\n format.html { redirect_to locations_url, notice: 'Location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @location.destroy\n respond_to do |format|\n format.html { redirect_to locations_url, notice: 'Location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @location.destroy\n respond_to do |format|\n format.html { redirect_to locations_url, notice: 'Location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @location.destroy\n respond_to do |format|\n format.html { redirect_to locations_url, notice: 'Location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @location.destroy\n respond_to do |format|\n format.html { redirect_to locations_url, notice: 'Location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @location.destroy\n respond_to do |format|\n format.html { redirect_to locations_url, notice: 'Location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @location.destroy\n respond_to do |format|\n format.html { redirect_to locations_url, notice: 'Location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @location.destroy\n respond_to do |format|\n format.html { redirect_to locations_url, notice: 'Location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @location.destroy\n respond_to do |format|\n format.html { redirect_to locations_url, notice: 'Location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @location.destroy\n respond_to do |format|\n format.html { redirect_to locations_url, notice: 'Location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @location.destroy\n respond_to do |format|\n format.html { redirect_to locations_url, notice: 'Location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @location.destroy\n respond_to do |format|\n format.html { redirect_to locations_url, notice: 'Location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @location.destroy\n respond_to do |format|\n format.html { redirect_to locations_url, notice: 'Location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @location.destroy\n respond_to do |format|\n format.html { redirect_to locations_url, notice: 'Location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @location.destroy\n respond_to do |format|\n format.html { redirect_to locations_url, notice: 'Location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @location.destroy\n respond_to do |format|\n format.html { redirect_to locations_url, notice: \"Location was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to locations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @location_have_location = LocationHaveLocation.find(params[:id])\n @location_have_location.destroy\n\n respond_to do |format|\n format.html { redirect_to location_have_locations_url }\n format.json { head :ok }\n end\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to( admin_locations_path) }\n end\n end", "def destroy\n @location.destroy\n respond_to do |format|\n format.html { redirect_to locations_url, notice: 'location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @location.destroy\n respond_to do |format|\n format.html { redirect_to locations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @location.destroy\n respond_to do |format|\n format.html { redirect_to locations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @location.destroy\n respond_to do |format|\n format.html { redirect_to locations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @location.destroy\n respond_to do |format|\n format.html { redirect_to locations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @location = Location.find(params[:id])\n #@client = Client.find(@location.client_ids)\n #@contact = Contact.find(@location.contact_ids)\n \n @location.destroy\n\n respond_to do |format|\n \n format.html { redirect_to request.referer }\n format.json { head :no_content }\n end\n end", "def destroy\n @service_location.destroy\n end", "def destroy\n @totem_location.destroy\n respond_to do |format|\n format.html { redirect_to totem_locations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to locations_url }\n format.json { head :ok }\n end\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to locations_url }\n format.json { head :ok }\n end\n end", "def destroy\n begin\n @sicoss_location.destroy\n flash[:success] = \"successfully destroyed.\"\n rescue ActiveRecord::DeleteRestrictionError => e\n @sicoss_location.errors.add(:base, e)\n flash[:error] = \"#{e}\"\n redirect_to sicoss_location_url\n else\n redirect_to sicoss_locations_url\n end\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to locations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to locations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to locations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to locations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to locations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to locations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to locations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to locations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @api_v1_location.destroy\n respond_to do |format|\n format.html { redirect_to api_v1_locations_url, notice: 'Location was successfully destroyed.' }\n format.json { render json: { results: @api_v1_location, message: 'Location was successfully destroyed.' } }\n end\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_locations_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @current_location.destroy\n respond_to do |format|\n format.html { redirect_to current_locations_url, notice: 'Current location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @ms_location.destroy\n respond_to do |format|\n format.html { redirect_to ms_locations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n if (current_user.role == \"customer\" || current_user.role == \"supervisor\")\n @location = Location.find(params[:id])\n @action = request.referrer\n @location.delflag = true\n if @location.update_attributes(params[:location])\n flash[:notice] = \"Successfully Deleted\"\n respond_to do |format|\n format.html { redirect_to @action }\n format.json { head :no_content }\n end\n else\n flash[:notice] = \"Could not Deleted\"\n respond_to do |format|\n format.html { redirect_to @action }\n format.json { head :no_content }\n end\n end\n else\n redirect_to error_users_path and return\n end \n end", "def destroy\n @locid = params[:id]\n Location.destroy(@locid)\n end", "def destroy\n if current_user.is_admin\n @location.destroy\n render json: @location.transform_json, status: 204\n else\n # email being sent tho the admin\n LocationNotifierMailer.delete_location_mailer(current_user, @location, params[:description]).deliver\n render json: { notice: 'Location changes have been sent to the admin for approval, they should be in touch soon.' },\n status: 201\n end\n end", "def destroy\n @muster_location.destroy\n respond_to do |format|\n format.html { redirect_to muster_locations_url, notice: 'Muster location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @locations = nil\n\n if params.has_key? :id\n location = Location.find params[:id]\n @locations = [ location ]\n elsif params.has_key? :ids\n @locations = Location.find params[:ids].split(\",\")\n end\n\n if not @locations.empty?\n @locations.each do |l|\n l.destroy\n end\n end\n\n respond_to do |format|\n format.html { redirect_to locations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n Location.destroy(params[:id])\n flash[:notice] = \"Successfully Deleted\"\n respond_to { |format|\n format.html { redirect_to :action => \"index\", :method => \"get\", :status=> 303 }\n }\n end", "def destroy\n if(current_user!=nil && current_user.rol==\"admin\"||(current_user.rol==\"regular\" && [email protected]_id))\n @[email protected]\n if(@location.delivers.size>0)\n \n flash[:alert]=\"No se puede eliminar hay pedidos a esta direccion!\"\n else\[email protected]\nflash[:alert]=\"Eliminado correctamente\"\n end\n if(current_user.rol==\"admin\")\n redirect_to '/locations/index/'[email protected]_s\n else\n redirect_to locations_url\n end\n else\n redirect_to root_path\n end\n end", "def destroy\r\n @location = Location.find(params[:id])\r\n @location.destroy\r\n\r\n respond_to do |format|\r\n format.json { head :no_content }\r\n end\r\n end", "def destroy\r\n @profile_location.destroy\r\n respond_to do |format|\r\n format.html { redirect_to profile_locations_url, notice: 'Profile location was successfully destroyed.' }\r\n format.json { head :no_content }\r\n end\r\n end", "def destroy\n\t @location = Location.find(params[:id])\n\t @location.destroy\n\n\t respond_to do |format|\n\t format.html { redirect_to locations_url }\n\t format.json { head :no_content }\n\t end\n\t end", "def destroy\n @user_location_change.destroy\n respond_to do |format|\n format.html { redirect_to user_location_changes_url, notice: 'User location change was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @storage_location = StorageLocation.find(params[:id])\n @storage_location.destroy\n\n respond_to do |format|\n format.html { redirect_to storage_locations_url }\n format.json { head :ok }\n end\n end", "def destroy\n @maplocation.destroy\n respond_to do |format|\n format.html { redirect_to maplocations_url, notice: 'Maplocation was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @location = Location.find(params[:id])\n end", "def destroy\n @catalog_location.destroy\n respond_to do |format|\n format.html { redirect_to catalog_locations_url, notice: 'Location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to(locations_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to(locations_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to(locations_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to(locations_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to(locations_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to(locations_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to(locations_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to(locations_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to(locations_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to(locations_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to(locations_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to(locations_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to(locations_url) }\n format.xml { head :ok }\n end\n end", "def destroy\r\n @backend_location.destroy\r\n respond_to do |format|\r\n format.html { redirect_to backend_locations_url, notice: 'Location was successfully destroyed.' }\r\n format.json { head :no_content }\r\n end\r\n end", "def destroy\n @patient_location.destroy\n respond_to do |format|\n format.html { redirect_to patient_locations_url, notice: 'Patient location was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @corp_location = CorpLocation.get(params[:id])\n @corp_location.destroy\n\n respond_to do |format|\n format.html { redirect_to corp_locations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n debug('Removing location')\n crm('configure', 'delete', @resource[:name])\n @property_hash.clear\n end", "def destroy\n @location = Location.find(params[:id])\n @location.destroy\n\n respond_to do |format|\n format.html { redirect_to(root_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @locationtype.destroy\n respond_to do |format|\n format.html { redirect_to locationtypes_url, notice: 'Locationtype was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @sign = Sign.find(params[:id])\n @location = Location.find(@sign.location_id)\n @sign.destroy\n\n respond_to do |format|\n format.html { redirect_to location_index_path(@location.name.downcase) }\n format.json { head :no_content }\n end\n end" ]
[ "0.79904115", "0.79009205", "0.78712076", "0.7864998", "0.779462", "0.7759236", "0.77300984", "0.7724419", "0.7718348", "0.7697779", "0.76676565", "0.7649388", "0.7642275", "0.76372886", "0.7634565", "0.75894624", "0.7577347", "0.756857", "0.75489223", "0.7539702", "0.7509996", "0.7509706", "0.7509706", "0.7509706", "0.7509706", "0.7509706", "0.7509706", "0.7509706", "0.7509706", "0.7509706", "0.7509706", "0.7509706", "0.7509706", "0.7509706", "0.7509706", "0.7509706", "0.7509706", "0.7509698", "0.7496337", "0.74843997", "0.74769354", "0.74592", "0.7451334", "0.7441575", "0.7441575", "0.7441575", "0.7441575", "0.74407834", "0.74340314", "0.74257624", "0.740618", "0.740618", "0.73847157", "0.7381997", "0.7381997", "0.7381997", "0.7381997", "0.7381997", "0.7381997", "0.7381997", "0.7381997", "0.73757184", "0.73638594", "0.73568606", "0.7344523", "0.7333481", "0.73317814", "0.7299681", "0.72865933", "0.7279502", "0.72771686", "0.7277113", "0.72751856", "0.72358173", "0.72299755", "0.7229121", "0.72262406", "0.7203343", "0.71935654", "0.71889067", "0.71792454", "0.71792454", "0.71792454", "0.71792454", "0.71792454", "0.71792454", "0.71792454", "0.71792454", "0.71792454", "0.71792454", "0.71792454", "0.71792454", "0.71792454", "0.7178394", "0.7175059", "0.7174767", "0.71476173", "0.7142641", "0.7140532", "0.7137543" ]
0.76102585
15
Only allow a trusted parameter "white list" through.
def location_params params.require(:location).permit(:longitude, :latitude, :altitude, :user_id) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def allowed_params\n ALLOWED_PARAMS\n end", "def expected_permitted_parameter_names; end", "def param_whitelist\n [:role, :title]\n end", "def default_param_whitelist\n [\"mode\"]\n end", "def permitir_parametros\n \t\tparams.permit!\n \tend", "def permitted_params\n []\n end", "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 filtered_parameters; end", "def permitted_strong_parameters\n :all #or an array of parameters, example: [:name, :email]\n end", "def parameters_list_params\n params.require(:parameters_list).permit(:name, :description, :is_user_specific)\n end", "def parameter_params\n params.require(:parameter).permit(:name, :description, :param_code, :param_value, :active_from, :active_to)\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 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 param_whitelist\n [:rating, :review]\n end", "def valid_params?; end", "def permitted_params\n declared(params, include_missing: false)\n end", "def permitted_params\n declared(params, include_missing: false)\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 filter_parameters; end", "def filter_parameters; end", "def strong_params\n params.require(:team_member).permit(param_whitelist)\n end", "def strong_params\n params.require(:community).permit(param_whitelist)\n end", "def check_params; true; end", "def valid_params_request?; end", "def strong_params\n params.require(:experience).permit(param_whitelist)\n end", "def allowed_params\n params.require(:user).permit(:username, :email, :password, :password_confirmation)\n end", "def list_params\n params.permit(:name)\n end", "def check_params\n true\n end", "def grant_params\n @whitelisted = params.require(:grant).permit(:name, :description, :agency_id, :acronym)\n 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 additional_permitted_params\n []\n end", "def strong_params\n params.require(:education).permit(param_whitelist)\n end", "def resource_params\n params[resource_singular_name].try(:permit, self.class.param_whitelist)\n end", "def allow_params_authentication!; 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 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 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 paramunold_params\n params.require(:paramunold).permit!\n end", "def param_params\n params.require(:param).permit(:param_category_id, :param_table_id, :name, :english_name, :weighting, :description)\n end", "def quote_params\n params.permit!\n end", "def list_params\n params.permit(:list_name)\n end", "def allowed_params(parameters)\n parameters.select do |name, values|\n values.location != \"path\"\n end\n end", "def all_params; end", "def permitted_resource_params\n params[resource.object_name].present? ? params.require(resource.object_name).permit! : ActionController::Parameters.new\n end", "def source_params\n params.require(:source).permit(all_allowed_params)\n end", "def user_params\n end", "def get_allowed_parameters\n return _get_specific_action_config(:allowed_action_parameters, :allowed_parameters)&.map(&:to_s)\n end", "def params; end", "def params; end", "def params; end", "def params; end", "def params; end", "def params; end", "def params; end", "def params; end", "def params; end", "def params; end", "def params; end", "def params; end", "def params; end", "def params; end", "def params; end", "def params; end", "def params; end", "def permitted_params\n @wfd_edit_parameters\n end", "def user_params\r\n end", "def param_whitelist\n whitelist = [\n :comment,\n :old_progress, :new_progress,\n :metric_id\n ]\n \n unless action_name === 'create'\n whitelist.delete(:metric_id)\n end\n \n whitelist\n end", "def query_param\n\t\tparams.permit(:first_name, :last_name, :phone)\n\tend", "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 params.permit(:id, :email, :password, :nickname, :status, :avatar, :flat_picture, :flatsharing_id, :member,\n :user, :color, :solde)\n end", "def filter_params\n\t\treturn params[:candidate].permit(:name_for_filter)\n\tend", "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 get_params\n\t\t\n\t\treturn ActionController::Parameters.new(self.attributes).permit(:first_name, :last_name, :email, :provider)\n\n\tend", "def valid_params(params)\n params.permit(:user_id, :photo_id, :originX, :originY, :width, :height)\n end", "def valid_parameters\n sort_symbols(@interface.allowed_parameters)\n end", "def params_permit\n params.permit(:id)\n end", "def allowed_params\n params.require(:allowed).permit(:email)\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 filter_params\n params.permit(*resource_filter_permitted_params)\n end", "def specialty_params\n\t\tparams.require(:specialty).permit(*Specialty::DEFAULT_ACCESSIBLE_ATTRIBUTES)\n\tend", "def community_params\n params.permit(:profile_image, :name, :description, :privacy_type, :viewed_by, {tags: []}, {features: []}, {admins: []}, :members, :location, :beacon, :creator, :ambassadors, :current_events, :past_events, :feed, :category, :address, :allow_member_post_to_feed, :allow_member_post_to_events)\n end", "def authorize_params\n super.tap do |params|\n %w[display scope auth_type].each do |v|\n if request.params[v]\n params[v.to_sym] = request.params[v]\n end\n end\n end\n end", "def feature_params_filter\n params.require(:feature).permit(:name, :cat, :lower, :upper, :opts, :category, :description, :company, :active, :unit, :icon)\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 argument_params\n params.require(:argument).permit(:name)\n end", "def user_params_pub\n\t \tparams[:user].permit(:hruid)\n\t end", "def strong_params\n params.require(:success_metric).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 property_params\n params.permit(:name, :is_available, :is_approved, :owner_id)\n end", "def sponsor_params\n params.require(:sponsor).permit(WHITE_LIST)\n end", "def whitelist_person_params\n params.require(:person).permit(:family, :pre_title, :given_name, :dates, :post_title, :epithet, :dates_of_office, same_as: [], related_authority: [], altlabel: [], note: []) # Note - arrays need to go at the end or an error occurs!\n end", "def user_params \n \tparams.require(:user).permit(:name, :email, :password, :password_confirmation)# preventing CSTR\n end", "def parameters\n nil\n end", "def sequence_param_whitelist\n default_param_whitelist << \"show_index\"\n end", "def resource_filter_permitted_params\n raise(NotImplementedError, 'resource_filter_permitted_params method not implemented')\n end", "def normal_params\n reject{|param, val| param_definitions[param][:internal] }\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 special_device_list_params\n params.require(:special_device_list).permit(:name)\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" ]
[ "0.71217275", "0.7052942", "0.6947555", "0.6903013", "0.6735074", "0.67167085", "0.6687677", "0.66765445", "0.66602796", "0.65548825", "0.6524274", "0.6455697", "0.6451343", "0.645123", "0.64465624", "0.6433475", "0.64118403", "0.64118403", "0.6390524", "0.6378871", "0.6378871", "0.6374268", "0.6360606", "0.6354037", "0.6284485", "0.62780905", "0.624562", "0.6225378", "0.6224288", "0.62237734", "0.6210716", "0.62073183", "0.61760557", "0.61714864", "0.61689645", "0.6159245", "0.6145253", "0.61351544", "0.61209726", "0.61050045", "0.60978544", "0.6073292", "0.6052814", "0.60387754", "0.60352194", "0.60294884", "0.6018536", "0.6017761", "0.6016042", "0.6016042", "0.6016042", "0.6016042", "0.6016042", "0.6016042", "0.6016042", "0.6016042", "0.6016042", "0.6016042", "0.6016042", "0.6016042", "0.6016042", "0.6016042", "0.6016042", "0.6016042", "0.6016042", "0.6015598", "0.60044724", "0.6003913", "0.6001379", "0.599616", "0.5994301", "0.5994205", "0.5984454", "0.5983921", "0.5976679", "0.5974281", "0.59687614", "0.59656674", "0.59649783", "0.59649783", "0.59568197", "0.5950897", "0.5950399", "0.59472823", "0.59424376", "0.59294873", "0.59292394", "0.592647", "0.59236294", "0.59178543", "0.59175855", "0.5913039", "0.5912506", "0.59062296", "0.5905145", "0.5904936", "0.5901632", "0.5899609", "0.589707", "0.58955824", "0.5894598" ]
0.0
-1
Returns the user's fullname and its username in brackets.
def full_user_link(user) link_to edit_user_path(user) do html = content_tag :strong, "#{user.prename} #{user.name}" html << " (#{user.username})" end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def user_full_name\n if user\n user.first_name + ' ' + user.last_name\n else\n 'Anonymous'\n end\n end", "def full_name(user)\n user.first_name + ' ' + user.last_name\n end", "def full_name\n name = `finger $USER 2> /dev/null | grep Login | colrm 1 46`.chomp\n name.empty? ? \"John Doe\" : name.squish\n end", "def name\n if first_name.present? || last_name.present?\n [first_name, last_name].join(\" \").strip\n else\n username\n end\n end", "def full_user_name\n formatedName=first_name[0].upcase+first_name[1,first_name.size].downcase+\" \"+last_name[0].upcase+last_name[1,last_name.size].downcase\n return formatedName.strip if (first_name || last_name)\n return \"Anonymous\"\n end", "def full_name\n \n if (not self.first_name.nil? and not self.first_name.eql? \"\") or (not self.last_name.nil? and not self.last_name.eql? \"\")\n \"#{self.title} #{self.first_name} #{self.last_name}\".strip\n elsif self.username\n self.username \n else\n # wrapped email only prefix\n\n parsed_email = self.email.split('@')\n parsed_email[0]\n end\n end", "def user_full_name\n first_name + \" \" + last_name\n end", "def full_name\n name = `finger $USER 2> /dev/null | grep Login | colrm 1 46`.chomp\n name.present? ? name.squish : \"John Doe\"\n end", "def simple_username\n return user.firstname + ' ' + user.lastname.first + '.' if !user.nil?\n name\n end", "def user_full_name\n user ? user.full_name : \"Anonymous\"\n end", "def full_name\n \tif self.first_name != nil and self.last_name != nil\n \t\tself.first_name + \" \" + self.last_name\n \telse\n \t\t\"User does not have a full name\"\n \tend\n end", "def full_name\n if user_data\n \"#{user_data['first_name']&.downcase&.capitalize} #{user_data['last_name']&.downcase&.capitalize}\"\n end\n end", "def fullname\n \"#{first_name} #{last_name}\"\n end", "def full_name \n if current_user\n current_user.firstname + \" \" + current_user.lastname\n else\n \"Please Log in\"\n end\n end", "def user_full_name\n @user[\"name\"]\n end", "def full_name\n if self.profile.present?\n \"#{self.profile.first_name.capitalize} #{self.profile.last_name.capitalize}\"\n else\n \"#{username.capitalize}\"\n end\n end", "def full_name\n \"#{username}/#{name}\"\n end", "def name\n\t\tn = names\n\t\treturn n[:fullname] if n[:fullname]\n\t\treturn n[:username] if n[:username]\n\t\treturn I18n.translate(\"user.name.unknown\")\n\tend", "def username_and_first_name\n if first_name.nil?\n username\n else\n \"#{username} (#{first_name})\"\n end\n end", "def proper_name # method to get the full name of user\n first_name + \" \" + last_name\n end", "def full_name\n \treturn \"#{first_name} #{last_name}\".strip if(first_name || last_name) \n \t\"Anonymous\"\n end", "def fullname\n return first_name + \" \" + last_name\n end", "def full_name\n if (first_name && last_name) && (!first_name.blank? && !last_name.blank?)\n \" #{first_name} #{last_name}\"\n else\n \" #{nickname}\"\n end\n end", "def full_name\n \"#{user_profile.first_name} #{user_profile.last_name}\" unless user_profile.blank?\n end", "def full_name\n [first_name, last_name].join(' ')\n end", "def full_name\n return first_name + \" \" + last_name\n end", "def full_name\n return first_name + \" \" + last_name\n end", "def user_full_name\n return object.billing_name if object.billing_name.present?\n \"#{user_firstname} #{user_lastname}\"\n end", "def full_name\n \tif !self.first_name.nil? && !self.last_name.nil?\n\t\t\"#{self.first_name.titleize} #{self.last_name.titleize}\"\n\telsif !self.oauth_user_name.nil?\n\t\tself.oauth_user_name\n\telse\n\tend\n end", "def short_user_name\n user.first_name\n end", "def fullname\n [firstname,middlename,lastname].join(' ')\n end", "def fullname\n return @first_name + ' ' + @surname\n end", "def fullname\n [firstname, middlename, lastname].compact.join(\" \")\n end", "def full_name\n [@first_name, @last_name].join(' ')\n end", "def get_full_name(user_id)\n if user_id\n u = User.find(user_id)\n return u.firstname + \" \" + u.lastname\n else\n return \"Unknown\"\n end\n end", "def full_name\n \"#{self.first_name} #{self.last_name}\"\n # can got to rails console and type command \"user = User.first\" => \"user.full_name\"\n end", "def display_name\n \"#{username} <#{email}>\"\n end", "def full_name\n \"#{self.nickname.blank? ? self.first_name : self.nickname} #{self.last_name}\"\n end", "def full_name\n \"#{first_name} #{last_name}\"\n end", "def full_name\n \"#{first_name} #{last_name}\"\n end", "def full_name\n \"#{first_name} #{last_name}\"\n end", "def full_name()\n name + ' ' + last_name\n end", "def show_name\n return_string = \"\"\n if first_name.present? || last_name.present?\n return_string = \"#{first_name} #{last_name}\".strip\n end\n if login.present?\n return_string = return_string.blank? ? login : \"#{return_string} (#{login})\".strip\n end\n if return_string.blank?\n return_string = email\n end\n return_string\n end", "def name\n result = []\n result << self.first_name\n result << self.last_name\n if result.compact.empty?\n self.user.login if self.user\n else\n result.compact.map {|m| m.to_s.strip}.reject {|i| i.blank?}.join(' ')\n end\n end", "def full_name\n \t[self.first_name, self.last_name].join(\" \")\n end", "def full_name\n return \"#{@first_name} #{@last_name}\"\n end", "def full_name\n return \"#{@first_name} #{@last_name}\"\n end", "def full_name\n\t\tself.user_fname.capitalize + \" \" + self.user_lname.capitalize\n\tend", "def full_name\n first_name + \" \" + last_name\n end", "def full_name\n if !first_name && !last_name\n return \"New User\"\n else\n return first_name + \" \" + last_name\n end\n end", "def full_name\n [first_name, last_name].join(\" \")\n end", "def full_name\n [first_name, last_name].join(\" \")\n end", "def full_name\n [first_name, last_name].join(\" \")\n end", "def full_name\n [first_name, last_name].join(\" \")\n end", "def full_name\n [first_name, last_name].join(\" \")\n end", "def full_name\n [first_name, last_name].join(\" \")\n end", "def full_name \n [first_name, last_name].join(' ')\n end", "def full_name\n \"#{first_name}\" \" #{last_name}\"\n end", "def full_name\n [first_name, last_name].join(' ')\n end", "def full_name\n [first_name, last_name].join(' ')\n end", "def full_name\n [first_name, last_name].join(' ')\n end", "def full_name\n [first_name, last_name].join(' ')\n end", "def full_name\n [first_name, last_name].join(' ')\n end", "def get_user_name\n if first_name.blank?\n return email.split('@').first.capitalize unless email.blank? \n else\n return first_name.capitalize + \" \" + last_name.capitalize\n end \n return ''\n end", "def full_name\n \"#{first_name} #{last_name}\"\n end", "def full_name\n \"#{firstname} #{lastname}\".strip\n end", "def full_name\n @first_name + ' ' + @last_name\n end", "def display_name\n #self.email.split('@')[0]\n self.username\n end", "def full_name\n [self.first_name, self.last_name].join(' ')\n end", "def full_name\n \"#{first_name} #{last_name}\"\n end", "def fullname\n return @first_name.capitalize + \" \" + @surname.capitalize\n end", "def full_name\n\t\treturn self.salutation.to_s + \" \" + self.last_name.to_s + \" \" + self.first_name.to_s\n end", "def full_name\n \t([first_name, last_name].compact-['']).join(' ')\n end", "def full_name\n [self.first_name, self.last_name].compact.join(\" \").strip\n end", "def fullname\n @fullname = \"\"\n if !self.first_name.blank?\n @fullname = self.first_name\n end\n\n if !self.last_name.blank?\n @fullname += ' ' + self.last_name\n end\n\n @fullname\n end", "def full_name\n\t\tfirst_name + \" \" + last_name\n\tend", "def fullname\n \"#{@first_name} #{@surname}\"\n end", "def full_name\n [first_name, last_name].join(' ').strip\n end", "def full_name\n \"#{first_name} #{last_name}\"\n end", "def full_name\n\t\t\"#{first_name} #{last_name}\"\n\tend", "def full_name\n\t\t\"#{first_name} #{last_name}\"\n\tend", "def full_name\n\t\t\"#{first_name} #{last_name}\"\n\tend", "def full_name\n\t\t\"#{first_name} #{last_name}\"\n\tend", "def full_name\n\t\t\"#{first_name} #{last_name}\"\n\tend", "def full_name\n\t\t\"#{first_name} #{last_name}\"\n\tend", "def fullName\n return first_name + \" \" + last_name\n end", "def fullname\n firstname + \" \" + lastname\n end", "def fullname\n firstname + \" \" + lastname\n end", "def full_name\n \t\"#{first_name} #{last_name}\"\n end", "def full_name\n json[\"entry_data\"][\"ProfilePage\"].first[\"graphql\"][\"user\"][\"full_name\"]\n end", "def full_name\n # clean_name\n \"#{@first_name} #{@middle_name} #{@last_name}\"\n [first_name, middle_name, last_name].compact.join(' ')\n end", "def fullname\n \"#{prename} #{lastname}\"\n end", "def full_name\n (@session[:current_user_details] || {})[:description]\n end", "def full_name\n if self.first_name.present? and self.last_name.present?\n \"#{self.first_name} #{self.last_name}\"\n else\n self.first_name\n end\n end", "def full_name\n\t\tfirst_name + ' ' + last_name\n\tend", "def full_name\n\t\tfirst_name + ' ' + last_name\n\tend", "def get_full_name(user)\n begin\n Etc.getpwnam(\"#{user}\")[\"gecos\"].chomp\n # or with dscl\n # %x(dscl /Search -read /Users/#{user} dsAttrTypeNative:cn).split.drop(1).join(\" \") \n rescue Exception => e\n end\n \n end", "def full_name\n \"#{ first_name } #{ last_name }\"\n end", "def full_name\n if self.user\n user.full_name\n else\n self.name\n end\n end", "def full_name\n \"#{first_name} #{last_name}\".strip\n end", "def full_name\n \"#{first_name} #{last_name}\".strip\n end" ]
[ "0.8158177", "0.7872309", "0.783311", "0.7799578", "0.7790509", "0.77893984", "0.77218884", "0.7696811", "0.7643659", "0.7622009", "0.7613974", "0.7597232", "0.75905824", "0.75795305", "0.7576303", "0.75638163", "0.7555768", "0.75332564", "0.752702", "0.75214", "0.75159127", "0.7467956", "0.7455717", "0.7408222", "0.7381902", "0.73811334", "0.73811334", "0.7376943", "0.7376678", "0.734328", "0.7321317", "0.7308707", "0.73079735", "0.7306837", "0.7302229", "0.7298162", "0.7292942", "0.72900593", "0.728895", "0.728895", "0.728895", "0.72814673", "0.7255591", "0.72527564", "0.72526145", "0.7234719", "0.7234719", "0.7232139", "0.7225766", "0.7223956", "0.72182864", "0.72182864", "0.72182864", "0.72182864", "0.72182864", "0.72182864", "0.72059846", "0.7201502", "0.72006077", "0.72006077", "0.72006077", "0.72006077", "0.72006077", "0.7200349", "0.7194653", "0.7192035", "0.718255", "0.7157542", "0.7157101", "0.71493924", "0.71481913", "0.7142689", "0.7141665", "0.71412843", "0.7135906", "0.7127785", "0.7117011", "0.71139586", "0.7107776", "0.710345", "0.710345", "0.710345", "0.710345", "0.710345", "0.710345", "0.70928985", "0.70926577", "0.70926577", "0.7085276", "0.7084695", "0.707551", "0.7069486", "0.7067919", "0.7065754", "0.70650274", "0.70650274", "0.7063911", "0.7056829", "0.70552504", "0.7043456", "0.7043456" ]
0.0
-1
def self.prepended 1/ new method RM 4.0.3 OK Smile specicfic 784714 V4.0.0 : My page Time Entry queries
def name_and_project return name unless project "#{::ERB::Util.h name}&nbsp;&nbsp;|&nbsp;&nbsp;#{::ERB::Util.h project.name}".html_safe end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def internal\n if params[:col].blank? && params[:dir].blank?\n params.merge!(:col => 'created_at', :dir => 'up')\n end\n sort_column_order\n\t\tset_page_number(192,193,71,params[:status])\n\t\tsession[:referer] = nil\n\t\tdata=params\n\t\tapproved_or_billed_time_and_expense_entry(data)\n\t\tsession[:current_time_entry] = nil\n\t\tget_matters_and_contacts\n\t\tunless data[:start_date].nil?\n\t\t\tif (!data[:start_date].blank? && !data[:end_date].blank?)\n\t\t\t\tstart_date = data[:start_date].to_date if data[:start_date]\n\t\t\t\tend_date = data[:end_date].to_date if data[:end_date]\n\t\t\t\tif start_date <= end_date\n\t\t\t\t\tget_receiver_and_provider\n\t\t\t\t\tif data[:col]&& data[:dir]\n\t\t\t\t\t\torder = data[:dir].eql?(\"up\") ? \"#{data[:col]+ ' '+ 'asc'}\" : \"#{data[:col]+ ' '+ 'desc'}\"\n\t\t\t\t\t\t@icon = data[:dir].eql?(\"up\") ? 'sort_asc':'sort_desc'\n\t\t\t\t\telse\n\t\t\t\t\t\torder = \"created_at asc\"\n\t\t\t\t\tend\n\t\t\t\t\tconditions = \"is_internal and company_id = #{@receiver.company_id} and time_entry_date between '#{data[:start_date]}' and '#{data[:end_date]}'\"\n\t\t\t\t @saved_time_entries_new = Physical::Timeandexpenses::TimeEntry.find(:all,:conditions => conditions, :order=>order)\n unless params[:status].blank?\n\t\t\t\t\t\tconditions += \" and status = '#{params[:status]}'\"\n\t\t\t\t\tend\n\t\t\t\t\t@saved_time_entries = Physical::Timeandexpenses::TimeEntry.find(:all,:conditions => conditions, :order=>order)\n\n conditions = \"is_internal and company_id = #{@receiver.company_id} and expense_entry_date between '#{data[:start_date]}' and '#{data[:end_date]}'\"\n\t\t\t\t\t@saved_expense_entries_new = Physical::Timeandexpenses::ExpenseEntry.find(:all,:conditions => conditions, :order =>order)\n\n unless params[:status].blank?\n\t\t\t\t\t\tif params[:status]=='Billed'\n\t\t\t\t\t\t\tconditions += \" and status = '#{params[:status]}' and tne_invoice_id is not null\"\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tconditions += \" and status = '#{params[:status]}'\"\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\t@saved_expense_entries = Physical::Timeandexpenses::ExpenseEntry.find(:all,:conditions => conditions, :order =>order)\n\n get_total_hours_for_all_status\n get_expense_details_for_status\n get_total_billable_time_amount_status\n @grand_total_open = @total_amount_open + @total_expenses_open\n @grand_total_approved = @total_amount_approved + @total_expenses_approved\n @grand_total_billed = @total_amount_billed + @total_expenses_billed\n @total_hours = @total_hours_open + @total_hours_approved + @total_hours_billed\n @total_amount = @total_amount_open + @total_amount_approved + @total_amount_billed\n @grand_total_expense = @total_expenses_open + @total_expenses_approved + @total_expenses_billed\n @grand_total = @grand_total_open + @grand_total_approved + @grand_total_billed\n\t\t\t\telse\n\t\t\t\t\tflash[:error] = t(:flash_end_date_start_date)\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tflash[:error] = t(:flash_enter_date)\n\t\t\tend\n\t\tend\n\t\tparams[:current_tab]=params[:current_tab].nil? ? 'fragment-1' : params[:current_tab]\n\t\t@current_stage=params[:current_tab]\n\t\tadd_breadcrumb \"Internal\", :physical_timeandexpenses_internal_path\n\n #Following code added for Feature #8234 - export to excel in all view pages in T & E\n ##Params are stored in instance variable for the generating link for generating excel report\n\t\t@status = params[:status]\t\t\t\n\t\t@start_date= params[:start_date]\n\t\t@end_date = params[:end_date]\n\t\t@current_tab = params[:current_tab]\n\t\t@row_headers = [\"T/E\",\"Date\",\"Lawyer Designation / Non-User\",\"Time(HH:MM)\",\"Dur(Hrs)\",\"Rate($)\",\"Activity\",\"Description\",\"Billable (Y/N)\",\"Final Bill Amt($)\",\"Status\"]\n\t\t@report_heads = [params[:start_date],params[:end_date]]\n\t\trespond_to do|format|\n\t\t\tformat.html{}\n\t\t\tformat.xls {\n\t\t\t\tsend_data(LiviaExcelReport.generate_xls_for_time_expenses(@saved_time_entries,@saved_expense_entries,@row_headers,@report_heads,\"internal\",@dur_setng_is_one100th),:filename => \"time_expense.xls\", :type => 'application/xls', :disposition => 'inline')\n\t\t\t}\n\t\tend\n\n\tend", "def who_we_are\r\n end", "def probers; end", "def pre_pay_offered\n end", "def entry_order; end", "def page_load; end", "def coming_soon\n end", "def coming_soon\n end", "def page; end", "def page; end", "def page; end", "def page; end", "def page; end", "def page; end", "def page; end", "def page; end", "def page; end", "def page; end", "def page; end", "def page; end", "def prapor_quest; end", "def mission(page)\n\tend", "def meta_refresh; end", "def extra; end", "def offences_by; end", "def follow_meta_refresh; end", "def follow_meta_refresh; end", "def page_code\n \t0\n end", "def find_page_end\n \n end", "def def_dept_helper\n @basic_query_params[:fields] = ['timeoriginalestimate', 'customfield_10002']\n end", "def search_params_pre_1986(d)\n # http://proquest.umi.com.libproxy.mit.edu/pqdweb?SQ=&DBId=9866&date=ON&onDate=03%2F05%2F1979&beforeDate=&fromDate=&toDate=&FT=1&AT=article&author=&sortby=CHRON&RQT=305&querySyntax=PQ&searchInterface=1&moreOptState=OPEN&TS=1326313179&h_pubtitle=&h_pmid=&clientId=5482&JSEnabled=1\n add_default_params( d, {\n :DBId=>'9866',\n })\n end", "def p15\n\t\nend", "def\n\n# *********VENUE GET METHODS*********\n def get_till_receipts\n\n end", "def page=(_arg0); end", "def page=(_arg0); end", "def page=(_arg0); end", "def parts_query\n nil\n end", "def recurring; end", "def new_time_entry\n @pagenumber =68\n\t\tauthorize!(:new_time_entry,current_user) unless current_user.has_access?('Time & Expense')\n\t\tdata=params\n\t\tflash[:notice] = nil\n\t\t@time_entry = current_company.time_entries.new\n\t\tcondition_str = \"users.company_id = #{current_company.id}\"\n unless data[:physical_timeandexpenses_time_entry].blank?\n\t\t\t@entry_date = data[:physical_timeandexpenses_time_entry][:time_entry_date]\n\t\telse\n\t\t\t@entry_date = data[:time_entry_date] || Time.zone.now.to_date.strftime('%m/%d/%Y')\n\t\tend\n\t\tif(params[:from] == \"matters\" && !params[:matter_id].blank?)\n\t\t\t@matter = Matter.find(params[:matter_id],:conditions => [\"company_id = ? \",current_company.id])\n\t\t\tget_lawyers(@matter)\n else\n @lawyers = User.all(:joins => \"inner join employees on employees.user_id = users.id\", :conditions => [condition_str])\n\t\tend\n\t\t@expense_entry = Physical::Timeandexpenses::ExpenseEntry.new\n\t\t@note_id=params[:id]\n\t\t@note_name=StickyNote.find_by_note_id_and_assigned_to_user_id(params[:id],assigned_user) if params[:id]\n\t\t@time_entry.employee_user_id = get_employee_user_id\n\t\tget_unexpired_matters(@entry_date,@time_entry.employee_user_id)\n\t\tget_contacts\n\t\tadd_breadcrumb 'Add Time Entry' , request.request_uri unless params[:height]\t\t\t\n\t\tdefault_activity_type_id = CompanyActivityType.find(:first,:conditions=>\"company_id=#{current_company.id}\").id\n\t\t@time_entry.activity_rate = @time_entry.actual_activity_rate = rounding(Physical::Timeandexpenses::TimeEntry.get_billing_rate(get_company_id, get_employee_user_id, default_activity_type_id, get_user_designation_id,@time_entry.employee_user_id))\n if params[:timer_value].present?\n secs = params[:timer_value].to_i\n secs = (secs > 30 && secs < 60) ? 60 : secs\n min = (secs/60)\n @time_entry.actual_duration = min\n end\n\t\trender :layout => false if params[:height]\n\tend", "def show\n realtime_page_next_by_time Integer(params[:post_id]), Integer(params[:after]), Integer(params[:limit])\n end", "def schubert; end", "def kopal_layout_before_page_meta\n\n end", "def follow_meta_refresh=(_arg0); end", "def magic_params_not_truly_understood\n \"timekey=#{@timekey}&custom_search=0\"\n end", "def new_query\n @min_date, @max_date = PlateTube.find_min_and_max_dates\n @oligo_usages = PlatePosition::OLIGO_USAGE.invert.to_a.sort.insert(0,'(All)') \n end", "def history_added; end", "def allow_in_post_mortem; end", "def follow_meta_refresh_self; end", "def follow_meta_refresh_self; end", "def version_added; end", "def next_page; end", "def before; end", "def pages; end", "def more_advanced_date\n \tnil\n end", "def method_added(*) end", "def method_731(base); end", "def pro_rata_start_date\n # \n # Tue Nov 23 00:53:04 IST 2010, ramonrails\n # * we will never use \"installation_datetime\"\n # * installation_datetime is the \"desired\" installation datetime\n # * Pro-rata is charged from the date a panic button is received making user ready to install\n #\n # * check panic button press\n _date = panic_received_at\n # * no panic? check shipping date\n _date ||= (shipped_at + 7.days) unless shipped_at.blank? # if ( _date.blank? && !shipped_at.blank? )\n # * no panic or shipping? nothing returned\n # # \n # # Wed Mar 30 03:46:04 IST 2011, ramonrails\n # # * https://redmine.corp.halomonitor.com/issues/4253\n # # * pick local values that were copied\n # # * when missing?, pick from device_model_prices\n # unless (order.blank? || order.product_cost.blank? || _date.blank?)\n # _date += ( order.cc_monthly_recurring || order.product_cost.recurring_delay).to_i.months\n # end\n # # \n # # Tue May 24 20:07:41 IST 2011, ramonrails\n # # * https://redmine.corp.halomonitor.com/issues/4486\n # # * https://redmine.corp.halomonitor.com/attachments/3294/invalid_prorate_start_dates.jpg\n # _date ||= Date.today\n # _date = Date.today if _date > Date.today\n # \n # Thu May 26 19:32:15 IST 2011, ramonrails\n # * https://redmine.corp.halomonitor.com/issues/4486#note-47\n _date = _date.to_date unless _date.blank?\n _date\n end", "def custom; end", "def custom; end", "def search_params_pre_1984(d)\n # http://proquest.umi.com.libproxy.mit.edu/pqdweb?SQ=&DBId=15108&date=ON&onDate=03%2F05%2F1979&beforeDate=&fromDate=&toDate=&FT=1&AT=any&author=&sortby=CHRON&RQT=305&querySyntax=PQ&searchInterface=1&moreOptState=CLOSED&TS=1326228265&h_pubtitle=&h_pmid=&clientId=5482&JSEnabled=1\n add_default_params( d, {\n :DBId=>'15108',\n })\n end", "def fullFromPage\n \n request ||= requestHtml\n \n @previsoes = Hash.new\n count = 1\n \n until count > 5 do\n @previsoes[count] = { \n :last_update => request.xpath(\"//p[@class='clear left paragrafo-padrao']\").text[/(\\d+)/]+\":00\",\n :date => request.xpath(\"//div[@class='box-prev-completa'][#{count}]//span[@class='data-prev']\").text.strip+\"/\"+Time.now().year.to_s,\n :condition => request.xpath(\"//div[@class='box-prev-completa'][#{count}]/span[@class='left left5 paragrafo-padrao top10 fraseologia-prev']\").text.strip,\n :wind => { :direction => wind[\"br\"][request.xpath(\"//div[@class='box-prev-completa'][#{count}]//li[@class='velocidade-vento-prev-completa list-style-none']//span//a[1]\").text.strip],\n :velocity => request.xpath(\"//div[@class='box-prev-completa'][#{count}]//li[@class='velocidade-vento-prev-completa list-style-none']//span//a[2]\").text.strip},\n :probability_of_precipitation => { :volume => request.xpath(\"//div[@class='box-prev-completa'][#{count}]//li[@class='prob-chuva-prev-completa list-style-none']/span//a[1]\").text.strip,\n :percentage => request.xpath(\"//div[@class='box-prev-completa'][#{count}]//li[@class='prob-chuva-prev-completa list-style-none']/span//a[2]\").text.strip},\n :moisture_relative_complete => { :max => request.xpath(\"//div[@class='box-prev-completa'][#{count}]//li[@class='umidade-relativa-prev-completa list-style-none']/span[2]\").text.strip,\n :min => request.xpath(\"//div[@class='box-prev-completa'][#{count}]//li[@class='umidade-relativa-prev-completa list-style-none']/span[3]\").text.strip},\n :temperature => { :max => request.xpath(\"//div[@class='box-prev-completa'][#{count}]//span[@class='max']\").text.strip,\n :min => request.xpath(\"//div[@class='box-prev-completa'][#{count}]//span[@class='min']\").text.strip},\n :uv => request.xpath(\"//div[@class='box-prev-completa'][#{count}]//p[@class='left left10 top10 paragrafo-padrao uv-size']/span[1]\").text.strip,\n :sunrise => request.xpath(\"//div[@class='box-prev-completa'][#{count}]//div[@class='por-do-sol']/span[3]\").text.strip,\n :sunset => request.xpath(\"//div[@class='box-prev-completa'][#{count}]//div[@class='por-do-sol']/span[6]\").text.strip\n }\n \n count+=1\n end\n \n @previsoes\n \n end", "def new_query\n @versions = Version.curr_version.order(:id)\n @enzymes = Enzyme::ENZYMES_WO_GAPFILL\n end", "def page; self end", "def initial_query; end", "def search_by_cooking_time(cooking_time)\n clear\n choices = $default_recipe.recipe_name_and_cooktime.filter{|k,v|v <= cooking_time}.keys << 'Previous Page'##CATCH ERROR HERE\n recipe_choice = display_choices(\"List of Dish that can be made in less than #{cooking_time} minutes : \",choices)\n return level_2_option_1 if recipe_choice == 'Previous Page'\n display_ing_and_method(recipe_choice)\nend", "def outdated; end", "def online_special_ballot\n end", "def before() ; end", "def pages=(_arg0); end", "def entry_order=(_arg0); end", "def get_start_page\n raise 'Not implemented'\n end", "def pagination_column\n Log.debug { \"#{__method__}: not defined for #{self_class}\" }\n end", "def order; end", "def order; end", "def Com6 # Recuperation Info\n \n end", "def past_participle; end", "def oldmtd\r\n \"old method\"\r\nend", "def weighIntrade()\n\n end", "def skier_quest; end", "def weber; end", "def flag_comment\n page(MorePage).select_more_actions(\"Best Comments\")\n page(MorePage).page_handler(\"Best Comments\")\n page(MorePage).table_view\n page(MorePage).find_item\n page(MorePage).touch_subflag\n page(NavTabBarPage).flag_handler(\"Cancel\")\n page(MorePage).backpage\n page(MorePage).select_more_actions(\"New Comments\")\n page(MorePage).page_handler(\"New Comments\")\n page(MorePage).backpage\nend", "def upc_e; end", "def lead_time\n 1\n end", "def custom_fix! held_page\n self.custom_fix.call held_page unless self.custom_fix.nil?\n end", "def pa_request(*args)\n bp_request\n @page_number = convert_expression(@page_number, args, \"page number\") - 1 # Becaue it will be incremented\n end", "def production_curtailment; end", "def private; end", "def on_307; on_330; end", "def reap; end", "def previous_page; end", "def history_added=(_arg0); end", "def extra_pubish_tasks(p)\n \n end", "def reduce_ahead_of_time_penalty!\n warn \"Experimental code #{__method__}. Do not enable in release. #{__FILE__}:#{__LINE__}\"\n soft_patch_defines_lua!(\"fun_and_balance_ahead_of_time\",\n [\"NCountry.TECH_AHEAD_OF_TIME\", 0.1, 0.01],\n )\n end", "def ld_hl_sp_plusr8\n end", "def page()\n session[:edit_mode] ||= 0\n# Initialize parts\n @parts = nil\n @js, @css = '', ''\n# find domain name in sites\n @site = dc_get_site\n# site is not defined. render 404 error\n return dc_render_404('Site!') if @site.nil?\n dc_set_options(@site.settings)\n# HOMEPAGE. When no parameters is set\n params[:path] = @site.homepage_link if params[:id].nil? and params[:path].nil?\n# Search for page \n pageclass = @site.page_table.classify.constantize\n if params[:id]\n @page = pageclass.find_by(subject_link: params[:id])\n elsif params[:path]\n# path may point direct to page's subject_link\n @page = pageclass.find_by(subject_link: params[:path])\n end\n# if @page is not found render 404 error\n return dc_render_404('Page!') unless @page\n dc_set_options @page.params\n# find design if defined. Otherwise design MUST be declared in site\n if @page.dc_design_id\n @design = DcDesign.find(@page.dc_design_id)\n return dc_render_404('Design!') unless @design\n end\n# Add to edit menu\n if session[:edit_mode] > 0\n session[:site_id] = @site.id\n session[:site_page_table] = @site.page_table\n session[:page_id] = @page.id\n end\n# perform check every hour. Perhaps if user has rights changes\n session[:last_check] ||= Time.now\n if (session[:last_check] - Time.now) > 3600\n # perform checks\n # TO BE DONE\n \n # update time\n session[:last_check] = Time.now\n end \n @page_title = @page.subject.empty? ? @site.page_title : @page.subject\n get_design_and_render @design\nend", "def page_trx_sys\n 5\n end", "def trd; end", "def beginning_of_week=(_arg0); end", "def beginning_of_week=(_arg0); end", "def hits_prev\n # see PsiBlastJob for comment\n end", "def next_page\n end" ]
[ "0.5826976", "0.57364345", "0.5629898", "0.5559913", "0.5502287", "0.54747945", "0.54685026", "0.54685026", "0.54628676", "0.54628676", "0.54628676", "0.54628676", "0.54628676", "0.54628676", "0.54628676", "0.54628676", "0.54628676", "0.54628676", "0.54628676", "0.54628676", "0.54460734", "0.5445409", "0.5445372", "0.5430817", "0.53966886", "0.534922", "0.534922", "0.5323651", "0.53197235", "0.5317873", "0.5268431", "0.5237862", "0.52189404", "0.5196862", "0.5196862", "0.5196862", "0.51824045", "0.5173897", "0.51656073", "0.51601917", "0.5157483", "0.5155329", "0.5150255", "0.51463765", "0.5145406", "0.5138206", "0.51353145", "0.51177603", "0.51177603", "0.5117608", "0.51175797", "0.5107031", "0.509585", "0.50893414", "0.50706786", "0.5056149", "0.5051476", "0.5047266", "0.5047266", "0.5041709", "0.5031638", "0.5018458", "0.5013814", "0.49960867", "0.4993944", "0.4987795", "0.49827686", "0.49807492", "0.49796036", "0.49768296", "0.49717566", "0.49543613", "0.49518645", "0.49518645", "0.4950953", "0.49507153", "0.49501354", "0.49490115", "0.49463734", "0.4943773", "0.49320328", "0.4927113", "0.4925701", "0.49231058", "0.49179155", "0.49107647", "0.49090865", "0.490676", "0.49010512", "0.48984015", "0.4887199", "0.48810163", "0.48808998", "0.4873846", "0.48731434", "0.48704308", "0.48684818", "0.48681933", "0.48681933", "0.48669803", "0.4865767" ]
0.0
-1
GET /gatos GET /gatos.json
def index @gatos = Gato.all respond_to do |f| f.html f.pdf{ render template: 'gatos/ficha', pdf:'Ficha Gato' } f.csv{ send_data @gatos.to_csv} f.xls # { send_data @gatos.to_csv(col_sep: "\t") } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def index\n @gatos = Gato.all\n end", "def show\n @gasto = Gasto.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gasto }\n end\n end", "def index\n @ginasios = Ginasio.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @ginasios }\n end\n end", "def index\n @gatineos = Gatineo.all\n end", "def show\n @gpath = Gpath.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gpath }\n end\n end", "def index\n @estacionamientos = Estacionamiento.all\n\n @json = Estacionamiento.all.to_gmaps4rails\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @estacionamientos }\n end\n end", "def show\n @gig = Gig.find(params[:id])\n\n respond_to do |format|\n format.html {render json: @gig, status: :ok}\n format.json { render json: @gig, status: :ok }\n end\n end", "def list_tenants_for_circles(args = {}) \n get(\"/tenants.json/circles\", args)\nend", "def show\n @ginasio = Ginasio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @ginasio }\n end\n end", "def index\n @ganhos = Ganho.find_by_user(current_user)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @ganhos }\n end\n end", "def index\n @gathas = Gatha.all\n end", "def index\n @gonzos = Gonzo.all\n end", "def index_by_user\n @gifts = @current_user.gifts\n render json: @gifts, include: :ages, status: :ok\n end", "def show\n @goat = Goat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @goat }\n end\n end", "def index\n @colegios = Colegio.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @colegios }\n end\n end", "def show\n @gethotel = Gethotel.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gethotel }\n end\n end", "def index\n @gomis = Gomi.all\n end", "def show\n @gravity = Gravity.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gravity }\n end\n end", "def index\n @ganhos = Ganho.all\n end", "def consulta\n fiesta = Fiesta.all\n render json: fiesta\n end", "def show\n @gig_request = GigRequest.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gig_request }\n end\n end", "def new\n @gasto = Gasto.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @gasto }\n end\n end", "def index\n @genotypes = Genotype.paginate(:page => params[:page], :per_page => 10)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @genotypes }\n end\n end", "def get_json(path)\n response = Net::HTTP.get_response(build_uri(path))\n result = JSON.parse(response.body)\n #puts \"🤖 GET #{path}\"\n #puts \"HTTP #{response.code}\"\n #puts JSON.pretty_generate(result)\n result\nend", "def index\n @antecedentes = Antecedente.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @antecedentes }\n end\n end", "def index\n @cgvs = Cgv.order('created_at')\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @cgvs }\n end\n end", "def index\n @gakkas = Gakka.all\n end", "def show\n @gethotelstaticdatagd = Gethotelstaticdatagd.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gethotelstaticdatagd }\n end\n end", "def get_json(path)\n puts \"*** GET #{path}\"\n\n response = Net::HTTP.get_response(build_uri(path))\n result = JSON.parse(response.body)\n puts \"HTTP #{response.code}\"\n\n puts JSON.pretty_generate(result)\n result\nend", "def show\n @client = Client.find(params[:id])\n @pets = @client.pets\n @json = @client.to_gmaps4rails\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @client }\n end\n end", "def get_json(path)\n puts \"*** GET #{path}\"\n\n response = Net::HTTP.get_response(build_uri(path))\n result = JSON.parse(response.body)\n puts \"HTTP #{response.code}\"\n\n #puts JSON.pretty_generate(result)\n result\nend", "def get_json(path)\n puts \"*** GET #{path}\"\n\n response = Net::HTTP.get_response(build_uri(path))\n result = JSON.parse(response.body)\n puts \"HTTP #{response.code}\"\n\n #puts JSON.pretty_generate(result)\n result\nend", "def show\n @grm_grappt = GrmGrappt.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @grm_grappt }\n end\n end", "def get_json()\n\n http = Net::HTTP.new(STATUS_URI.host, STATUS_URI.port)\n http.use_ssl = false\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n request = Net::HTTP::Get.new(\"/api/services.json\")\n\n response = http.request(request)\n JSON.parse(response.body)\nend", "def index\n @grooming_services = GroomingService.all\n end", "def show\n @golfer = Golfer.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @golfer }\n end\n end", "def index\n @grupoassuntos = Grupoassunto.all\n\n render json: @grupoassuntos\n end", "def show\n @orgao = Orgao.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @orgao }\n end\n end", "def index\n @glasses = Glass.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @glasses }\n end\n end", "def show\n @gnode = Gnode.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gnode }\n end\n end", "def index\n @cfos = Cfo.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @cfos }\n end\n end", "def index\n @generations = Generation.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @generations }\n end\n end", "def list_tenants_for_circle(args = {}) \n get(\"/tenantcircles.json/tenants\", args)\nend", "def index\n @formatos = Formato.where(ativo: true)\n \t\n render json: @formatos\n end", "def index\n @peticion_servicio_tis = Peticion::ServicioTi.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @peticion_servicio_tis }\n end\n end", "def index\n @distros = getmydata(\"Distro\")\n pagination\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @distros }\n end\n end", "def index\n @todos = Todo.all\n gon.current_user_api_key = current_user.api_key\n gon.api_url = Settings.api.url\n end", "def get_json\n response = @api.request(:get, @location)\n response.body if response.status == 200\n end", "def index\n @greats = Great.all\n end", "def index\n @ultimo_grado_de_estudios = UltimoGradoDeEstudio.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @ultimo_grado_de_estudios }\n end\n end", "def index\n @gentres = Gentre.all\n end", "def index\n @ton_giaos = TonGiao.all\n end", "def index\n @representante_athletes = current_user.organization.athletes\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @representante_athletes }\n end\n end", "def index_by_age\n @age = Age.find(params[:age_id])\n @gifts = @age.gifts\n render json: @gifts, include: :ages, status: :ok\n end", "def index\n @gommis = Gommi.all\n end", "def index\n @gamerooms = Gameroom.all\n end", "def get_json\n params = {}\n params['access_token'] = EXPA.client.get_updated_token\n uri = URI(url_current_person)\n uri.query = URI.encode_www_form(params)\n force_get_response(uri)\n end", "def gabarra\n respond_to do |format|\n begin\n @gabarra = DescargaBauxita.descargar(params)\n format.json { render :json => @gabarra }\n rescue Exceptions::PresenciaValoresExcepcion => errores\n format.json { render :json => errores.errors, :status => 400 }\n end\n end\n end", "def show\n @galeria = Galeria.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @galeria }\n end\n end", "def show\n @gastracker = Gastracker.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gastracker }\n end\n end", "def show\n @colegio = Colegio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @colegio }\n end\n end", "def index\n @ugroupes = Ugroupe.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @ugroupes }\n end\n end", "def index\n \treclamos = Reclamo.all\n \trender json: reclamos.to_json(include: [:tipo_reclamo, :ubicacion, :user], methods: [:valoracion])\n end", "def show\n @datoscontacto = Datoscontacto.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @datoscontacto }\n end\n end", "def show\n @agronomiaquimica = Agronomiaquimica.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @agronomiaquimica }\n end\n end", "def show\n @gopy = Gopy.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gopy }\n end\n end", "def index\n @foros = Foro.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @foros }\n end\n end", "def index\n @asociados = Asociado.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @asociados }\n end\n end", "def index\n @geopoints = Geopoint.all\n @jsons = @geopoints.to_gmaps4rails\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @geopoints }\n end\n end", "def show\n @agendamento = Agendamento.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @agendamento }\n end\n end", "def index\n @attendees = Attendees.all\n render json: @attendees\n end", "def index\n\t\tauthorize! :index, DetalleGasto\n @detalle_gastos = DetalleGasto.all\n end", "def show\n @gitem = Gitem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gitem }\n end\n end", "def index\n @gpsds = Gpsd.all\n #respond_to do |format|\n # format.json { render }\n #end\n end", "def index_single_gift\n render json: @gift, include: :ages, status: :ok\n end", "def index\n @gigapans = Gigapan.all\n end", "def index\n @ofertas = Oferta.where(:status_id => Status.find_by_descricao('Ativo'))\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @ofertas }\n end\n end", "def index\n @ativo_outros = AtivoOutro.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @ativo_outros }\n end\n end", "def index\n @girlfriends = Girlfriend.all\n render json: @girlfriends, status: 200 \n end", "def index\n @socios = Socio.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @socios }\n end\n end", "def index\n @cartridges = Cartridge.all\n\n respond_to do |format|\n format.html\n format.json { render json: @cartridges }\n end\n end", "def index\n @cooperativas = Cooperativa.where(:status_id => Status.find_by_descricao('Ativo'))\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @cooperativas }\n end\n end", "def index\n @dia_eventos = DiaEvento.all\n render json: @dia_eventos\n end", "def request_raw_pantheons_data\n return unless authenticated?\n\n response = RestClient.get(\n \"https://godvillegame.com/fbh/feed?a=#{@pantheons_guid}\",\n cookies: @cookies, content_type: :json, accept: :json\n )\n JSON.parse(response)\n end", "def index\n @charges = Charge.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @charges }\n end\n end", "def show\n @tagg = Tagg.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @tagg }\n end\n end", "def index\n @coasters = Coaster.all\n\n render json: @coasters\n end", "def index\n @archdioceses = Archdiocese.all\n\n render json: @archdioceses\n end", "def get_all\n get_docs\n get_text\n return JSON.pretty_generate(@data)\n end", "def index\n @attris = Attri.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @attris }\n end\n end", "def index\n @src_gsts = SrcGst.where(hotel_src_id: current_user.hotel_src_id).page(params[:page])\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @src_gsts }\n end\n end", "def index\n url = \"https://data.cityofchicago.org/resource/x2n5-8w5q.json\"\n options = { :body => {:status => text}, :basic_auth => @auth }\n @response = HTTParty.get(url, options)\n\n @crime = Hash.new\n\n #@crime['block'] = @response[0]['block']\n @crime = @response\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @gittos }\n end\n end", "def index\n @anuncios = Anuncio.all\n render json: @anuncios, status: :ok\n end", "def index\n @profiles = Profile.page(params[:page]).order(:updated_at => 'DESC')\n @json = @profiles.to_gmaps4rails\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @profiles }\n end\n end", "def show\n @ocat = Ocat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @ocat }\n end\n end", "def index\n base_url = 'https://www.googleapis.com/books/v1/volumes?q=fiction&maxResults=20'\n and_key = '&key='\n key = ENV['GOOGLE_BOOKS_API_KEY'] \n googleurl = base_url + and_key + key\n\n response = RestClient.get(googleurl)\n @books = JSON.parse(response)\n\n respond_to do |format|\n format.html\n format.json { render json: @books }\n end\n\nend", "def show\n @gmap = Gmap.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gmap }\n end\n end", "def index\n @pagamentos = Pagamento.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @pagamentos }\n end\n end", "def index\n @gifs = Gif.sorted.paginate(page: params[:page], per_page: 12)\n\n respond_to do |format|\n format.html\n format.json { render json: @gifs }\n end\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 show\n\n @evento = Evento.find(params[:id])\n @comentarios = Comentario.where(:comentavel_id => @evento.id, :comentavel_type => \"Evento\").order('created_at DESC')\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @evento }\n end\n end" ]
[ "0.7011776", "0.65732145", "0.6563739", "0.63083196", "0.6190325", "0.6133004", "0.61266977", "0.6121094", "0.61160743", "0.60831946", "0.60776997", "0.6041592", "0.60226625", "0.59611094", "0.5936822", "0.5931319", "0.5910226", "0.58962333", "0.58932954", "0.5893085", "0.58599657", "0.5852364", "0.58448124", "0.5843721", "0.5838946", "0.5837519", "0.5818415", "0.58155394", "0.581112", "0.58104926", "0.57971424", "0.57971424", "0.5797007", "0.5795802", "0.5795261", "0.5787099", "0.57855546", "0.5783594", "0.57727796", "0.57580364", "0.5756986", "0.5756866", "0.5756365", "0.5740118", "0.57399076", "0.5723491", "0.5717177", "0.57147604", "0.57133645", "0.57095814", "0.5707934", "0.5707927", "0.5702983", "0.57001334", "0.5698669", "0.5686861", "0.5683157", "0.5682701", "0.5679889", "0.5667398", "0.5662535", "0.56577885", "0.5655124", "0.5650546", "0.5648954", "0.56477594", "0.56455106", "0.5637976", "0.56353813", "0.56353664", "0.56338143", "0.5614509", "0.5610728", "0.5610254", "0.56027174", "0.5599706", "0.5596001", "0.5594286", "0.55898875", "0.5589303", "0.5588168", "0.55878484", "0.5582936", "0.55818045", "0.5581031", "0.5579082", "0.5578745", "0.5576315", "0.5569918", "0.55652463", "0.5559568", "0.55577475", "0.55572045", "0.5552815", "0.55497515", "0.55496603", "0.55477667", "0.5545534", "0.5539932", "0.5536464", "0.55363256" ]
0.0
-1
GET /gatos/1 GET /gatos/1.json
def show respond_to do |f| f.js f.pdf{ render template: 'gatos/ficha', pdf:'Ficha Gato' } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def index\n @gatos = Gato.all\n end", "def show\n @gasto = Gasto.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gasto }\n end\n end", "def index\n @ginasios = Ginasio.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @ginasios }\n end\n end", "def show\n @ginasio = Ginasio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @ginasio }\n end\n end", "def show\n @gig = Gig.find(params[:id])\n\n respond_to do |format|\n format.html {render json: @gig, status: :ok}\n format.json { render json: @gig, status: :ok }\n end\n end", "def show\n @goat = Goat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @goat }\n end\n end", "def show\n @gpath = Gpath.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gpath }\n end\n end", "def index\n @gatineos = Gatineo.all\n end", "def index\n @ganhos = Ganho.find_by_user(current_user)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @ganhos }\n end\n end", "def index\n @genotypes = Genotype.paginate(:page => params[:page], :per_page => 10)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @genotypes }\n end\n end", "def index\n @colegios = Colegio.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @colegios }\n end\n end", "def show\n @gig_request = GigRequest.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gig_request }\n end\n end", "def show\n @gethotel = Gethotel.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gethotel }\n end\n end", "def index\n @ofertas = Oferta.where(:status_id => Status.find_by_descricao('Ativo'))\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @ofertas }\n end\n end", "def show\n @orgao = Orgao.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @orgao }\n end\n end", "def show\n @golfer = Golfer.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @golfer }\n end\n end", "def show\n @datoscontacto = Datoscontacto.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @datoscontacto }\n end\n end", "def list_tenants_for_circles(args = {}) \n get(\"/tenants.json/circles\", args)\nend", "def show\n @genotype = Genotype.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @genotype }\n end\n end", "def index\n @formatos = Formato.where(ativo: true)\n \t\n render json: @formatos\n end", "def show\n @gethotelstaticdatagd = Gethotelstaticdatagd.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gethotelstaticdatagd }\n end\n end", "def show\n @ocat = Ocat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @ocat }\n end\n end", "def show\n @colegio = Colegio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @colegio }\n end\n end", "def consulta\n fiesta = Fiesta.all\n render json: fiesta\n end", "def index\n @estacionamientos = Estacionamiento.all\n\n @json = Estacionamiento.all.to_gmaps4rails\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @estacionamientos }\n end\n end", "def show\n @gravity = Gravity.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gravity }\n end\n end", "def show\n @agronomiaquimica = Agronomiaquimica.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @agronomiaquimica }\n end\n end", "def index_by_user\n @gifts = @current_user.gifts\n render json: @gifts, include: :ages, status: :ok\n end", "def index\n @ganhos = Ganho.all\n end", "def index\n @generations = Generation.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @generations }\n end\n end", "def show\n @osoba = Osoba.find(params[:id])\n\n render json: @osoba\n end", "def index\n @gathas = Gatha.all\n end", "def index_single_gift\n render json: @gift, include: :ages, status: :ok\n end", "def index\n @cooperativas = Cooperativa.where(:status_id => Status.find_by_descricao('Ativo'))\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @cooperativas }\n end\n end", "def index\n @cfos = Cfo.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @cfos }\n end\n end", "def index\n @gonzos = Gonzo.all\n end", "def show\n @client = Client.find(params[:id])\n @pets = @client.pets\n @json = @client.to_gmaps4rails\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @client }\n end\n end", "def get_json(path)\n puts \"*** GET #{path}\"\n\n response = Net::HTTP.get_response(build_uri(path))\n result = JSON.parse(response.body)\n puts \"HTTP #{response.code}\"\n\n puts JSON.pretty_generate(result)\n result\nend", "def index\n @glasses = Glass.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @glasses }\n end\n end", "def new\n @gasto = Gasto.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @gasto }\n end\n end", "def index\n @antecedentes = Antecedente.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @antecedentes }\n end\n end", "def index\n @foros = Foro.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @foros }\n end\n end", "def show\n @gopy = Gopy.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gopy }\n end\n end", "def index\n @peticion_servicio_tis = Peticion::ServicioTi.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @peticion_servicio_tis }\n end\n end", "def index\n @socios = Socio.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @socios }\n end\n end", "def index_by_age\n @age = Age.find(params[:age_id])\n @gifts = @age.gifts\n render json: @gifts, include: :ages, status: :ok\n end", "def show\n @galeria = Galeria.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @galeria }\n end\n end", "def tattoos\n render :nothing => true and return if params[:id].nil?\n\n @tattoo = Tattoo.find(params[:id])\n render :json => @tattoo.to_json(:include => [:artist, :assets])\n #render :json => @tattoo.to_json(:include => { :assets => { :only => [:id, :data_file_name] } })\n return\n end", "def index\n @distros = getmydata(\"Distro\")\n pagination\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @distros }\n end\n end", "def index\n @coasters = Coaster.all\n\n render json: @coasters\n end", "def get_json(path)\n puts \"*** GET #{path}\"\n\n response = Net::HTTP.get_response(build_uri(path))\n result = JSON.parse(response.body)\n puts \"HTTP #{response.code}\"\n\n #puts JSON.pretty_generate(result)\n result\nend", "def get_json(path)\n puts \"*** GET #{path}\"\n\n response = Net::HTTP.get_response(build_uri(path))\n result = JSON.parse(response.body)\n puts \"HTTP #{response.code}\"\n\n #puts JSON.pretty_generate(result)\n result\nend", "def show\n @grm_grappt = GrmGrappt.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @grm_grappt }\n end\n end", "def index\n @gomis = Gomi.all\n end", "def show\n @tipo_atendimento = TipoAtendimento.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @tipo_atendimento }\n end\n end", "def show\n @agendamento = Agendamento.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @agendamento }\n end\n end", "def index\n @asociados = Asociado.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @asociados }\n end\n end", "def get_json(path)\n response = Net::HTTP.get_response(build_uri(path))\n result = JSON.parse(response.body)\n #puts \"🤖 GET #{path}\"\n #puts \"HTTP #{response.code}\"\n #puts JSON.pretty_generate(result)\n result\nend", "def show\n @dato = Dato.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @dato }\n end\n end", "def show\n @goody = Goody.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @goody }\n end\n end", "def show\n @gastracker = Gastracker.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gastracker }\n end\n end", "def show\n @baton = Baton.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @baton }\n end\n end", "def index\n @attris = Attri.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @attris }\n end\n end", "def index\n @gets = Get.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @gets }\n end\n end", "def index\n\t\tboats = Boat.all\n \trender json: boats, status: 200\n\tend", "def show\n @gitem = Gitem.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gitem }\n end\n end", "def index\n @ocats = Ocat.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @ocats }\n end\n end", "def index\n @cgvs = Cgv.order('created_at')\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @cgvs }\n end\n end", "def show\n @colegiatura = Colegiatura.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @colegiatura }\n end\n end", "def index\n @charges = Charge.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @charges }\n end\n end", "def index\n @familia = Familium.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @familia }\n end\n end", "def show\n @oferta_academica = OfertaAcademica.find(params[:id])\n\n render json: @oferta_academica\n end", "def index\n @ativo_outros = AtivoOutro.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @ativo_outros }\n end\n end", "def show\n @servicio = Servicio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @servicio }\n end\n end", "def index\n @ultimo_grado_de_estudios = UltimoGradoDeEstudio.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @ultimo_grado_de_estudios }\n end\n end", "def get_json()\n\n http = Net::HTTP.new(STATUS_URI.host, STATUS_URI.port)\n http.use_ssl = false\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n request = Net::HTTP::Get.new(\"/api/services.json\")\n\n response = http.request(request)\n JSON.parse(response.body)\nend", "def show\n @tango = Tango.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @tango }\n end\n end", "def show\n @agente = Agente.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @agente } \n end\n end", "def index\n @grupoassuntos = Grupoassunto.all\n\n render json: @grupoassuntos\n end", "def show\n @aactio = Aactio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @aactio }\n end\n end", "def index\r\n @attestations = Attestation.all\r\n\r\n respond_to do |format|\r\n format.html # index.html.erb\r\n format.json { render json: @attestations }\r\n end\r\n end", "def show\n @gnode = Gnode.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gnode }\n end\n end", "def index\n @anuncios = Anuncio.all\n render json: @anuncios, status: :ok\n end", "def index\n @tacos = Taco.all\n\n respond_to do |format|\n format.html { render :index }\n format.json { render @tacos }\n end\n end", "def index\n @patrocinios = Patrocinio.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @patrocinios }\n end\n end", "def index\n @greats = Great.all\n end", "def index\n @dia_eventos = DiaEvento.all\n render json: @dia_eventos\n end", "def index\n @acoes = Acao.all\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @acoes }\n end\n end", "def index\n @cartridges = Cartridge.all\n\n respond_to do |format|\n format.html\n format.json { render json: @cartridges }\n end\n end", "def index\n #pseudo scope \n if params[:phone] \n @agencies = Agency.find_by_phone(params[:phone]);\n if @agencies \n respond_to do |format|\n format.json { render :json => @agencies }\n format.xml { render :xml => @agencies }\n end \n else\n head :not_found\n end\n else\n # Aqui estoy haciendo que el api responda en mas de 1 formato\n @agencies = Agency.all\n respond_to do |format|\n format.json { render :json => @agencies }\n format.xml { render :xml => @agencies }\n end\n\n end \n end", "def index\n @formatoventa = Formatoventum.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @formatoventa }\n end\n end", "def show\n @boat = Boat.find(params[:id])\n\n render json: @boat\n end", "def index\n @grooming_services = GroomingService.all\n end", "def index\n @gommis = Gommi.all\n end", "def show\n @statuspagamento = Statuspagamentoe.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @statuspagamento }\n end\n end", "def show\n\n @evento = Evento.find(params[:id])\n @comentarios = Comentario.where(:comentavel_id => @evento.id, :comentavel_type => \"Evento\").order('created_at DESC')\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @evento }\n end\n end", "def show\n @cliente = Cliente.find(params[:cliente_id])\n @pago = @cliente.pagos.find(params[:id])\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @pago }\n end\n end", "def show\n @tecnico = Tecnico.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @tecnico }\n end\n end", "def show\n @tecnico = Tecnico.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @tecnico }\n end\n end", "def index\n url = \"https://data.cityofchicago.org/resource/x2n5-8w5q.json\"\n options = { :body => {:status => text}, :basic_auth => @auth }\n @response = HTTParty.get(url, options)\n\n @crime = Hash.new\n\n #@crime['block'] = @response[0]['block']\n @crime = @response\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @gittos }\n end\n end", "def index\n @archdioceses = Archdiocese.all\n\n render json: @archdioceses\n end" ]
[ "0.6885853", "0.6746555", "0.6587885", "0.6397008", "0.6312808", "0.6303259", "0.6300389", "0.6160753", "0.6085799", "0.608402", "0.6079833", "0.60390484", "0.6019983", "0.60183126", "0.6017463", "0.60060394", "0.6004982", "0.5993295", "0.5985673", "0.5971384", "0.5970874", "0.596993", "0.59682894", "0.59606475", "0.5953019", "0.5944374", "0.5940911", "0.5924364", "0.59154266", "0.5912219", "0.5908678", "0.5907672", "0.58991796", "0.5891757", "0.5891223", "0.58905166", "0.5889962", "0.58768624", "0.58756644", "0.586895", "0.5868647", "0.5862368", "0.5862008", "0.5860759", "0.5859273", "0.5857708", "0.58564484", "0.585493", "0.5850505", "0.58382386", "0.58372796", "0.58372796", "0.58333427", "0.58299434", "0.5802201", "0.58009356", "0.5796869", "0.5790923", "0.5789404", "0.5780764", "0.577399", "0.57681704", "0.57641214", "0.576381", "0.5758676", "0.5758296", "0.57563436", "0.575486", "0.5753778", "0.57509774", "0.57461417", "0.5742732", "0.57401913", "0.573816", "0.5724727", "0.57244486", "0.5717263", "0.5711017", "0.57067955", "0.570352", "0.57022625", "0.5702125", "0.57016003", "0.5701406", "0.5696643", "0.5694543", "0.56920075", "0.5691542", "0.56904274", "0.5686435", "0.56834674", "0.56789815", "0.5670446", "0.5670002", "0.5669342", "0.5667906", "0.56657064", "0.56616604", "0.56616604", "0.56606984", "0.56604236" ]
0.0
-1
POST /gatos POST /gatos.json
def create @gato = Gato.new(gato_params) respond_to do |format| if @gato.save format.html { redirect_to gatos_url, notice: 'Gato Creado.' } format.json { render :show, status: :created, location: @gato } else format.html { render :new } format.json { render json: @gato.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create\n @gato = Gato.new(gato_params)\n @gato.user_id = current_user.id\n\n respond_to do |format|\n if @gato.save\n format.html { redirect_to @gato, notice: 'Gato was successfully created.' }\n format.json { render :show, status: :created, location: @gato }\n else\n format.html { render :new }\n format.json { render json: @gato.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @gasto = Gasto.new(params[:gasto])\n\n respond_to do |format|\n if @gasto.save\n format.html { redirect_to @gasto, notice: 'Gasto was successfully created.' }\n format.json { render json: @gasto, status: :created, location: @gasto }\n else\n format.html { render action: \"new\" }\n format.json { render json: @gasto.errors, status: :unprocessable_entity }\n end\n end\n end", "def gato_params\n params.require(:gato).permit(:name, :gender, :race, :color, :avatar, :description, :status, :age, :user_id, :castration_id)\n end", "def create\n @ton_giao = TonGiao.new(ton_giao_params)\n\n respond_to do |format|\n if @ton_giao.save\n format.html { redirect_to @ton_giao, notice: 'Ton giao was successfully created.' }\n format.json { render :show, status: :created, location: @ton_giao }\n else\n format.html { render :new }\n format.json { render json: @ton_giao.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @gatineo = Gatineo.new(gatineo_params)\n\n respond_to do |format|\n if @gatineo.save\n format.html { redirect_to @gatineo, notice: 'Gatineo criado com sucesso!' }\n format.json { render :show, status: :created, location: @gatineo }\n else\n format.html { render :new }\n format.json { render json: @gatineo.errors, status: :unprocessable_entity }\n end\n end\n end", "def add_tenant_circle(args = {}) \n post(\"/tenantcircles.json/\", args)\nend", "def create\n @tipo_agressor = TipoAgressor.new(tipo_agressor_params)\n\n respond_to do |format|\n if @tipo_agressor.save\n format.html { redirect_to @tipo_agressor, notice: @@msgs }\n format.json { render :show, status: :created, location: @tipo_agressor }\n else\n format.html { render :new }\n format.json { render json: @tipo_agressor.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @gosok = Gosok.new(gosok_params)\n\n respond_to do |format|\n if @gosok.save\n format.html { redirect_to gosoks_url, notice: 'Gosok was successfully created.' }\n format.json { render :show, status: :created, location: @gosok }\n else\n format.html { render :new }\n format.json { render json: @gosok.errors, status: :unprocessable_entity }\n end\n end\n end", "def gato_params\n params.require(:gato).permit(:nombre, :edad, :formato_edad, :sexo, :raza, :tipo, :peso, :porte, :chip, :numero_chip, :agresividad, :color, :senas, :fecha_operacion, :comentario, :ficha_id, :propietario_es, :veterinario_id, :apto_cirujia, :apto_cirujia_text, :medico_tratante, :hora_ingreso, :tipo_cirujia, :hallazgos, :hora_alta, :complicaciones,vacunas_attributes:[:id,:nombre,:_destroy], enfermedades_attributes:[:id,:nombre,:_destroy],veterinario_atributes:[:id,:nombre,:_destroy],medicamentos_attributes:[:id,:nombre,:cantidad,:unidad,:cada,:durante,:durante_unidad,:_destroy])\n end", "def create\n @ganho = Ganho.new(ganho_params)\n\n respond_to do |format|\n if @ganho.save\n format.html { redirect_to ganhos_path, notice: 'Ganho was successfully created.' }\n format.json { render :show, status: :created, location: @ganho }\n else\n format.html { render :new }\n format.json { render json: @ganho.errors, status: :unprocessable_entity }\n end\n end\n end", "def post(path, data = {})\n request 'POST', path, body: data.to_json\n end", "def create\n @gatha = Gatha.new(gatha_params)\n\n respond_to do |format|\n if @gatha.save\n format.html { redirect_to @gatha, notice: 'Gatha was successfully created.' }\n format.json { render action: 'show', status: :created, location: @gatha }\n else\n format.html { render action: 'new' }\n format.json { render json: @gatha.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @cetak_gtg = CetakGtg.new(cetak_gtg_params)\n\n respond_to do |format|\n if @cetak_gtg.save\n format.html { redirect_to cetak_gtgs_url, notice: 'Cetak gtg was successfully created.' }\n format.json { render :show, status: :created, location: @cetak_gtg }\n else\n format.html { render :new }\n format.json { render json: @cetak_gtg.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @ginasio = Ginasio.new(params[:ginasio])\n\n respond_to do |format|\n if @ginasio.save\n format.html { redirect_to @ginasio, :flash => { :success => 'Ginasio criado com sucesso!' } }\n format.json { render :json => @ginasio, :status => :created, :location => @ginasio }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @ginasio.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n megam_rest.post_promos(to_hash) #WONT BE USED AS OF NOW\n end", "def create\n @uasg = Uasg.new(uasg_params)\n\n respond_to do |format|\n if @uasg.save\n format.html { redirect_to @uasg, notice: 'Uasg was successfully created.' }\n format.json { render :show, status: :created, location: @uasg }\n else\n format.html { render :new }\n format.json { render json: @uasg.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @gua = Gua.new(gua_params)\n\n respond_to do |format|\n if @gua.save\n format.html { redirect_to @gua, notice: 'Gua was successfully created.' }\n format.json { render :show, status: :created, location: @gua }\n else\n format.html { render :new }\n format.json { render json: @gua.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @gondola = Gondola.new(gondola_params)\n\n respond_to do |format|\n if @gondola.save\n format.html { redirect_to @gondola, notice: 'Gondola was successfully created.' }\n format.json { render :show, status: :created, location: @gondola }\n else\n format.html { render :new }\n format.json { render json: @gondola.errors, status: :unprocessable_entity }\n end\n end\n end", "def ganho_params\n params.require(:ganho).permit(:nome, :valor_ganho, :status)\n end", "def create\n @goat = Goat.new(params[:goat])\n\n respond_to do |format|\n if @goat.save\n format.html { redirect_to @goat, notice: 'Goat was successfully created.' }\n format.json { render json: @goat, status: :created, location: @goat }\n else\n format.html { render action: \"new\" }\n format.json { render json: @goat.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @regraponto = Regraponto.new(regraponto_params)\n\n respond_to do |format|\n if @regraponto.save\n format.html { redirect_to @regraponto, notice: 'Regraponto was successfully created.' }\n format.json { render :show, status: :created, location: @regraponto }\n else\n format.html { render :new }\n format.json { render json: @regraponto.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n megam_rest.post_appdefn(to_hash)\n end", "def create\n @gig_request = GigRequest.new(params[:gig_request])\n\n respond_to do |format|\n if @gig_request.save\n format.html { redirect_to @gig_request, notice: 'Gig request was successfully created.' }\n format.json { render json: @gig_request, status: :created, location: @gig_request }\n else\n format.html { render action: \"new\" }\n format.json { render json: @gig_request.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @ingresso = Ingresso.new(ingresso_params)\n\n respond_to do |format|\n if @ingresso.save\n format.html { redirect_to @ingresso, notice: 'Ingresso was successfully created.' }\n format.json { render :show, status: :created, location: @ingresso }\n else\n format.html { render :new }\n format.json { render json: @ingresso.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n # Instantiate a new object using form parameters\n @gonzo = Gonzo.new(gonzo_params)\n\n respond_to do |format|\n # Save the object\n if @gonzo.save\n # If save succeeds, redirect to show action\n format.html { redirect_to @gonzo, notice: 'Gonzo was successfully created.' }\n format.json { render :show, status: :created, location: @gonzo }\n else\n # If save fails, redisplay the form so that the user can fix problems\n format.html { render :new }\n format.json { render json: @gonzo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @grupoassunto = Grupoassunto.new(grupoassunto_params)\n\n if @grupoassunto.save\n render json: @grupoassunto, status: :created, location: @grupoassunto\n else\n render json: @grupoassunto.errors, status: :unprocessable_entity\n end\n end", "def create\n megam_rest.post_node(to_hash)\n end", "def create\n @tipo_pregunta = TipoPregunta.new(params[:tipo_pregunta])\n\n if @tipo_pregunta.save\n render json: @tipo_pregunta, status: :created, location: @tipo_pregunta\n else\n render json: @tipo_pregunta.errors, status: :unprocessable_entity\n end\n end", "def create\n megam_rest.post_appreq(to_hash)\n end", "def post(path, json, params = {})\n if path.include?('covid19')\n request = Net::HTTP::Post.new(path, @headers)\n else\n request = Net::HTTP::Post.new('/v2' + path, @headers)\n end\n request.add_field('Content-Type', 'application/json')\n request.body = json\n params.each do |k, v|\n request[k] = v\n end\n send_request(request)\n end", "def create\r\n @egresso = Egresso.new(egresso_params)\r\n\r\n respond_to do |format|\r\n if @egresso.save\r\n format.html { redirect_to @egresso, notice: 'Egresso criado com sucesso.' }\r\n format.json { render :show, status: :created, location: @egresso }\r\n else\r\n format.html { render :new }\r\n format.json { render json: @egresso.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def create\n @gentre = Gentre.new(gentre_params)\n\n respond_to do |format|\n if @gentre.save\n format.json { render :show, status: :created, location: @gentre }\n else\n format.json { render json: @gentre.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @gomi = Gomi.new(gomi_params)\n\n respond_to do |format|\n if @gomi.save\n format.html { redirect_to @gomi, notice: 'Gomi was successfully created.' }\n format.json { render :show, status: :created, location: @gomi }\n else\n format.html { render :new }\n format.json { render json: @gomi.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @gig_request = GigRequest.new(gig_request_params)\n \n #@gig_request.name = encode(@gig_request.name)\n #@gig_request.address = encode(@gig_request.address)\n #@gig_request.email = encode(@gig_request.email)\n\n respond_to do |format|\n if @gig_request.save\n format.html { redirect_to @gig_request, notice: 'Gig request was successfully created.' }\n format.json { render :show, status: :created, location: @gig_request }\n else\n format.html { render :new }\n format.json { render json: @gig_request.errors, status: :unprocessable_entity }\n #flash[:error] = @gig_request.errors.full_messages[0]\n #render 'new'\n end\n end\n end", "def post(resource, params)\n case resource\n when \"pedidos\", \"place_order\", \"new_order\" then url = \"/pedidos\"\n when \"envios\", \"shipping\" then url = \"/envios\"\n else url = \"/#{resource}\"\n end\n\n post_request(url, params)\n end", "def create\n @osoba = Osoba.new(params[:osoba])\n\n if @osoba.save\n render json: @osoba, status: :created, location: @osoba\n else\n render json: @osoba.errors, status: :unprocessable_entity\n end\n end", "def create\n @fact = @cat.facts.create!({ fact: api_request })\n if @fact.save\n render json: @fact\n else\n render error: { message: \"Não foi possível criar esse fato para este gatinho! :(\" }, status: 400\n end\n end", "def create\n @tapioca = Tapioca.new(tapioca_params)\n\n respond_to do |format|\n if @tapioca.save\n format.html { redirect_to @tapioca, notice: 'Tapioca was successfully created.' }\n format.json { render action: 'show', status: :created, location: @tapioca }\n else\n format.html { render action: 'new' }\n format.json { render json: @tapioca.errors, status: :unprocessable_entity }\n end\n end\n end", "def detalle_gasto_params\n params.require(:detalle_gasto).permit(:titulo, :descripcion, :monto, :concepto_gasto_id, :informe_gastos_id, :voluntario_id, :comprobante_id)\n end", "def create\n gig = Gig.new()\n respond_to do |format|\n if update_gig(gig)\n format.html { render json: gig, status: :created, location: gig }\n format.json { render json: gig, status: :created, location: gig }\n else\n format.html { render action: \"new\" }\n format.json { render json: gig.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @sender = params[:sender]\n @destination = params[:destination]\n @package = params[:package]\n @notification = params[:notification]\n @preferences = params[:preferences]\n @settlement_info = params[:settlement_info]\n @request = {\n sender: @sender,\n destination: @destination,\n package: @package,\n notification: @notification,\n preferences: @preferences,\n settlement_info: @settlement_info,\n group_id: '5241556',\n mailing_date: Date.today,\n contract_number: '0042956527',\n service_code: params[:service_code],\n mobo: {\n customer_number: params[:mobo],\n username: 'bc02d6bd3733555c',\n password: '111d1a0d29fc00aa47b66a',\n contract_number: '0042956527'\n }\n }\n puts \"**** #{@request}\"\n\n @response = CANADA_POST_SERVICE.create(\n sender: @sender,\n destination: @destination,\n package: @package,\n notification: @notification,\n preferences: @preferences,\n settlement_info: @settlement_info,\n group_id: '5241556',\n mailing_date: Date.today,\n contract_id: '0042956527',\n service_code: params[:service_code],\n mobo: {\n customer_number: params[:mobo],\n username: 'bc02d6bd3733555c',\n password: '111d1a0d29fc00aa47b66a',\n contract_number: '0042956527'\n }\n )\n puts \"Full Response: #{@response}\"\n unless @response[:create_shipping][:errors].present?\n Shipping.track_shipping(@response)\n end\n respond_to do |format|\n format.js {}\n end\n end", "def create\n s = Spooge.new()\n create_status = s.save\n n = generate_random_name\n s.name = n\n s.email = \"#{n}@gmail.com\"\n s.touch_date = DateTime.now\n s.status = STATUS[rand(STATUS.length)]\n\n resp = {:create_status => create_status, :record => s}\n render :json => resp\n end", "def create\n @gakka = Gakka.new(gakka_params)\n\n respond_to do |format|\n if @gakka.save\n format.html { redirect_to @gakka, notice: \"Gakka was successfully created.\" }\n format.json { render :show, status: :created, location: @gakka }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @gakka.errors, status: :unprocessable_entity }\n end\n end\n end", "def http_post(path, request)\n @http.post(\n :body => JSON(:request => request.to_hash),\n :headers => headers,\n :path => \"/api/v2/#{path}\",\n :expects => [200, 201, 202]\n )\n end", "def create\n @soatseguro = Soatseguro.new(soatseguro_params)\n\n respond_to do |format|\n if @soatseguro.save\n format.html { redirect_to @soatseguro, notice: 'Soatseguro was successfully created.' }\n format.json { render :show, status: :created, location: @soatseguro }\n else\n format.html { render :new }\n format.json { render json: @soatseguro.errors, status: :unprocessable_entity }\n end\n end\n end", "def create(url, data)\n RestClient.post ENV['APIBASE']+url, data, :content_type => :json\nend", "def post operation, data={}\n body = case data\n when String\n body = data\n else\n Yajl::Encoder.encode(data)\n end\n\n request = new_request operation, body\n request.sign sts\n hydra.queue request\n hydra.run\n response = request.response\n puts response.inspect if @debug\n\n if response.code == 200\n Yajl::Parser.parse response.body\n else\n raise_error response\n end\n end", "def create\n @gigapan = Gigapan.new(gigapan_params)\n\n respond_to do |format|\n if @gigapan.save\n format.html { redirect_to @gigapan, notice: 'Gigapan was successfully created.' }\n format.json { render :show, status: :created, location: @gigapan }\n else\n format.html { render :new }\n format.json { render json: @gigapan.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @ocs_generada = OcsGenerada.new(ocs_generada_params)\n\n respond_to do |format|\n if @ocs_generada.save\n format.html { redirect_to @ocs_generada, notice: 'Ocs generada was successfully created.' }\n format.json { render :show, status: :created, location: @ocs_generada }\n else\n format.html { render :new }\n format.json { render json: @ocs_generada.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @gnode = Gnode.new(params[:gnode])\n\n respond_to do |format|\n if @gnode.save\n format.html { redirect_to @gnode, notice: 'Gnode was successfully created.' }\n format.json { render json: @gnode, status: :created, location: @gnode }\n else\n format.html { render action: \"new\" }\n format.json { render json: @gnode.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\n @antropo = Antropo.new(antropo_params)\n\n\n respond_to do |format|\n if @antropo.save\n format.html { redirect_to @antropo, notice: 'Antropo was successfully created.' }\n format.json { render action: 'show', status: :created, location: @antropo }\n else\n format.html { render action: 'new' }\n format.json { render json: @antropo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @gig_type = GigType.new(gig_type_params)\n\n respond_to do |format|\n if @gig_type.save\n format.html { redirect_to @gig_type, notice: 'Gig type was successfully created.' }\n format.json { render :show, status: :created, location: @gig_type }\n else\n format.html { render :new }\n format.json { render json: @gig_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @gpost = Gpost.new(gpost_params)\n\n respond_to do |format|\n if @gpost.save\n format.html { redirect_to @gpost, notice: 'Gpost was successfully created.' }\n format.json { render :show, status: :created, location: @gpost }\n else\n format.html { render :new }\n format.json { render json: @gpost.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @gastos_balanceado = GastosBalanceado.new(gastos_balanceado_params)\n\n respond_to do |format|\n if @gastos_balanceado.save\n format.html { redirect_to @gastos_balanceado, notice: 'Gastos balanceado was successfully created.' }\n format.json { render :show, status: :created, location: @gastos_balanceado }\n else\n format.html { render :new }\n format.json { render json: @gastos_balanceado.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @grua = Grua.new(grua_params)\n @grua.dicc_mantenciones = @grua.set_dicc_mantenciones(@grua.tipo, @grua.horometro)\n\n if @grua.tipo == \"Eléctrica\"\n @grua.mantenciones = [6000, 2000, 1000, 250]\n elsif @grua.tipo == \"Gas\"\n @grua.mantenciones = [2800, 1400, 700, 350]\n elsif @grua.tipo == \"Apilador\"\n @grua.mantenciones = [2000, 1000, 500]\n else @grua.mantenciones = []\n end\n\n respond_to do |format|\n if @grua.save\n format.html { redirect_to @grua, notice: 'Grua creada exitosamente.' }\n format.json { render :show, status: :created, location: @grua }\n else\n format.html { render :new }\n format.json { render json: @grua.errors, status: :unprocessable_entity }\n end\n end\n end", "def api_post(action, data)\n api_request(action, data, 'POST')\n end", "def create\n @agronomiaquimica = Agronomiaquimica.new(params[:agronomiaquimica])\n\n respond_to do |format|\n if @agronomiaquimica.save\n format.html { redirect_to @agronomiaquimica, notice: 'Agronomiaquimica was successfully created.' }\n format.json { render json: @agronomiaquimica, status: :created, location: @agronomiaquimica }\n else\n format.html { render action: \"new\" }\n format.json { render json: @agronomiaquimica.errors, status: :unprocessable_entity }\n end\n end\n end", "def post_spoonacular\n # %encode ingredients to url\n encoded_ingr = URI.escape(@translated_recipe[:ingredients_list])\n # post call block :\n url = URI(\"https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/parseIngredients?includeNutrition=true\")\n http = Net::HTTP.new(url.host, url.port)\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n request = Net::HTTP::Post.new(url)\n request[\"content-type\"] = \"application/x-www-form-urlencoded\"\n request[\"x-rapidapi-key\"] = ENV[\"X_RAPIDAPI_KEY\"]\n request[\"x-rapidapi-host\"] = \"spoonacular-recipe-food-nutrition-v1.p.rapidapi.com\"\n # body of the call with ingredients and servings\n request.body = \"ingredientList=#{encoded_ingr}&#{@recipe_hash[:servings]}\"\n # response\n response = http.request(request)\n end", "def create\n params[:orgao][:tipo_atendimento_ids] ||= []\n\trespond_to do |format|\n if @orgao.save\n format.html { redirect_to @orgao, notice: \"Local de atendimento: #{@orgao.nome}, foi criado com sucesso.\" }\n format.json { render json: @orgao, status: :created, location: @orgao }\n else\n format.html { render action: \"new\" }\n format.json { render json: @orgao.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @gestacao = Gestacao.new(gestacao_params)\n\n respond_to do |format|\n if @gestacao.save\n format.html { redirect_to @gestacao, notice: 'Gestacao was successfully created.' }\n format.json { render action: 'show', status: :created, location: @gestacao }\n else\n format.html { render action: 'new' }\n format.json { render json: @gestacao.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @grua = Grua.new(grua_params)\n\n respond_to do |format|\n if @grua.save\n format.html { redirect_to gruas_url, notice: 'Grua Se creó correctamente.' }\n format.json { render :index, status: :created, location: @grua }\n else\n format.html { render :new }\n format.json { render json: @grua.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @tangazo = Tangazo.new(tangazo_params)\n\n respond_to do |format|\n if @tangazo.save\n format.html { redirect_to @tangazo, notice: 'Tangazo was successfully created.' }\n format.json { render :show, status: :created, location: @tangazo }\n else\n format.html { render :new }\n format.json { render json: @tangazo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @ngo = Ngo.new(ngo_params)\n\n respond_to do |format|\n if @ngo.save\n format.html { redirect_to @ngo, notice: 'Ngo was successfully created.' }\n format.json { render :show, status: :created, location: @ngo }\n else\n format.html { render :new }\n format.json { render json: @ngo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @grm_grappt = GrmGrappt.new(params[:grm_grappt])\n\n respond_to do |format|\n if @grm_grappt.save\n format.html { redirect_to @grm_grappt, notice: 'Grooming appointment was successfully created.' }\n format.json { render json: @grm_grappt, status: :created, location: @grm_grappt }\n else\n format.html { render action: \"new\" }\n format.json { render json: @grm_grappt.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @tipo_aposta = TipoAposta.new(tipo_aposta_params)\n\n respond_to do |format|\n if @tipo_aposta.save\n format.html { redirect_to @tipo_aposta, notice: 'Tipo aposta was successfully created.' }\n format.json { render :show, status: :created, location: @tipo_aposta }\n else\n format.html { render :new }\n format.json { render json: @tipo_aposta.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n puts 'AQQQQQUUUUUUUIIIIII'\n json = ActiveSupport::JSON.decode(params[:pessoa])\n puts json\n @pessoa = Pessoa.new(json)\n # @address = Address.new(params[:address])\n\n # @client.addresses = @address\n\n respond_to do |format|\n if @pessoa.save\n format.html { redirect_to @pessoa, notice: 'Pessoa was successfully created.' }\n format.json { render json: @pessoa, status: :created, location: @pessoa }\n else\n format.html { render action: \"new\" }\n format.json { render json: @pessoa.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @gpath = Gpath.new(params[:gpath])\n\n respond_to do |format|\n if @gpath.save\n format.html { redirect_to @gpath, notice: 'Gpath was successfully created.' }\n format.json { render json: @gpath, status: :created, location: @gpath }\n else\n format.html { render action: \"new\" }\n format.json { render json: @gpath.errors, status: :unprocessable_entity }\n end\n end\n end", "def gatineo_params\n params.require(:gatineo).permit(:Name, :Cor, :Tutor, :Raça)\n end", "def create\n prepara_form\n @garagem = Garagem.new(garagem_params)\n @garagem.endereco = Endereco.new(endereco_params)\n\n respond_to do |format|\n if @garagem.save\n format.html { redirect_to @garagem, notice: 'Garagem foi salva com sucesso' }\n format.json { render :show, status: :created, location: @garagem }\n else\n format.html { render :new }\n format.json { render json: @garagem.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @ventas_agrupador_cliente = Ventas::AgrupadorCliente.new(ventas_agrupador_cliente_params)\n\n respond_to do |format|\n if @ventas_agrupador_cliente.save\n format.html { redirect_to @ventas_agrupador_cliente, notice: 'Agrupador cliente was successfully created.' }\n format.json { render :show, status: :created, location: @ventas_agrupador_cliente }\n else\n format.html { render :new }\n format.json { render json: @ventas_agrupador_cliente.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @ventas_agrupador_cliente = Ventas::AgrupadorCliente.new(ventas_agrupador_cliente_params)\n\n respond_to do |format|\n if @ventas_agrupador_cliente.save\n format.html { redirect_to @ventas_agrupador_cliente, notice: 'Agrupador cliente was successfully created.' }\n format.json { render :show, status: :created, location: @ventas_agrupador_cliente }\n else\n format.html { render :new }\n format.json { render json: @ventas_agrupador_cliente.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @tatoo = Tatoo.new(tatoo_params)\n\n respond_to do |format|\n if @tatoo.save\n format.html { redirect_to @tatoo, notice: 'Tatoo was successfully created.' }\n format.json { render :show, status: :created, location: @tatoo }\n else\n format.html { render :new }\n format.json { render json: @tatoo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @grooming_service = GroomingService.new(grooming_service_params)\n\n respond_to do |format|\n if @grooming_service.save\n format.html { redirect_to @grooming_service, notice: 'Grooming service was successfully created.' }\n format.json { render :show, status: :created, location: @grooming_service }\n else\n format.html { render :new }\n format.json { render json: @grooming_service.errors, status: :unprocessable_entity }\n end\n end\n end", "def api_post(path, data = {})\n api_request(:post, path, :data => data)\n end", "def create\r\n @usuario_gusto = UsuarioGusto.new(usuario_gusto_params)\r\n\r\n respond_to do |format|\r\n if @usuario_gusto.save\r\n format.html { redirect_to @usuario_gusto, notice: 'Usuario gusto was successfully created.' }\r\n format.json { render action: 'show', status: :created, location: @usuario_gusto }\r\n else\r\n format.html { render action: 'new' }\r\n format.json { render json: @usuario_gusto.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def create\n @questionario_egresso = QuestionarioEgresso.new(questionario_egresso_params)\n\n respond_to do |format|\n if @questionario_egresso.save\n format.html { redirect_to questionario_egressos_path, notice: 'Questionario incluído com sucesso.' }\n format.json { render :show, status: :created, location: questionario_egressos_path }\n else\n format.html { render :new }\n format.json { render json: @questionario_egresso.errors, status: :unprocessable_entity }\n end\n end\n end", "def grua_params\n params.require(:grua).permit(:tipo, :numero_serie, :horometro, :lugar_actual, :cliente, :contrato,\n :propietario, :asegurada, :estado, :marca, :modelo, :serie, :motor, :patente, :ano,\n :ton, :mastil, :observaciones, :dicc_mantenciones)\n end", "def create\n @gizmo = Gizmo.new(gizmo_params)\n\n respond_to do |format|\n if @gizmo.save\n format.html { redirect_to @gizmo.family || @gizmo, notice: 'Gizmo was successfully created.' }\n format.json { render :show, status: :created, location: @gizmo }\n else\n format.html { render :new }\n format.json { render json: @gizmo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\t\turi = URI.parse(Counter::Application.config.simplyurl)\n\t\thttp = Net::HTTP.new(uri.host, uri.port)\n\t\t\n\t\trequest = Net::HTTP::Post.new('/offsets.json')\n\t\tputs params\n\t\tputs params.slice(*['custids','acctids','itemids'])\n\t\t\n\t\t# ok, this join stuff is bogus - it encodes properly, but the other side only sees the last element and loses the array type - it's just string\n\t\t# this way, i 'split' it at the other side to recover my array\n\t\t# it should work without the join/split crap, but it doesn't\n\t\trequest.set_form_data({:custids => ( params['custids'] || []).join(','), :acctids => ( params['acctids'] || []).join(','), :itemids => ( params['itemids'] || []).join(','), :amount => params['amount'], :type => params['type']})\n\t\t\n\t\tputs request.body\n\t\t\n\t\tresponse = http.request(request)\n\t\tputs response.body\n\n respond_to do |format|\n format.html { render :text => response.code == :ok ? \"\" : response.body, status: response.code }\n format.json { render :text => response.code == :ok ? \"\" : response.body, status: response.code }\n end\n end", "def create\n @gang = Gang.new(gang_params)\n\n respond_to do |format|\n if @gang.save\n format.html { redirect_to @gang, notice: 'Gang was successfully created.' }\n format.json { render :show, status: :created, location: @gang }\n else\n format.html { render :new }\n format.json { render json: @gang.errors, status: :unprocessable_entity }\n end\n end\n end", "def post(request)\n # sure thing!\n json_response(200, { message: \"This dummy POST endpoint didn't do anything.\" })\n end", "def generate_tags\n uri = URI.parse(\"https://api.thomsonreuters.com/permid/calais\")\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = true\n post_body = []\n post_body << \"<Document><Body>\"\n # stip html\n post_body << ActionView::Base.full_sanitizer.sanitize(params[:desc])\n # no strip\n # post_body << params[:desc]\n post_body << \"</Body></Document>\"\n request = Net::HTTP::Post.new(uri.request_uri)\n request.add_field(\"Content-Type\",\"text/xml\")\n request.add_field(\"outputFormat\",\"application/json\")\n #request.add_field(\"outputFormat\",\"text/n3\") \n request.add_field(\"x-ag-access-token\",\"fY7WUM3GGCXHm9ATOhtzhrvlWX8oPo5X\")\n request.body = post_body.join\n # request[\"Content-Type\"] = \"multipart/form-data, boundary=#{BOUNDARY}\"\n\n render :json => http.request(request).body\n end", "def new\n @gasto = Gasto.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @gasto }\n end\n end", "def create\n @oferta_academica = OfertaAcademica.new(params[:oferta_academica])\n\n if @oferta_academica.save\n render json: @oferta_academica, status: :created, location: @oferta_academica\n else\n render json: @oferta_academica.errors, status: :unprocessable_entity\n end\n end", "def create\n @datoscontacto = Datoscontacto.new(params[:datoscontacto])\n\n respond_to do |format|\n if @datoscontacto.save\n format.html { redirect_to @datoscontacto, notice: 'Datoscontacto was successfully created.' }\n format.json { render json: @datoscontacto, status: :created, location: @datoscontacto }\n else\n format.html { render action: \"new\" }\n format.json { render json: @datoscontacto.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @asignatura = Asignatura.new(asignatura_params)\n\n respond_to do |format|\n if @asignatura.save\n format.json { render json: \"Asignatura Creada\", status: :created, location: @asignatura }\n else\n format.json { render json: @asignatura.errors, status: :unprocessable_entity }\n end\n end\n end", "def POST; end", "def create\n @tipoapreensao = Tipoapreensao.new(tipoapreensao_params)\n\n respond_to do |format|\n if @tipoapreensao.save\n format.html { redirect_to @tipoapreensao, notice: 'Tipoapreensao was successfully created.' }\n format.json { render action: 'show', status: :created, location: @tipoapreensao }\n else\n format.html { render action: 'new' }\n format.json { render json: @tipoapreensao.errors, status: :unprocessable_entity }\n end\n end\n end", "def transmit(path, data)\n http_post (host + path),\n {'Content-Type' => 'application/json'},\n [data.to_json]\n end", "def create\n @dia_evento = DiaEvento.new(dia_evento_params)\n\n if @dia_evento.save\n render json: @dia_evento, status: :created, location: @dia_evento\n else\n render json: @dia_evento.errors, status: :unprocessable_entity\n end\n end", "def create\n @formapagto = Formapagto.new(formapagto_params)\n\n respond_to do |format|\n if @formapagto.save\n format.html { redirect_to @formapagto, notice: 'Forma de pagto criado com sucesso.' }\n format.json { render :show, status: :created, location: @formapagto }\n else\n format.html { render :new }\n format.json { render json: @formapagto.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n megam_rest.post_accounts(to_hash)\n end", "def post(path, form_data=nil)\n parse_json do |parser|\n @http_client.post(path, form_data) {|chunk| parser << chunk }\n end\n end", "def post_api(path, params={}, headers={})\n headers.merge!('CONTENT_TYPE' => \"application/json\")\n post path, params, headers\nend", "def post\n Salesforce.set_http(session[:accesstoken], session[:accessurl])\n \t@response = Salesforce.create_post(params)\n \trespond_to do |format|\n format.json { render :json => @response.to_json}\n # example of multiple reponses mapped to one object\n # format.json { render :json => {:data => @response, :meta => @describe}.to_json}\n \tend\n end", "def create\n #@gig = Gig.new(gig_params)\n\n @gig = current_user.gigs.build(gig_params)\n\n respond_to do |format|\n if @gig.save\n format.html { redirect_to @gig, notice: \"Gig was successfully created.\" }\n format.json { render :show, status: :created, location: @gig }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @gig.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @giohang = Giohang.new(giohang_params)\n\n respond_to do |format|\n if @giohang.save\n format.html { redirect_to @giohang, notice: \"Giohang was successfully created.\" }\n format.json { render :show, status: :created, location: @giohang }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @giohang.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @gonullu = Gonullu.new(gonullu_params)\n\n respond_to do |format|\n if @gonullu.save\n format.html { redirect_to @gonullu, notice: 'Gonullu was successfully created.' }\n format.json { render :show, status: :created, location: @gonullu }\n else\n format.html { render :new }\n format.json { render json: @gonullu.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @respuesta = Respuesta.new(params[:respuesta])\n\n if @respuesta.save\n render json: @respuesta, status: :created, location: @respuesta\n else\n render json: @respuesta.errors, status: :unprocessable_entity\n end\n end", "def create\n @gpsquest = Gpsquest.new(gpsquest_params)\n\n respond_to do |format|\n if @gpsquest.save\n format.html { redirect_to @gpsquest, notice: 'Gpsquest was successfully created.' }\n format.json { render :show, status: :created, location: @gpsquest }\n else\n format.html { render :new }\n format.json { render json: @gpsquest.errors, status: :unprocessable_entity }\n end\n end\n end" ]
[ "0.62240034", "0.6188656", "0.6131201", "0.5958368", "0.5938348", "0.59288913", "0.5917163", "0.59059304", "0.5882015", "0.58559597", "0.5823399", "0.5804692", "0.58017516", "0.58016104", "0.57912993", "0.56942344", "0.56591713", "0.5654604", "0.5634455", "0.56294835", "0.56188273", "0.5598498", "0.5597652", "0.55976105", "0.5580495", "0.55736715", "0.5546381", "0.55462724", "0.5540167", "0.55388457", "0.55385727", "0.55279315", "0.5526993", "0.55104357", "0.5507297", "0.5499872", "0.5483132", "0.5482054", "0.54815644", "0.547704", "0.5467481", "0.54661465", "0.5460555", "0.5460535", "0.5460087", "0.54582316", "0.5456851", "0.54447687", "0.5438457", "0.54350704", "0.5434337", "0.5424969", "0.54212856", "0.5406908", "0.540453", "0.54033583", "0.53936654", "0.5388328", "0.5388124", "0.5385591", "0.5384081", "0.53804034", "0.5378679", "0.5366733", "0.5363537", "0.53577274", "0.5348718", "0.5341965", "0.53339213", "0.5326173", "0.5326173", "0.53236806", "0.5312719", "0.5306975", "0.52998585", "0.52965057", "0.5281859", "0.52801645", "0.5277283", "0.52722263", "0.52690434", "0.52638566", "0.5256151", "0.52541023", "0.5249888", "0.5246933", "0.5244649", "0.5236895", "0.5234821", "0.5233027", "0.5228958", "0.52237797", "0.5223538", "0.52201885", "0.52194786", "0.52178353", "0.5212027", "0.52109444", "0.52106065", "0.52058953" ]
0.65635693
0
PATCH/PUT /gatos/1 PATCH/PUT /gatos/1.json
def update respond_to do |format| if @gato.update(gato_params) format.html { redirect_to gatos_url, notice: 'Gato actualizado.' } format.json { render :show, status: :ok, location: @gato } else format.html { render :edit } format.json { render json: @gato.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def api_patch(path, data = {})\n api_request(:patch, path, :data => data)\n end", "def patch!\n request! :patch\n end", "def update\n respond_to do |format|\n if @gato.update(gato_params)\n format.html { redirect_to @gato, notice: 'Gato was successfully updated.' }\n format.json { render :show, status: :ok, location: @gato }\n else\n format.html { render :edit }\n format.json { render json: @gato.errors, status: :unprocessable_entity }\n end\n end\n end", "def patch(path, data)\n request 'PATCH', path, body: data.to_json\n end", "def put!\n request! :put\n end", "def update_tenant_circle(args = {}) \n put(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend", "def update!(params)\n res = @client.put(path, nil, params, \"Content-Type\" => \"application/json\")\n @attributes = res.json if res.status == 201\n res\n end", "def patch\n headers = {\"If-Match\" => @version}\n response = @context.request :patch, \"#{@path}/#{@id}\", @data.to_json, headers\n @version += 1\n response\n # 'X-HTTP-Method-Override' => 'PATCH'\n end", "def patch(type, info)\n path, info = type_info(type, :path), force_case(info)\n ida = type == :client ? 'client_id' : 'id'\n raise ArgumentError, \"info must include #{ida}\" unless id = info[ida]\n hdrs = headers\n if info && info['meta'] && (etag = info['meta']['version'])\n hdrs.merge!('if-match' => etag)\n end\n reply = json_parse_reply(@key_style,\n *json_patch(@target, \"#{path}/#{Addressable::URI.encode(id)}\", info, hdrs))\n\n # hide client endpoints that are not quite scim compatible\n type == :client && !reply ? get(type, info['client_id']): reply\n end", "def patch options\n rest_request({ method: :patch }.merge(options))\n end", "def patch options\n rest_request({ method: :patch }.merge(options))\n end", "def update(url, data)\n RestClient.put url, data, :content_type => :json\nend", "def update\n @gasto = Gasto.find(params[:id])\n\n respond_to do |format|\n if @gasto.update_attributes(params[:gasto])\n format.html { redirect_to @gasto, notice: 'Gasto was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @gasto.errors, status: :unprocessable_entity }\n end\n end\n end", "def http_put(path, data, content_type = 'application/json')\n http_methods(path, :put, data, content_type)\n end", "def patch(path, params = {})\n request(:patch, path, params)\n end", "def patch(path, params = {})\n request(:patch, path, params)\n end", "def patch(path, data, params = {}, request_options = {})\n request(:patch, path, data, params)\n end", "def update\n respond_to do |format|\n if @gatha.update(gatha_params)\n format.html { redirect_to @gatha, notice: 'Gatha was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @gatha.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @gig_request = GigRequest.find(params[:id])\n\n respond_to do |format|\n if @gig_request.update_attributes(params[:gig_request])\n format.html { redirect_to @gig_request, notice: 'Gig request was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @gig_request.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_aos_version(args = {}) \n id = args['id']\n temp_path = \"/aosversions.json/{aosVersionId}\"\n path = temp_path\nargs.keys.each do |key|\n if (key == \"aosversionId\")\n args.delete(key)\n path = temp_path.gsub(\"{#{key}}\", id)\n end\nend\n puts \" PATH : #{path}\"\n put(path, args)\nend", "def patch\n end", "def patch(path, **args); end", "def update\n @ginasio = Ginasio.find(params[:id])\n\n respond_to do |format|\n if @ginasio.update_attributes(params[:ginasio])\n format.html { redirect_to @ginasio, :flash => { :success => 'Dados do ginasio alterados com successo!' } }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @ginasio.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @tapioca.update(tapioca_params)\n format.html { redirect_to @tapioca, notice: 'Tapioca was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @tapioca.errors, status: :unprocessable_entity }\n end\n end\n end", "def patch(path, opts = {})\n request(:patch, path, opts).body\n end", "def update\n respond_to do |format|\n if @gosok.update(gosok_params)\n format.html { redirect_to gosoks_url, notice: 'Gosok was successfully updated.' }\n format.json { render :show, status: :ok, location: @gosok }\n else\n format.html { render :edit }\n format.json { render json: @gosok.errors, status: :unprocessable_entity }\n end\n end\n end", "def update options={}\n client.put(\"/#{id}\", options)\n end", "def update\n @goat = Goat.find(params[:id])\n\n respond_to do |format|\n if @goat.update_attributes(params[:goat])\n format.html { redirect_to @goat, notice: 'Goat was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @goat.errors, status: :unprocessable_entity }\n end\n end\n end", "def update(&block)\n validate_request()\n\n # Params includes all of the PATCH data at the top level along with other\n # other Rails-injected params like 'id', 'action', 'controller'. These\n # are harmless given no namespace collision and we're only interested in\n # the 'Operations' key for the actual patch data.\n #\n render(json: yield(self.safe_params()[:id], self.safe_params().to_hash()))\n end", "def update\n respond_to do |format|\n if @tatoo.update(tatoo_params)\n format.html { redirect_to tatoos_path, notice: 'Tatoo was successfully updated.' }\n format.json { render :show, status: :ok, location: @tatoo }\n else\n format.html { render :edit }\n format.json { render json: @tatoo.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @golfer = Golfer.find(params[:id])\n\n respond_to do |format|\n if @golfer.update_attributes(params[:golfer])\n format.html { redirect_to @golfer, notice: 'Golfer was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @golfer.errors, status: :unprocessable_entity }\n end\n end\n end", "def update(data = :object || :json)\n end", "def rm_update path, data, msg\n\n re = rm_request path, data, 'PUT'\n puts re.body\n chk (re.code!='200'), msg + \"\\n#{re.code} #{re.msg}\\n\\n\"\n return true\n\nend", "def update # PATCH\n raise NotImplementedError\n end", "def api_put(path, data = {})\n api_request(:put, path, :data => data)\n end", "def update(request)\n end", "def update(request)\n end", "def update(attrs, path=nil)\n resp = api_client.put(path || url, JSON.dump(attrs))\n refresh(JSON.load(resp.body))\n end", "def patch(operation, path, value = nil)\n ensure_client && ensure_uri\n body = {\n 'op' => operation,\n 'path' => path,\n 'value' => value\n }\n response = @client.rest_patch(@data['uri'], { 'Content-Type' => 'application/json-patch+json', 'body' => [body] }, @api_version)\n @client.response_handler(response)\n end", "def rest_edit(path, options={}, &blk)\n callback = Proc.new { |*args|\n @object = yield(*args) or pass\n rest_params.each { |k, v| @object.send :\"#{k}=\", v unless k == 'id' }\n\n return 400, @object.errors.to_json unless @object.valid?\n\n @object.save\n rest_respond @object\n }\n\n # Make it work with `Backbone.emulateHTTP` on.\n put path, &callback\n post path, &callback\n end", "def rest_edit(path, options={}, &blk)\n callback = Proc.new { |*args|\n @object = yield(*args) or pass\n rest_params.each { |k, v| @object.send :\"#{k}=\", v unless k == 'id' }\n\n return 400, @object.errors.to_json unless @object.valid?\n\n @object.save\n rest_respond @object\n }\n\n # Make it work with `Backbone.emulateHTTP` on.\n put path, &callback\n post path, &callback\n end", "def update\n respond_to do |format|\n if @gatineo.update(gatineo_params)\n format.html { redirect_to @gatineo, notice: 'Gatineo atualizado com sucesso!' }\n format.json { render :show, status: :ok, location: @gatineo }\n else\n format.html { render :edit }\n format.json { render json: @gatineo.errors, status: :unprocessable_entity }\n end\n end\n end", "def patch(path, params)\n time(\"PATCH #{path}\") { Cloudflarer.new.patch(path, params) }\n end", "def update\n respond_to do |format|\n if @gig_request.update(gig_request_params)\n format.html { redirect_to @gig_request, notice: 'Gig request was successfully updated.' }\n format.json { render :show, status: :ok, location: @gig_request }\n else\n format.html { render :edit }\n format.json { render json: @gig_request.errors, status: :unprocessable_entity }\n end\n end\n end", "def put(*args)\n request :put, *args\n end", "def update\n respond_to do |format|\n if @ton_giao.update(ton_giao_params)\n format.html { redirect_to @ton_giao, notice: 'Ton giao was successfully updated.' }\n format.json { render :show, status: :ok, location: @ton_giao }\n else\n format.html { render :edit }\n format.json { render json: @ton_giao.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @api_v1_todo.update(api_v1_todo_params)\n format.json { render json: @api_v1_todo, status: :ok }\n else\n format.json { render json: @api_v1_todo.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @goody = Goody.find(params[:id])\n\n respond_to do |format|\n if @goody.update_attributes(params[:goody])\n format.html { redirect_to @goody, notice: 'Goody was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @goody.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @patch.update(patch_params)\n format.html { redirect_to @patch, notice: 'Patch was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @patch.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @kota_stone.update(kota_stone_params)\n format.html { redirect_to kota_stones_url, notice: 'Kota stone was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @kota_stone.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @ganho.update(ganho_params)\n format.html { redirect_to @ganho, notice: 'Ganho was successfully updated.' }\n format.json { render :show, status: :ok, location: @ganho }\n else\n format.html { render :edit }\n format.json { render json: @ganho.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @gig = Gig.find(params[:id])\n\n respond_to do |format|\n if update_gig(@gig)\n format.html { redirect_to @gig, notice: 'Gig was successfully updated.' }\n format.json { render json: @gig, status: :ok, location: @gig }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @gig.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @gakka.update(gakka_params)\n format.html { redirect_to @gakka, notice: \"Gakka was successfully updated.\" }\n format.json { render :show, status: :ok, location: @gakka }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @gakka.errors, status: :unprocessable_entity }\n end\n end\n end", "def update(path)\n output { patch(path, params) }\n end", "def put(path, data = {})\n request 'PUT', path, body: data.to_json\n end", "def update_user_for_tenant(args = {}) \n id = args['id']\n temp_path = \"/tenants.json/{tenantId}/users/{userId}\"\n path = temp_path\nargs.keys.each do |key|\n if (key == \"tenantId\")\n args.delete(key)\n path = temp_path.gsub(\"{#{key}}\", id)\n end\nend\n puts \" PATH : #{path}\"\n put(path, args)\nend", "def patch(operation, path, value)\n response = @client.rest_patch(@data['uri'], 'body' => [{ op: operation, path: path, value: value }])\n @client.response_handler(response)\n end", "def update\n @grm_grappt = GrmGrappt.find(params[:id])\n\n respond_to do |format|\n if @grm_grappt.update_attributes(params[:grm_grappt])\n format.html { redirect_to @grm_grappt, notice: 'Grooming appointment was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @grm_grappt.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\r\n respond_to do |format|\r\n @egresso.skip_fields_validation = false\r\n if @egresso.update(egresso_params)\r\n if current_admin.try(:adm?)\r\n format.html { redirect_to egressos_path, notice: 'Egresso atualizado com sucesso.' }\r\n format.json { render :show, status: :ok, location: egressos_path }\r\n else\r\n format.html { redirect_to :back, notice: 'Dados atualizados com sucesso.' }\r\n format.json { render :show, status: :ok, location: :back }\r\n end\r\n\r\n else\r\n format.html { render :edit }\r\n format.json { render json: @egresso.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def update\n respond_to do |format|\n if @json.update(json_params)\n format.html { redirect_to @json, notice: 'Json was successfully updated.' }\n format.json { render :show, status: :ok, location: @json }\n else\n format.html { render :edit }\n format.json { render json: @json.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @json.update(json_params)\n format.html { redirect_to @json, notice: 'Json was successfully updated.' }\n format.json { render :show, status: :ok, location: @json }\n else\n format.html { render :edit }\n format.json { render json: @json.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_method\n :put_json\n end", "def update\n# respond_to do |format|\n# if @req.update(req_params)\n format.json { render :json => {:status => 'success'}}\n# format.html { redirect_to @req, notice: 'Req was successfully updated.' }\n# format.json { render :show, status: :ok, location: @req }\n# else\n format.json { render :json => {:status => 'failed'}}\n# format.html { render :edit }\n# format.json { render json: @req.errors, status: :unprocessable_entity }\n# end\n# end\n end", "def UpdateView params = {}\n \n APICall(path: 'views.json',method: 'PUT',payload: params.to_json)\n \n end", "def update\n respond_to do |format|\n if @antropo.update(antropo_params)\n format.html { redirect_to @antropo, notice: 'Antropo was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @antropo.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @ocs_generada.update(ocs_generada_params)\n format.html { redirect_to @ocs_generada, notice: 'Ocs generada was successfully updated.' }\n format.json { render :show, status: :ok, location: @ocs_generada }\n else\n format.html { render :edit }\n format.json { render json: @ocs_generada.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @gift_request = GiftRequest.find(params[:id])\n \n respond_to do |format|\n if @gift_request.update_attributes(params[:gift_request])\n format.html { redirect_to @gift_request, notice: 'Gift request was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @gift_request.errors.full_messages.to_sentence, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @ingresso.update(ingresso_params)\n format.html { redirect_to @ingresso, notice: 'Ingresso was successfully updated.' }\n format.json { render :show, status: :ok, location: @ingresso }\n else\n format.html { render :edit }\n format.json { render json: @ingresso.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @request_for_change.set_manager(force: true)\n @request_for_change.set_security_officer(force: true)\n\n respond_to do |format|\n if @request_for_change.update(request_for_change_params)\n format.html { redirect_to edit_request_for_change_path(@request_for_change), notice: 'Request for change was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @request_for_change.errors, status: :unprocessable_entity }\n end\n end\n end", "def patch(request)\n request.method = :patch\n request.call\n end", "def jsonapi_update!(attributes)\n assign_jsonapi_attributes(attributes)\n save!\n end", "def patch(path, opts = {}, &block)\n request(:patch, path, opts, &block)\n end", "def patch(path, opts = {}, &block)\n request(:patch, path, opts, &block)\n end", "def from_merge_patch_json\n if request.patch?\n from_json\n else\n 415\n end\n end", "def update\n respond_to do |format|\n if @great.update(great_params)\n format.html { redirect_to @great, notice: 'Great was successfully updated.' }\n format.json { render :show, status: :ok, location: @great }\n else\n format.html { render :edit }\n format.json { render json: @great.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @apoio.update(apoio_params)\n format.html { redirect_to @apoio, notice: 'Apoio was successfully updated.' }\n format.json { render :show, status: :ok, location: @apoio }\n else\n format.html { render :edit }\n format.json { render json: @apoio.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @spoofer = Spoofer.find(params[:id])\n\n respond_to do |format|\n if @spoofer.update_attributes(params[:spoofer])\n format.html { redirect_to @spoofer, notice: 'Spoofer was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @spoofer.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @request.assign_json_attributes(params) if @request.resume?\n respond_to do |format|\n if @request.update(request_params)\n format.html { redirect_to @request, notice: 'Request was successfully updated.' }\n format.json { render :show, status: :ok, location: @request }\n else\n format.html { render :edit }\n format.json { render json: @request.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_method\n :http_put\n end", "def create_method\n :http_put\n end", "def update\n respond_to do |format|\n format.xml { head :method_not_allowed }\n format.json { head :method_not_allowed }\n end\n end", "def update\n respond_to do |format|\n if @tipoapreensao.update(tipoapreensao_params)\n format.html { redirect_to @tipoapreensao, notice: 'Tipoapreensao was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @tipoapreensao.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @patch = Patch.find(params[:id])\n\n respond_to do |format|\n if @patch.update_attributes(params[:patch])\n format.html { redirect_to @patch, notice: 'Patch was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @patch.errors, status: :unprocessable_entity }\n end\n end\n end", "def patch(action, **args); end", "def update\n #respond_to do |format|\n # if @request.update(request_params)\n # format.html { redirect_to @request, notice: 'Request was successfully updated.' }\n # format.json { head :no_content }\n # else\n # format.html { render action: 'edit' }\n # format.json { render json: @request.errors, status: :unprocessable_entity }\n # end\n #end\n end", "def update\n @koti = Koti.find(params[:id])\n\n respond_to do |format|\n if @koti.update_attributes(params[:koti])\n format.html { redirect_to @koti, notice: 'Koti was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @koti.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @objeto.update(objeto_params)\n format.html { redirect_to @objeto, notice: 'Objeto was successfully updated.' }\n format.json { render :show, status: :ok, location: @objeto }\n else\n format.html { render :edit }\n format.json { render json: @objeto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @objeto.update(objeto_params)\n format.html { redirect_to @objeto, notice: 'Objeto was successfully updated.' }\n format.json { render :show, status: :ok, location: @objeto }\n else\n format.html { render :edit }\n format.json { render json: @objeto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n put :update\n end", "def update_by_body\n @person = Person.find(person_update_params[:id])\n\n if @person.update_attributes(person_update_params)\n render json: { status: 'PUT Success' }, status: :ok\n else\n render json: { status: 'Error', message:'Error updating person', person: @person.errors }, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @jogo.update(jogo_params)\n format.html { redirect_to @jogo, notice: 'Jogo was successfully updated.' }\n format.json { render :show, status: :ok, location: @jogo }\n else\n format.html { render :edit }\n format.json { render json: @jogo.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @gondola.update(gondola_params)\n format.html { redirect_to @gondola, notice: 'Gondola was successfully updated.' }\n format.json { render :show, status: :ok, location: @gondola }\n else\n format.html { render :edit }\n format.json { render json: @gondola.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n keystone.update_tenant({:id=>params[:id],:name=>params[:name],:description=>params[:description],:enabled=>params[:enabled]})\n respond_to do |format|\n format.html { redirect_to tenants_path, :notice => 'Tenant was successfully updated.' }\n format.json { head :ok }\n end\n end", "def update\n respond_to do |format|\n if @cetak_gtg.update(cetak_gtg_params)\n format.html { redirect_to cetak_gtgs_url, notice: 'Cetak gtg was successfully updated.' }\n format.json { render :show, status: :ok, location: @cetak_gtg }\n else\n format.html { render :edit }\n format.json { render json: @cetak_gtg.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n authorize! :update, Tipo\n respond_to do |format|\n if @tipo.update(tipo_params)\n log(\"Se ha editado la nomina #{@lt}\", 1)\n format.html { redirect_to tipos_path, notice: 'Los datos de la nómina fueron actualizados exitosamente.' }\n format.json { head :no_content }\n end\n end\n end", "def update\n respond_to do |format|\n if @gig.update(gig_params)\n format.html { redirect_to @gig, notice: \"Gig was successfully updated.\" }\n format.json { render :show, status: :ok, location: @gig }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @gig.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @congresso.update(congresso_params)\n format.html { redirect_to @congresso, notice: 'Congresso was successfully updated.' }\n format.json { render :show, status: :ok, location: @congresso }\n else\n format.html { render :edit }\n format.json { render json: @congresso.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @prueba_json.update(prueba_json_params)\n format.html { redirect_to @prueba_json, notice: 'Prueba json was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @prueba_json.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @momsg = Momsg.find(params[:id])\n\n respond_to do |format|\n if @momsg.update_attributes(params[:momsg])\n format.html { redirect_to @momsg, notice: 'Momsg was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @momsg.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @genotype = Genotype.find(params[:id])\n\n respond_to do |format|\n if @genotype.update_attributes(params[:genotype])\n format.html { redirect_to @genotype, notice: 'Genotype was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @genotype.errors, status: :unprocessable_entity }\n end\n end\n end" ]
[ "0.67134315", "0.663127", "0.6481839", "0.63991874", "0.63627356", "0.6356359", "0.62897944", "0.6287018", "0.62193406", "0.6199958", "0.6199958", "0.619835", "0.6140744", "0.6104011", "0.6093891", "0.6093891", "0.6053616", "0.60272473", "0.60092235", "0.6000355", "0.59866273", "0.5985657", "0.5975166", "0.5967351", "0.5954368", "0.59406006", "0.59216446", "0.5884095", "0.5883476", "0.5879021", "0.58751595", "0.5864409", "0.58579385", "0.5838198", "0.5828776", "0.58281046", "0.58281046", "0.5818837", "0.5817296", "0.5816028", "0.5816028", "0.57941055", "0.5775704", "0.5755198", "0.5748831", "0.57374805", "0.5718372", "0.5716658", "0.57036316", "0.5699181", "0.5681817", "0.56809986", "0.5677352", "0.56763977", "0.56713396", "0.56711936", "0.56683", "0.56677914", "0.5655326", "0.56516606", "0.56516606", "0.5649987", "0.5640467", "0.56395125", "0.5629168", "0.56286335", "0.56254077", "0.5624415", "0.5622581", "0.5621466", "0.56077707", "0.55998665", "0.55998665", "0.55992466", "0.55981857", "0.5596249", "0.55946386", "0.559274", "0.55863345", "0.55863345", "0.5582814", "0.5580192", "0.5576389", "0.5572554", "0.557012", "0.5568818", "0.5563135", "0.5563135", "0.556024", "0.55551463", "0.5553243", "0.55496746", "0.5548489", "0.55484086", "0.5547764", "0.55472255", "0.5544912", "0.554131", "0.5540282", "0.55392843" ]
0.6308932
6
DELETE /gatos/1 DELETE /gatos/1.json
def destroy @gato.destroy respond_to do |format| format.html { redirect_to gatos_url, notice: 'Gato eliminado.' } format.json { head :no_content } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def delete\n client.delete(\"/#{id}\")\n end", "def delete_tenant_circle(args = {}) \n delete(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend", "def destroy\n @gato.destroy\n respond_to do |format|\n format.html { redirect_to gatos_url, notice: 'Gato was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @gasto = Gasto.find(params[:id])\n @gasto.destroy\n\n respond_to do |format|\n format.html { redirect_to gastos_url }\n format.json { head :no_content }\n end\n end", "def delete path\n make_request(path, \"delete\", {})\n end", "def delete(path)\n RestClient.delete request_base+path\n end", "def destroy\n @gatha.destroy\n respond_to do |format|\n format.html { redirect_to gathas_url }\n format.json { head :no_content }\n end\n end", "def delete_json(path)\n url = [base_url, path].join\n resp = HTTParty.delete(url, headers: standard_headers)\n parse_json(url, resp)\n end", "def destroy\n @gpath = Gpath.find(params[:id])\n @gpath.destroy\n\n respond_to do |format|\n format.html { redirect_to gpaths_url }\n format.json { head :no_content }\n end\n end", "def delete_aos_version(args = {}) \n delete(\"/aosversions.json/#{args[:aosVersionId]}\", args)\nend", "def delete\n request(:delete)\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def destroy\n @gatineo.destroy\n respond_to do |format|\n format.html { redirect_to gatineos_url, notice: 'Gatineo apagado com sucesso!' }\n format.json { head :no_content }\n end\n end", "def api_delete(path, data = {})\n api_request(:delete, path, :data => data)\n end", "def delete!\n request! :delete\n end", "def destroy\n @gig_request = GigRequest.find(params[:id])\n @gig_request.destroy\n\n respond_to do |format|\n format.html { redirect_to gig_requests_url }\n format.json { head :no_content }\n end\n end", "def delete(*rest) end", "def delete\n api(\"Delete\")\n end", "def delete\n url = prefix + \"delete\"\n return response(url)\n end", "def delete\n url = prefix + \"delete\"\n return response(url)\n end", "def destroy\n @ginasio = Ginasio.find(params[:id])\n @ginasio.destroy\n\n respond_to do |format|\n format.html { redirect_to ginasios_url, :flash => { :notice => 'Ginasio apagado.' } }\n format.json { head :ok }\n end\n end", "def delete(path)\n request(:delete, path)\n end", "def cmd_delete argv\n setup argv\n uuid = @hash['uuid']\n response = @api.delete(uuid)\n msg response\n return response\n end", "def deletef\n url = prefix + \"deletef\" + id_param\n return response(url)\n end", "def delete\n client.delete(url)\n @deleted = true\nend", "def delete(path)\n request 'DELETE', path\n end", "def delete(id:)\n id_check(:id, id)\n\n cf_delete(path: \"/organizations/#{org_id}/railguns/#{id}\")\n end", "def delete(path)\n\t\trequest(path, :delete)\n\tend", "def delete!( opts = {} )\n http_action :delete, nil, opts\n end", "def delete(path, data = {})\n self.class.delete path, :body => data.merge(:u => access_token)\n end", "def delete\n url = prefix + \"delete\" + id_param\n return response(url)\n end", "def delete\n render :json => @fiestas.delete_at(params[:id].to_i)\n end", "def destroy\n @asignatura.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @kota_stone.destroy\n respond_to do |format|\n format.html { redirect_to kota_stones_url }\n format.json { head :no_content }\n end\n end", "def http_delete(path, data = nil, content_type = 'application/json')\n http_methods(path, :delete, data, content_type)\n end", "def destroy\n @gakka.destroy\n respond_to do |format|\n format.html { redirect_to gakkas_url, notice: \"Gakka was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @go = Go.find(params[:id])\n @go.destroy\n\n respond_to do |format|\n format.html { redirect_to manager_gos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @datoscontacto = Datoscontacto.find(params[:id])\n @datoscontacto.destroy\n\n respond_to do |format|\n format.html { redirect_to datoscontactos_url }\n format.json { head :no_content }\n end\n end", "def delete\n render json: Alien.delete(params[\"id\"])\n end", "def test_del\n header 'Content-Type', 'application/json'\n\n data = File.read 'sample-traces/0.json'\n post('/traces', data, 'CONTENT_TYPE': 'application/json')\n\n id = last_response.body\n\n delete \"/traces/#{id}\"\n assert last_response.ok?\n\n get \"/traces/#{id}\"\n\n contents = JSON.parse last_response.body\n assert_kind_of(Hash, contents, 'Response contents is not a hash')\n assert contents.key? 'description'\n assert(!last_response.ok?)\n end", "def delete(path, params)\n headers = {:Authorization => \"token #{token}\", :content_type => :json, :accept => :json}\n res = RestClient.delete(\"#{github_api_uri}/#{path}\", params.to_json, headers)\n Yajl.load(res)\n end", "def delete\n start { |connection| connection.request http :Delete }\n end", "def delete(url, headers = {})\n http :delete, \"#{url}.json\", headers\n end", "def destroy\n @gig = Gig.find(params[:id])\n @gig.destroy\n\n respond_to do |format|\n format.html { redirect_to gigs_url }\n format.json { render json: nil, status: :ok }\n end\n end", "def destroy\n @gethotelstaticdatagd = Gethotelstaticdatagd.find(params[:id])\n @gethotelstaticdatagd.destroy\n\n respond_to do |format|\n format.html { redirect_to gethotelstaticdatagds_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @dataload_ga = DataloadGa.find(params[:id])\n @dataload_ga.destroy\n\n respond_to do |format|\n format.html { redirect_to dataload_gas_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @gentre.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def delete(*args)\n request(:delete, *args)\n end", "def destroy\n @goat = Goat.find(params[:id])\n @goat.destroy\n\n respond_to do |format|\n format.html { redirect_to goats_url }\n format.json { head :no_content }\n end\n end", "def delete\n res = HTTParty.get URL, headers: HEADERS\n message = JSON.parse res.body, symbolize_names: true\n if res.code == 200\n numSubs = message[:data].count\n if numSubs > 0\n message[:data].each do |sub|\n id = sub[:id]\n delRes = HTTParty.delete \"#{URL}/#{id}\", headers: HEADERS\n #TODO handle status codes\n end\n end\n end\n end", "def delete(path)\n path = relativize_path path\n\n Precog.connect self do |http|\n uri = Addressable::URI.new\n uri.query_values = { :apiKey => api_key }\n\n http.delete \"/ingest/v#{VERSION}/fs/#{path}?#{uri.query}\"\n end\n end", "def destroy\n @agronomiaquimica = Agronomiaquimica.find(params[:id])\n @agronomiaquimica.destroy\n\n respond_to do |format|\n format.html { redirect_to agronomiaquimicas_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @ganho = Ganho.find(params[:id])\n @ganho.destroy\n\n respond_to do |format|\n format.html { redirect_to(ganhos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @cetak_gtg.destroy\n respond_to do |format|\n format.html { redirect_to cetak_gtgs_url, notice: 'Cetak gtg was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\r\n checar_egresso_super\r\n @egresso.destroy\r\n respond_to do |format|\r\n format.html { redirect_to egressos_url, notice: 'Egresso excluído com sucesso.' }\r\n format.json { head :no_content }\r\n end\r\n end", "def destroy\n @tatoo.destroy\n respond_to do |format|\n format.html { head :no_content }\n format.json { head :no_content }\n end\n end", "def destroy\n @bodega.destroy\n respond_to do |format|\n format.html { redirect_to bodegas_url }\n format.json { head :no_content }\n end\n end", "def delete(path)\n request(:delete, path)\n end", "def destroy\n @ganho.destroy\n respond_to do |format|\n format.html { redirect_to ganhos_url, notice: 'Ganho was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @gonzo.destroy\n respond_to do |format|\n format.html { redirect_to gonzos_url, notice: 'Gonzo was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @specific_gravity.destroy\n respond_to do |format|\n format.html { redirect_to @batch, notice: 'Specific gravity was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete(path, params={})\n request(:delete, path, params)\n end", "def delete(path, params={})\n request(:delete, path, params)\n end", "def delete(path, params={})\n request(:delete, path, params)\n end", "def delete(path, params={})\n request(:delete, path, params)\n end", "def delete(path, params={})\n request(:delete, path, params)\n end", "def delete(path, params={})\n request(:delete, path, params)\n end", "def delete(path, params={})\n request(:delete, path, params)\n end", "def delete(path, params)\n request(:delete, path, {})\n end", "def delete\n url = prefix + \"delete\"\n return response(url)\n end", "def delete\n url = prefix + \"delete\"\n return response(url)\n end", "def delete\n api_client.delete(url)\n end", "def destroy\n @gig_request.destroy\n respond_to do |format|\n format.html { redirect_to gig_requests_url, notice: 'Gig request was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete\n \n end", "def destroy\n @gosok.destroy\n respond_to do |format|\n format.html { redirect_to gosoks_url, notice: 'Gosok was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @gua.destroy\n respond_to do |format|\n format.html { redirect_to guas_url, notice: 'Gua was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @tapioca.destroy\n respond_to do |format|\n format.html { redirect_to tapiocas_url }\n format.json { head :no_content }\n end\n end", "def delete(path, params)\n parse_response @client[path].delete(:params => params)\n end", "def destroy\n @tipo_agressor.destroy\n respond_to do |format|\n format.html { redirect_to tipo_agressores_url, notice: @@msgs }\n format.json { head :no_content }\n end\n end", "def destroy\n @gama.destroy\n respond_to do |format|\n format.html { redirect_to gamas_url, notice: 'Gama was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete(type, id)\n http_delete @target, \"#{type_info(type, :path)}/#{Addressable::URI.encode(id)}\", @auth_header, @zone\n end", "def delete(options={})\n connection.delete(\"/\", @name)\n end", "def delete(path, params = {})\n request(:delete, path, params)\n end", "def delete(path, params = {})\n request(:delete, path, params)\n end", "def delete(path, params = {})\n request(:delete, path, params)\n end", "def destroy\n @gravity.destroy\n respond_to do |format|\n format.html { redirect_to gravities_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @gomi.destroy\n respond_to do |format|\n format.html { redirect_to gomis_url, notice: 'Gomi was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @baton = Baton.find(params[:id])\n @baton.destroy\n\n respond_to do |format|\n format.html { redirect_to batons_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @golfer = Golfer.find(params[:id])\n @golfer.destroy\n\n respond_to do |format|\n format.html { redirect_to golfers_url }\n format.json { head :no_content }\n end\n end", "def delete\n\n end", "def delete(path)\n repository = path.split(/\\//)[2]\n objectid = path.split(/\\//)[3]\n if storage_fetch(repository, objectid) && storage_delete(repository, objectid)\n ['200', {}, []]\n else\n ['404', {}, [\"Repository #{repository} or ObjectID #{objectid} not found: #{path}\"]]\n end\n end", "def delete(path, params={})\n request(:delete, path, params)\n end", "def delete_json(url)\n JSON.parse(delete(url, :json, :json))\n end", "def destroy\n @ton_giao.destroy\n respond_to do |format|\n format.html { redirect_to ton_giaos_url, notice: 'Ton giao was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete\n execute_request('DELETE') do |uri, headers|\n HTTP.http_client.delete(uri, header: headers)\n end\n end", "def destroy\n @gig_type.destroy\n respond_to do |format|\n format.html { redirect_to gig_types_url, notice: 'Gig type was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete endpoint\n do_request :delete, endpoint\n end" ]
[ "0.7076654", "0.70082253", "0.6974017", "0.69264495", "0.6873137", "0.685613", "0.68513274", "0.68319887", "0.6825646", "0.6816378", "0.68099326", "0.6740092", "0.6740092", "0.6740092", "0.6740092", "0.66871685", "0.6687002", "0.66235137", "0.66104037", "0.66040975", "0.6604077", "0.6602901", "0.6602901", "0.6595828", "0.6585348", "0.65670127", "0.65666056", "0.65485966", "0.65485", "0.65472203", "0.6531934", "0.6526888", "0.65208215", "0.65131676", "0.6509651", "0.64825726", "0.64756215", "0.6475591", "0.64754313", "0.6473997", "0.6473627", "0.6472545", "0.6470628", "0.64630336", "0.6461191", "0.6456307", "0.6451214", "0.6450968", "0.6449668", "0.644882", "0.6443534", "0.6442747", "0.6442519", "0.64354795", "0.64333534", "0.64279675", "0.642708", "0.642405", "0.6422751", "0.642263", "0.6418121", "0.6413303", "0.64074516", "0.6403446", "0.64002424", "0.64002424", "0.64002424", "0.64002424", "0.64002424", "0.64002424", "0.64002424", "0.6390963", "0.6389152", "0.6389152", "0.6388749", "0.63874596", "0.63735306", "0.637255", "0.6371389", "0.6371365", "0.6368659", "0.63682544", "0.6366048", "0.6359909", "0.6355566", "0.63554996", "0.63554996", "0.63554996", "0.6354962", "0.6354634", "0.63535404", "0.63532794", "0.6351032", "0.63499373", "0.6344587", "0.63442934", "0.6341859", "0.6340227", "0.63368446", "0.6336387" ]
0.68643546
5
Use callbacks to share common setup or constraints between actions.
def set_gato @gato = Gato.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 setup_handler\n end", "def before_actions(*logic)\n self.before_actions = logic\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 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 workflow\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 default_action; end", "def my_actions(options)\n @setup = false\n get_template_part(\"custom_used\",\"action_users\",true)\n 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.6163927", "0.6046165", "0.59465253", "0.59167755", "0.58904207", "0.58346355", "0.577713", "0.5703502", "0.5703502", "0.56531286", "0.56215113", "0.54224145", "0.5410795", "0.5410795", "0.5410795", "0.53924775", "0.5379919", "0.53580743", "0.53401667", "0.53397506", "0.5332605", "0.5312215", "0.5296594", "0.52965283", "0.52957606", "0.5259903", "0.52443177", "0.523896", "0.523896", "0.523896", "0.523896", "0.523896", "0.52329034", "0.52322394", "0.5227445", "0.5222394", "0.5220348", "0.5212759", "0.5207747", "0.5205933", "0.5176468", "0.5173833", "0.5171983", "0.51663405", "0.5159596", "0.5158247", "0.51526845", "0.5152398", "0.5151361", "0.5145775", "0.5140135", "0.51338995", "0.51127726", "0.5112607", "0.5112607", "0.5110613", "0.51067513", "0.5092337", "0.508788", "0.5081578", "0.5080434", "0.50679874", "0.50567716", "0.5051213", "0.5048352", "0.5048352", "0.5035347", "0.5026666", "0.5023127", "0.5016081", "0.50129867", "0.5000684", "0.4999752", "0.49979812", "0.499026", "0.499026", "0.49866846", "0.49800366", "0.49795717", "0.49771172", "0.4968475", "0.4965813", "0.4958072", "0.49561292", "0.4954901", "0.49536785", "0.4953058", "0.49468648", "0.49424478", "0.4932989", "0.49291888", "0.49273813", "0.49271655", "0.4925948", "0.49236968", "0.49203572", "0.49181753", "0.49173692", "0.4916862", "0.49161318", "0.49155986" ]
0.0
-1
Never trust parameters from the scary internet, only allow the white list through.
def gato_params params.require(:gato).permit(:nombre, :edad, :formato_edad, :sexo, :raza, :tipo, :peso, :porte, :chip, :numero_chip, :agresividad, :color, :senas, :fecha_operacion, :comentario, :ficha_id, :propietario_es, :veterinario_id, :apto_cirujia, :apto_cirujia_text, :medico_tratante, :hora_ingreso, :tipo_cirujia, :hallazgos, :hora_alta, :complicaciones,vacunas_attributes:[:id,:nombre,:_destroy], enfermedades_attributes:[:id,:nombre,:_destroy],veterinario_atributes:[:id,:nombre,:_destroy],medicamentos_attributes:[:id,:nombre,:cantidad,:unidad,:cada,:durante,:durante_unidad,:_destroy]) 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 user_params\n params.permit(:name, :phoneNumber, :address, :postalCode, :local, :link, :counter, :latitude, :longitude) \n end", "def valid_params_request?; 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 strong_params\n params.require(:metric_change).permit(param_whitelist)\n end", "def safe_params\n params.require(:user).permit(:name)\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 url_params\n params.require(:url).permit(:short_url, :original_url, :clicks, :ip_addresses)\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 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 active_code_params\n params[:active_code].permit\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 ip_address_params\n\t\t\tparams.require(:ip_address).permit!\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 reserved_params\n params.require(:reserved).permit(:name, :email, :pax, :address, :KTP, :title)\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 list_params\n params.permit(:name)\n end", "def filter_parameters; end", "def filter_parameters; 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 url_whitelist; end", "def admin_social_network_params\n params.require(:social_network).permit!\n end", "def filter_params\n params.require(:filters).permit(:letters)\n end", "def origin_params\n params.permit(:country, :state, :city, :postal_code, :address, :description)\n end", "def valid_params(params)\n params.permit(:login, :first_name, :last_name, \n :password, :password_confirmation)\n end", "def sensitive_params=(params)\n @sensitive_params = params\n end", "def permit_request_params\n params.permit(:address)\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 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 user_params\n params.permit(:name, :age, :username, :display_photo, :password)\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.69792545", "0.6781151", "0.67419964", "0.674013", "0.6734356", "0.6591046", "0.6502396", "0.6496313", "0.6480641", "0.6477825", "0.64565", "0.6438387", "0.63791263", "0.63740575", "0.6364131", "0.63192815", "0.62991166", "0.62978333", "0.6292148", "0.6290449", "0.6290076", "0.62894756", "0.6283177", "0.6242471", "0.62382483", "0.6217549", "0.6214457", "0.6209053", "0.6193042", "0.6177802", "0.6174604", "0.61714715", "0.6161512", "0.6151757", "0.6150663", "0.61461", "0.61213595", "0.611406", "0.6106206", "0.6105114", "0.6089039", "0.6081015", "0.6071004", "0.60620916", "0.6019971", "0.601788", "0.6011056", "0.6010898", "0.6005122", "0.6005122", "0.6001556", "0.6001049", "0.59943926", "0.5992201", "0.59909594", "0.5990628", "0.5980841", "0.59669393", "0.59589154", "0.5958826", "0.5957911", "0.5957385", "0.5953072", "0.59526145", "0.5943361", "0.59386164", "0.59375334", "0.59375334", "0.5933856", "0.59292704", "0.59254247", "0.5924164", "0.59167904", "0.59088355", "0.5907542", "0.59064597", "0.5906243", "0.5898226", "0.589687", "0.5896091", "0.5894501", "0.5894289", "0.5891739", "0.58860534", "0.5882406", "0.587974", "0.58738774", "0.5869024", "0.58679986", "0.5867561", "0.5865932", "0.5864461", "0.58639693", "0.58617616", "0.5861436", "0.5860451", "0.58602303", "0.5854586", "0.58537364", "0.5850427", "0.5850199" ]
0.0
-1
Use callbacks to share common setup or constraints between actions.
def set_freight @freight = Freight.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 freight_params params.require(:freight).permit(:airport_id, :inspectedon, :carrier, :brmtype_id, :ctnpresented, :ctnreleased, :start_time, :finish_time, :importer, :exporter, :permit, :noncompliance, :avatar, :comment) 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 valid_params_request?; end", "def user_params \n \tparams.require(:user).permit(:name, :email, :password, :password_confirmation)# preventing CSTR\n 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 active_code_params\n params[:active_code].permit\n end", "def valid_params(params)\n params.permit(:user_id, :photo_id, :originX, :originY, :width, :height)\n end", "def filtering_params\n params.permit(:email)\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 list_params\n params.permit(:name)\n end", "def filter_parameters; end", "def filter_parameters; 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 url_whitelist; 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 valid_params(params)\n params.permit(:login, :first_name, :last_name, \n :password, :password_confirmation)\n end", "def filter_params\n params.require(:filters).permit(:letters)\n end", "def origin_params\n params.permit(:country, :state, :city, :postal_code, :address, :description)\n end", "def sensitive_params=(params)\n @sensitive_params = params\n end", "def permit_request_params\n params.permit(:address)\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 maintenance_request_params\n params[:maintenance_request].permit! #allow all parameters for now\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 url_params\n params[:url].permit(:full)\n end", "def backend_user_params\n params.permit!\n end", "def unwanted_params\n params.require(:unwanted).permit(:title, :description, :image)\n end", "def filter_params\n\t\treturn params[:candidate].permit(:name_for_filter)\n\tend", "def user_params\n params.permit(:name, :age, :username, :display_photo, :password)\n end", "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 droptraining_params\n params.permit(:training_id,:user_id, :utf8, :authenticity_token, :commit)\n end", "def pass_params\n params[:pass].permit(:name, :price, :description, :colour, :events)\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.6980957", "0.6783065", "0.6747844", "0.6741468", "0.67356336", "0.6592548", "0.65036845", "0.64978707", "0.64825076", "0.64795035", "0.64560914", "0.64397955", "0.6379666", "0.6376688", "0.6366702", "0.6319728", "0.6300833", "0.6300629", "0.6294277", "0.6293905", "0.6291174", "0.62905735", "0.6283171", "0.6242344", "0.62403613", "0.6218049", "0.62143815", "0.62104696", "0.61949855", "0.6178671", "0.6176147", "0.6173327", "0.6163395", "0.6153005", "0.6151833", "0.6147288", "0.61224324", "0.6118827", "0.61075264", "0.61054534", "0.6092497", "0.6080082", "0.60710967", "0.60627776", "0.60219413", "0.60175914", "0.60153484", "0.60107356", "0.60081726", "0.60081726", "0.60013986", "0.6000165", "0.59978646", "0.59936947", "0.59925723", "0.5992084", "0.59796256", "0.5967569", "0.5960056", "0.59589803", "0.5958441", "0.5958401", "0.5952607", "0.5952406", "0.5944409", "0.59391016", "0.593842", "0.593842", "0.5933845", "0.59312123", "0.5926475", "0.59248453", "0.59179676", "0.59109294", "0.59101623", "0.5908172", "0.59058356", "0.5899052", "0.5897749", "0.5896101", "0.58942914", "0.58939576", "0.5892063", "0.5887407", "0.588292", "0.58797663", "0.587367", "0.58681566", "0.5868038", "0.5866578", "0.58665025", "0.58655846", "0.58640826", "0.5863465", "0.5862226", "0.586065", "0.58581287", "0.5854443", "0.5854172", "0.58507544", "0.5849934" ]
0.0
-1
Here our task is to convert string to number
def string_to_number(string) string.to_i end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def convert_string_to_number(str); end", "def string_to_number(string)\n string.to_f\nend", "def str_to_number(s)\r\n\t\tval_str = s.to_s()\r\n\t\tif INT_REGEX.match(val_str)\r\n\t\t\treturn val_str.to_i()\r\n\t\telsif FLOAT_REGEX.match(val_str)\r\n\t\t\treturn val_str.to_f()\r\n\t\telse\r\n\t\t\traise ArgumentError, \"can't understand numeric format '#{s}'\"\r\n\t\tend\r\n\tend", "def convert_string_to_number(str)\n matches = RE_NUMBER_STR.match(str)\n\n s = matches[:sign] == '-' ? -1 : 1\n i = matches[:integer].to_i\n f = matches[:fractional].to_i\n d = matches[:fractional] ? matches[:fractional].length : 0\n t = matches[:exponent_sign] == '-' ? -1 : 1\n e = matches[:exponent].to_i\n\n # I know this looks nutty, but it's exactly what's defined in the spec,\n # and it works.\n s * (i + f * 10**-d) * 10**(t * e)\n end", "def string_to_number(s)\n s.to_i\nend", "def string_to_number(s)\n s.to_i\nend", "def string_to_number(string)\n case string\n when /^\\d+$/\n string.to_i\n when /^\\d+.\\d$/\n string.to_f\n else \n string\n end\n end", "def string_to_number(string)\n case string\n when /^\\d+$/\n string.to_i\n when /^\\d+.\\d$/\n string.to_f\n else\n string\n end\n end", "def convert_string_to_number(str)\n matches = RE_NUMBER_STR.match(str)\n\n s = matches[:sign] == '-' ? -1 : 1\n i = matches[:integer].to_i\n f = matches[:fractional].to_i\n d = matches[:fractional] ? matches[:fractional].length : 0\n t = matches[:exponent_sign] == '-' ? -1 : 1\n e = matches[:exponent].to_i\n\n # I know this formula looks nutty, but it's exactly what's defined in the\n # spec, and it works.\n value = s * (i + f * 10**-d) * 10**(t * e)\n\n # Maximum and minimum values aren't defined in the spec, but are enforced\n # here for sanity.\n if value > Float::MAX\n value = Float::MAX\n elsif value < -Float::MAX\n value = -Float::MAX\n end\n\n value\n end", "def cast_to_num(str)\n Integer(str)\n rescue ArgumentError\n Float(str)\n rescue ArgumentError\n nil\n end", "def to_num(string)\n string.gsub!(' ', '')\n string.each_char.map { |char| \"#{convert[char]} \" }.join.chop\n end", "def to_number(string)\n Integer(string || '')\n rescue ArgumentError\n 0\n end", "def convert_number_string_to_integer(number_string)\n Integer(number_string.gsub(\" \", \"\"))\nend", "def parse_number(string)\n if string.include? \".\"\n string.to_f\n elsif string.include? \"E\"\n Complex(string).to_f\n else\n string.to_i\n end\n end", "def string_to_integer(string)\nend", "def string_to_integer(str)\n str.to_i\nend", "def string_to_integer(str)\n return str.to_i\nend", "def str_to_int(str_num)\n arr_num = str_to_array_of_num(str_num)\n new_num = 0\n while arr_num.length > 0\n n = arr_num.length\n i = arr_num.shift\n new_num += i * 10**(n-1)\n end\n new_num\nend", "def str_to_num(string)\n int_list = []\n final_num = 0\n string_list = string.split(\"\")\n for char in string_list\n if 48 <= char.ord && char.ord <= 57\n int_list.push(char.ord - 48)\n else\n return false\n end\n end\n for i in 0...int_list.length\n value = int_list[-i-1]\n place = 10**i\n final_num += value*place\n end\n final_num\nend", "def string_to_integer(str)\n convert_hash = {\n '0' => 0,\n '1' => 1,\n '2' => 2,\n '3' => 3,\n '4' => 4,\n '5' => 5,\n '6' => 6,\n '7' => 7,\n '8' => 8,\n '9' => 9,\n }\n sum = 0\n value = 0\n str_arr = str.chars\n str_arr.each do |num|\n value = convert_hash[num]\n sum += value * (10 ** (str_arr.length - (str_arr.index(num) + 1)))\n end\n sum\nend", "def my_number_parse(num_str)\n output = 0\n\n num_str.split(\"\").reverse.each_with_index do |num, index|\n output = output + num.to_i * (10 ** index)\n end\n\n output\nend", "def to_float_or_int str\n Integer(str) rescue Float(str) rescue nil\n end", "def string_to_integer(string)\n digits = string.chars.map(&:to_i)\n value = 0\n digits.each do |digit|\n value = 10 * value + digit\n end\n value\nend", "def number_from_string(string)\n bd = BigDecimal.new(string)\n if @style == :dash || @style == :dash_long\n return (bd * Dash::COIN).to_i\n else\n # TODO: support other styles\n raise \"Not Implemented\"\n end\n end", "def string_to_integer(string, numbers)\n str_nums = string.chars.reverse\n number = 0\n str_nums.each_with_index do |num, index|\n number += numbers[num] * 10**(index)\n end\n number\nend", "def string_to_integer(string)\n \n digit_array = string.chars.map do |digit|\n digit = DIGITS[digit]\n end\n \n converted_string = 0\n \n digit_array.each do |digit|\n converted_string = converted_string * 10 + digit\n end\n \n converted_string\nend", "def number_from_string(string)\n bd = BigDecimal.new(string)\n if @style == :btc || @style == :btc_long\n return (bd * BTC::COIN).to_i\n else\n # TODO: support other styles\n raise \"Not Implemented\"\n end\n end", "def string_to_integer(str)\n arr = []\n str.each_char { |char| arr << char if STR_TO_INT.key?(char) }\n\n sum = 0\n arr.reverse.each.with_index do |num, index|\n sum += STR_TO_INT[num] * 10**index\n end\n sum\nend", "def to_number(obj)\n case obj\n when Numeric\n obj\n when String\n (obj.strip =~ /^\\d+\\.\\d+$/) ? obj.to_f : obj.to_i\n when DateTime, Date, Time\n obj.to_time.to_i\n else\n 0\n end\n end", "def to_number(obj)\n case obj\n when Numeric\n obj\n when String\n (obj.strip =~ /^\\d+\\.\\d+$/) ? obj.to_f : obj.to_i\n when DateTime, Date, Time\n obj.to_time.to_i\n else\n 0\n end\n end", "def to_integer(string)\n string.to_i\n rescue\n 0\n end", "def atoi(s)\n offset = '0'.ord\n neg = false\n sum = 0\n\n begin\n s.each_byte do |i|\n if i == 45 # the number is negative\n neg = true\n next\n elsif i == 46 # Number is a float, disregard mantissa\n break \n elsif (i < 48 || i > 57) # Not a valid number\n raise InvalidNumberException, \"Error: Invalid Number\"\n end\n\n # Get value of char as int and add to current sum\n tmp = i - offset\n sum = (sum * 10) + tmp\n end \n\n # Make number negative if it was originally negative\n return neg ? -sum : sum\n\n rescue InvalidNumberException => e\n abort(e.message) # inform user about error\n end\nend", "def numberfy(input_string)\n if input_string.include?(\".\")\n input_string.to_f\n else input_string.to_i\n end\nend", "def string_to_integer2(string)\n digits = string.chars.map { |char| HASH[char] }\n\n value = 0\n digits.each { |digit| value = 10 * value + digit }\n value\nend", "def number_from_text(text)\n return nil unless starts_with_numeric_text?(text)\n text.to_i\n end", "def string_to_integer(string)\n digits = string.chars.map { |digit| MATCH[digit] }\n\n value = 0\n digits.each { |digit| value = 10 * value + digit }\n value\nend", "def convert_string_input_to_integer(str)\n is_string_a_valid_integer?(str) ? str.to_i : nil\nend", "def string_to_integer(string)\n\n\tnumbers = {'0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5,\n\t\t\t\t'6' => 6, '7' => 7, '8' => 8, '9' => 9 }\n\n\tarray = string.chars.map do |n|\n\t\tnumbers[n]\n\tend\n\n\tarray.inject(0){ |total, num| total * 10 + num}\n\nend", "def string_to_integer(string)\n\n\tnumbers = {'0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5,\n\t\t\t\t'6' => 6, '7' => 7, '8' => 8, '9' => 9 }\n\n\tarray = string.chars.map do |n|\n\t\tnumbers[n]\n\tend\n\n\tarray.inject(0){ |total, num| total * 10 + num}\n\nend", "def value(string)\n Sass::Script::Number.new(string.value)\n end", "def string_to_integer(str)\n place_idx = (str.length - 1)\n \n num = 0\n while place_idx >= 0\n digit = str[place_idx].ord - '0'.ord\n num = num + digit * (10 ** (str.length - 1 - place_idx))\n place_idx -= 1\n end\n\n num\nend", "def string_to_value(string)\n case string\n when '1p'\n 1\n when '2p'\n 2\n when '5p'\n 5\n when '10p'\n 10\n when '20p'\n 20\n when '50p'\n 50\n when '£1'\n 100\n when '£2'\n 200\n end\n end", "def string_to_integer(str)\n num_hsh = {'1'=>1,'2'=>2,'3'=>3,'4'=>4,'5'=>5,'6'=>6,'7'=>7,'8'=>8,'9'=>9,'0'=>0,}\n arr = str.chars.reverse\n total = 0\n new_arr = []\n arr.each do |str|\n new_arr << num_hsh[str]\n end\n new_arr.each_with_index do |num, i|\n total += num * 10**i\n end\n total\nend", "def parse_number(num)\n if num.is_float?\n num.to_f\n else\n num.to_i\n end\n end", "def get_number_from_string(s)\n s.gsub(/[^\\d]/,\"\").to_i\nend", "def parse_decimal_part(str)\n map = if str.index('割')\n Numeja::JA_割合用小数\n else\n Numeja::JA_小数\n end\n keys = map.keys()\n keys.reduce(0) do |t, ja_digit|\n index = str.index(ja_digit)\n break t if index.nil?\n unit = str.slice!(0, index)\n str.slice!(0, 1)\n t += (unit.to_f * map[ja_digit])\n t\n end\n end", "def get_number_from_string(s)\n s.scan(/\\d/).map(&:to_i).join.to_i\nend", "def numberfy(string)\n message = string.downcase.split(//)\n message.each do |char|\n (ALPHA.include? char) ? number = ALPHA_HASH[char] : number = char\n @numeric_message << number\n end\n end", "def string_to_integer(num_string)\n digits = { '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4,\n '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9 }\n\n num_string.chars.reverse.map.with_index { |char, idx| digits[char] * (10 ** idx) }.sum\nend", "def string_to_integer(string)\n char_to_int = {\n '1'=> 1,\n '2'=> 2,\n '3'=> 3,\n '4'=> 4,\n '5'=> 5,\n '6'=> 6,\n '7'=> 7,\n '8'=> 8,\n '9'=> 9,\n '0'=> 0,\n }\n \n if string[0] == '-' then\n string[1..string.length].chars.reduce(0) { |int, char| int * 10 + char_to_int[char]} * -1\n elsif string[0] == '+' then\n string[1..string.length].chars.reduce(0) { |int, char| int * 10 + char_to_int[char]}\n else\n string.chars.reduce(0) { |int, char| int * 10 + char_to_int[char]}\n end\nend", "def get_number_from_string(s)\n s.delete(\"^[0-9]\").to_i\nend", "def float_or_interger(str)\n if str.include?\".\"\n num =str.to_f\n else\n num = str.to_i\n end\n return num\nend", "def to_number(value)\n return value.to_i unless value =~ /\\./\n return value.to_f if value =~ /\\./ \n end", "def param_to_number(v, consts_mgr = @consts_mgr)\n if v.class == NilClass then\n return 0\n elsif v.kind_of? Integer then\n return v # ok, it's already a number\n elsif v.kind_of? String then\n dw = consts_mgr.parse(v) # might raise an exception\n if dw != nil\n return dw\n else\n raise ArgumentError, \"Param #{v} (class #{v.class}) cannot be converted to a number. It's a string but matches no constants I know.\"\n end\n else\n raise \"Param #{v} (class #{v.class}) should be a number but isn't\"\n end\n end", "def string_to_integer(str)\n str.chars.map { |chr| chr.ord - 48 }.reduce { |a, e| (a * 10) + e }\nend", "def convert number\n raise_on_type_mismatch number\n typed_conversion number\n end", "def convert number\n raise_on_type_mismatch number\n typed_conversion number\n end", "def convert number\n raise_on_type_mismatch number\n typed_conversion number\n end", "def convert number\n raise_on_type_mismatch number\n typed_conversion number\n end", "def convert number\n raise_on_type_mismatch number\n typed_conversion number\n end", "def to_numeric(anything)\n\n num = BigDecimal.new(anything.to_s)\n if num.frac == 0\n num.to_i\n else\n num.to_r\n end\n end", "def convert_to_int num_string\n num_hash = {\n '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4,\n '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9 \n }\n\n num_array = num_string.chars.map do |char|\n num_hash[char]\n end\n\n final_number = 0\n count = num_array.length - 1\n\n num_array.each do |num| \n final_number += num * (10 ** count)\n count -=1\n end\n\n p final_number\nend", "def convert_to_integer(string)\n unless /^-?\\d+$/ =~ string\n raise \"'#{string}' is not an integer.\" #(1)\n end\n string.to_i\nend", "def convert_to_integer\n @valid = false\n DIGIT_DATA.each do |integer,data|\n if string == data['string']\n @integer = integer\n @valid = true\n end\n end\n end", "def convert_number(number)\n return 0 if number.nil?\n return number if number.is_a?(BigDecimal)\n\n number = number.gsub(\".\", \"\").gsub(\",\", \".\") unless number.is_a?(Numeric)\n number.to_d\n end", "def convert_to_number\n @roman_util.compute_number\n end", "def to_int(string)\n Integer(string)\nrescue ArgumentError\n nil\nend", "def input_to_num\n @input = @input.to_i\n end", "def number\n @number ||= parse(read)\n end", "def convert_to_numeric(val)\n return BigDecimal(val, Float::DIG) if val.is_a?(Float)\n return val if val.is_a?(Numeric)\n # Eliminate any commas, $'s (or other currency symbol), or _'s.\n cursym = Regexp.quote(FatTable.currency_symbol)\n clean_re = /[,_#{cursym}]/\n val = val.to_s.clean.gsub(clean_re, '')\n return nil if val.blank?\n case val\n when /(\\A[-+]?\\d+\\.\\d*\\z)|(\\A[-+]?\\d*\\.\\d+\\z)/\n BigDecimal(val.to_s.clean)\n when /\\A[-+]?[\\d]+\\z/\n val.to_i\n when %r{\\A([-+]?\\d+)\\s*[:/]\\s*([-+]?\\d+)\\z}\n Rational($1, $2)\n end\n end", "def string_to_integer(string)\n integer = 0\n idx = 0\n while idx < string.length\n integer = integer * 10\n integer += string[idx].to_i\n idx += 1\n end\n\n integer\nend", "def string_to_integer(string)\n integer_hash = {\n '0' => 0,\n '1' => 1,\n '2' => 2,\n '3' => 3,\n '4' => 4,\n '5' => 5,\n '6' => 6,\n '7' => 7,\n '8' => 8,\n '9' => 9\n }\n\n output_array = []\n\n string.chars.reverse.each_with_index { |val, i| output_array << integer_hash[val] * 10 ** i }\n\n output_array.reduce(:+)\nend", "def translate_string_to_number(input)\n\n #take the input\n #break it up into individual letters\n #map the letters to a dictionary (a = 1) or\n #map the input to a placement in an array\n\nend", "def getNum (string)\n\tif string.to_i == 0\n\t\tif string.eql?('0')\n\t\t\treturn 0\n\t\telse\n\t\t\treturn 10\n\t\tend\n\tend\n\treturn string.to_i\nend", "def extractNumber str\n match = STDNUMPAT.match str\n return nil unless match\n return (match[1].gsub(/\\-/, '')).upcase\n end", "def to_integer(input); end", "def to_non_shorthand(value_string)\n return_float = 0\n if !value_string.nil? && value_string != \"N/A\"\n if value_string.include?(\"B\")\n return_float = value_string.delete(\"B\").to_f * 1000000000\n elsif value_string.include?(\"M\")\n return_float = value_string.delete(\"M\").to_f * 1000000\n elsif value_string.include?(\"K\")\n return_float = value_string.delete(\"K\").to_f * 1000000\n end\n end\n return_float\n end", "def string_to_integer(string_num)\n hash = {\n '0'=>0, '1'=>1, '2'=>2, '3'=>3, '4'=>4,\n '5'=>5, '6'=>6, '7'=>7, '8'=>8, '9'=>9\n }\n int_array = string_num.chars.map { |num| hash[num] }\n tens = 1\n integer = 0\n int_array.size.times do\n integer += int_array.pop * tens\n tens *= 10\n end\n integer\nend", "def str_to_val(s)\n case s\n when /^\\d+$/ then s.to_i\n when /^\\d+\\.\\d*/ then s.to_f\n when /^true$/ then true\n when /^false$/ then false\n else s\n end\nend", "def string_to_integer(str)\n str_size = str.size\n num_str = '0123456789'\n curr_size = 1\n str_size.times{curr_size *= 10}\n result = 0\n pos = 0\n\n arr = str.split('')\n\n arr.each do |a|\n pos = num_str.index(a)\n add_up = pos * curr_size\n result += add_up\n curr_size /= 10\n end\n result /= 10\nend", "def to_i( str )\n return str if !str.is_a?( String )\n\n if str.match( /\\d+/ ).to_s.size == str.size\n return str.to_i\n else\n return str\n end\n end", "def add_string_as_number(a, b)\n a = a.to_i\n b = b.to_i\n add_result = a + b\nreturn add_result\nend", "def my_parse_int(string)\n string.respond_to?(:to_i) ? string.to_i : \"NaN\"\nend", "def convert_numeric_strings\n @interval = @interval.to_i if @interval\n @timeout = @timeout.to_i if @timeout\n @maximum_reconnects = @maximum_reconnects.to_i if @maximum_reconnects\n end", "def string_to_signed_integer_refactored(str)\n /[0-9]/.match(str[0]) ? num = str : num = str[1..-1]\n str[0] == '-' ? -string_to_integer(num) : string_to_integer(num)\nend", "def typecast_to_numeric(value, method)\n if value.is_a?(String)\n value = value.strip.gsub(/,/, '.').gsub(/[^\\d\\-\\.]/, '').gsub(/\\.(?!\\d*\\Z)/, '')\n value.empty? ? nil : value.send(method)\n elsif value.respond_to?(method)\n value.send(method)\n else\n nil\n end\n end", "def convertToNum(price)\n \treturn Float(price.gsub(/\\s+/, \"\").gsub(\"USD \",\"\"))\n end", "def string_to_integer(string)\n base_dict = { 1 => 1, 2 => 10, 3 => 100, 4 => 1000, 5 => 10000, 6 => 100000}\n keys = base_dict.keys\n store = []; count = 0 ; result = []; \n string.each_byte {|dec| store.push(dec - 48)}\n base = keys[0,store.length].reverse\n loop do \n result.push(base_dict[base[count]] * store[count])\n count += 1\n break if count == store.length\n end\n result = result.inject(0) {|x, i| x + i}\n puts result\n end", "def parse_value value\r\n case value\r\n when /\\d+/\r\n value.to_f\r\n else\r\n value\r\n end\r\n end", "def _floatify(str, increment = true)\n if (( inf = str.to_s.match(/^([+-])?inf/i) ))\n (inf[1] == \"-\" ? -1.0 : 1.0) / 0.0\n elsif (( number = str.to_s.match(/^\\((-?\\d+)/i) ))\n number[1].to_i + (increment ? 1 : -1)\n else\n Float str.to_s\n end\n rescue ArgumentError\n raise Redis::CommandError, \"ERR value is not a valid float\"\n end", "def number\n number = number.to_s\n if number.includes?('.')\n number = number.to_f\n else\n number = number.to_i\n end\nend", "def convert number\n raise_on_type_mismatch number\n check = self.of(number)\n if number.is_a?(String) or check.is_a?(String)\n number.to_s << self.of(number).to_s\n else\n convert_to_int(number) * 10 + self.of(number)\n end\n end", "def add_string_as_number(string_1, string_2)\n string_a = string_1.to_i\n string_b = string_2.to_i\n return string_a + string_b\nend", "def convert_variable var\n\n # if it returns nil, it is a string\n if /^[0-9]+$/.match(var).nil?\n\n var\n\n else # otherwise it is a integer, so convert to integer\n\n var.to_i\n\n end\n\n end", "def binary_string_to_number(string)\n string = string.clone.force_encoding(Encoding::ASCII_8BIT)\n string.bytes.inject(0) do |number, byte|\n number * 256 + byte.ord\n end\n end", "def locNumToInt(str)\n\tnum = 0\n\tstr.split('').each {|c|\n\t\tnum += 2**(c.ord - 97)\n\t}\n\tnum\nend", "def default_num_value from_string, to_f = false\n if from_string == nil\n return nil\n end\n\n num = to_f ? from_string.to_f : from_string.to_i\n return num == -1? nil : num\nend", "def default_num_value from_string, to_f = false\n if from_string == nil\n return nil\n end\n\n num = to_f ? from_string.to_f : from_string.to_i\n return num == -1? nil : num\nend", "def toNumbers(strList)\n strList.each do |i|\n \ti.to_i\n end\nend", "def string_to_signed_integer(str)\n case str[0]\n when '-' then -string_to_integer(str.slice(1, str.length))\n when '+' then string_to_integer(str.slice(1, str.length))\n else string_to_integer(str)\n end\nend" ]
[ "0.9173285", "0.80351496", "0.79944414", "0.79724705", "0.7946466", "0.7946466", "0.79224306", "0.7891063", "0.7818706", "0.7808193", "0.76191306", "0.7596244", "0.755788", "0.7302884", "0.72686845", "0.71819144", "0.7033213", "0.70211655", "0.7014203", "0.7008867", "0.700345", "0.6953031", "0.692411", "0.68927485", "0.68882656", "0.6885713", "0.6839034", "0.6803289", "0.6777329", "0.67768747", "0.67584634", "0.6752835", "0.67502785", "0.67443126", "0.67239755", "0.6719179", "0.6712833", "0.6703722", "0.6703722", "0.6684457", "0.6654461", "0.6648911", "0.6642406", "0.6634842", "0.66147447", "0.660591", "0.66031116", "0.65878046", "0.65781164", "0.6571695", "0.6571127", "0.65658617", "0.6556835", "0.6542713", "0.65401816", "0.65308166", "0.65305394", "0.65305394", "0.65305394", "0.65305394", "0.6526023", "0.6523903", "0.6515403", "0.65054566", "0.6483867", "0.6481349", "0.6472466", "0.64666265", "0.64652896", "0.6454886", "0.64498883", "0.64497864", "0.6442768", "0.64373994", "0.6437226", "0.64338183", "0.6401178", "0.63997227", "0.63974804", "0.6395442", "0.63709426", "0.6368219", "0.6364565", "0.635824", "0.633377", "0.63237196", "0.63026357", "0.6282374", "0.62758374", "0.6264422", "0.6234519", "0.62094", "0.62091887", "0.6206097", "0.61837786", "0.6180947", "0.61768454", "0.61768454", "0.6162047", "0.6152929" ]
0.7849734
8
O(n + m) O(1)
def exists_in_matrix(matrix, k) return false if matrix.length == 0 || matrix[0].length == 0 r, c = 0, matrix[0].length - 1 while(r >= 0 && c >= 0 && r < matrix.length && c < matrix[0].length) if matrix[r][c] == k return true elsif matrix[r][c] > k c -= 1 else r += 1 end end false end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def solution(m, a)\n n = a.count\n result = 0\n front = 0\n numbers = Array.new(m + 1, false)\n n.times { |back|\n while front < n and not numbers[a[front] - 1]\n numbers[a[front] - 1] = true\n front += 1\n result += front - back\n return 1_000_000_000 if result >= 1_000_000_000\n end\n numbers[a[back] - 1] = false\n }\n result\nend", "def find_difference(a, m)\n a.sort!\n first = 0\n last = 0\n i = 0\n min_diff = 1000000\n while i+m-1 < a.length\n diff = a[i+m-1] - a[i]\n if diff < min_diff\n min_diff = diff\n first = i\n last = i+m-1\n end\n i += 1\n end\n result = a[last]-a[first]\n return result\nend", "def icecreamParlor(m, arr)\n # Complete this function\n res = []\n arr.each_index do |i|\n if i + 1 !=nil\n j = i + 1\n while j <= arr.length - 1\n if arr[i]+arr[j] == m\n res.push([i+1,j+1])\n end\n j+=1\n end\n end\n end\n res\nend", "def solution(k, m, a)\n from = a.max\n to = a.inject(:+)\n min = from\n while from <= to\n mid = (from + to) / 2\n if check(mid, k, m, a)\n min = mid\n to = mid - 1\n else\n from = mid + 1\n end\n end\n min\nend", "def unique_paths(m, n, cache = {})\n return 0 if m < 0 || n < 0\n return 1 if m == 1 || n == 1\n\n result = (cache[[m - 1, n]] || unique_paths(m - 1, n, cache)) + (cache[[m, n - 1]] || unique_paths(m, n -1, cache))\n cache[[m, n]] = result\n result\nend", "def find_dublicate(array)\n sum = 1000000*(1000000+1)/2 # (n*(n+1))/2\n array.each do |el| \n sum -= el\n end\n return sum\nend", "def unique_paths(m, n)\n return 0 if m == 0 && n == 0\n return 1 if m == 0 || n == 0\n\n arr = [0] * n\n matrix = []\n m.times do \n matrix << arr\n end\n\n for i in 0...m do \n for j in 0...n do \n if i == 0 && j == 0\n matrix[i][j] *= 1\n elsif i == 0 && j != 0\n matrix[i][j] = matrix[i][j - 1]\n elsif j == 0\n matrix[i][j] = matrix[i - 1][j]\n else\n matrix[i][j] = matrix[i - 1][j] + matrix[i][j - 1]\n end\n end\n end\n\n matrix[m-1][n-1]\nend", "def process_queries(queries, m)\n arr = []\n perm = *(1..m)\n i = 0\n while i < queries.length\n if perm.include?(queries[i])\n index = perm.find_index(queries[i])\n arr += [index]\n deleted = perm.delete_at(index)\n perm.unshift(deleted)\n end\n i+=1\n end\n\n return arr\nend", "def unrank_indices(m)\n result = Array.new(size, 0)\n for i in 0...size\n f = factorial(i)\n x = m % (f * (i + 1))\n m -= x\n x /= f\n result[size - i - 1] = x\n x -= 1\n for j in (size - i)...size\n result[j] += 1 if result[j] > x\n end\n end\n result\n end", "def solution(a)\r\n n=a.size\r\n i=1\r\n for k in a.sort do\r\n\tif k!=i \r\n\t then \r\n\t return 0\r\n\t break;\r\n\tend\r\n i+=1;\r\n end\t\r\n return 1 if a.inject(:+) ==n*(n+1)/2;\r\nend", "def minor(m,i)\n n = m.length\n mb = m[1..-1]\n mb.map{|row| row.first(i) + row[i+1..n-1]}\nend", "def josephus(n,m)\n arr = Array.new\n order = Array.new\n\n for i in 1..n\n arr[i] = i\n end\n\n arr.compact!\n\n for i in 0..n-1\n arr= arr.rotate(m-1)\n order << arr[0]\n arr[0] = nil\n arr.compact!\n end\n\n puts \"order: #{order.to_s}\"\nend", "def merge(nums1, m, nums2, n)\n last = m + n - 1\n infinity = -2 ** (0.size * 8 - 1)\n m -= 1\n n -= 1\n while last >= 0\n first = m < 0 ? infinity : nums1[m]\n second = n < 0 ? infinity : nums2[n]\n if first > second\n nums1[last] = nums1[m]\n m -= 1\n else\n nums1[last] = nums2[n]\n n -= 1\n end\n \n last -= 1\n end\nend", "def unique_paths_iterative(m, n)\n return 0 if m == 0 || n == 0\n\n grid = Array.new(m) { Array.new(n) {0} }\n grid[0][0] = 1\n\n row = 0\n column = 0\n\n while row < m\n while column < n\n # check top\n if row > 0\n grid[row][column] += grid[row - 1][column]\n end\n # check left\n if column > 0\n grid[row][column] += grid[row][column - 1]\n end\n\n column += 1\n end\n column = 0\n row += 1\n end\n\n grid[row - 1][column - 1]\nend", "def solve(n, m)\n m -= 1\n fac(n+m)/(fac(m)*fac(n)) % 1000000007\nend", "def merge(nums1, m, nums2, n)\n p1 = m - 1\n p2 = n - 1\n last = m + n - 1\n \n while p1 >= 0 && p2 >= 0\n if nums1[p1] >= nums2[p2]\n nums1[last] = nums1[p1]\n p1 -= 1\n else\n nums1[last] = nums2[p2]\n p2 -= 1\n end\n last -= 1\n end\n \n while p2 >= 0\n nums1[last] = nums2[p2]\n last -= 1\n p2 -= 1\n end\nend", "def fast_solution(n, m)\n # eaten = c * n / m. Find c that makes (c * n) % m == 0.\n c = 0\n begin\n c += 1\n c = m / n if m == 1000000000\n end until (c * n) % m == 0\n c * n / m\nend", "def cantor_pairing(n, m)\n (n + m) * (n + m + 1) / 2 + m\nend", "def merge(nums1, m, nums2, n)\n m -= 1\n n -= 1\n # Convert to index positions\n i = nums1.length - 1\n\n until i == -1\n p \"n: #{n}, m: #{m}, #{nums1}\"\n if n >= 0 && nums2[n] >= nums1[m]\n nums1[i] = nums2[n]\n n -= 1\n else\n nums1[i] = nums1[m]\n m -= 1\n end\n i -= 1\n end\n return nums1\nend", "def my_min_2(list)\r\n min = 0 # O(1)\r\n \r\n list.each do |ele| # O(n) \r\n if ele < min # O(1)\r\n min = ele # O(1)\r\n end\r\n end\r\n min # O(1) \r\nend", "def merge_three_pointers(nums1, m, nums2, n)\n nums1_copy = []\n nums1.each { |n| nums1_copy.push(n) }\n \n p, p1, p2 = 0, 0, 0\n for p in (0...(m+n))\n if (nums1_copy[p1] < nums2[p2] && p1 < m) || p2 >= n\n nums1[p] = nums1_copy[p1]\n p1 += 1\n elsif \n nums1[p] = nums2[p2]\n p2 += 1\n end\n end\nend", "def largest_contiguous_subsum(list)\r\n sub_arr = []\r\n list.each_with_index do |ele1,idx1|\r\n list.each_with_index do |ele2,idx2|\r\n sub_arr<< list[idx1..idx2] if idx2>=idx1\r\n end\r\n end\r\n p sub_arr.size\r\n sub_arr.map{ |sub| sub.sum}.max\r\n #(O(n^2 + m)\r\nend", "def distribute(m, n)\n arr=[]\n return arr if n<=0\n \n if m <=0\n \ta = 0\n \tb = 0\n else \n \ta = m/n\n \tb = m%n\n\tend \n\n n.times {|i| arr[i] = a}\n b.times {|i| arr[i] += 1}\n \n return arr\nend", "def count_recursive(n, m)\n if n < 0 or m < 0\n return 0\n end\n if n == 0\n return 1 # We found one solution!\n end\n return count_recursive(n, m-1) + count_recursive(n - S[m], m)\n\nend", "def equal(arr)\n size = arr.size\n hash = Hash.new{|h,k| h[k] = []}\n (0...size).each do |i|\n (i + 1...size - 1).each do |j|\n sum = arr[i] + arr[j]\n if hash.has_key?(sum)\n values = hash[sum]\n values << i\n values << j\n return values\n else\n hash[sum] = [i, j]\n end\n end\n end\nend", "def twoDArray(m,n)\n arr = Hash.new\n for m in 0..m\n for n in 0..n\n if m.gcd(n) == 1\n arr[[m,n]] = true\n else\n arr[[m,n]] = false\n end\n end\n end\n\n for m in 0..m\n for n in 0..n\n if arr[[m,n]] == true\n puts \"#{m} :m and #{n} :n\"\n end\n end\n end\nend", "def find_m_and_n sum\n m = 1\n while m < sum do\n n = 1\n while n < m do\n return [m, n] if (2*(m**2) + 2*m*n) == sum\n n += 1\n end\n m += 1\n end\nend", "def sub_sum(list)\n sub_arr = []\n (0...list.length).each do |i| #O(n)\n (i...list.length).each do |j| #O(n)\n sub_arr << list[i..j] if i <= j\n end\n end\n largest_continuous_sub_sum1(sub_arr)\nend", "def naive(array)\n max = -10000\n for i in (0..array.length - 1)\n for j in (i..array.length - 1)\n total = array[i..j].inject { |m,k| m + k }\n max = total if total > max\n end\n end\n max\nend", "def merge_three_pointers_inplace(nums1, m, nums2, n)\n p1 = m - 1\n p2 = n - 1\n for p in (m+n-1).downto(0)\n if (nums1[p1] > nums2[p2] && p1 >=0 ) || p2 < 0\n nums1[p] = nums1[p1]\n p1 -= 1\n else\n nums1[p] = nums2[p2]\n p2 -= 1\n end\n end \nend", "def my_min(list) \n\n list.each_with_index do |ele, i| #O(n)\n compare_arr = list[0...i] + list[i+1..-1] # O(2n) \n return ele if compare_arr.all? { |ele2| ele < ele2 } #O(n)\n end\n\n #time complexity = O(n^2) + O(2n)\n\nend", "def unique_paths_recursive(m, n, store = {})\n return store[[m, n]] if store[[m, n]]\n\n if m == 1 && n == 1\n store[[m, n]] = 1\n return 1\n end\n\n above = m > 1 ? unique_paths_recursive(m - 1, n, store) : 0\n left = n > 1 ? unique_paths_recursive(m, n - 1, store) : 0\n\n store[[m - 1, n]] = above\n store[[m, n - 1]] = left\n total = above + left\nend", "def recessive k, m, n\n all = k + m + n\n mix = m + n\n total = 4.0 * triangle(all) # 2 * squareish all = 2 * 2 * triangle all\n\n lhs = triangle n\n mid = n * mix - n\n rhs = triangle mix\n\n 1 - (lhs+mid+rhs) / total\n end", "def amicables(limit)\n numbers = Array.new(limit, 0)\n (1...limit).each do |i|\n ((i * 2)...limit).step(i) do |j|\n numbers[j] += i\n end\n end\n result = []\n numbers.each_with_index do |j, i|\n if j < limit && i == numbers[j] && i != j\n result << i\n end\n end\n result\nend", "def three_sum_fastest(arr)\n count = 0\n\n (0..arr.length - 2).each { |i|\n set = Set.new\n\n (i + 1..arr.length - 1).each { |j|\n if set.include?(-arr[i] - arr[j])\n count += 1\n end\n\n set.add(arr[j])\n }\n }\n count\nend", "def my_min_2(array)#O(n)\n array.inject do |acc, ele|#O(n)\n if acc < ele\n acc\n else\n ele\n end\n end\nend", "def largest_contiguous_subsum1(list)\n p Time.now\n sub_arrays = []\n list.each_index do |i|\n list.each_index do |j|\n next if j < i\n sub_arrays << list[i..j]\n end\n end\n sub_arrays.map{|numbers| numbers.inject(:+)}.max\n p Time.now\nend", "def unique_items(arr) #O(n)\n hash = Hash.new(0)\n results = []\n arr.each do |el|\n hash[el] += 1\n end\n hash.select { |k, v| k if v == 1 }.keys\nend", "def msort(arr)\n n = arr.length / 2\n if (n == 0)\n arr\n else\n merge msort(arr[0..n-1]), msort(arr[n..arr.length])\n end\nend", "def merge(m, a, b)\n loop do\n return m + a if b.empty?\n return m + b if a.empty?\n if a[0] < b[0]\n m << a.first\n a.delete_at(0)\n else\n m << b.first\n b.delete_at(0)\n end\n end\nend", "def hamm(u,v)\n h=0\n k=u.length\n for i in (0..k-1) do\n if (u[i]!=v[i])\n then h+=1\n end\n end\n return h\n end", "def merge(a,p,q,m)\n b = Array.new(q-p+1)\n i = p\n j = m+1\n k = 0\n while(i<=m && j<=q) do\n if(a[i]<=a[j])\n b[k] = a[i]\n k = k + 1\n i = i + 1\n else\n b[k] = a[j]\n j = j + 1\n k = k + 1\n end\n end\n\n while(i<=m) do\n b[k] = a[i]\n i = i + 1\n k = k + 1\n end\n\n while(j<=q) do\n b[k] = a[j]\n i = i + 1\n j = j + 1\n end\n\n l = 0\n for i in p..q\n a[i] = b[l]\n l = l+1\n end\nend", "def permutationEquation(p)\n n = p.size\n (1..n).map do |x|\n res = 0\n p.each do |y|\n res = y if p[p[y - 1] - 1] == x\n end\n res\n end\nend", "def amicable_numbers(n)\r\n numbers = Array.new\r\n 2.upto(n) do |x|\r\n y = d(x)\r\n if !numbers.include?(y)\r\n numbers.push(x,y) if d(y) == x && y != x\r\n end\r\n end\r\n return numbers\r\nend", "def c v1, v2, o\n m = false\n d = []\n (0...v2.size).each{ |j|\n if !v1.include? v2[j] + o\n d << v2[j]\n m = true\n end\n }\n for x in d\n v2.delete x\n end\n m\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 find_nb(m)\n n = 0\n while m.positive?\n n += 1\n m -= n**3\n end\n m.zero? ? n : -1\nend", "def flatlandSpaceStations(n,c,m)\r\n answer = 0\r\n cc = c.sort()\r\n\r\n for i in (0..cc.size-2) do\r\n answer = [answer,(cc[i+1]-cc[i])/2].max\r\n end\r\n answer = [answer, cc[0], n-1 - cc[-1]].max\r\nend", "def f(n,m)\n array = [*1..n]\n array.inject(0) do |result, int|\n result += int % m\n end\nend", "def largest_contiguous_subsum_1(list) \n subs = [] #O(1)\n (0...list.length).each do |start_num| #O(n)\n (start_num...list.length).each do |end_num| #O(n)\n subs << list[start_num..end_num] #O(n)\n end\n end\n subs_sum = [] #O(1)\n subs.each do |sub| #O(n**2)\n sub_sum = 0 #O(1)\n sub.each {|s| sub_sum += s} #O(n)\n subs_sum << sub_sum #O(1)\n end\n subs_sum.inject do |acc,el| #O(n)\n if acc > el #O(1)\n acc #O(1)\n else\n el #O(1)\n end\n end\n end", "def findNb(m)\n # n^3 + (n-1)^3 + (n-2)^3 + ... 1^3 = m\n # m - 1 - 8 - 27 - 64 - ... etc = 0\n base = 1\n loop do\n m -= (base ** 3)\n break if m <= 0\n base += 1\n end\n m < 0 ? -1 : base\nend", "def unique_path(m, n, cache = {})\n return 1 if m == 1 || n == 1\n if cache[[m, n]]\n return cache[[m,n]]\n end\n cache[[m,n]] = unique_path(m-1, n) + unique_path(m, n-1)\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 restrict(convolution, m)\n alphabet = []\n freq = convolution.each_with_object({}) { |itm, hsh| hsh[itm] = hsh[itm].to_i + 1 if convolution.include?(itm) }\n eligible = freq.select {|k, v| 57 <= k && k <= 200}\n sorted = eligible.sort_by {|k,v| v}.reverse\n sorted.each do |am, f|\n if alphabet.size < m\n alphabet << am \n # let's ensure we include any ties\n elsif alphabet.size == m\n alphabet << am if alphabet[m-1] == am\n end\n break if alphabet[m-1] > am unless alphabet[m-1].nil?\n end\n alphabet\nend", "def mof(i, p)\n arr = []\n x_swap = []\n (0..(p-2)).each do |x|\n arr.push((i**x) % p)\n end\n (1..(p-1)).each do |n|\n x_swap.push((arr.index {|item| n == item }) % 12 )\n end\n return x_swap\nend", "def okay_two_sum?(arr, target)\n arr = arr.sort #n log n\n (0...arr.length).each do |i| #n\n search = bsearch(arr, target-arr[i]) # log n\n return true unless search.nil?\n end #n log n\n false\nend", "def intersect nums1, nums2\n result = []\n return result if nums1.size == 0 or nums2.size == 0\n\n counter_cache = {}\n counter_cache = nums1.inject({}) { |result, n|\n result[n] ||= 0\n result[n] += 1\n result\n }\n\n nums2.each do |n|\n if counter_cache[n] and counter_cache[n] > 0\n result << n\n counter_cache[n] -= 1\n end\n end\n result\nend", "def min_cost(cost, m, n)\n if n < 0 || m < 0\n return 100000\n elsif m == 0 && n == 0\n return cost[m][n]\n else\n return cost[m][n] + find_min( min_cost(cost, m-1, n-1),\n min_cost(cost, m-1, n),\n min_cost(cost, m, n-1))\n end\nend", "def three_sum_fast(arr)\n arr = merge_sort(arr)\n count = 0\n\n (0..arr.length - 1).each { |i|\n (i + 1..arr.length - 1).each { |j|\n if bin_search(arr, -arr[i] - arr[j]) > j\n count += 1\n end\n }\n }\n count\nend", "def mc_ph cm\n ac = [0,0,0]\n cm.each do |cv|\n ac = cv.each_with_index.map do |c, i|\n c + ac.each_with_index.select{ |_, j| j != i }.map{ |c, _| c }.min\n end\n end\n return ac.min\nend", "def map_then_iterate_two_sum(array, target)\n hash = {}\n array.each.with_index do |i, index|\n hash[i] = index\n end\n indexes = []\n array.each.with_index do |ii, index|\n complement = target - ii \n if hash.has_key?(complement) && hash.fetch(complement) != index\n indexes.push(index, hash.fetch(complement))\n return indexes\n end\n end\nend", "def solution(a)\n n = a.size\n a.sort!\n\n count = 0\n for i in 0...n-2 do\n k = i+2\n for j in i+1...n-1 do\n while k < n and a[i] + a[j] > a[k] do\n k += 1\n end\n count += k - j - 1\n end\n end\n count\nend", "def solution(a)\n len = a.size\n unique = {}\n i = 0\n while i < len\n item = a[i]\n if unique.has_key?(item)\n unique[item] += 1\n else\n unique[item] = 1\n end\n i += 1\n end\n pairs = 0\n unique.each do |key,count|\n (1...count).step {|n| pairs += n }\n end\n return pairs > 1_000_000_000 ? 1_000_000_000 : pairs\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 find_nb(m)\nindex=sum=0\n while sum < m\n sum+=index**3\n return index if sum == m\n index+=1\n end\n-1\nend", "def largest_contiguous_subsum(list)\n new_arr = []\n\n (0...list.length).each do |idx1| #O(n)\n (0...list.length).each do |idx2| #O(n)\n if idx2 >= idx1 #O(1)\n new_arr << list[idx1..idx2].sum #O(1)\n end \n end \n \n end \n \n return new_arr.max #O(n)\nend", "def arrayManipulation(n, queries)\n nums = Array.new(n+1, 0)\n queries.each do |query|\n nums[query[0]-1] += query[2]\n nums[query[1]] -= query[2]\n end\n\n max = nums.first\n (1..nums.length-1).each do |i|\n nums[i] += nums[i - 1]\n max = nums[i] if nums[i] > max && i < (nums.size - 1)\n end\n\n max\nend", "def find_amicables(n)\n pairs = []\n sum = 0\n for i in 0..n do \n next if pairs.include? i\n d = sum_proper_divisors(i)\n next if d == i\n p = sum_proper_divisors(d)\n if p == i \n pairs << d\n pairs << i\n sum += d + i\n end\n end\n return sum\nend", "def sum(n, m)\n if n > m\n return 0\n else\n return sum(n+1, m) + n\n end\nend", "def arrayManipulation(n, queries)\n arr = Array.new(n + 2, 0)\n\n queries.each do |a, b, k|\n arr[a] += k\n arr[b + 1] -= k\n end\n\n max_sum = 0\n sum = 0\n arr.filter { |diff| diff != 0 }.each do |diff|\n sum += diff\n max_sum = [max_sum, sum].max\n end\n\n max_sum\nend", "def two_sum?(array, target)\n #O(n)\n hash = Hash.new(0)\n i = 1\n array.each do |ele|\n hash[ele] = i \n i += 1\n end\n hash.each_key do |k|\n return true if hash.has_key?(target - k) && hash[k] != hash[target - k]\n end\n false \nend", "def solution(a)\n n = a.size\n passing_cars = 0\n\n suffix_sums = Array.new(n + 1, 0)\n\n a.reverse.each_with_index do |elem, i|\n suffix_sums[i + 1] = suffix_sums[i] + elem\n end\n suffix_sums.reverse!\n\n a.each_with_index do |car, i|\n if car == 0\n passing_cars += suffix_sums[i]\n end\n end\n\n passing_cars > 1_000_000_000 ? -1 : passing_cars\nend", "def transpositions( m )\n count = 0\n (0...(m.size - 1)).each do |idx|\n item = m[idx]\n after = m[idx + 1]\n count += 1 if item > after\n end\n return count\n end", "def bucketSort(a, n, buckets, m)\n for j in 0 ... m\n buckets[j] = 0\n end\n for i in 0 ... n\n buckets[a[i]] += 1\n end\n i = 0\n for j in 0 ... m\n for k in 0 ... buckets[j]\n a[i] = j\n i += 1\n\tend\n end\nend", "def start_to_end(m, n)\n combinatorics(m+n, [m,n].max)\n end", "def crt(r, m)\n raise ArgumentError if r.size != m.size\n \n n = r.size\n r0, m0 = 0, 1\n n.times{ |i|\n raise ArgumentError if m[i] < 1\n\n r1, m1 = r[i]%m[i], m[i]\n if m0 < m1 then\n r0, r1 = r1, r0\n m0, m1 = m1, m0\n end\n\n if m0%m1 == 0 then\n return [0, 0] if r0%m1 != r1\n next\n end\n\n g, im = inv_gcd(m0, m1)\n u1 = m1/g\n return [0, 0] if (r1-r0)%g != 0\n\n x = (r1-r0)/g*im%u1\n r0 += x*m0\n m0 *= u1\n r0 += m0 if r0 < 0\n }\n\n return [r0, m0]\nend", "def my_min1(arr)\n arr.each do |el1| #O(n)\n if arr.all? {|el2| el1 <= el2 } #O(n + 1)\n return el1\n end\n end \nend", "def visit_all_rooms?(array) \n visited = {}\n queue = [] \n\n first = array.shift \n\n \n first.each do |key|\n queue << key //3, 0\n end\n\n\n # O(n) * o(m) => O(nm)\n while queue.length > 0 //O(n)\n current_key = queue.shift\n visited[current_key] = true\n array[current_key].each do |key| \n queue << key unless visited[key] == false // 3,0,1 \n end\n end\n\n visited.keys.length == array.length\n\nend", "def arrayManipulation(n, queries)\r\n arr = Array.new(n, 0)\r\n\r\n queries.each do |query|\r\n left = query[0] - 1\r\n right = query[1] - 1\r\n summand = query[2]\r\n\r\n arr[(left..right)] = arr[(left..right)].map { |a| a + summand }\r\n end\r\n\r\n arr.max\r\nend", "def cache_intersection(nums1, nums2)\n array = []\n outer_cache = {}\n inner_cache = {}\n nums1.each do |outer|\n next if outer_cache[outer]\n outer_cache[outer] = true\n nums2.each do |inner| \n next if inner_cache[inner]\n if outer == inner \n array << inner\n inner_cache[inner] = true\n end\n end\n end\n array\nend", "def two_sum(arr) #o(ns)\n set = Set.new\n arr.each{|el| set << el}\n arr.select{|el| set.include?(-1 * el)}\nend", "def solution(a)\n # In production environment this will be my solution:\n # a.uniq.size\n #\n # But since this is a coding challenge, my assumption\n # is that you're looking for a by-hand O(N*logN) solution\n\n return 0 if a.empty?\n\n n = a.size\n ary = a.sort\n uniques = 1\n (1...n).each do |i|\n uniques += 1 if ary[i] != ary[i - 1]\n end\n uniques\nend", "def solution_slow_2(n, p, q)\n sieve = sieve_of_erathosteneses(n)\n # puts \"sieve:#{sieve}\"\n semi = semiprimes(n, sieve)\n # puts \"sp:#{semi}\"\n prefix = [0,0,0,0,1]\n 5.upto(n) do |x|\n if semi.include? x \n prefix << prefix.last + 1\n else\n prefix << prefix.last\n end\n end\n # puts \"prefix:#{prefix}\"\n\n queries = [p,q].transpose\n\n\n res = queries.map do |query|\n prefix[query.last] - prefix[query.first - 1]\n end\n\n # puts \"res:#{res}\"\n\n res\n end", "def sift_down_full(m, n)\n\t\t\t\tunless n >= 3\n\t\t\t\t\traise RuntimeError.new(\"expected n >= 3 but was #{n}\")\n\t\t\t\tend\n\t\t\t\ti = 0\n\t\t\t\tj = 1\n\t\t\t\tk = 2\n\t\t\t\tej = m[j]\n\t\t\t\twhile true\n\t\t\t\t\tek = m[k]\n\t\t\t\t\tif ej < ek\n\t\t\t\t\t\t__set(m, i, ej)\n\t\t\t\t\t\ti = j\n\t\t\t\t\telse\n\t\t\t\t\t\t__set(m, i, ek)\n\t\t\t\t\t\ti = k\n\t\t\t\t\tend\n\t\t\t\t\tj = i * 2 + 1\n\t\t\t\t\tk = i * 2 + 2\n\t\t\t\t\tif k > n\n\t\t\t\t\t\tbreak\n\t\t\t\t\tend\n\t\t\t\t\tej = m[j]\n\t\t\t\t\tif k == n\n\t\t\t\t\t\t__set(m, i, ej)\n\t\t\t\t\t\ti = j\n\t\t\t\t\t\tbreak\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\treturn i\n\t\t\tend", "def cache_intersection2(nums1, nums2)\n outer_cache = {}\n nums1.each do |n|\n next if outer_cache[n]\n outer_cache[n] = true\n end\n array = []\n inner_cache = {}\n nums2.each do |n|\n next if inner_cache[n]\n array << n if outer_cache[n]\n inner_cache[n] = true\n end\n array\nend", "def solution(a)\n # write your code in Ruby 2.2\n \n is_perm = 0\n \n n = a.length\n b = [0]*n\n \n \n a.each do |v|\n break if v > n \n break if b[v] == 1 \n b[v] = 1\n end\n \n sum = b.inject(:+)\n if sum == n\n is_perm = 1\n end\n \n is_perm\nend", "def twosum(array, target)\n return [] if array.length<=1\n cache = {}\n array.each.with_index do |e,i|\n if cache.include? (target-e)\n return [i,cache[target-e]]\n else\n cache[e] = i\n end\n end\n return []\nend", "def solve( n = 10_000 )\n (1..n).select {|i| i.amicable?}.reduce( :+ )\n end", "def three_sum(nums)\n n = nums.length\n result = []\n for i in 0...n-2\n req_sum = 0\n hsh = Hash.new\n curr_sum = req_sum - nums[i]\n \n for j in (i+1)...n\n num = curr_sum - nums[j]\n if hsh[num]\n elements = [nums[i], num, nums[j]].sort\n result << elements unless result.include?(elements)\n end\n hsh[nums[j]] = true\n end \n end\n result\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 largest_contiguous_subsum(list)\n # debugger\n results = [] # O(1)\n\n list.each_with_index do |el1, idx1| # O(n)\n list.each_with_index do |el2, idx2| # O(n) => O(n^2)\n next if idx2 < idx1 # O(1)\n results << list[idx1..idx2] # O(1)\n end\n end\n\n results.map! { |subsum| subsum.reduce(:+) } # O(n^2)\n results.max # O(1)\nend", "def fast_lcss(arr)\n i_arr = []\n biggest = 0\n max_sub_arr = []\n arr.length.times do |x|\n arr.map do |ele1|\n i_arr += [ele1]\n sum = i_arr.inject(0) do |a, b|\n a + b\n end\n max_sub_arr = i_arr if sum > biggest\n biggest = sum if sum > biggest \n end\n i_arr = []\n arr.shift\n end\n max_sub_arr\nend", "def parlor(m,arr)\n\tmenu = []\n\tarr.each do |num|\n\t\tmenu << num\n\tend\n\tfind_comp = ->(cost, arr){ #binary serach that returns the index of the complement\n\t\tsearch_for = m - cost\n\t\tstartdex = 0\n\t\tenddex = arr.length-1\n\t\twhile startdex <= enddex\n\t\t\tmiddex = ((startdex + enddex) / 2).floor\n\t\t\tif arr[middex] == search_for\n\t\t\t\treturn middex\n\t\t\telsif arr[middex] > search_for\n\t\t\t\tenddex = middex - 1\n\t\t\telse\n\t\t\t\tstartdex = middex + 1\n\t\t\tend\n\t\tend\n\t\tfalse\n\t}\n\n\tindex_of = ->(value, skip_index){\n\t\tfor i in 0..arr.length-1\n\t\t\tif arr[i] == value && i != skip_index\n\t\t\t\treturn i\n\t\t\tend\n\t\tend\n\t}\n\tget_original = ->(value1, value2){\n\t\tindex1 = index_of.call(value1, -1)\n\t\tindex2 = index_of.call(value2, index1)\n\t\t[[index1,index2].min + 1, [index1,index2].max + 1]\n\t}\n\tsorted = menu.sort!\n\tmenu_places = []\n\tfor i in 0..sorted.length-1\n\t\t# p find_comp.call(sorted[i], sorted)\n\t\tif find_comp.call(sorted[i], sorted)\n\t\t\tindex_of_match = find_comp.call(sorted[i], sorted)\n\t\t\tmenu_places = get_original.call(sorted[i], sorted[index_of_match])\n\t\t\tbreak #if complement is found - you don't need to check anymore\n\t\tend\n\tend\n\tmenu_places.join(\" \")\nend", "def bad_contig_subsum(arr)\n # n! || n^3 ?\n sub_arrays = []\n arr.each_index do |i|\n (i...arr.length).each do |j|\n sub_arrays << arr[i..j]\n end\n end\n\n # above * n^2 ? << bottleneck\n max = sub_arrays.first.inject(&:+)\n sub_arrays.each do |sub_arr|\n sub_sum = sub_arr.inject(&:+)\n max = sub_sum if sub_sum > max\n end\n max\nend", "def sim(m, w, h)\n\to = m.map{|x|x.clone}\n\t(1..w-2).each do |x|\n\t\t(1..h-2).each do |y|\n\t\t\tnext if m[y][x] == ?.\n\t\t\toccupied=[-1,0,1].product([-1,0,1]).count{|dx,dy|\n\t\t\t\tif dx != 0 || dy != 0 then\n\t\t\t\t\tpx=x+dx\n\t\t\t\t\tpy=y+dy\n\t\t\t\t\tpx,py=px+dx,py+dy until 'L#'[m[py][px]]\n\t\t\t\t\tm[py][px] == ?#\n\t\t\t\telse\n\t\t\t\t\tfalse\n\t\t\t\tend\n\t\t\t}\n\t\t\to[y][x] = ?# if m[y][x] == ?L && occupied == 0\n\t\t\to[y][x] = ?L if m[y][x] == ?# && occupied >= 5\n\t\tend\n\tend\n\treturn o\nend", "def fds(n)\n\n # arr = []\n # (n + 1).times.each{|e| arr << e if e > 0}\n # arr.flat_map.reduce(:*)\n # arr.flat_map.reduce(:*).to_s.split(//).map(&:to_i).reduce(:+)\n (1..n).to_a.flat_map.reduce(:*).to_s.split(//).map(&:to_i).reduce(:+)\n\nend", "def naive(set)\n solutions = []\n indexes = (0..set.size-1).to_a\n\n Backtracker.generate do\n candidates { |a| indexes - a }\n solution? { |a| a.size == set.size }\n found_solution do |a| \n solution = a.map { |i| set[i] } \n solutions << solution unless solutions.include? solution\n end\n end\n\n return solutions\nend", "def test(arr)\n arr.map do |el|\n arr.inject(1) do |memo, el2|\n next memo if arr.index(el2) == arr.index(el)\n memo * el2\n end\n end\nend", "def arrayManipulation(n, queries)\n diffArr =[]\n for i in 0..n\n diffArr.push(0)\n end\n for j in queries\n diffArr[j[0]-1] += j[2]\n diffArr[j[1]] -= j[2]\n end\n max = 0\n sum = 0\n for k in diffArr\n sum += k\n max = [sum, max].max\n end\n return max\n\nend", "def solve(n, s, d, m)\n # Complete this function\n records = s;\n\n (1...n).each do |i|\n records[i] += records[i-1]\n end\n\n numberOfWays = (m <= n && records[m - 1] == d) ? 1 : 0;\n\n (m...n).each do |i|\n if records[i] - records[i - m] == d\n numberOfWays += 1\n end\n end\n\n numberOfWays\n\nend", "def optimize(ary, total)\n return [] if ary.empty?\n table = []\n (ary.size+1).times { |i| table[i] = [] }\n (0..total).each { |zerg| table[0][zerg] = 0 }\n (1..ary.size).each do |base|\n table[base][0] = 0\n (1..total).each do |zerg|\n if ary[base-1].zerg <= zerg && (ary[base-1].minerals + table[base-1][zerg - ary[base-1].zerg] > table[base-1][zerg])\n table[base][zerg] = ary[base-1].minerals + table[base-1][zerg - ary[base-1][1]]\n else\n table[base][zerg] = table[base-1][zerg]\n end\n end\n end\n result = []\n i, k = ary.size, total\n while i > 0 && k > 0\n if table[i][k] != table[i-1][k]\n result << ary[i-1]\n k -= ary[i-1].zerg\n end\n i -= 1\n end\n result\nend" ]
[ "0.6496528", "0.63134277", "0.60639024", "0.60598534", "0.60155207", "0.5987571", "0.5979741", "0.5973184", "0.5908554", "0.5899429", "0.58580816", "0.5830351", "0.58284014", "0.58173484", "0.5794095", "0.577454", "0.5767894", "0.5758229", "0.57176214", "0.569795", "0.5692872", "0.5651017", "0.56115633", "0.5611028", "0.5603927", "0.56007874", "0.5591352", "0.5582817", "0.55683166", "0.55534196", "0.5550796", "0.554931", "0.5546173", "0.5538631", "0.553695", "0.5535775", "0.5535737", "0.551805", "0.55166566", "0.55051863", "0.5489696", "0.548702", "0.5485936", "0.54570657", "0.54481655", "0.54451346", "0.5441824", "0.5424455", "0.5423608", "0.5418759", "0.54029316", "0.540192", "0.53914666", "0.53754467", "0.5374798", "0.5374724", "0.53643495", "0.5345896", "0.5342275", "0.53330094", "0.5331473", "0.53228384", "0.5316508", "0.5312525", "0.5311121", "0.5308252", "0.5307487", "0.5302954", "0.530233", "0.52983695", "0.52897245", "0.52882713", "0.5288064", "0.52870005", "0.52846485", "0.52785194", "0.5275442", "0.5272081", "0.5266114", "0.52593845", "0.52557445", "0.52538085", "0.5253565", "0.5247259", "0.5245952", "0.52345073", "0.52306134", "0.52286637", "0.522582", "0.522152", "0.5220411", "0.5217206", "0.52150035", "0.5211896", "0.52076024", "0.5207602", "0.5203729", "0.5192775", "0.51899", "0.5183834", "0.5182859" ]
0.0
-1
gather performance data for a single PID
def record(pid, data = nil) pid_stats_map[pid] = Stat.new(pid, data) unless pid_stats_map[pid] pid_stats_map[pid].record end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def print_perf_info\n @perf_end_timestamp = Time.now\n @hosts.map { |h| get_perf_data(h, @perf_timestamp, @perf_end_timestamp) }\n end", "def get_perf_data(host, perf_start, perf_end)\n @logger.perf_output(\"Getting perf data for host: \" + host)\n if PERF_SUPPORTED_PLATFORMS.match?(host['platform']) # All flavours of Linux\n host.exec(Command.new(\"sar -A -s #{perf_start.strftime('%H:%M:%S')} -e #{perf_end.strftime('%H:%M:%S')}\"), :acceptable_exit_codes => [0, 1, 2]) if not @options[:collect_perf_data]&.include?('aggressive')\n if (defined? @options[:graphite_server] and not @options[:graphite_server].nil?) and\n (defined? @options[:graphite_perf_data] and not @options[:graphite_perf_data].nil?)\n export_perf_data_to_graphite(host)\n end\n else\n @logger.perf_output(\"Perf (sysstat) not supported on host: \" + host)\n end\n end", "def get_data\n cpuinfos = cat_proc\n percents = cpuinfos.zip(@prev_cpuinfos).map do |cpui, prev_cpui|\n cpui.percent(prev_cpui)\n end\n @prev_cpuinfos = cpuinfos\n percents\n end", "def collect\n parse_process_list(multiline('top -l 1 -o mem -stats pid,mem,command'), split_tokens: 3) do |tokens| \n [tokens.first, tokens.last, hostname, plain_memory_value(tokens[1])]\n end\n end", "def get_process_stat\n self.get_all_pid.each do |pid|\n uid = self.get_uid_of_pid(pid)\n username = Etc::getpwuid(uid).name\n\n statline = IO.read(\"/proc/#{pid}/stat\")\n stat = statline.split(' ')\n #time = stat[13].to_i+stat[14].to_i+stat[15].to_i+stat[16].to_i\n time = stat[13].to_i+stat[14].to_i\n if ([email protected]_key?(username))\n @currprocstat[username] = 0\n end\n @currprocstat[username] = @currprocstat[username] + time \n\n iowait = stat[41].to_i\n if ([email protected]_key?(username))\n @currprociowait[username] = 0\n end\n @currprociowait[username] += iowait\n end\n end", "def performance\n authenticated_post(\"auth/r/stats/perf:1D/hist\")\n end", "def workload\n [@nodeid,@data.count]\n end", "def report(process_pids)\n ret = {}\n return ret if pid_stats_map.size == 0\n age_sec = 0\n cpu_pct = 0\n resident_set_bytes = 0\n threads = 0\n virtual_mem_bytes = 0\n pid_stats_map.each do |pid, stat|\n unless process_pids.include? pid\n pid_stats_map.delete(pid)\n next\n end\n age_sec += stat.perf_detail[:age_seconds]\n threads += stat.perf_detail[:threads]\n resident_set_bytes += stat.perf_detail[:mem][:resident_set_bytes]\n virtual_mem_bytes += stat.perf_detail[:mem][:virtual_mem_bytes]\n cpu_pct += process_cpu_pct stat.perf_detail[:cpu]\n end\n ret[:age_seconds] = age_sec\n ret[:threads] = threads\n ret[:mem] = {}\n ret[:mem][:resident_set_bytes] = resident_set_bytes\n ret[:mem][:virtual_mem_bytes] = virtual_mem_bytes\n ret[:cpu_pct] = cpu_pct\n ret\n end", "def export_perf_data_to_graphite(host)\n @logger.perf_output(\"Sending data to Graphite server: \" + @options[:graphite_server])\n\n data = JSON.parse(host.exec(Command.new(\"sadf -j -- -A\"), :silent => true).stdout)\n hostname = host['vmhostname'].split('.')[0]\n\n data['sysstat']['hosts'].each do |host|\n host['statistics'].each do |poll|\n timestamp = DateTime.parse(poll['timestamp']['date'] + ' ' + poll['timestamp']['time']).to_time.to_i\n\n poll.keys.each do |stat|\n case stat\n when 'cpu-load-all'\n poll[stat].each do |s|\n s.keys.each do |k|\n next if k == 'cpu'\n\n socket = TCPSocket.new(@options[:graphite_server], 2003)\n socket.puts \"#{@options[:graphite_perf_data]}.#{hostname}.cpu.#{s['cpu']}.#{k} #{s[k]} #{timestamp}\"\n socket.close\n end\n end\n\n when 'memory'\n poll[stat].keys.each do |s|\n socket = TCPSocket.new(@options[:graphite_server], 2003)\n socket.puts \"#{@options[:graphite_perf_data]}.#{hostname}.memory.#{s} #{poll[stat][s]} #{timestamp}\"\n socket.close\n end\n end\n end\n end\n end\n end", "def pds_meters\n @data_list = PdsMeter.where(Project: project.ProjectID)\n .includes({ hw_ic: [:hw_ped, pds_project_unit: :unit] }, :system, :pds_section_assembler)\n end", "def usage_query(pid:)\n @usage_query ||= FedoraAccessEvent.all_usage_including_child_objects_for(pid: pid)\n end", "def get_cpu_info(workstation_id); end", "def collect_query_data\n status = PdhFFI.PdhCollectQueryData(@handle)\n Pdh.check_status status\n end", "def parse_proc_stat\n file = '/proc/stat'\n puts \"Parsing #{file}\" if (@config[:verbose]) \n data = File.read(file)\n\n parsed = parse_proc_type_1(data)\n parsed[\"intr_total\"] = parsed[\"intr\"].slice(0,1)\n\n parsed.keys.grep(/^cpu/).sort.each do |cpu_id|\n [\"user_ticks\", \"user_nice_ticks\", \"system_ticks\", \"idle_ticks\", \"iowait_ticks\", \"irq_ticks\", \"softirq_ticks\"].zip(parsed[cpu_id]).each do |label,value|\n full_label = \"#{prefix}.stats.#{cpu_id}.#{label}\"\n prop_name = \"stats.#{label}\"\n emit_stats(prop_name, full_label, value)\n end\n end\n [\"btime\", \"ctxt\", \"intr_total\", \"softirq\", \"procs_blocked\", \"procs_running\", \"processes\"].each do |stat|\n full_label = \"#{prefix}.stats.#{stat}\" \n prop_name = \"stats.#{stat}\"\n value = parsed[stat].first\n \n emit_stats(prop_name, full_label, value)\n end\n end", "def plist(psname)\n counter = 0\n %x{ps h -o rss,size,vsize,pcpu -C #{psname}}.each do |ps|\n rss,size,vsize,cpu = ps.split\n counter += 1\n puts \"#{psname}_#{counter}.value #{rss}\"\n\n end\n return\nend", "def collect_metrics\n\n # Build a set of matchers to match the paths we need to find metrics\n # for.\n path_matchers = []\n @paths.each do |path|\n path_matchers << { :path => matcher_for_path(path) }\n end\n\n # Figure out what metric model to use (Metric or one of the average\n # models).\n metric_model = metric_model_for_timespan\n\n # Build a query to locate the metrics.\n query = metric_model.where(:$or => path_matchers)\n query = query.where(:node_id => @node_id)\n query = query.where(:timestamp.gte => @from)\n query = query.where(:timestamp.lte => @to)\n query = query.sort(:timestamp.asc)\n metrics = query.all\n\n # Return a data set based on the collection of metrics.\n data_set_for_metrics(metrics)\n\n end", "def get_full_ps_info(pid)\n ps_fullcmd = @ps_fullcmd_fmt % pid\n # p ps_fullcmd\n output = `#{ps_fullcmd}`\n return output\n end", "def param_from_pid( param )\n tuples = {}\n `ps -eo pid,#{param}`.split(\"\\n\").each_with_index() do |row, index|\n next unless index > 0\n cols = row.split(' ')\n tuples[cols[0]] = cols[1]\n end\n tuples\nend", "def find_perf( path )\n perfs[path]\n end", "def collect\n @this_mem[:rss_size] = ::GetProcessMem.new(Process.pid).kb\n @this_mem\n rescue => e\n ::Instana.logger.info \"#{__method__}:#{File.basename(__FILE__)}:#{__LINE__}: #{e.message}\"\n ::Instana.logger.debug e.backtrace.join(\"\\r\\n\")\n end", "def load_per_cpu(_)\n cpu_per_source = {}\n @client.query(\n '(count(node_cpu{mode=\"system\"})by(instance))'\n ).each do |result|\n source = result['metric']['instance']\n cpu_per_source[source] = result['value'][1]\n end\n\n metrics = []\n @client.query('node_load5').each do |result|\n source = result['metric']['instance']\n value = result['value'][1].to_f.round(2)\n load_on_cpu = value / cpu_per_source[source].to_f\n log.debug(\n \"[load_per_cpu] value: '#{load_on_cpu}', source: '#{source}'\"\n )\n metrics << {\n 'source' => source,\n 'value' => load_on_cpu\n }\n end\n metrics\n end", "def get_datastreams( pid )\n repository.find(pid).datastreams.keys\n end", "def summarize()\n fields.each do |name, metric|\n params = {}\n params[:service] = \"process;#{pid};#{name}\"\n params[:description] = name\n params[:pname] = comm\n if name == \"State\"\n params[:state] = riemann_statemap(metric)\n params[:value] = metric\n # elsif name.end_with?(\"time\")\n # params[:metric] = time_of(name)\n elsif metric.is_a?(Numeric)\n params[:metric] = metric\n else\n params[:value] = metric\n end\n yield(params)\n end\n end", "def perfdata\n if self.perfdata_json.nil?\n @perfdata = nil\n return\n end\n @perfdata ||= Flapjack.load_json(self.perfdata_json)\n end", "def get_mem_usage( pid )\n\tp = @client.sys.process.open( pid.to_i, PROCESS_QUERY_INFORMATION | PROCESS_VM_READ )\n\tif( p )\n\t\tbegin\n\n\t\t\tif( not @client.railgun.get_dll( 'psapi' ) )\n\t\t\t\[email protected]_dll( 'psapi' )\n\t\t\tend\n\n\t\t\t# http://msdn.microsoft.com/en-us/library/ms683219%28v=VS.85%29.aspx\n\t\t\tif( not @client.railgun.psapi.functions['GetProcessMemoryInfo'] )\n\t\t\t\[email protected]_function( 'GetProcessMemoryInfo', 'BOOL', [\n\t\t\t\t\t[ \"HANDLE\", \"hProcess\", \"in\" ],\n\t\t\t\t\t[ \"PBLOB\", \"ProcessMemoryCounters\", \"out\" ],\n\t\t\t\t\t[ \"DWORD\", \"Size\", \"in\" ]\n\t\t\t\t\t]\n\t\t\t\t)\n\t\t\tend\n\n\t\t\tr = @client.railgun.psapi.GetProcessMemoryInfo( p.handle, 72, 72 )\n\t\t\tif( r['return'] )\n\t\t\t\tpmc = r['ProcessMemoryCounters']\n\t\t\t\t# unpack the PROCESS_MEMORY_COUNTERS structure (http://msdn.microsoft.com/en-us/library/ms684877%28v=VS.85%29.aspx)\n\t\t\t\t# Note: As we get the raw structure back from railgun we need to account\n\t\t\t\t# for SIZE_T variables being 32bit on x86 and 64bit on x64\n\t\t\t\tmem = nil\n\t\t\t\tif( @client.platform =~ /win32/ )\n\t\t\t\t\tmem = pmc[12..15].unpack('V').first\n\t\t\t\telsif( @client.platform =~ /win64/ )\n\t\t\t\t\tmem = pmc[16..23].unpack('Q').first\n\t\t\t\tend\n\t\t\t\treturn (mem/1024)\n\t\t\tend\n\t\trescue\n\t\t\tp \"Exception - #{$!}\"\n\t\tend\n\n\t\tp.close\n\tend\n\n\treturn nil\nend", "def processes(agent_id, options = {})\n offset_request('get', \"/syscollector/#{agent_id}/processes\", options)\n end", "def profiler_report(label='', extra_pids={})\n report_perf_profiler(label, extra_pids)\n end", "def ps\n sql = %q(\n select\n procpid,\n application_name as source,\n age(now(),query_start) as running_for,\n waiting,\n current_query as query\n from pg_stat_activity\n where\n current_query <> '<insufficient privilege>'\n AND current_query <> '<IDLE>'\n and procpid <> pg_backend_pid()\n order by 3 desc\n )\n\n exec_sql(sql, find_uri)\n end", "def query_data(host, varname, from_ts, to_ts)\n #hash_value = ActiveSupport.HashOrder\n\n data_by_label = {}\n data = MonitoringData.where({ :host => host,:varname => varname,:ts => (from_ts..to_ts) }).order(:ts).all\n data.each { |d|\n if data_by_label.has_key?(d.labels)\n data_by_label[d.labels].push([d.ts * 1000, d.value])\n else\n data_by_label[d.labels] = [[d.ts * 1000, d.value]]\n end\n }\n\n return data_by_label\n end", "def data\n measurements.collect do |measurement|\n {\n id: measurement.id, key: measurement.seconds,\n value: measurement.ppm, area: measurement.area,\n deleted: measurement.excluded\n }\n end\n end", "def cputime(pid)\n if cpu = cache.proc_cpu(pid)\n cpu.total.to_f / 1000\n end\n end", "def cputime(pid)\n if cpu = cache.proc_cpu(pid)\n cpu.total.to_f / 1000\n end\n end", "def get_all_time_sampling_profile\n {\n method: \"Memory.getAllTimeSamplingProfile\"\n }\n end", "def info\n _get(\"/query/dataleaks/info\") { |json| json }\n end", "def main\n Puppet.initialize_settings\n metrics_collector_setup\n\n output_file = Time.now.utc.strftime('%Y%m%dT%H%M%SZ') + '.json'\n\n @hosts.each do |host|\n timestamp = Time.now\n dataset = { 'timestamp' => timestamp.utc.iso8601, 'servers' => {} }\n hostkey = host.tr('.', '-')\n dataset['servers'][hostkey] = { @metrics_type => {} }\n url = \"https://#{host}:#{@port}\"\n\n # Puma based services use a different status endpoint and have an additional GC endpoint\n if ['ace', 'bolt'].include?(@metrics_type)\n status_url = URI(\"#{url}/admin/status\")\n\n gc_url = URI(\"#{url}/admin/gc_stat\")\n gc_status_output = get_endpoint(gc_url)\n else\n status_url = URI(\"#{url}/status/v1/services?level=debug\")\n end\n\n status_output = get_endpoint(status_url)\n dataset['servers'][hostkey][@metrics_type] = status_output\n dataset['servers'][hostkey][@metrics_type]['gc_stats'] = gc_status_output if gc_status_output\n\n unless @additional_metrics.empty?\n metrics_array = retrieve_additional_metrics(URI(\"#{url}/metrics/v2/read\"), @metrics_type, @additional_metrics)\n\n metrics_array.each do |metric_hash|\n metric_name = metric_hash['name']\n metric_data = metric_hash['data']\n dataset['servers'][hostkey][@metrics_type][metric_name] = metric_data\n end\n end\n\n dataset['servers'][hostkey][@metrics_type]['error'] = @errors\n dataset['servers'][hostkey][@metrics_type]['error_count'] = @errors.count\n dataset['servers'][hostkey][@metrics_type]['api-query-start'] = timestamp.utc.iso8601\n dataset['servers'][hostkey][@metrics_type]['api-query-duration'] = Time.now - timestamp\n\n filtered_dataset = filter_metrics(dataset, @excludes)\n json_dataset = JSON.generate(filtered_dataset)\n\n unless @output_dir.nil?\n Dir.chdir(@output_dir) do\n Dir.mkdir(host) unless File.exist?(host)\n File.open(File.join(host, output_file), 'w') do |file|\n file.write(json_dataset)\n end\n end\n end\n\n next unless @print\n # Use puts so that data gatherd from each host is written to stdout\n # with a newline separator. This enables parsing of multiple datasets\n # as the output stream is in line-delimited JSON form.\n STDOUT.puts(json_dataset)\n end\nrescue StandardError => e\n STDERR.puts \"Failed to collect #{@metrics_type} metrics: #{e.message}\"\n STDERR.puts e.backtrace\n nil\nend", "def get_process_memory(pid)\n case @platform ||= Gem::Platform.local.os\n when \"linux\"\n begin\n file = Pathname.new \"/proc/#{pid}/smaps\"\n return 0 unless file.exist?\n\n lines = file.each_line.select { |line| line.match(/^Pss/) }\n return 0 if lines.empty?\n\n lines.reduce(0) do |sum, line|\n line.match(/(?<value>(\\d*\\.{0,1}\\d+))\\s+(?<unit>\\w\\w)/) do |m|\n sum += m[:value].to_i\n end\n\n sum\n end\n rescue Errno::EACCES\n 0\n end\n when \"darwin\"\n mem = `ps -o rss= -p #{pid}`.strip\n mem.empty? ? 0 : mem.to_i\n else\n raise \"Can't check process memory, wrong type of platform: #{@platform}\"\n end\n end", "def performance(id)\n request_query = { 'iPerf_no' => id.to_s, 'iModeOfSale' => '10' }\n response = self.class.get(performance_detail_path, query: request_query)\n\n case response.code\n when 200 then Performance.new(response.body)\n else false\n end\n end", "def get_datastream( pid, dsID )\n pid.include?(\"druid\") ? pid = pid : pid = \"druid:#{pid}\"\n uri = URI.parse(@fedora + '/objects/' + pid + '/datastreams/' + dsID + '/content') \n RestClient.get(uri.to_s)\n rescue => e\n e.response \n end", "def metrics\n with_stats_lock do\n @stats_hash.keys.map { |spec| spec.to_s }\n end\n end", "def instance_metrics\n metrics = Dir.glob(\"tmp/drb-process-metrics-*.sock\").map do |filename|\n application_metrics = DRbObject.new_with_uri(\"drbunix:#{filename}\")\n application_metrics.update_process_metrics\n rescue IOError, DRb::DRbConnError\n # XXX Ignore any errors we may receive when fetching metrics from a remote process that has shut down (usually by the Puma worker killer)\n Danbooru::Metric::Set.new\n end\n\n metrics.reduce(&:merge) || Danbooru::Metric::Set.new\n end", "def get_data\n (mem, w_cache) = get_mem\n [100*mem.to_f/@total, 100*w_cache.to_f/@total]\n end", "def get_metrics\n {\n method: \"Performance.getMetrics\"\n }\n end", "def set_performance\n @performance = Performance.find(params[:id])\n end", "def set_performance\n @performance = Performance.find(params[:id])\n end", "def set_performance\n @performance = Performance.find(params[:id])\n end", "def set_performance\n @performance = Performance.find(params[:id])\n end", "def collect_metrics(data: {}, labels: {})\n metric(:pool_jobs_waiting_total)&.observe(data['pool_jobs_waiting_total'].to_i, labels)\n metric(:pool_ready_workers_total)&.observe(data['pool_ready_workers_total'].to_i, labels)\n metric(:pool_workers_total)&.observe(data['pool_workers_total'].to_i, labels)\n metric(:pool_initial_size)&.observe(data['pool_initial_size'].to_i, labels)\n metric(:poll_period)&.observe(data['poll_period'].to_i, labels)\n metric(:thread_pool_exhausted)&.observe(data['thread_pool_exhausted'].to_i, labels)\n end", "def tvp_report\n #Searches OrderLine report and pulls all current orders multiplying the price by order quantity to return the total amount of that product sold\n @data = OrderLine.find(:all , :select => \"product_id as pid, sum(product_price*ordered_quantity) as value \", :group => \"pid\")\n end", "def cpu_metrics\n super\n end", "def all_metrics\n output = `cube_info #{@fname} -l`\n output.split(\"\\n\")\n end", "def monitor\n log_opts = LogOpts.new.num(10000).tail\n log_opts = log_opts.ps(options[:ps]) if options[:ps]\n \n process_data = {}\n lines = 1\n \n heroku.read_logs(app, log_opts.to_opts) do |line|\n line.split(/\\n/).each do |real_line|\n merge_data_from_line(real_line, process_data)\n end\n metrics_table(process_data)\n end\n end", "def cpu_usage_extended_information(opts)\n opts = check_params(opts,[:host_ids])\n super(opts)\n end", "def collect\n parse_process_list(multiline('top -n 1 -b'), split_tokens: 9) do |tokens| \n [tokens[0], tokens.last, hostname, tokens[4].to_i]\n end\n end", "def grabtop5\n # grab 6 cause the top part is a header\n top5 = `ps -eo pcpu,pid,pmem,args | sort -k 1 -r | head -6`\n top5 = top5.split(/\\n/)\n\n top5procs = {}\n\n # pop the first element of the array cause it's a header\n top5.shift\n\n top5.each do |process|\n prochash = {}\n ps = process.split\n \n #### debugging info...\n prochash['cpu'] = ps[0]\n \n prochash['pid'] = ps[1]\n\n prochash['mem'] = ps[2]\n\n prochash['fullname'] = ps[3]\n\n name = ps[3].split(\"/\")\n name = name[name.size-1]\n prochash['name'] = name\n\n top5procs[prochash['name']] = prochash\n end\n\n return top5procs\n end", "def memory_per_cluster(cfg)\n cluster = cfg['cluster']\n query = @client.percent_query_free(\n \"sum(node_memory_MemTotal{job=\\\"#{cluster}\\\"})\",\n \"sum(node_memory_MemAvailable{job=\\\"#{cluster}\\\"})\"\n )\n\n metrics = []\n source = cfg['source']\n @client.query(query).each do |result|\n value = result['value'][1].to_f.round(2)\n log.debug(\"[memory_per_cluster] value: '#{value}', source: '#{source}'\")\n metrics << { 'source' => source, 'value' => value }\n end\n metrics\n end", "def find_by_pid(pid)\n @proc_table = Array.new\n ProcFetch.get_process(:processid => pid).each do |proc_attrs|\n @proc_table.push(ProcInfo.new(proc_attrs))\n end\n childs_tree\n end", "def get_metrics_data_for(app_id)\n return nil unless Config.metrics\n f = Fiber.current\n resp = work_data.find_one('app_id' => app_id)\n resp.callback do |doc|\n f.resume doc\n end\n resp.errback do |err|\n raise *err\n end\n doc = Fiber.yield\n return {nb_connections: 0, nb_messages: 0} if doc.nil?\n # count the number of connections\n nb_connections = if doc['connections']\n doc['connections'].count\n else\n 0\n end\n {nb_connections: nb_connections, nb_messages: doc['nb_messages']}\n end", "def processor_percents\n reply = `sar -P ALL #{@sleep} 1`\n lines = reply.split(\"\\n\")\n header = lines.shift\n num_cpus = header[/\\((\\d+) CPU\\)$/, 1].to_i\n # read a cycle\n 3.times { lines.shift }\n @cpus = num_cpus.times.map do\n line = lines.shift\n line.chomp!\n # the total usage (100% - idle)\n 100.0 - line[/\\s+([\\d\\.]+)$/,1].to_f\n end\n end", "def gather_information\n @@collectors[@type].keys.sort.each do |priority|\n @@collectors[@type][priority].each do |collector|\n c = collector.new @options\n c.run\n @report[collector::NAME] = c.to_hash\n end\n end\n end", "def index\n @dor_variant_performances = DorVariantPerformance.all\n end", "def record_result_to_tsdb()\n log_time_sec=@time_now.to_i-120\n @pv_response_time.each do |uri,response_time|\n send_metric(\"jpaas_app_responsetime\",log_time_sec,response_time,{\"uri\"=>uri,\"router\"=>@hostname})\n end\n @pv_response_code.each do |uri,response_code_hash|\n response_code_hash.each do |response_code,count|\n send_metric(\"jpaas_app_pv\",log_time_sec,count,{\"uri\"=>uri,\"response_code\"=>response_code,\"router\"=>@hostname})\n end\n end\n end", "def get_stats()\n val = [@dex, @str, @int, @lck]\n end", "def read_output(pid)\n access_processes do |processes|\n File.read(processes[pid].io.stdout.path) rescue nil \n end\n end", "def get_datastream( pid, dsID )\n repository.find(pid).datastreams[dsID].content\n end", "def data\n @entries.keys.map do |k|\n key_data = data_for(k)\n data = Hash[key_data.collect{|h| [h[:label], h[:microseconds_per_iters]]}]\n {name: k, data: data}\n end\n end", "def stats\n @server.make_json_request('show.stats', tvdbid: @tvdbid)['data']\n end", "def stats\n # Memory stats may show more processes than status.\n status = passenger_status\n passenger_memory_stats.each_pair.inject({}) do |hash, (pid, stats)|\n hash[pid] = stats\n stats.merge! status[pid] if status[pid]\n\n hash\n end\n end", "def cpu_usage\r\n # all usage\r\n total_used_cpu = IO.popen(\"ps aux\").read.split(\"\\n\").inject 0 do |a, i|\r\n a += i.split(' ')[2].to_f\r\n end\r\n # mysqld usage\r\n tread_desc = IO.popen(\"ps aux|grep mysqld\").read.split(\"\\n\")[0].split \" \" #get total info about mysql-process\r\n #form json\r\n return {\r\n rows: [{\r\n type: \"CPU free\",\r\n total: 100\r\n },{\r\n type: \"Mysql used\",\r\n total: tread_desc[2].to_f\r\n },{\r\n type: 'Other',\r\n total: total_used_cpu - tread_desc[2].to_f\r\n }]\r\n }.to_json\r\nend", "def cpu_usage_information\n super\n end", "def load_data!(time_start=nil, time_end=nil, tags = {}, agg = \"sum\", downsample = nil)\n metric_data = metrics(time_start, time_end, tags, agg, downsample).first\n if metric_data then\n self.data = metric_data[:vals]\n self.metadata = metric_data[:tags]\n end\n self.query = { :start => time_start, :end => time_end, :tags => tags, :downsample => downsample }\n end", "def pva_statistics(opts)\n opts = check_params(opts,[:pva_ids])\n super(opts)\n end", "def index\n @performances = Performance.all\n end", "def call\n `ps -o rss -p #{@pid}`.split(\"\\n\").last.to_i\n end", "def _ps_browser(pat)\n x = `ps -ocomm,pcpu,rss -xwwc | grep -i #{pat}`\n\n if x.length > 0\n cpu = Float(/\\d+\\.\\d+/.match(x)[0])\n mem = Float(/\\d+$/.match(x)[0])*1024.0\n else\n cpu = -1.0\n mem = -1.0\n end\n \n return [cpu, mem]\n end", "def cat_proc\n # user nice system idle iowait irq softirq\n @io.readline # cpu_totals\n cpuinfos = @num_cpus.times.map do\n pieces = @io.readline.split(' ')\n data = pieces[1,7].map(&:to_i)\n CPUInfo.new( data[IDLE_IDX], data.reduce(:+) )\n end\n @io.rewind\n cpuinfos\n end", "def getYieldAndClusterInfo(demuxStatsHTM)\n doc = open(demuxStatsHTM) { |f| Hpricot(f) }\n rows = (doc/\"/html/body/div[@ID='ScrollableTableBodyDiv']/table/tr\")\n\n if rows == nil || rows.length == 0\n rows = (doc/\"/html/body/div[@id='ScrollableTableBodyDiv']/table/tr\")\n end\n\n rows.each do |row|\n dataElements = (row/\"td\")\n\n if dataElements[1].inner_html.eql?(@fcBarcode)\n @yield = dataElements[7].inner_html.gsub(\",\", \"\")\n @percentPFReads = dataElements[8].inner_html\n @numRawReads = dataElements[9].inner_html.gsub(/,/, \"\")\n @numPFReads = (@numRawReads.to_f / 100.0) * @percentPFReads.to_f \n @percentPFReads = dataElements[8].inner_html\n @percentPerfectIndex = dataElements[11].inner_html\n @percent1MismatchIndex = dataElements[12].inner_html\n @percentQ30Bases = dataElements[13].inner_html\n @meanQualScore = dataElements[14].inner_html\n end\n end\n end", "def stats\n handle_fork\n _stats\n end", "def os_x_raw_ps\n\t\t`COLUMNS=9999 ps ax -o \"pid uid ppid rss cpu command\"`\n\tend", "def os_x_raw_ps\n\t\t`COLUMNS=9999 ps ax -o \"pid uid ppid rss cpu command\"`\n\tend", "def stats(metric_name, start_timestamp, end_timestamp=Time.now, attempt=0)\n results = []\n values = send_command(\"values #{metric_name} #{start_timestamp.to_i} #{end_timestamp.to_i}\")\n if values.nil? || values[metric_name].nil?\n if attempt < max_attempts\n return stats(metric_name, start_timestamp, end_timestamp, attempt+1)\n else\n []\n end\n end\n results = if values[metric_name].is_a?(Hash)\n fields = values[metric_name][:fields]\n values[metric_name][:data].collect do |v|\n hash = { :timestamp => Time.at(v[:timestamp].to_i) }\n fields.each_with_index do |f,i|\n hash.update({ f.to_s => v[:value][i].to_f })\n end\n hash\n end\n elsif values[metric_name].is_a?(Array)\n values[metric_name].collect{|v| { :timestamp => Time.at(v[:timestamp].to_i), :value => v[:value].to_f } }\n end\n results\n end", "def get_pool_measure(category, dimension)\n [get_data_measure(stored_data_start, category, dimension),\n get_data_measure(stored_data_last, category, dimension)]\n end", "def cp_performance_chart_data\n data = ::Api::Charts::CPPerformance.new.cp_performance_all_sectors_data\n\n render json: data.chart_json\n end", "def performance_chart_data\n chart_data = {}\n new_ev = complement_evm_value @ev\n new_ac = complement_evm_value @ac\n new_pv = complement_evm_value @pv\n performance_min_date = [new_ev.keys.min,\n new_ac.keys.min,\n new_pv.keys.min].max\n performance_max_date = [new_ev.keys.max,\n new_ac.keys.max,\n new_pv.keys.max].min\n spi = {}\n cpi = {}\n cr = {}\n (performance_min_date..performance_max_date).each do |date|\n spi[date] = (new_ev[date] / new_pv[date]).round(2)\n cpi[date] = (new_ev[date] / new_ac[date]).round(2)\n cr[date] = (spi[date] * cpi[date]).round(2)\n end\n chart_data[:spi] = convert_to_chart(spi)\n chart_data[:cpi] = convert_to_chart(cpi)\n chart_data[:cr] = convert_to_chart(cr)\n chart_data\n end", "def all_cpu_usage_extended_information\n super\n end", "def serve_process_metrics\n filename = \"tmp/drb-process-metrics-#{puma_worker_id}.sock\"\n FileUtils.rm_f(filename)\n DRb.start_service(\"drbunix:#{filename}\", ApplicationMetrics.instance)\n end", "def get_series(current_hour)\n @series = []\n logs_per_hour = {}\n Array (00..23).each{|hour| logs_per_hour[hour] = [ServerLoad.new({:ram_usage => 0})]}\n \n Server.all.each { |server| \n logs_per_hour = logs_per_hour.merge!(ServerLoad.where(server_id: server.id, updated_at: (Time.now - 24.hours)..Time.now).group_by(&:hour))\n average_ram_per_hour = logs_per_hour.map { |_,array| (array.map(&:ram_usage).reduce(:+).to_f/ array.size).round(2) }\n \n @series.push({name: server.name, data: change_order(average_ram_per_hour, current_hour)})\n }\n @series\n end", "def get_metrics_for(app_id)\n return nil unless Config.metrics\n f = Fiber.current\n resp = metrics.find_one('_id' => app_id)\n resp.callback do |doc|\n f.resume doc\n end\n resp.errback do |err|\n raise *err\n end\n doc = Fiber.yield\n # convert id to int\n doc['_id'] = doc['_id'].to_i unless doc.nil?\n doc\n end", "def infoFor(regex)\n info = `ps -eo pcpu,pid,pmem,args | sort -k 1 -r | grep #{regex} | head -1`\n info.split\n end", "def get_usage(args= {})\n args = {:day=>\"today\", :type=>\"heat\"}.merge(args)\n result = HTTParty.get( @tstat_ip + '/tstat/datalog', :headers => @headers) \n \n day = result[args[:day]]\n runtime = day[args[:type] + '_runtime']\n\n return runtime\n end", "def usage_by_ps\n memory = cmd(\"ps -o rsz #{process}\").split(\"\\n\")[1].to_f / 1.kilobyte\n return nil if memory <= 0\n\n memory\n end", "def get_metrics_list\n\t\turi = \"#{@base_url}/data\"\n\t\tresults = json_metrics_list uri\n\t\tlist = []\n\t\tresults[:hosts][0..@hosts_limit].each {|h|\n\t\t\thost_results = json_metrics_list \"#{uri}/#{h}/\"\n\t\t\tlist << host_results[:metrics].map{|r| \"#{h}/#{r}\"}\n\t\t}\n\t\treturn list.flatten\n\tend", "def convert_pt_query_to_series(pt_query)\n num_series=pt_query.count\n fingerprints=Set.new\n \n # Get list of fingerprints\n pt_query.each do |row|\n row.each {|k,v| fingerprints.add(k)}\n end\n\n fingerprints.delete(nil)\n\n series={}\n # cycle through list\n fingerprints.each do |f|\n series[f]=[]\n (0...num_series).each do |i|\n val = pt_query[i][f]\n series[f].push(val)\n end\n end\n series\nend", "def throughput\n return {}\n end", "def all_processes\n `ps -eo pid,ppid`.lines.reduce(Hash.new []) do |hash, line|\n pid, ppid = line.split.map(&:to_i)\n hash[ppid] = [] unless hash.key?(ppid)\n hash[ppid] << pid\n hash\n end\n end", "def get_stats(params)\n node_ip = get_ip(params)\n result = {}\n if params.has_key?(:pool)\n pool_name = params[:pool]\n node_port = (params[:port] || 80).to_i\n notify(:msg => \"[#{@name}] Retrieving stats for member #{node_ip}:#{node_port} in pool #{pool_name} on load balancer #{@config[:host]}\",\n :tags => [:f5, :trace])\n stats = with_f5('LocalLB.PoolMember') do\n get_statistics([ pool_name ], [[{ 'address' => node_ip, 'port' => node_port }]])\n end\n # TODO: deal with node not existing (stats is nil)\n stats = stats[0] if stats[0]\n else\n notify(:msg => \"[#{@name}] Retrieving stats for node #{node_ip} on load balancer #{@config[:host]}\",\n :tags => [:f5, :trace])\n stats = with_f5('LocalLB.NodeAddress') do\n get_statistics([ node_ip ])\n end\n end\n # TODO: deal with node not existing (stats is nil)\n if stats['statistics'] && stats['statistics'][0] && stats['statistics'][0]['statistics']\n stats['statistics'][0]['statistics'].each do |stat|\n name = extract_type(stat)\n if name\n # TODO: switch on the type and support all possible values\n if extract_type(stat.value) == 'iControl:Common.ULong64'\n result[name] = (stat.value.high << 32) | stat.value.low\n end\n end\n end\n end\n result\n end", "def get_realtime_data(context_id:)\n {\n method: \"WebAudio.getRealtimeData\",\n params: { contextId: context_id }.compact\n }\n end", "def get_vm_monitor_data(vm)\n reset_monitor\n\n cpu_mhz = vm[:mob].runtime.host.summary.hardware.cpuMhz.to_f\n\n @monitor[:used_memory] = vm[:mob].summary.quickStats.hostMemoryUsage *\n 1024\n\n used_cpu = vm[:mob].summary.quickStats.overallCpuUsage.to_f / cpu_mhz\n used_cpu = (used_cpu * 100).to_s\n @monitor[:used_cpu] = format('%.2f', used_cpu).to_s\n\n # Check for negative values\n @monitor[:used_memory] = 0 if @monitor[:used_memory].to_i < 0\n @monitor[:used_cpu] = 0 if @monitor[:used_cpu].to_i < 0\n\n guest_ip_addresses = []\n unless vm[:mob].guest.net.empty?\n vm[:mob].guest.net.each do |net|\n next unless net.ipConfig\n next if net.ipConfig.ipAddress.empty?\n\n net.ipConfig.ipAddress.each do |ip|\n guest_ip_addresses << ip.ipAddress\n end\n end\n end\n @guest_ip_addresses = guest_ip_addresses.join(',')\n\n pm = vm[:mob]._connection.serviceInstance.content.perfManager\n\n provider = pm.provider_summary(vm[:mob])\n\n refresh_rate = provider.refreshRate\n\n stats = {}\n\n @one_vm = OpenNebula::VirtualMachine\n .new_with_id(vm[:id], @client)\n\n if @one_vm['MONITORING/LAST_MON'] &&\n @one_vm['MONITORING/LAST_MON'].to_i != 0\n # Real time data stores max 1 hour. 1 minute has 3 samples\n interval = (Time.now.to_i -\n @one_vm['MONITORING/LAST_MON'].to_i)\n\n # If last poll was more than hour ago get 3 minutes,\n # else calculate how many samples since last poll\n if interval > 3600\n samples = 9\n else\n samples = (interval / refresh_rate) + 1\n end\n samples > 0 ? max_samples = samples : max_samples = 1\n\n stats = pm.retrieve_stats(\n [vm[:mob]],\n ['net.transmitted', 'net.bytesRx', 'net.bytesTx',\n 'net.received', 'virtualDisk.numberReadAveraged',\n 'virtualDisk.numberWriteAveraged', 'virtualDisk.read',\n 'virtualDisk.write'],\n interval => refresh_rate, max_samples => max_samples\n ) rescue {}\n else\n # First poll, get at least latest 3 minutes = 9 samples\n stats = pm.retrieve_stats(\n [vm[:mob]],\n ['net.transmitted', 'net.bytesRx', 'net.bytesTx',\n 'net.received', 'virtualDisk.numberReadAveraged',\n 'virtualDisk.numberWriteAveraged', 'virtualDisk.read',\n 'virtualDisk.write'],\n interval => refresh_rate, max_samples => 9\n ) rescue {}\n end\n\n if !stats.empty? && !stats.first[1][:metrics].empty?\n metrics = stats.first[1][:metrics]\n\n nettx_kbpersec = 0\n if metrics['net.transmitted']\n metrics['net.transmitted'].each do |sample|\n nettx_kbpersec += sample if sample > 0\n end\n end\n\n netrx_kbpersec = 0\n if metrics['net.bytesRx']\n metrics['net.bytesRx'].each do |sample|\n netrx_kbpersec += sample if sample > 0\n end\n end\n\n read_kbpersec = 0\n if metrics['virtualDisk.read']\n metrics['virtualDisk.read'].each do |sample|\n read_kbpersec += sample if sample > 0\n end\n end\n\n read_iops = 0\n if metrics['virtualDisk.numberReadAveraged']\n metrics['virtualDisk.numberReadAveraged'].each do |sample|\n read_iops += sample if sample > 0\n end\n end\n\n write_kbpersec = 0\n if metrics['virtualDisk.write']\n metrics['virtualDisk.write'].each do |sample|\n write_kbpersec += sample if sample > 0\n end\n end\n\n write_iops = 0\n if metrics['virtualDisk.numberWriteAveraged']\n metrics['virtualDisk.numberWriteAveraged'].each do |sample|\n write_iops += sample if sample > 0\n end\n end\n\n else\n nettx_kbpersec = 0\n netrx_kbpersec = 0\n read_kbpersec = 0\n read_iops = 0\n write_kbpersec = 0\n write_iops = 0\n end\n\n # Accumulate values if present\n if @one_item && @one_item['MONITORING/NETTX']\n previous_nettx = @one_item['MONITORING/NETTX'].to_i\n else\n previous_nettx = 0\n end\n\n if @one_item && @one_item['MONITORING/NETRX']\n previous_netrx = @one_item['MONITORING/NETRX'].to_i\n else\n previous_netrx = 0\n end\n\n if @one_item && @one_item['MONITORING/DISKRDIOPS']\n previous_diskrdiops = @one_item['MONITORING/DISKRDIOPS'].to_i\n else\n previous_diskrdiops = 0\n end\n\n if @one_item && @one_item['MONITORING/DISKWRIOPS']\n previous_diskwriops = @one_item['MONITORING/DISKWRIOPS'].to_i\n else\n previous_diskwriops = 0\n end\n\n if @one_item && @one_item['MONITORING/DISKRDBYTES']\n previous_diskrdbytes = @one_item['MONITORING/DISKRDBYTES'].to_i\n else\n previous_diskrdbytes = 0\n end\n\n if @one_item && @one_item['MONITORING/DISKWRBYTES']\n previous_diskwrbytes = @one_item['MONITORING/DISKWRBYTES'].to_i\n else\n previous_diskwrbytes = 0\n end\n\n @monitor[:nettx] = previous_nettx +\n (nettx_kbpersec * 1024 * refresh_rate).to_i\n @monitor[:netrx] = previous_netrx +\n (netrx_kbpersec * 1024 * refresh_rate).to_i\n\n @monitor[:diskrdiops] = previous_diskrdiops + read_iops\n @monitor[:diskwriops] = previous_diskwriops + write_iops\n @monitor[:diskrdbytes] = previous_diskrdbytes +\n (read_kbpersec * 1024 * refresh_rate).to_i\n @monitor[:diskwrbytes] = previous_diskwrbytes +\n (write_kbpersec * 1024 * refresh_rate).to_i\n @monitor\n end", "def get_results(in_progress)\nhostname2pid = {}\nin_progress.each { |pid, hostname|\n hostname2pid[hostname] = pid\n}\nissue_command_on_hosts(hostname2pid, 30){ |vp, pid| vp.get_results(pid) }\nend", "def compute_statistics_for_slice(slice)\n ret = {}\n stats = slice.statistics\n history = slice.history\n stats.each do |stat|\n k = stat.key\n k2 = \".time.#{k}\"\n t0 = Time.now\n ret[k] = stat.compute(history, memory_size)\n t1 = Time.now\n ret[k2] = (t1 - t0) if $DEBUG\n end\n ret\n end", "def fetch_data\n _mem = mem\n _loadavg = loadavg\n {\n :server => \"#{@config[\"server\"]}\",\n :key => \"#{@config[\"key\"]}\",\n :data => {\n :mem => _mem.to_json,\n :loadavg => _loadavg.to_json\n }}.to_json\nend" ]
[ "0.6122074", "0.5885567", "0.58374125", "0.5763835", "0.56918347", "0.5570379", "0.5553219", "0.5532301", "0.55108595", "0.5493562", "0.53463674", "0.53402525", "0.5289529", "0.52815604", "0.52645046", "0.5239986", "0.5237518", "0.52252936", "0.5220956", "0.5208771", "0.5207992", "0.5200178", "0.5189968", "0.5179691", "0.51792604", "0.5163809", "0.5158789", "0.5147356", "0.5125477", "0.51015735", "0.50691634", "0.50691634", "0.50679374", "0.50634116", "0.5062847", "0.505659", "0.50539", "0.5051736", "0.50345683", "0.4992823", "0.497588", "0.49618956", "0.49388286", "0.49388286", "0.49388286", "0.49388286", "0.4935641", "0.49230972", "0.4916866", "0.49118552", "0.49050245", "0.49039397", "0.4902286", "0.4901452", "0.48946038", "0.48844364", "0.48840967", "0.4882378", "0.48776168", "0.48594728", "0.48521006", "0.48519543", "0.4845162", "0.4839161", "0.4837166", "0.48301923", "0.48274192", "0.4821118", "0.48136345", "0.48061717", "0.48055878", "0.4804294", "0.48005354", "0.4799297", "0.47988403", "0.47978544", "0.47955644", "0.4790654", "0.4790654", "0.47877708", "0.47850037", "0.47775573", "0.47687483", "0.4766041", "0.47611398", "0.475954", "0.47546825", "0.4745839", "0.47404516", "0.47392595", "0.4736974", "0.473566", "0.4735416", "0.47269022", "0.47240946", "0.47196677", "0.47190586", "0.47124153", "0.4697258", "0.46955177" ]
0.47154638
97
Roll up the stats from individual PIDs into a summary
def report(process_pids) ret = {} return ret if pid_stats_map.size == 0 age_sec = 0 cpu_pct = 0 resident_set_bytes = 0 threads = 0 virtual_mem_bytes = 0 pid_stats_map.each do |pid, stat| unless process_pids.include? pid pid_stats_map.delete(pid) next end age_sec += stat.perf_detail[:age_seconds] threads += stat.perf_detail[:threads] resident_set_bytes += stat.perf_detail[:mem][:resident_set_bytes] virtual_mem_bytes += stat.perf_detail[:mem][:virtual_mem_bytes] cpu_pct += process_cpu_pct stat.perf_detail[:cpu] end ret[:age_seconds] = age_sec ret[:threads] = threads ret[:mem] = {} ret[:mem][:resident_set_bytes] = resident_set_bytes ret[:mem][:virtual_mem_bytes] = virtual_mem_bytes ret[:cpu_pct] = cpu_pct ret end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def stats_summary\n html = \"\"\n %w(inhale exhale cycle).each do |phase|\n %w(min max avg).each do |stat|\n time = format_time(self.meditations.map {|med| med.send(phase + \"_\" + stat)}.max)\n html += \"record #{phase} #{stat}: #{time}<br>\"\n end\n end\n html\n end", "def summary(permutations = 99, seed = nil)\n p_val = mc(permutations, seed)\n { stat: stat, p: p_val }\n end", "def summary(procedure = nil)\n tags =\n if procedure\n if @by_procedure.include?(procedure.oid)\n @by_procedure[procedure.oid]\n else\n []\n end\n else\n @by_id.values\n end\n\n grouped = Util::Enumerable.group_by(tags){|x| x.type }\n\n summary = Hash.new{|h,k| h[k] = Hash.new }\n grouped.each do |type, ts|\n summary[type][:count] = ts.size\n summary[type][:percent] = Util::Enumerable.sum(ts){|x| x.to_f } / ts.size\n end\n\n summary\n end", "def status_summary(statuspage_id)\n request :method => :get,\n :url => @url + 'status/summary/' + statuspage_id\n end", "def raw_summary\n report = { \"version\" => { \"config\" => configuration_version, \"puppet\" => Puppet.version } }\n\n @metrics.each do |name, metric|\n key = metric.name.to_s\n report[key] = {}\n metric.values.each do |name, label, value|\n report[key][name.to_s] = value\n end\n report[key][\"total\"] = 0 unless key == \"time\" or report[key].include?(\"total\")\n end\n (report[\"time\"] ||= {})[\"last_run\"] = Time.now.tv_sec\n report\n end", "def summary(id)\n connection.get do |req|\n req.url \"job/#{id}/summary\"\n end\n end", "def stats\n groups = ::Twigg::Pivotal::Status.status\n\n groups.each do |current_state, stories|\n header = pluralize stories.size,\n \"#{current_state} story\",\n \"#{current_state} stories\"\n puts header\n\n stories.each do |story|\n print \"[#{story.story_type}] #{story.name}\"\n if story.owned_by\n puts \" [#{story.owned_by['initials']}]\"\n else\n puts\n end\n end\n\n puts\n end\n\n puts '', 'Totals'\n groups.each do |current_state, stories|\n puts number_with_delimiter(stories.size) + \" #{current_state}\"\n end\n puts\n end", "def summaries\n header = summarize_per.header\n summaries = default_summaries\n operand.each { |tuple| summaries.summarize_by(header, tuple) }\n summaries\n end", "def print_summary\n puts \"\\n\\nScore : # Instances\\n\" << (\"=\" * 19)\n @summary_totals.each_with_index { |value, index| puts \" %5d:%8d\\n\" % [index, value] unless value.nil? }\n puts \"\\n** End of Report\"\n end", "def summary\n \n end", "def summarize_stats(events)\n mawing_incidents = events.count(:lumberjack_mawed)\n lumber_collected = events.map { |event| \n if event == :tree_chopped\n 1\n elsif event == :elder_tree_chopped\n 2\n else\n 0\n end\n }.reduce(0, :+)\n saplings_created = events.count(:sapling_planted)\n saplings_aged = events.count(:sapling_to_tree)\n trees_aged = events.count(:tree_to_elder)\n\n {\n saplings_created: saplings_created,\n saplings_aged: saplings_aged,\n trees_aged: trees_aged,\n lumber_collected: lumber_collected,\n mawing_incidents: mawing_incidents \n }\n end", "def summary\n stats = Hash.new { |h,k| h[k] = {} }\n @stats.each do |field, actions|\n actions.each do |action|\n col = action.column_name\n ## register the value of this \"stats\" for the column name\n action.iterate do |ts,value|\n stats[ts][col] = value\n end\n end\n end\n return stats\n end", "def dump_summary(duration, example_count, failure_count, pending_count)\n end", "def dump_summary(duration, example_count, failure_count, pending_count)\n end", "def cp_summary(*filter)\n @the_nurse.completed_procs_summary(*filter).map {|name, n| \"#{name} #{n}\"}\n end", "def summarize\n print \"# of asks: #{ask_count}\\n# of bids: #{bid_count}\\nAsk volume: #{ask_volume.to_s('F')}\\nBid volume: #{bid_volume.to_s('F')}\\n\"\n $stdout.flush\n end", "def summarize()\n fields.each do |name, metric|\n params = {}\n params[:service] = \"process;#{pid};#{name}\"\n params[:description] = name\n params[:pname] = comm\n if name == \"State\"\n params[:state] = riemann_statemap(metric)\n params[:value] = metric\n # elsif name.end_with?(\"time\")\n # params[:metric] = time_of(name)\n elsif metric.is_a?(Numeric)\n params[:metric] = metric\n else\n params[:value] = metric\n end\n yield(params)\n end\n end", "def dump_summary *args; end", "def print_summary(dsobj)\n dshash = get_dshash(dsobj)\n ds_pollint_m = dshash['pollint_s'].to_i / 60\n dp_alert_count = 0.to_i\n\n # iterate over each datapoint\n dshash['datapoints'].each { |datapoint|\n dphash = get_dphash(datapoint)\n\n # is the alert trigger set on this datapoint\n if ( dphash['alert_trigger'].size > 0 )\n # yes, increment the alert count var\n dp_alert_count += 1\n end\n\n }\n\n puts \"Summary:\\n\"\n\n puts \" - datasource name:\\t\" + dshash['name'] + \"\\n\"\n puts \" - display name:\\t\" + dshash['dname'] + \"\\n\"\n puts \" - applies to:\\t\\t\" + dshash['applies'] + \"\\n\"\n puts \" - search keywords:\\t\" + dshash['tags'] + \"\\n\"\n puts \" - polling interval:\\t\" + ds_pollint_m.to_s + \"m\\n\"\n puts \" - multi instance:\\t\" + dshash['multi'] + \"\\n\"\n puts \" - datapoints:\\t\\t\" + dshash['datapoints'].size.to_s + \"\\n\"\n puts \" - datapoint alerts:\\t\" + dp_alert_count.to_s + \"\\n\"\n puts \" - graphs:\\t\\t\" + dshash['graphs'].size.to_s + \"\\n\"\n puts \" - overview graphs:\\t\" + dshash['ographs'].size.to_s + \"\\n\"\n puts \"=====================\\n\"\n end", "def statistics(id, keys = [Streak.positive_key, Streak.positive_total_key, Streak.positive_streak_key, Streak.negative_key, Streak.negative_total_key, Streak.negative_streak_key, Streak.total_key])\n values = Streak.redis.multi do |transaction|\n keys.each do |key|\n transaction.get(\"#{Streak.namespace}:#{key}:#{id}\")\n end\n end.map(&:to_i)\n\n Hash[keys.map(&:to_sym).zip(values)]\n end", "def summary\n end", "def summary\n end", "def summarize!\n %i[critical warning unknown].each do |status|\n send(status, summary) unless results[status].empty?\n end\n ok(summary)\n end", "def summary; end", "def summary; end", "def summary; end", "def summary; end", "def summary\n {\n :identity => @identity,\n :alias => @alias,\n :status => @status,\n :retries => @retries,\n :disconnects => @disconnect_stats.total,\n :failures => @failure_stats.total,\n }\n end", "def getPullRequestSummary(id)\n jsonHash = getJson(@url_pullrequests + \"/\" + id.to_s)\n return Summary.new(jsonHash, @options)\n end", "def pva_statistics(opts)\n opts = check_params(opts,[:pva_ids])\n super(opts)\n end", "def summary\n Nba.game_summary(id)\n end", "def summary\n # TODO\n end", "def summary(args)\n out = {'known'=> {}, 'forwarded'=>{},'unknown'=>{} }\n args[:end] ||= Time.now\n args[:start] ||= args[:end] - 10*86400 # 10 days\n get_all_reports_by_date(args[:start],args[:end]).each do |r|\n get_all_records_filtered(\"report_metadata_id\",r.id).each do |record|\n # if record.source_ip is part of authorized_senders\n out['known']['count'] += record.count\n end\n end\n return out\n end", "def summarize_results!(all_results)\n \t summaries = {}\n \t all_results.each do |paramset, results|\n \t File.open(@dir + \"/results-#{param_string(paramset)}.yaml\", 'w' ) do |out|\n \t\t\tYAML.dump(results, out)\n \t\tend\n \t\tsummaries[paramset] = {}\n \t\t# create an array of arrays\n \t\tres = results.keys.map do |key| \n \t\t # calculate stats\n \t\t a = results[key]\n \t\t if a.all? {|el| el.is_a? Numeric }\n \t\t summaries[paramset][\"#{key} mean\"] = Stats::mean(a)\n \t\t summaries[paramset][\"#{key} SD\"] = Stats::standard_deviation(a)\n \t\t [key] + a + [Stats::mean(a), Stats::standard_deviation(a)]\n \t\t else\n \t\t [key] + a + [\"--\", \"--\"]\n \t end\n \t\t end\n\t\t \n \t\t ls = results.keys.map{|v| [7, v.to_s.length].max }\n \t\t\n \t\tls = [\"Std Deviation\".length] + ls\n \t\tres = header_column + res\n \t\tres = res.transpose\n \t\tout = build_table res, ls\n \t\tFile.open(@dir + \"/#{paramset}-summary.mmd\", 'w') do |f|\n \t\t f << \"## Results for #{@experiment} with parametres #{param_string(paramset, \", \")} ##\\n\\n\"\n \t\t f << out\n \t\t end\n\t\t end\n\t\t \n\t\t # Build CSV file with all of the results\n\t\t #puts summaries.inspect\n\t\t \n\t\t summaries = summaries.to_a\n #puts summaries.inspect\n\t\t keys1 = summaries.first.first.keys\n\t\t keys2 = summaries.first.last.keys\n\t\t #puts keys1.inspect, keys2.inspect, \"=====\"\n CSV.open(@dir + \"/results.csv\", \"w\") do |csv|\n \t csv << keys1 + keys2\n \t summaries.each do |summary|\n \t #puts summary.first.inspect\n \t #puts summary.first.values_at(*keys1).inspect + summary.last.values_at(*keys2).inspect\n \t csv << summary.first.values_at(*keys1) + summary.last.values_at(*keys2)\n \t \n \t end\n \t end\n\t\t \n\t end", "def accumulate_summary_totals( score )\n @summary_totals[score] ||= 0\n @summary_totals[score] += 1\n end", "def summary\n result = []\n @subprocessors.each { |processor| result << processor.summary }\n result.flatten(1).compact\n end", "def print_summary\n stats = [statistics[:total_code_loc], statistics[:total_spec_loc]]\n stats.push(stats[1].to_f / stats[0].to_f)\n \n puts \" Code LOC: %s Test LOC: %s Code to Test Ratio: 1:%1.1f\" % stats\n puts\n end", "def stats\n @additions ||= 0\n @deletions ||= 0\n @stats_row_one = {\n active_user_count: @active_user_count,\n pull_count: @pull_count,\n comment_count: @comment_count,\n qa_signoff_count: @qa_signoff_count\n }\n @stats_row_two = {\n avg_additions: @additions.round.to_i,\n avg_deletions: @deletions.round.to_i,\n net_additions: @net_additions\n }\n end", "def print_rpc_stats(stats)\n out.puts stats.report(\"Task Stats\", false, @verbose)\n end", "def summary\n if Core.pokemon_taken?\n new_poke = Core.download_pokemon($pokemon_party.online_id).to_pokemon\n return display_message(ext_text(8997, 10)) unless new_poke\n\n if GTS.finish_trade($pokemon_party.online_pokemon, new_poke, false)\n $pokemon_party.add_pokemon(new_poke)\n $pokemon_party.online_pokemon = nil\n GamePlay::Save.save\n end\n return\n end\n call_scene(GamePlay::Summary, $pokemon_party.online_pokemon)\n if display_message(ext_text(8997, 36), 2, ext_text(8997, 33), ext_text(8997, 34)) == 0\n if display_message(ext_text(8997, 37), 2, ext_text(8997, 33), ext_text(8997, 34)) == 0\n if Core.delete_pokemon\n $pokemon_party.add_pokemon($pokemon_party.online_pokemon)\n $pokemon_party.online_pokemon = nil\n GamePlay::Save.save\n display_message(ext_text(8997, 38))\n end\n end\n end\n end", "def summary\n response = get \"summary\", {}\n Hashie::Mash.new(response)\n end", "def summary *args\n @summary = args.first if args.size > 0\n end", "def statistics\n find(:all, :select => \"title, count(*) AS count, sum(amount) AS sum, avg(amount) AS avg\", :group => :title).map{|stat| stat.attributes}\n end", "def output_details_grouped io, threshold = nil\n calculate\n\n scores.sort_by { |_, n| -n }.each do |klass, total|\n io.puts\n\n io.puts \"%8.1f: %s\" % [total, \"#{klass} total\"]\n\n method_scores[klass].each do |name, score|\n self.print_score io, name, score\n end\n end\n end", "def summary\n report = raw_summary\n\n ret = \"\"\n report.keys.sort { |a,b| a.to_s <=> b.to_s }.each do |key|\n ret += \"#{Puppet::Util::Metric.labelize(key)}:\\n\"\n\n report[key].keys.sort { |a,b|\n # sort by label\n if a == :total\n 1\n elsif b == :total\n -1\n else\n report[key][a].to_s <=> report[key][b].to_s\n end\n }.each do |label|\n value = report[key][label]\n next if value == 0\n value = \"%0.2f\" % value if value.is_a?(Float)\n ret += \" %15s %s\\n\" % [Puppet::Util::Metric.labelize(label) + \":\", value]\n end\n end\n ret\n end", "def get_process_stat\n self.get_all_pid.each do |pid|\n uid = self.get_uid_of_pid(pid)\n username = Etc::getpwuid(uid).name\n\n statline = IO.read(\"/proc/#{pid}/stat\")\n stat = statline.split(' ')\n #time = stat[13].to_i+stat[14].to_i+stat[15].to_i+stat[16].to_i\n time = stat[13].to_i+stat[14].to_i\n if ([email protected]_key?(username))\n @currprocstat[username] = 0\n end\n @currprocstat[username] = @currprocstat[username] + time \n\n iowait = stat[41].to_i\n if ([email protected]_key?(username))\n @currprociowait[username] = 0\n end\n @currprociowait[username] += iowait\n end\n end", "def summarize(parser)\n\n\t\t# the UID is MANDATORY\t\t\n\t\tif parser[:uid].nil?\n\t\t\traise ArgumentError\n\t\tend\n\t\t\n\t\t# concatenate all of the fields other\n\t\t# than UID, which always goes first\n\t\tsummary = (parser.matches.collect do |m|\n\t\t\tunless m.token.name == :uid\n\t\t\t\t\"#{m.token.name}=#{m.humanize}\"\n\t\t\tend\n\t\tend).compact.join(\", \")\n\t\t\n\t\t# return the mandatory UID, and if any\n\t\t# fields were summarized, append them\n\t\tsuffix = (summary != \"\") ? \": #{summary}\" : \"\"\n\t\t\"#{parser[:uid].humanize}#{suffix}\"\n\tend", "def stats\n rooms = objs = scripts = characters = accounts = 0\n self.each do |val|\n case val\n when Room\n rooms += 1\n when Character\n characters += 1\n when GameObject\n objs += 1\n when Script\n scripts += 1\n when Account\n accounts += 1\n end\n end\n stats=<<EOD\n[COLOR Cyan]\n---* Database Statistics *---\n Rooms - #{rooms}\n Objects - #{objs}\n Scripts - #{scripts}\n Accounts - #{accounts}\n Characters - #{characters}\n Total Objects - #{rooms+objs+characters+accounts+scripts}\n Highest OID in use - #{@dbtop}\n---* *---\n[/COLOR]\nEOD\n end", "def list_stats\r\n puts \"#{@name} Stats:\"\r\n puts \"Total HP: #{@hp}\"\r\n puts \"Class: #{@job}\"\r\n puts \"Total Strength: #{@strength}\"\r\n puts \"Total Speed: #{@speed}\"\r\n end", "def summary\n report = raw_summary\n\n ret = \"\"\n report.keys.sort_by(&:to_s).each do |key|\n ret += \"#{Puppet::Util::Metric.labelize(key)}:\\n\"\n\n report[key].keys.sort { |a,b|\n # sort by label\n if a == TOTAL\n 1\n elsif b == TOTAL\n -1\n else\n report[key][a].to_s <=> report[key][b].to_s\n end\n }.each do |label|\n value = report[key][label]\n next if value == 0\n value = \"%0.2f\" % value if value.is_a?(Float)\n ret += \" %15s %s\\n\" % [Puppet::Util::Metric.labelize(label) + \":\", value]\n end\n end\n ret\n end", "def print_details( result_counts, score )\n puts ('=' * 10) << \"\\n\"\n @groups.each_with_index { |group, index| group.each { |row| puts \"#{row} Group \" << (index + 1).to_s } }\n puts '-' * (@groups[0][0].length * 3)\n puts \"#{result_counts} Score\"\n puts \"\\nTotal Score: #{score}\\n\"\n end", "def print_stats\n puts \"==================================================\"\n puts \"================= Statistics =====================\"\n puts \"==================================================\"\n \n calc_stats()\n \n puts \"Total Records = #{@total_rec_cnt}\"\n puts \"Well Formed Records = #{@well_formed_rec_cnt}\"\n puts \"Malformed Records = #{@malformed_rec_cnt}\"\n puts \"Unique Business Records = #{@biz_rec_cnt}\"\n puts \"Unique User Records = #{@user_rec_cnt}\"\n puts \"\"\n end", "def get_stats_for_one(stat_entries, id)\n arr = stat_entries.extract(id)\n {max: arr.max, min: arr.min, avg: arr.avg, median: arr.median, stddev: arr.stddev}\n end", "def summary_from_metadata\n messages = self.summary_messages_from_metadata\n return \"#{self.user.name} #{summary_messages_from_metadata.join(', ')}\".gsub(/\\s+/,' ')\n end", "def summarize_results(results)\n sort_order = ['scenario', 'step', 'failed', 'flaky', 'undefined', 'skipped', 'pending', 'passed']\n\n ['scenario', 'step'].map do |group|\n group_results = results.grep(/^\\d+ #{group}/)\n next if group_results.empty?\n\n sums = sum_up_results(group_results)\n sums = sums.sort_by { |word, _| sort_order.index(word) || 999 }\n sums.map! do |word, number|\n plural = \"s\" if (word == group) && (number != 1)\n \"#{number} #{word}#{plural}\"\n end\n \"#{sums[0]} (#{sums[1..-1].join(\", \")})\"\n end.compact.join(\"\\n\")\n end", "def summary\n {}\n end", "def _ilo_progress_summary(data)\n result = {}\n\n learning_outcomes.each do |ilo|\n if data.nil?\n lower_value = upper_value = median_value = min_value = max_value = 0\n else\n values = data.map { |e| (e.has_key? ilo.id) ? e[ilo.id] : 0 }\n values = values.sort\n\n if values.length % 2 == 0\n median_value = ((values[values.length / 2] + values[values.length/2 - 1]) / 2.0).round(1)\n else\n median_value = values[values.length / 2]\n end\n\n lower_value = values[values.length * 3 / 10]\n upper_value = values[values.length * 8 / 10]\n min_value = values.first\n max_value = values.last\n end\n\n result[ilo.id] = {\n median: median_value,\n lower: lower_value,\n upper: upper_value,\n min: min_value,\n max: max_value\n }\n end\n\n result\n end", "def stats\n {\n 'Living souls' => souls.where(alive: true).count,\n 'Dead souls' => souls.where(alive: false).count,\n 'Free souls' => players.sum(:free_souls),\n 'Players' => players.count,\n 'Rocks' => souls.where(alive: true, role: 'rock').count,\n 'Papers' => souls.where(alive: true, role: 'paper').count,\n 'Scissors' => souls.where(alive: true, role: 'scissor').count,\n 'Giants' => souls.where(alive: true, role: ['rock giant', 'paper giant', 'scissors giant']).count,\n 'Dragons' => souls.where(alive: true, role: ['rock dragon', 'paper dragon', 'scissors dragon']).count,\n 'Average soul age' => souls.average(:age).to_i\n }\n end", "def summarize_reports(places, range)\n stats = {}\n \n places.each do |place|\n \treports = place.reports(range)\n \t\n \tstats[place.title] = {\n \t\t:mod_mal => percentage(reports, :malnourished?, :moderate),\n \t\t:sev_mal => percentage(reports, :malnourished?, :severe),\n \t\t:oedema => percentage(reports, :oedema),\n \t\t:diarrhea => percentage(reports, :diarrhea)\n \t}\n end\n \n stats\n end", "def stats\n return self.endpoint.stats(self.id)\n end", "def total_summary\n\n products = {}\n products.store(:item_cost, item_cost)\n products.store(:extras_cost, extras_cost)\n\n supplements = {}\n supplements.store(:pick_up_place, pickup_place_cost)\n supplements.store(:return_place, return_place_cost)\n supplements.store(:time_from_cost, time_from_cost)\n supplements.store(:time_to_cost, time_to_cost)\n supplements.store(:driver_age_cost, driver_age_cost)\n supplements.store(:category_supplement_1, category_supplement_1_cost)\n supplements.store(:category_supplement_2, category_supplement_2_cost)\n supplements.store(:category_supplement_3, category_supplement_3_cost)\n supplements.store(:supplement_1, supplement_1_cost)\n supplements.store(:supplement_2, supplement_2_cost)\n supplements.store(:supplement_3, supplement_3_cost)\n\n deposit = {}\n deposit.store(:product_deposit_cost, product_deposit_cost)\n\n totals = {}\n totals.store(:total_cost, total_cost)\n totals.store(:total_paid, total_paid)\n totals.store(:total_pending, total_pending)\n\n summary = {products: products,\n supplements: supplements,\n deposit: deposit,\n totals: totals }\n\n end", "def get_full_ps_info(pid)\n ps_fullcmd = @ps_fullcmd_fmt % pid\n # p ps_fullcmd\n output = `#{ps_fullcmd}`\n return output\n end", "def stats\n end", "def stats\n end", "def single_response_summary(id)\n get(\"/response/#{id}\")\n end", "def dump_summary(summary)\n @output_hash[:version] = Inspec::VERSION\n @output_hash[:statistics] = {\n duration: summary.duration,\n }\n end", "def summarize\n {\n id: id,\n name: name,\n username: username,\n email: email,\n hashed_email: hashed_email,\n user_type: user_type,\n gender: gender,\n birthday: birthday,\n total_lines: total_lines,\n secret_words: secret_words,\n secret_picture_name: secret_picture.name,\n secret_picture_path: secret_picture.path,\n location: \"/v2/users/#{id}\",\n age: age,\n sharing_disabled: sharing_disabled?,\n }\n end", "def show\n @logsbygame = Log.joins(:player_scores).where(game_id: @log.game).pluck(:score, :pcount)\n @logpoints = PlayerScore.joins(:log).where(log_id: @log.id).pluck(:score, :pcount)\n @sum = @logsbygame + @logpoints\n end", "def summary\n @data['summary']\n end", "def stats\n \n end", "def output_summary\n output_summary = \"\"\n unless $matches_played.empty?\n output_summary << \"Team | MP | W | D | L | P \"\n output_summary << \" \\n \"\n\n # sorting the results on the basis of points if points are greater than 0\n $points = $points.sort.to_h\n $points.each do |team, val|\n output_summary << \"#{team} | #{$matches_played[team]} | #{$wins[team] || 0} | #{$draws[team] || 0} | #{$loses[team] || 0} | #{val || 0}\"\n output_summary << \" \\n \"\n end\n\n # finding teams with 0 points\n $matches_played.delete_if { |k,_| $points.key?(k) }\n\n # output the teams with 0 points\n $matches_played.each do |team, val|\n output_summary << \"#{team} | #{val} | #{$wins[team] || 0} | #{$draws[team] || 0} | #{$loses[team] || 0} | #{$points[team] || 0}\"\n output_summary << \" \\n \"\n end\n end\n output_summary\nend", "def stats\n Stats.all.inject({}) do |acc_hash, keyval|\n key, val = keyval\n acc_hash.merge(key => val[self.name])\n end\n end", "def statistics; end", "def stats\n\t\t@counts\n\tend", "def print_task_summary(taskid, names, callers, completed, running, task_not_known, wrapper_failure, success, fails, runtime, rpcstats)\n if callers.size > 1 || names.size > 1\n out.puts\n out.puts(\"%s received more than 1 task name or caller name for this task, this should not happen\" % Util.colorize(:red, \"WARNING\"))\n out.puts(\"happen in normal operations and might indicate forged requests were made or cache corruption.\")\n out.puts\n end\n\n out.puts(\"Summary for task %s\" % [Util.colorize(:bold, taskid)])\n out.puts\n out.puts(\" Task Name: %s\" % names.join(\",\"))\n out.puts(\" Caller: %s\" % callers.join(\",\"))\n out.puts(\" Completed: %s\" % (completed > 0 ? Util.colorize(:green, completed) : Util.colorize(:yellow, completed)))\n out.puts(\" Running: %s\" % (running > 0 ? Util.colorize(:yellow, running) : Util.colorize(:green, running)))\n out.puts(\" Unknown Task: %s\" % Util.colorize(:red, task_not_known)) if task_not_known > 0\n out.puts(\" Wrapper Failure: %s\" % Util.colorize(:red, wrapper_failure)) if wrapper_failure > 0\n out.puts\n out.puts(\" Successful: %s\" % (success > 0 ? Util.colorize(:green, success) : Util.colorize(:red, success)))\n out.puts(\" Failed: %s\" % (fails > 0 ? Util.colorize(:red, fails) : fails))\n out.puts\n out.puts(\" Average Run Time: %.2fs\" % [runtime / (running + completed)])\n\n if rpcstats.noresponsefrom.empty?\n out.puts\n out.puts rpcstats.no_response_report\n end\n\n if running > 0\n out.puts\n out.puts(\"%s nodes are still running, use 'mco tasks status %s' to check on them later\" % [Util.colorize(:bold, running), taskid])\n end\n end", "def stats\n ## TODO:\n end", "def results\n x = Profile.all.select { |profile| profile.user_id == self.id }\n k = x.map {|profile| profile[:name]}\n v = x.map do |profile|\n if profile[:sentiment_id] == 1\n \"Negative\"\n elsif profile[:sentiment_id] == 2\n \"Positive\"\n elsif profile[:sentiment_id] == 3\n \"Neutral\"\n end\n end\n hash = [k, v].transpose.to_h\n sleep(3)\n hash\n end", "def summaries\n plot_summaries.css(\"p.plotSummary\").map { |summary| summary.text.strip }\n end", "def parse_summary_stats(nokogiri)\n\n summary_stats = {}\n\n # Summary Stats.\n # Example:\n # <div class=\"spaceit_pad\"><span class=\"dark_text\">Watching:</span> 12,334</div>\n # <div class=\"spaceit_pad\"><span class=\"dark_text\">Completed:</span> 59,459</div>\n # <div class=\"spaceit_pad\"><span class=\"dark_text\">On-Hold:</span> 3,419</div>\n # <div class=\"spaceit_pad\"><span class=\"dark_text\">Dropped:</span> 2,907</div>\n # <div class=\"spaceit_pad\"><span class=\"dark_text\">Plan to Watch:</span> 17,571</div>\n # <div class=\"spaceit_pad\"><span class=\"dark_text\">Total:</span> 95,692</div>\n\n left_column_nodeset = nokogiri.xpath('//div[@id=\"content\"]/table/tr/td[@class=\"borderClass\"]')\n\n if (node = left_column_nodeset.at('//span[text()=\"Reading:\"]')) && node.next\n summary_stats[:in_progress] = node.next.text.strip.gsub(',','').to_i\n end\n if (node = left_column_nodeset.at('//span[text()=\"Completed:\"]')) && node.next\n summary_stats[:completed] = node.next.text.strip.gsub(',','').to_i\n end\n if (node = left_column_nodeset.at('//span[text()=\"On-Hold:\"]')) && node.next\n summary_stats[:on_hold] = node.next.text.strip.gsub(',','').to_i\n end\n if (node = left_column_nodeset.at('//span[text()=\"Dropped:\"]')) && node.next\n summary_stats[:dropped] = node.next.text.strip.gsub(',','').to_i\n end\n if (node = left_column_nodeset.at('//span[text()=\"Plan to Read:\"]')) && node.next\n summary_stats[:planned] = node.next.text.strip.gsub(',','').to_i\n end\n if (node = left_column_nodeset.at('//span[text()=\"Total:\"]')) && node.next\n summary_stats[:total] = node.next.text.strip.gsub(',','').to_i\n end\n\n summary_stats\n end", "def stats\n {:money => @money , :life => @life, :fights => @fights, :respect => @respect, :state => @state.id, :substate => @state.state.id}\n end", "def add_stats(_stats)\n _stats.each do |e|\n self.add_stat(e)\n end\n end", "def dump_summary *args\n return unless iterm?\n\n if args.count == 4\n notification = Struct.new(:duration, :example_count, :failure_count, :pending_count).new *args\n else\n notification = args.first\n end\n _dump_summary notification\n p @error_message if @error_message\n end", "def summarize_suite(suite, tests)\n summary = Hash.new(0)\n summary[:name] = suite.to_s\n tests.each do |test|\n summary[:\"#{result(test)}_count\"] += 1\n summary[:assertion_count] += test.assertions\n summary[:test_count] += 1\n summary[:time] += test.time\n end\n summary[:has_errors_or_failures] = (summary[:fail_count] + summary[:error_count]) > 0\n summary[:has_skipps] = summary[:skip_count] > 0\n summary\n end", "def summary(results, session_count)\n # header\n method = :ok\n headers = [\"Total: #{session_count}\"]\n messages = []\n\n headers << \"Ok: #{results[:ok].size}\" unless results[:ok].empty?\n\n [:warning, :critical].each do |type|\n next if results[type].empty?\n method = type\n label = type.to_s.capitalize\n headers << \"#{label}: #{results[type].size}\"\n messages << [label, results[type].compact.sort.join(\"\\n\\n\")]\n end\n\n [method, [headers, messages].flatten]\n end", "def summary\n {\n length: @length,\n width: @width,\n perimeter: @perimeter,\n area: @ area\n }\nend", "def summarise()\n summary = Hash.new\n page_count = 0\n\n @nodes.each {|node|\n if summary.include?(node['content_type'])\n summary[node['content_type']] += 1\n else\n summary[node['content_type']] = 1\n end\n }\n\n summary.keys.sort.each {|node_type|\n count = summary[node_type].to_i\n page_count += count\n puts \"%-50s: %s\" % [node_type, count]\n }\n\n puts \"%-50s: %s\" % ['Total pages:', page_count]\n puts \"See output CSV in #{csv_output_path}\"\n end", "def stats\n users.stats.to_a.map { |row| { name: (row.fullname || row.username).strip, progress: \"#{'+' * row.count } (#{row.count})\" } }\n end", "def aggregate profile_name, interface=nil\n extend TCD::Common\n count=0\n Dir.glob(File.expand_path(\"~/.tcd/stats/#{profile_name}/#{interface || '*'}/*\")).each {|path|\n next unless TCD::Profiles.needsAggregating(path)\n day= getDateFromPath(path)\n interface= File.basename(File.dirname(path))\n stats= TCD::Storage.readStats(profile_name, interface) {|p| TCD::Profiles.isDay(day,p) }\n in_sum= out_sum= 0\n stats[:in].each {|size, date| in_sum+=size }\n stats[:out].each {|size, date| out_sum+=size }\n stats[:in]= [[in_sum, :sum]] + stats[:in]\n stats[:out]=[[out_sum,:sum]] + stats[:out]\n writeFile YAML.dump(stats), '00-00-00_aggr.txt', path+'/'\n TCD::Storage.postAggDeletion( path )\n count+=1\n }\n count\n end", "def stats; end", "def stats; end", "def summary(value)\n merge(summary: value.to_s)\n end", "def summary(value)\n merge(summary: value.to_s)\n end", "def getPokemonStat \n @hp = JSON.parse(@random_pokemon.body)[\"stats\"][0][\"base_stat\"]\n @attack = JSON.parse(@random_pokemon.body)[\"stats\"][1][\"base_stat\"]\n @defense = JSON.parse(@random_pokemon.body)[\"stats\"][2][\"base_stat\"]\n @sp_atk = JSON.parse(@random_pokemon.body)[\"stats\"][3][\"base_stat\"]\n @sp_def = JSON.parse(@random_pokemon.body)[\"stats\"][4][\"base_stat\"]\n @speed = JSON.parse(@random_pokemon.body)[\"stats\"][5][\"base_stat\"]\n\n @base_stat_total = @hp + @attack + @defense + @sp_atk + @sp_def + @speed \n end", "def summary\n authenticated_post(\"summary\").body\n end", "def summary(args, options)\n\n experiments = options.experiments.split(',')\n machines = options.machines.split(',')\n\n data = Ppbench::load_data(args)\n filtered_data = Ppbench::filter(\n data,\n experiments: experiments,\n machines: machines\n )\n aggregated_data = Ppbench::aggregate(filtered_data)\n\n rows = []\n aggregated_data.each do |experiment, machines|\n machines.each do |machine, data|\n mtr = data.map { |e| e[:transfer_rate] }.median / 1000 # median transfer rate\n tpr = data.map { |e| e[:tpr] }.median # median round trip latency\n rps = 1000 / tpr # median request per second\n\n rows << [experiment, machine, data.count, \"%.2f\" % mtr, \"%.2f\" % rps, \"%.2f\" % tpr]\n end\n rows << :separator\n end\n rows.pop\n\n print(\"We have data for: \\n\")\n table = Terminal::Table.new(:headings => ['Experiment', 'Machine', 'Samples', 'Transfer (kB/s)', \"Requests/sec\", \"Latency (ms)\"], :rows => rows)\n table.align_column(2, :right)\n table.align_column(3, :right)\n table.align_column(4, :right)\n table.align_column(5, :right)\n print(\"#{table}\\n\")\nend", "def roll_dice_and_process(player_id,roll_count,total_score)\n player_rolls = roll(roll_count)\n remaining_elements , roll_score = get_score(player_rolls)\n total_score[player_id] += roll_score\n puts \"Player #{player_id} rolls: #{player_rolls}\"\n puts \"Score in this round: #{roll_score}\"\n [remaining_elements,roll_score]\nend", "def stats(id)\n request(:get, \"/users/#{id}/vm_stats.json\")\n end", "def summary\n score = Hash.new 0\n\n masses.each do |hash, mass|\n sexps = hashes[hash]\n mass_per_file = mass.to_f / sexps.size\n sexps.each do |sexp|\n score[sexp.file] += mass_per_file\n end\n end\n\n score\n end", "def metrics\n with_stats_lock do\n @stats_hash.keys.map { |spec| spec.to_s }\n end\n end", "def add_statistics stats_arr\n stats_arr.each do |stats|\n add_statistic stats\n end\n return\n end" ]
[ "0.61231524", "0.6025786", "0.6012312", "0.5933369", "0.5794421", "0.5773226", "0.57561785", "0.5745157", "0.5728771", "0.5668581", "0.5663509", "0.5642775", "0.56234944", "0.56234944", "0.55735254", "0.5525645", "0.5514889", "0.54742026", "0.5460928", "0.545071", "0.54444134", "0.54444134", "0.5443141", "0.5420887", "0.5420887", "0.5420887", "0.5420887", "0.54193306", "0.5405669", "0.54018545", "0.5386651", "0.5384471", "0.53785974", "0.5350412", "0.53444153", "0.5301407", "0.52970916", "0.527056", "0.5259252", "0.5255564", "0.52379525", "0.5235538", "0.52344066", "0.5234211", "0.5223196", "0.52160287", "0.5207735", "0.51995194", "0.5183867", "0.5162833", "0.5160068", "0.5153894", "0.5146773", "0.51455593", "0.51453745", "0.5139717", "0.51367867", "0.5132187", "0.5121468", "0.51195437", "0.5117962", "0.5112859", "0.51117647", "0.51117647", "0.510733", "0.51056826", "0.50962734", "0.5091392", "0.507512", "0.50735444", "0.50716686", "0.5069898", "0.50590813", "0.5054269", "0.50496805", "0.5049407", "0.5046263", "0.50454247", "0.50445", "0.504096", "0.50392157", "0.50283444", "0.50272346", "0.50270355", "0.50243306", "0.5022141", "0.5020607", "0.5020387", "0.5013028", "0.5013028", "0.5011991", "0.5011991", "0.5007673", "0.49894452", "0.49892238", "0.49849987", "0.49797568", "0.49790266", "0.4975945", "0.49712956" ]
0.52312607
44
Perform the monitoring checks.
def run( nodes ) super do |host, snmp| self.check_battery( host, snmp ) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def check_monitoring\n @servers.each do |server|\n obj_behavior(server, :settings)\n response = nil\n count = 0\n until response || count > 20 do\n begin\n response = obj_behavior(server, :monitoring)\n rescue\n response = nil\n count += 1\n sleep 10\n end\n end\n raise \"Fatal: Failed to verify that monitoring is operational\" unless response\n#TODO: pass in some list of plugin info to check multiple values. For now just\n# hardcoding the cpu check\n unless server.multicloud\n sleep 180 # This is to allow monitoring data to accumulate\n monitor = obj_behavior(server, :get_sketchy_data, {'start' => -60,\n 'end' => -20,\n 'plugin_name' => \"cpu-0\",\n 'plugin_type' => \"cpu-idle\"})\n idle_values = monitor['data']['value']\n raise \"No cpu idle data\" unless idle_values.length > 0\n raise \"CPU idle time is < 0: #{idle_values}\" unless idle_values[0] > 0\n puts \"Monitoring is OK for #{server.nickname}\"\n end\n end\n end", "def check_monitoring\n @servers.each do |server|\n server.settings\n response = nil\n count = 0\n until response || count > 20 do\n begin\n response = server.monitoring\n rescue\n response = nil\n count += 1\n sleep 10\n end\n end\n raise \"Fatal: Failed to verify that monitoring is operational\" unless response\n#TODO: pass in some list of plugin info to check multiple values. For now just\n# hardcoding the cpu check\n sleep 60 # This is to allow monitoring data to accumulate\n monitor=server.get_sketchy_data({'start'=>-60,'end'=>-20,'plugin_name'=>\"cpu-0\",'plugin_type'=>\"cpu-idle\"})\n idle_values = monitor['data']['value']\n raise \"No cpu idle data\" unless idle_values.length > 0\n raise \"No idle time\" unless idle_values[0] > 0\n puts \"Monitoring is OK for #{server.nickname}\"\n end\n end", "def check\n megamgw_health\n #megamceph_health\n overall\n end", "def check(events)\n if !@check_warning_notified\n puts \"[NOTICE] Inherit from FileMonitor and override method check(events) or\\n use file_monitor_instance.run do|events| end to do anything when any file changes\"\n @check_warning_notified = true\n end\n end", "def check_passenger_monitoring\n passenger_plugins = [\n {\"plugin_name\"=>\"passenger\", \"plugin_type\"=>\"passenger_instances\",\"field\"=>\"value\"},\n {\"plugin_name\"=>\"passenger\", \"plugin_type\"=>\"passenger_processes\",\"field\"=>\"max\"},\n {\"plugin_name\"=>\"passenger\", \"plugin_type\"=>\"passenger_queued\",\"field\"=>\"value\"},\n {\"plugin_name\"=>\"passenger\", \"plugin_type\"=>\"passenger_requests\",\"field\"=>\"value\"}\n ]\n sleep 60 # wait for some data to be available\n @servers.each do |server|\n unless server.multicloud\n#passenger commands to generate data for collectd to return\n# for ii in 1...100\n# # how do we force there to be data?? For now just check that the graph exists - cause the\n# # bug was missing graphs.\n# end\n passenger_plugins.each do |plugin|\n monitor = obj_behavior(server, :get_sketchy_data, {'start' => -60,\n 'end' => -20,\n 'plugin_name' => plugin['plugin_name'],\n 'plugin_type' => plugin['plugin_type']})\n value = monitor['data'][\"#{plugin['field']}\"]\n puts \"Checking #{plugin['plugin_name']}-#{plugin['plugin_type']}: value #{value}\"\n raise \"No #{plugin['plugin_name']}-#{plugin['plugin_type']} data\" unless value.length > 0\n# # Need to check for that there is at least one non 0 value returned.\n# for nn in 0...value.length\n# if value[nn] > 0\n# break\n# end\n# end\n# raise \"No #{plugin['plugin_name']}-#{plugin['plugin_type']} time\" unless nn < value.length\n puts \"Monitoring is OK for #{plugin['plugin_name']}-#{plugin['plugin_type']}\"\n end\n end\n end\n end", "def checks; end", "def evaluate_checks\n log.info(\"Evaluating Checks: '#{@config['checks'].length}'\")\n\n @config['checks'].each do |check|\n check_name = check['check']\n check_cfg = check['cfg']\n\n collect_metrics(check_name, check_cfg).each do |metric|\n status = 0\n\n # on service it will come with \"state_required\" flag\n if check_name == 'service'\n # adding defaults in case they are not set\n check_cfg = check_cfg.merge(\n 'state' => 'active',\n 'state_required' => 1\n )\n # giving a service hint by adding it's name\n check_name = \"service_#{check_cfg['name']}\"\n status = equals(metric['value'], check_cfg['state_required'])\n else\n # normal threshold evaluation\n status = evaluate(\n metric['value'],\n check_cfg['warn'],\n check_cfg['crit']\n )\n end\n\n template_variables = metric\n template_variables['cfg'] = check_cfg\n\n append_event(\n \"check_#{check_name}\",\n @tmpl.render(check['check'], template_variables),\n status,\n metric['source']\n )\n end\n end\n end", "def run\n evaluate_checks if @config.key?('checks')\n evaluate_custom if @config.key?('custom')\n evaluate_and_dispatch_events\n end", "def run_checks\n # check that backup cron script exits success\n [s_one, s_two].each do |server|\n chk1 = probe(server, \"/usr/local/bin/pgsql-binary-backup.rb --if-master --max-snapshots 10 -D 4 -W 1 -M 1 -Y 1\")\n \n chk2 = probe(server, \"/usr/local/bin/pgsql-binary-backup.rb --if-slave --max-snapshots 10 -D 4 -W 1 -M 1 -Y 1\")\n \n raise \"CRON BACKUPS FAILED TO EXEC, Aborting\" unless (chk1 || chk2) \n end\n end", "def run\n checks.each(&:run)\n end", "def monitor; end", "def run\n require File.expand_path(\"../#{config[:check]}\", $PROGRAM_NAME)\n\n threads.each(&:join)\n\n puts status_information unless status_information.empty?\n summarize!\n end", "def monitor_process( *processes )\n options = processes.extract_options!\n options.symbolize_keys!\n\n processes.each do |process_name|\n monitor_name = \"check_process_#{process_name.to_s.underscore}\".to_sym\n class_eval <<-END_SRC, __FILE__, __LINE__\ndef #{monitor_name}\n process_health( #{process_name.inspect}, monitored_features[#{monitor_name.inspect}] )\nend\nEND_SRC\n\n monitor_health monitor_name, options\n end\n end", "def monitor\n raise ArgumentError, MONITOR_PARAMS if monitor_params_missing?\n loop do \n sleep minutesInterval.minutes\n if notify? \n books_report \n exit\n end\n end\n end", "def start_monitor!\n begin\n trap(\"INT\") do\n on_exit\n exit\n end\n # Daemonize only if we are not in the test environment\n run_thread_loop(:daemonize => !Application.test?) do\n add_task {PoolParty.message \"Checking cloud\"}\n add_task {launch_minimum_instances}\n add_task {reconfigure_cloud_when_necessary}\n add_task {scale_cloud!}\n add_task {check_stats}\n end\n rescue Exception => e\n Process.kill(\"HUP\", Process.pid)\n end\n end", "def perform_checks\n # tests & checks are only meaningful if the input can be varied\n return unless @input_can_change\n @checks.each_with_index do |check, i|\n output, time, error = run_with_benchmark(check[:input])\n @checks[i].merge!({ output: output, time: time, error: error })\n end\n @checks\n end", "def perform!\n log_start\n check_all\n store_audit_results\n notify_if_failed\n delete_stale_reports\n log_end\n end", "def check\n puts\n puts \"Load Apache Balancer-Manager at '#{@balancer_manager_url}'\"\n puts\n puts \"Loading Details\"\n puts\n puts \" Balancer: #{get_balancer_manager.balancer_name}\"\n puts\n get_balancer_manager.hosts_with_status.each{|h,s| puts \" #{h} => #{s}\"}\n\n @live_hosts = get_balancer_manager.enabled_hosts\n puts\n puts \"Checking #{@live_hosts.size} live hosts\"\n puts\n\n @live_hosts.each do |host, state|\n status = check_host(host, @test_page)\n puts \" #{host} is #{status ? 'OK' : 'not responsive. Disabling via BalancerManager.'}\"\n disable_host(host) if !status\n end\n puts\n puts \"#{@live_hosts.size}/#{get_balancer_manager.hosts.size} hosts are enabled\"\n puts\n end", "def run\n # Run all the steps below. Stop as soon as one of them returns\n # false or throws an error.\n true &&\n fetch_internal_date_and_size &&\n check_for_really_old_internal_date &&\n check_for_pre_creation_internal_date &&\n check_for_relapsed_internal_date &&\n check_for_big_messages &&\n fetch_uid_envelope_rfc822 &&\n update_user_mark_email_processed &&\n handle_tracer_email &&\n check_for_duplicate_message_id &&\n check_for_duplicate_sha1 &&\n create_mail_log &&\n deploy_webhook &&\n update_daemon_stats\n ensure\n clean_up\n end", "def check_stats\n str = registered_monitors.collect {|m| \"#{m}\"}\n PoolParty.message \"Monitors: #{str.join(\", \")}\"\n end", "def check_db_monitoring\n db_plugins = [\n {\"plugin_name\"=>\"postgresql-i_heart_monkey\", \"plugin_type\"=>\"pg_n_tup_c-del\"},\n {\"plugin_name\"=>\"postgresql-i_heart_monkey\", \"plugin_type\"=>\"pg_n_tup_c-ins\"},\n {\"plugin_name\"=>\"postgresql-i_heart_monkey\", \"plugin_type\"=>\"pg_n_tup_c-upd\"}\n ]\n [s_one, s_two].each do |server|\n unless server.multicloud\n # PostgreSQL commands to generate data for collectd to return\n for ii in 1...100\n #TODO: have to select db with every call. figure a better way to do this and get rid of fast and ugly\n # cut and past hack.\n run_query(\"create table test#{ii}(test text); insert into test#{ii} values ('1'); update test#{ii} set test='2'; select * from test#{ii}; delete from test#{ii};\", server, \"i_heart_monkey\")\n # run_query(\"insert into test#{ii} values ('1')\", server, \"i_heart_monkey\")\n # run_query(\"update test#{ii} set test='2'\", server, \"i_heart_monkey\")\n # run_query(\"select * from test#{ii}\", server, \"i_heart_monkey\")\n # run_query(\"delete from test#{ii}\", server, \"i_heart_monkey\")\n end\n db_plugins.each do |plugin|\n monitor = obj_behavior(server, :get_sketchy_data, {'start' => -60,\n 'end' => -20,\n 'plugin_name' => plugin['plugin_name'],\n 'plugin_type' => plugin['plugin_type']})\n value = monitor['data']['value']\n raise \"No #{plugin['plugin_name']}-#{plugin['plugin_type']} data\" unless value.length > 0\n # Need to check for that there is at least one non 0 value returned.\n for nn in 0...value.length\n if value[nn] > 0\n break\n end\n end\n raise \"No #{plugin['plugin_name']}-#{plugin['plugin_type']} time\" unless nn < value.length\n puts \"Monitoring is OK for #{plugin['plugin_name']}-#{plugin['plugin_type']}\"\n end\n end\n end\n end", "def run_checks\n # check that mysql tmpdir is custom setup on all servers\n query = \"show variables like 'tmpdir'\"\n query_command = \"echo -e \\\"#{query}\\\"| mysql\"\n @servers.each do |server|\n server.spot_check(query_command) { |result| raise \"Failure: tmpdir was unset#{result}\" unless result.include?(\"/mnt/mysqltmp\") }\n end\n end", "def check_status!\n events\n if should_be_offline?\n if online?\n events.create!(key: :offline).notify\n update_attribute(:online, false)\n end\n else # should be online\n if offline?\n events.create!(key: :online).notify\n update_attribute(:online, true)\n end\n end\n if low_balance?\n events.create!(key: :low_balance).notify if online?\n end\n end", "def ensure_running\n agent_status = `service logicmonitor-agent status`\n if agent_status.include?(\"not running\")\n puts \"LogicMonitor collector isn't running\"\n puts `service logicmonitor-agent start`\n else\n puts \"LogicMonitor collector is running\"\n end\n\n watchdog_status = `service logicmonitor-watchdog status`\n if watchdog_status.include?(\"not running\")\n puts \"LogicMonitor watchdog isn't running\"\n puts `service logicmonitor-watchdog start`\n end\nend", "def run_check\n Railroader.debug \"Finding system calls using ``\"\n check_for_backticks tracker\n\n check_open_calls\n\n Railroader.debug \"Finding other system calls\"\n calls = tracker.find_call :targets => [:IO, :Open3, :Kernel, :'POSIX::Spawn', :Process, nil],\n :methods => [:capture2, :capture2e, :capture3, :exec, :pipeline, :pipeline_r,\n :pipeline_rw, :pipeline_start, :pipeline_w, :popen, :popen2, :popen2e,\n :popen3, :spawn, :syscall, :system], :nested => true\n\n Railroader.debug \"Processing system calls\"\n calls.each do |result|\n process_result result\n end\n end", "def run()\n # first see if we should just exit\n if !ec2_user_data('disable', '').empty?\n info \"disable flag is set, so returning...\\n\\n\"\n return\n end\n\n run_pre_scripts\n\n is_monitor = provides.include?('monitor')\n \n # evaluate our actions\n # this is important as it can both notify us of errors early on,\n # and it also allows the actions to perform any initialization code\n actions\n\n if is_monitor\n monitor_thread = monitor()\n ## TODO: don't just leave this thread dangling, \n ## do something if it crashes!\n end\n \n listener_thread = subscribe(subscribes, instance_id, 10)\n\n # even if we're a monitor, we may provide some other services as well.\n avail_thread = broadcast_availability(provides, 3)\n\n sleep 3\n run_post_scripts\n\n # keep listening...\n listener_thread.join if listener_thread\n avail_thread.join if avail_thread\n end", "def run_syscheck_all_agents\n put '/syscheck'\n end", "def run_checks\n @checks = Brakeman::Checks.run_checks(self)\n end", "def check!\n check_existence! && check_installed! && run_scanner!\n end", "def run_check\n check_for_default_routes\n check_for_action_globs\n check_for_cve_2014_0130\n end", "def init_uptime_checks\n keys = @db[:keys].where(key_type: 'uptime').each do |k|\n name = k[:name]\n time, value = last(name)\n bump_uptime(name, get_key(name)) if value == true\n end\n end", "def check\n \n end", "def check\n \n end", "def run\n logger = EzNemo.logger\n ds = EzNemo.datastore\n\n Signal.trap('INT') do\n puts 'Interrupted.'\n ds.flush\n exit\n end\n\n Signal.trap('SIGTERM') do\n puts 'Stopping...'\n ds.flush\n exit\n end\n \n EM.run do\n logger.debug 'Loading checks...'\n EzNemo.monitor.start_checks(ds.checks)\n ds.start_loop\n end\n end", "def run_reboot_checks\n # one simple check we can do is the backup. Backup can fail if anything is amiss\n @servers.each do |server|\n run_script(\"do_backup\", server)\n end\n end", "def process\n return if self.metrics.nil? # failed reports may have no metrics? be safe.\n changes = self.metrics['changes']['total']\n\n if changes > 0\n epochtime = Time.now.utc.to_i\n host_as_underscores = self.host.gsub(/\\./, '_')\n name = \"#{PATH_PREFIX}.#{host_as_underscores}\" \n\n send_metric \"#{name} #{changes} #{epochtime}\"\n end\n end", "def leader_monitoring(monitor_function)\n\n puts \"#{MY_IP} is the leader\"\n \n # Do monitoring\n deads = []\n vm_ips, vm_ip_roles, vm_img_roles = obtain_vm_data(@resource)\n vm_ips.each do |vm|\n puts \"Monitoring #{vm}...\"\n unless @vm_manager.monitor_vm(vm, vm_ip_roles, monitor_function)\n deads << vm\n end\n puts \"...Monitored\"\n end\n \n # Check pool of physical machines\n pm_up, pm_down = check_pool()\n \n if deads.count == 0\n puts \"==========================\"\n puts \"== Cloud up and running ==\"\n puts \"==========================\"\n else\n # Raise again the dead machines\n deads.each do |vm|\n @vm_manager.start_vm(vm, vm_ip_roles, vm_img_roles, pm_up)\n end\n end\n \n end", "def scan()\n scanConfig() ;\n scanTrailLog() ;\n analyzeDemandLog() ;\n end", "def monitor\n summary = @host.summary\n hardware = summary.hardware\n stats = summary.quickStats\n\n @cpuModel = hardware.cpuModel\n @cpuMhz = hardware.cpuMhz\n\n @total_cpu = hardware.numCpuCores*100\n @used_cpu = (stats.overallCpuUsage.to_f / @cpuMhz.to_f) * 100\n @used_cpu = sprintf('%.2f', @used_cpu).to_f # Trim precission\n\n @total_memory = hardware.memorySize/1024\n @used_memory = stats.overallMemoryUsage*1024\n\n net = VIDriver::retrieve_stats([@host],\n [\"net.packetsRx\",\"net.packetsTx\"])\n @net_rx = 0\n @net_tx = 0\n\n if net[@host] && net[@host][:metrics]\n if net[@host][:metrics][\"net.packetsRx\"]\n @net_rx = net[@host][:metrics][\"net.packetsRx\"].first\n end\n\n if net[@host][:metrics][\"net.packetsTx\"]\n @net_tx = net[@host][:metrics][\"net.packetsTx\"].first\n end\n end\n\n # Check for negative values\n @used_memory = 0 if @used_memory.to_i < 0\n @used_cpu = 0 if @used_cpu.to_i < 0\n @net_rx = 0 if @net_rx.to_i < 0\n @net_tx = 0 if @net_tx.to_i < 0\n\n # Check free datastore space\n @free_ds_info = VIDriver::retrieve_free_ds(@host)\n end", "def monitor\n raise NotImplementedError\n end", "def check_status\n logger.debug { \"#{self.class}##{__method__}\" }\n mutex = Mutex.new\n running_agents = []\n self.visit_clusterables do |cluster_instance|\n agents = cluster_instance.check_status\n mutex.synchronize { running_agents.push(*agents) } unless agents.empty?\n end\n running_agents\n end", "def call_start_monitoring\n start_monitoring\n self.save!\n rescue StandardError => e\n logger.error(e.message)\n raise\n end", "def do_work\n scan!\n server.scan_semaphore.wait(server.cluster.heartbeat_interval)\n end", "def check\n refresh\n primary_status = self.primary_status\n secondary_status = self.secondary_status\n mark_message \"Connected to #{session.cluster.nodes.count} nodes in mongodb replica set '#{primary_status['set']}'\"\n rescue ConnectionFailed => e\n mark_failure\n mark_message \"Error: '#{e}'\"\n end", "def report\n if data[:ping].nil?\n @fails += 1\n if @fails >= @alert_after\n alarm \"Miner #{@num} did not respond to status query\"\n end\n else\n @fails = 0\n if self[:mhs] < @min_speed*0.95 and upminutes > 5\n alarm \"Miner #{@num} performance is #{self[:mhs]}, should be #{@min_speed}\"\n elsif upminutes < 2\n alarm \"Miner #{@num} restarted\", \"Frog.aiff\"\n end\n end\n end", "def run_reboot_checks\n # one simple check we can do is the backup. Backup can fail if anything is amiss\n [s_one, s_two].each do |server|\n run_script(\"backup\", server)\n end\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 nagios_check!\n exit nagios_check\n end", "def monitor_system\n if @is_fire || @is_power_outage || @is_mechanical_failure\n \n @status = \"offline\"\n for column in @column_list do\n column.status = \"offline\"\n for elevator in column.elevator_list do\n elevator.status = \"offline\"\n end\n end\n puts \"Battery #{@id} has been shut down for maintenance. Sorry for the inconvenience\"\n exit()\n end\n end", "def run_all\n fail \"no scanner opts (start not called?)!\" if @scanner_opts.nil?\n tracker.run_checks\n ::Brakeman.filter_warnings tracker, @scanner_opts\n print_failed\n throw :task_has_failed if tracker.filtered_warnings.any?\n end", "def health_check\n puts 'Performing health check containers'\n puts Open3.capture3(\"pushd #{dot_futureadvisor} 2>&1; ./bin/container_health_check.rb 2>&1; popd 2>&1\")\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 healthchecks\n write_test = Add.write_test\n detect_infected = Scan.healthcheck_infected\n clean_file = Scan.healthcheck_clean\n service_status = if write_test && detect_infected && clean_file\n 'ok'\n else\n 'failed'\n end\n {\n service_status: service_status,\n write_test: write_test ? 'ok' : 'failed',\n detected_infected_file: detect_infected ? 'ok' : 'failed',\n passed_clean_file: clean_file ? 'ok' : 'failed'\n }\n end", "def run_elb_checks\n run_unified_application_check(elb_href, ELB_PORT)\n end", "def evaluate_and_dispatch_events\n non_successful_events = []\n\n @events.reverse_each do |event|\n # skipping events that are not whitelisted\n if @config['config'].key?('whitelist') && event['source'] !~ /#{@config['config']['whitelist']}/\n @events.delete(event)\n log.debug(\n \"Skipping event! Source '#{event['source']}' does not \" \\\n \"match /#{@config['config']['whitelist']}/\"\n )\n next\n end\n # removing source key to use local's sensu source name (hostname)\n if @config.key?('config') && \\\n @config['config'].key?('use_default_source') && \\\n @config['config']['use_default_source']\n log.debug(\"Removing 'source' from event, using Sensu's default\")\n event.delete('source')\n end\n # selecting the non-succesful events\n non_successful_events << event if event['status'] != 0\n # dispatching event to Sensu\n @dispatcher.dispatch(event)\n end\n\n # setting up final status and output message\n amount_checks = @config['checks'].length + @config['custom'].length\n amount_events = @events.length\n\n if non_successful_events.empty?\n @status = 0\n @output = \\\n \"OK: Ran #{amount_checks} checks succesfully on #{amount_events} events!\"\n else\n log.debug(\"#{non_successful_events.length} failed events\")\n @status = 1\n non_successful_events.sort_by { |e| e['status'] } .reverse.each do |event|\n @output << ' | ' unless @output.empty?\n @output << \"Source: #{event['source']}, \" \\\n \"Check: #{event['name']}, \" \\\n \"Output: #{event['output']}, \" \\\n \"Status: #{event['status']}\"\n end\n end\n\n log.debug(\"Ran #{amount_checks}, and collected #{amount_events} events\")\n log.debug(\"Final Status: #{@status}\")\n log.debug(\"Final Output: #{@output}\")\n end", "def evaluate!\n eval_start = Time.now\n\n reset\n\n @@checks.each do |name,check|\n @status_code = [check.evaluate!, @status_code].max\n end\n\n @finished = Time.now.utc\n @ms = (Time.now - eval_start) * 1000\n\n if @@checks.size == 0\n @status = :unknown\n @status_code = self.class.valid_status_map[@status]\n else\n @status = self.class.valid_status_map.invert[@status_code]\n end\n end", "def check(*args)\n process_using(*args.unshift(:check))\n end", "def check\n # TODO check if should execute this(because of connection exception)\n if valid_check_interval? && Device::Network.connected? == Device::Network::SUCCESS\n if @fiber.alive?\n if (notification = @fiber.resume)\n Notification.execute(NotificationEvent.new(notification))\n end\n else\n if Device::Notification.create_fiber?(true)\n self.close\n @fiber = create_fiber\n end\n end\n @last_check = Time.now\n end\n end", "def require_recollect_status\n return @periodic_checker.fire\n end", "def execute\n \t@checkup = {}\n \tServices::Slog.debug({:message => \"Processing agent #{identifier}\", :module => \"Checkup\", :task => \"agent\", :extra => {:agent => identifier, :publisher => publisher}})\n\n \tcase publisher\n \twhen 'sql'\n \t\tbegin\n \t\t\t@d = Services::SQLDetector.new(identifier)\n \t\trescue Exception => e\n \t\t\tServices::Slog.exception e\n \t\t\t@response = {:status => 400, :error => e}\n \t\tend\n \twhen 'csv'\n \t\tbegin\n \t\t\t@d = Services::CSVDetector.new(identifier)\n \t\trescue Exception => e\n \t\t\tServices::Slog.exception e\n \t\t\t@response = {:status => 400, :error => e}\n \t\tend\n \twhen 'xml'\n \t\tbegin\n \t\t\t@d = Services::XMLDetector.new(identifier)\n \t\trescue Exception => e\n \t\t\tServices::Slog.exception e\n \t\t\t@response = {:status => 400, :error => e}\n \t\tend\n \twhen 'json'\n \t\tbegin\n \t\t\t@d = Services::JSONDetector.new(identifier)\n \t\trescue Exception => e\n \t\t\tServices::Slog.exception e\n \t\t\t@response = {:status => 400, :error => e}\n \t\tend\n \tend\n\n\n # Start checkup\n begin\n \tunless content.nil? then\n \t\[email protected] = content\n \tend\n \t@checkup = @d.checkup\n rescue Exception => e\n \tServices::Slog.exception e\n end\n\n\n\n # Start detection\n begin\n \[email protected] do |object|\n \t\[email protected] object\n \tend\n rescue Exception => e\n \tServices::Slog.exception e\n end\n\n begin\n \tif @checkup[:status] == 100 then\n \t\tServices::Slog.info({:message => \"Starting integrations processing\", :module => \"Checkup\", :task => \"integrations\", :extra => {:agent => identifier, :payload => @checkup[:payload].size}})\n \t\tprocess @checkup\n \telse\n \tend\n rescue Exception => e\n \tServices::Slog.exception e\n end\n response = {:status => @checkup[:status], :message => \"[i2x][Checkup][execute] All OK.\"} \n end", "def check_for_timer_events\n super\n return if @worker_method_triggers.nil? or @worker_method_triggers.empty?\n @worker_method_triggers.delete_if { |key,value| value[:trigger].respond_to?(:end_time) && value[:trigger].end_time <= Time.now }\n\n @worker_method_triggers.each do |key,value|\n time_now = Time.now.to_i\n if value[:runtime] < time_now\n check_db_connection\n invoke_user_method(key,value[:data])\n t_time = value[:trigger].fire_after_time(Time.now)\n value[:runtime] = t_time.to_i\n end\n end\n end", "def worker_check_interval(interval); end", "def check_config_and_start_agent\n return unless monitoring? && has_correct_license_key?\n return if using_forking_dispatcher?\n\n setup_and_start_agent\n end", "def broadcast\n @monitor.__send__(:mon_check_owner)\n @cond.broadcast\n end", "def run_error_checks\r\n @error_checkers.each { |e| e.call(self) }\r\n end", "def check(session,avs,killbit)\n\tprint_status(\"Checking for contermeasures...\")\n\tsession.sys.process.get_processes().each do |x|\n\t\tif (avs.index(x['name'].downcase))\n\t\t\tprint_status(\"\\tPossible countermeasure found #{x['name']} #{x['path']}\")\n\t\t\tif (killbit)\n\t\t\t\tprint_status(\"\\tKilling process for countermeasure.....\")\n\t\t\t\tsession.sys.process.kill(x['pid'])\n\t\t\tend\n\t\tend\n\tend\nend", "def check_OLD\n # Check if we are configured to skip all backup checks\n if @backup_skip_all\n incstatus(\"OK\")\n @short=@backup_skip_all\n return\n end\n\n ## Not skipped, we check backups\n @objects=readObjects(\"backup\")\n\n # Create logdir if it doesn't exist\n FileUtils.mkdir_p @log_dir unless File.directory? @log_dir\n\n ## Initialize to OK since we may skip everything\n incstatus(\"OK\")\n\n ## CHECK CODE \n entries=Hash.new\n # Add mount entries\n entries=get_mounts_to_backup(entries) unless @backup_skip_mounts\n entries=get_lvs_to_backup(entries) unless @backup_skip_lvscan\n puts YAML.dump(entries) if @debug\n entries.values.each do |entry|\n check_entry(entry)\n end\n\n # Set Messages if OK and empty messages\n if status == \"OK\" and @short == \"\"\n @short=\"Everything OK\"\n end\n end", "def checks\n [\n ->(name: 'database') { [name, (ActiveRecord::Base.connection.active? rescue false)] },\n ->(name: 'sidekiq') { [name, (Sidekiq::ProcessSet.new.size.positive? rescue false)] },\n ->(name: 'sidekiq_latency') { [name, (Sidekiq::Queue.all.sum(&:latency) rescue false)] },\n #->(name: 'courtfinder'){ [name, (C100App::CourtfinderAPI.new.is_ok? rescue false)] },\n ]\n end", "def run_lamp_chef_checks\n # check that the standard unified app is responding on port 80\n run_unified_application_checks(@servers, 80)\n \n=begin \n # check that running the mysql backup script succeeds\n @servers.first.spot_check_command(\"/etc/cron.daily/mysql-dump-backup.sh\")\n \n # exercise operational RightScript(s)\n run_script(\"backup\", @servers.first)\n run_script(\"restart_apache\", @servers.first)\n \n # check that mysql tmpdir is custom setup on all servers\n query = \"show variables like 'tmpdir'\"\n query_command = \"echo -e \\\"#{query}\\\"| mysql\"\n @servers.each do |server|\n server.spot_check(query_command) { |result| raise \"Failure: tmpdir was unset#{result}\" unless result.include?(\"/mnt/mysqltmp\") }\n end\n \n # check that logrotate has mysqlslow in it\n @servers.each do |server|\n res = server.spot_check_command(\"logrotate --force -v /etc/logrotate.d/mysql-server\")\n raise \"LOGROTATE FAILURE, exited with non-zero status\" if res[:status] != 0\n raise \"DID NOT FIND mysqlslow.log in the log rotation!\" if res[:output] !~ /mysqlslow/\n end\n=end\n \n end", "def start\n logger.info \"watchdog start\"\n @timer = every(@interval) do\n check\n end\n end", "def check\n each { |m| m.check }\n end", "def check_idle_servers!\n\t\tmust_not_be_in_synchronize_block\n\t\[email protected] do\n\t\t\t@next_cleaning_time = Time.now - 60 * 60\n\t\t\[email protected]\n\t\tend\n\tend", "def run\n read_lock,write_lock,total_lock=0\n\n stat1=` mongo --eval \"printjson( db.serverStatus().globalLock.currentQueue.readers)\"`\n stat1.each_line do |line|\n read_lock=line if line.match /^[0-9]*/\nend\nstat2=` mongo --eval \"printjson( db.serverStatus().globalLock.currentQueue.writers)\"`\nstat2.each_line do |line|\n write_lock=line if line.match /^[0-9]*/\nend\nstat3=` mongo --eval \"printjson( db.serverStatus().globalLock.currentQueue.total)\"`\nstat3.each_line do |line|\n total_lock=line if line.match /^[0-9]*/\nend\n \n warning if read_lock.to_i > config[:warn] && write_lock.to_i > config[:warn] && total_lock.to_i > config[:warn]\n critical if read_lock.to_i > config[:crit] && write_lock.to_i > config[:crit] && total_lock.to_i > config[:crit] \n ok\n\n end", "def check\n if ping?\n mark_message \"Solr ping reported success\"\n else\n mark_failure\n mark_message \"Solr ping reported failure\"\n end\n rescue => e\n mark_failure\n mark_message \"Error: '#{e}'\"\n end", "def monitor\n @summary = @vm.summary\n @state = state_to_c(@summary.runtime.powerState)\n\n if @state != 'a'\n @used_cpu = 0\n @used_memory = 0\n\n @net_rx = 0\n @net_tx = 0\n\n return\n end\n\n @used_memory = @summary.quickStats.hostMemoryUsage * 1024\n\n host = VIDriver::host\n cpuMhz = host.cpuMhz.to_f\n @used_cpu =\n ((@summary.quickStats.overallCpuUsage.to_f / cpuMhz) * 100).to_s\n @used_cpu = sprintf('%.2f',@used_cpu).to_s\n\n vm_stats = VIDriver::retrieve_stats([@vm],\n [\"net.packetsRx\",\"net.packetsTx\"])\n @net_rx = 0\n @net_tx = 0\n\n if vm_stats[@vm] && vm_stats[@vm][:metrics]\n if vm_stats[@vm][:metrics][\"net.packetsRx\"]\n @net_rx = vm_stats[@vm][:metrics][\"net.packetsRx\"].first\n end\n\n if vm_stats[@vm][:metrics][\"net.packetsTx\"]\n @net_tx = vm_stats[@vm][:metrics][\"net.packetsTx\"].first\n end\n end\n\n # Check for negative values\n @used_memory = 0 if @used_memory.to_i < 0\n @used_cpu = 0 if @used_cpu.to_i < 0\n @net_rx = 0 if @net_rx.to_i < 0\n @net_tx = 0 if @net_tx.to_i < 0\n end", "def check_schedule()\n create_daily_tests()\n create_weekly_tests()\n end", "def checks\n return if @server.info[:server_version].nil? && @server.info[:app_server_version].nil? \n\n cve_data = update_cve_files(@server.info[:server_name])\n\n if cve_data.nil?\n @result.warned(\"CVE Data not available for #{@server.info[:server_name].capitalize}.\")\n return\n end\n\n server_version = @server.info[:server_version] \n\n short_name = \"#{@server.info[:server_name]}/#{@server.info[:server_version]}\"\n\n cve_data[\"cves\"].each do |cve|\n from_v = Version.new cve['from']\n to_v = cve['to'].nil? ? nil : Version.new(cve['to']) \n prior_v = cve['prior'].nil? ? nil : Version.new(cve['prior']) \n\n # If the server version is \n if server_version >= from_v \n \n # if there are no to_ / prior_v or to_v is present and we're in the range or prior is present and we're in the range, then...\n if ( to_v.nil? && prior_v.nil? ) || ( !to_v.nil? && server_version <= to_v ) || ( !prior_v.nil? && server < prior_v )\n @result.failed(\"CVE: #{short_name} CVE-#{cve['cve']}: #{cve['title']}: #{cve['url']}\")\n end\n end\n\n end\n\n end", "def monitor_health\n find_features\n @results = @features.inject({}) do |results, feature_name|\n results[ feature_name ] = monitor_health_of( feature_name )\n results\n end\n healthy? ? on_healthy : on_unhealthy\n render_health\n end", "def check_all_here\n end", "def run_checks\n methods.keep_if { |m| m.match(/^check_/) }.each do |check|\n send check.to_sym unless @skip.include? check.to_s.sub 'check_', ''\n end\n end", "def do_poll\n\t\tstatus_lamp\n\t\tstatus_input\n\t\tprojector_information\n\t\tstatus_error\n\tend", "def run\n loop do\n next unless @all_workers_started\n begin\n check_workers\n sleep Skynet::CONFIG[:WORKER_CHECK_DELAY]\n rescue SystemExit, Interrupt => e\n printlog \"Manager Exiting!\"\n exit\n rescue Exception => e\n fatal \"Something bad happened #{e.inspect} #{e.backtrace.join(\"\\n\")}\"\n end\n end\n end", "def start_monitoring\n @scheduler.start()\n end", "def monitor\n loop do\n sleep opts[:period]\n group.engine.logger.info \"#{group.banner}Monitoring group elasticity rule...\"\n # this is blocking because we don't want the rule to be triggered\n # too many times.\n if scale_up?\n group.engine.logger.info \"#{group.banner}Scaling up!\"\n manage(scale(:up))\n elsif scale_down?\n group.engine.logger.info \"#{group.banner}Scaling down!\"\n manage(scale(:down))\n else\n group.engine.logger.info \"#{group.banner}...\"\n end\n end\n end", "def perform\n alerts = Alert.utilization_efficiency.where(\"enabled=?\",true)\n\n # if it has just alert the user\n alerts.each do |alert|\n begin\n #calculate in hours the frequency\n utilization_efficiency_hours = 0\n amount = alert.utilization_efficiency_number\n\n #convert the aggregation [days or hours] into hours for calculations\n hours_per_day = 24\n if alert.aggregation_frequency == \"month\"\n utilization_efficiency_hours = amount * hours_per_day * 30 \n elsif alert.aggregation_frequency == \"week\"\n utilization_efficiency_hours = amount * hours_per_day * 7 \n elsif alert.aggregation_frequency == \"day\"\n utilization_efficiency_hours = amount * hours_per_day \n else\n utilization_efficiency_hours = amount\n end\n\n hour_difference = (Time.parse(DateTime.now.to_s) - Time.parse(alert.utilization_efficiency_last_checked.to_s))/3600\n if hour_difference > utilization_efficiency_hours\n alert.update_column(\"utilization_efficiency_last_checked\", Time.now)\n alert_history_count=AlertHistory.where('alert_id=?', alert.id).where('created_at >= ?', alert.utilization_efficiency_last_checked).where('for_aggregation_calculation=true').count\n\n # minimum value for the threshold is one\n if alert_history_count <= alert.aggregation_threshold\n alert_history_triggered(alert, alert_history_count)\n else\n #the sample was read x times correctly so the alert does not need to monitor for this sample id, now disable the alert\n # or do we reset the utilization_efficiency_last_checked and recheck??\n alert.update_column(\"enabled\", false)\n alert.delete_percolator\n end\n end\n\n rescue => e\n Rails.logger.error { \"Encountered an error when trying to run background job HourlyUtilizationEfficiencyJob : #{alert.id}, #{e.message} #{e.backtrace.join(\"\\n\")}\" }\n end\n end\n end", "def run_on_changes paths\n return run_all unless tracker.checks\n info \"\\n\\nrescanning #{paths}, running all checks\" unless options[:quiet]\n report = ::Brakeman::rescan(tracker, paths)\n print_changed(report)\n throw :task_has_failed if report.any_warnings?\n end", "def scan_now\r\n # Setup the checks\r\n # ToDo: CRC\r\n checks = {\r\n \t :name => {\r\n :use=>false,\r\n :proc=>Proc.new{ |the_file,stats| the_file.path }\r\n },\r\n :date => {\r\n :use=>false,\r\n :proc=>Proc.new{ |the_file,stats| stats.mtime }\r\n },\r\n :size => {\r\n :use=>true,\r\n :proc=>Proc.new{ |the_file,stats| stats.size }\r\n },\r\n }\r\n checks.each_pair{ |check_name,check|\r\n check[:use] = (@onmodify_checks == check_name) || ( @onmodify_checks.respond_to?( :include? ) && @onmodify_checks.include?( check_name ) )\r\n }\r\n\r\n #Check for add/modify\r\n @directory.rewind\r\n count = 0\r\n @directory.each{ |fname|\r\n file_path = \"#{@directory.path}/#{fname}\"\r\n next if (@name_regexp.respond_to?( :match ) && !@name_regexp.match( fname )) || !File.file?( file_path )\r\n the_file = File.new( file_path )\r\n file_stats = File.stat( file_path )\r\n\r\n saved_stats = @known_file_stats[file_path]\r\n new_stats = {}\r\n checks.each_pair{ |check_name,check|\r\n new_stats[check_name] = check[:proc].call( the_file, file_stats )\r\n }\r\n\r\n\t @known_files.push file_path if !@known_files.include? file_path\r\n\r\n if saved_stats\r\n if @on_modify.respond_to?( :call )\r\n sufficiently_modified = @onmodify_requiresall\r\n saved_stats = @known_file_stats[file_path]\r\n checks.each_pair{ |check_name,check|\r\n stat_changed = check[:use] && ( saved_stats[check_name] != new_stats[check_name] )\r\n if @onmodify_requiresall\r\n sufficiently_modified &&= stat_changed\r\n else\r\n sufficiently_modified ||= stat_changed\r\n end\r\n saved_stats[check_name] = new_stats[check_name]\r\n }\r\n @on_modify.call( the_file, saved_stats ) if sufficiently_modified\r\n end\r\n elsif @on_add.respond_to?( :call ) && (@scanned_once || @onadd_for_existing)\r\n @known_file_stats[file_path] = new_stats\r\n @on_add.call( the_file, new_stats )\r\n count += 1\r\n end\r\n the_file.close\r\n }\r\n\r\n # Check for removed files\r\n if @on_remove.respond_to?( :call )\r\n @known_file_stats.each_pair{ |path,stats|\r\n next if File.file?( path )\r\n stats[:path] = path\r\n @on_remove.call( stats )\r\n @known_file_stats.delete(path)\r\n }\r\n end\r\n\r\n @scanned_once = true\r\n return count\r\n end", "def run_syscheck(agent_id)\n put \"/syscheck/#{agent_id}\"\n end", "def tick\n if process_alive?\n get_cpu_usage\n get_ram_usage\n $db.monitor_services.insert(:cpu_usage => self.cpu_usage, :ram_usage => self.ram_usage, :service_id => self.id, :date => DateTime.now)\n @monitor.reset_ps_axu\n else\n Console.show \"Process #{@daemon_id} has been killed\", 'info'\n ServiceManager.remove_service(self.id)\n @monitor_timer.pause()\n end\n end", "def startup_config_check\n\t\tfw_connect\n\t\t# they are ALL stale right now...\n\t\tcheck_config_freshness\n\t\tpending = get_pending_commits\n\t\tdo_pending_commits(pending) if pending != 0\n\t\tfw_exit\n\tend", "def register_health_check #:nodoc:\n @publisher.hset GilmourHealthKey, self.ident, 'active'\n\n # - Start listening on a dyanmic topic that Health Monitor can publish\n # on.\n #\n # NOTE: Health checks are not run as forks, to ensure that event-machine's\n # ThreadPool has sufficient resources to handle new requests.\n #\n topic = \"gilmour.health.#{self.ident}\"\n backend = self\n add_listener(topic) do\n respond backend.get_subscribers\n end\n end", "def check_target(target) \n # Default warning_limit\n warning_limit=@warning_limit\n # Default critical_limit\n critical_limit=@critical_limit\n # Default nobackup_status\n nobackup_status=@nobackup_status\n\n puts \"Checking target: #{target}\" if @verbose\n\n if @objects.has_key?(target)\n # Return if target marked as skip\n return if @objects[target].has_key?(:skip)\n\n # Set target limits if given\n warning_limit=@objects[target][:warning_limit] if @objects[target].has_key? :warning_limit\n puts \" warning_limit for #{target} is #{warning_limit}\" if @debug\n critical_limit=@objects[target][:critical_limit] if @objects[target].has_key? :critical_limit\n puts \" critical_limit for #{target} is #{critical_limit}\" if @debug\n nobackup_status=@objects[target][:nobackup_status] if @objects[target].has_key? :nobackup_status\n puts \" nobackup_status for #{target} is #{nobackup_status}\" if @debug\n end\n # Check backup age\n check_time=Time.now\n last_backup=current_mirror(target)\n if last_backup\n if check_time < last_backup + warning_limit.to_i\n incstatus(\"OK\")\n elsif check_time >= last_backup + warning_limit.to_i and check_time < last_backup + critical_limit.to_i\n @short+=\"#{target} OLD, \"\n @long+=\"#{target} is too OLD\\n\"\n incstatus(\"WARNING\")\n elsif check_time >= last_backup + critical_limit.to_i\n @short+=\"#{target} OLD, \"\n @long+=\"#{target} is too OLD\\n\"\n incstatus(\"CRITICAL\")\n end\n else\n @short+=\"no backups for #{target}, \"\n @long+=\"No backups found for target #{target}\\n\"\n incstatus(nobackup_status)\n end\n end", "def m2c_check!\n MoabOnStorage::StorageDirectory.find_moab_paths(storage_location) do |druid, _path, _match|\n Audit::MoabToCatalogJob.perform_later(self, druid)\n end\n end", "def check_triggers\n @triggers.each do |trigger|\n trigger.evaluate\n end\n end", "def run\n clear\n with_benchmarking do\n check\n end\n OkComputer.logger.info \"[okcomputer] #{to_text}\"\n end", "def internal_update_stats(metric, up, users, two_min, five_min, fifteen_min)\n alert_status = cur_alert\n\n if (alert?) # Alert case\n if (two_min < $ALERT_THRESHOLD)\n alert_status.trigger_clear(metric.create_time)\n Rails.logger.info(\"Cleared alert #{metric.create_time} #{two_min}\")\n end\n else # Clear case\n if (two_min > $ALERT_THRESHOLD)\n alert_status.trigger_alert(metric.create_time)\n Rails.logger.info(\"Started alert #{metric.create_time} #{two_min}\")\n end\n end\n\n @stats.setup(metric, up, users, two_min, five_min, fifteen_min, alert_status)\n end", "def checkTrigger\n\t 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 check_state\n EM.stop if @setup.report_state.content =~ /operational|stranded/\n end", "def broadcast\n @monitor.mon_check_owner\n @cond.broadcast\n end" ]
[ "0.76253325", "0.7601913", "0.69044155", "0.68843925", "0.66576385", "0.6642668", "0.65737313", "0.6556669", "0.65349877", "0.6534936", "0.6504919", "0.6417568", "0.6373893", "0.6370729", "0.63407713", "0.63247293", "0.631746", "0.62872535", "0.6251566", "0.62446713", "0.6213427", "0.62102264", "0.61527205", "0.61435986", "0.61271393", "0.611715", "0.6114488", "0.6085869", "0.60570884", "0.60275024", "0.60064423", "0.59994394", "0.59994394", "0.5996137", "0.59530914", "0.59470844", "0.5925769", "0.5922089", "0.5919968", "0.591304", "0.5902327", "0.58951986", "0.5881143", "0.5857654", "0.5851014", "0.5828643", "0.582769", "0.58269644", "0.5825493", "0.5789454", "0.5754977", "0.575178", "0.5747947", "0.5742365", "0.5740082", "0.573302", "0.5709085", "0.57085425", "0.5694935", "0.5690783", "0.56829655", "0.56784433", "0.56683624", "0.56656444", "0.56651264", "0.56553197", "0.56535363", "0.56488454", "0.5647338", "0.5635853", "0.5635142", "0.5626916", "0.5623119", "0.56145483", "0.56110096", "0.56068027", "0.5597446", "0.5593999", "0.55858845", "0.5575291", "0.5568582", "0.55654323", "0.556483", "0.55604357", "0.55392295", "0.5533051", "0.55321735", "0.5529951", "0.55228424", "0.55049604", "0.55022144", "0.54975605", "0.5489324", "0.54853594", "0.54848886", "0.54819494", "0.546219", "0.546201", "0.546123", "0.5459032" ]
0.6410466
12
Query SNMP and format information into a hash.
def format_battery( snmp ) info = {} # basic info that's always available info[ :status ] = snmp.get( oid: OIDS[:battery_status] ) info[ :capacity ] = snmp.get( oid: OIDS[:est_charge_remaining] ) rescue nil info[ :temperature ] = snmp.get( oid: OIDS[:battery_temperature] ) rescue nil info[ :minutes_remaining ] = snmp.get( oid: OIDS[:est_minutes_remaining] ) rescue nil # don't report voltage if the UPS doesn't voltage = snmp.get( oid: OIDS[:battery_voltage] ) rescue nil info[ :voltage ] = voltage / 10 if voltage # don't report current if the UPS doesn't current = snmp.get( oid: OIDS[:battery_current] ) rescue nil info[ :current ] = current/10 if current # see if we are on battery info[ :seconds_on_battery ] = snmp.get( oid: OIDS[:seconds_on_battery] ) rescue 0 info[ :in_use ] = ( info[ :seconds_on_battery ] != 0 ) return { battery: info.compact } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_ethernet_oids(host)\n ifTable_columns = [\"ifDescr\", \"ifOutOctets\",\"ifIndex\"]\n eth_name = nil\n eth_octets = nil\n eth_index = nil\n SNMP::Manager.open(:Host => host) do |manager|\n manager.walk(ifTable_columns) do |row|\n next if row[0].value.to_s.match('^lo')\n if eth_name.nil? then\n eth_name = row[0].value\n eth_octets = row[1].value\n eth_index = row[2].value\n end\n if row[1].value > eth_octets then\n eth_name = row[0].value\n eth_octets = row[1].value\n eth_index = row[2].value\n end\n end\n end\n if eth_index.nil?\n eth_index = 0\n end\n return {\n \"ifOutOctets\" => \".1.3.6.1.2.1.2.2.1.16.#{eth_index}\",\n \"ifInOctets\" => \".1.3.6.1.2.1.2.2.1.10.#{eth_index}\"\n }\nend", "def query_snmp(opts=nil)\n self.options = opts unless opts.nil?\n\n exit_code = nil\n exit_message = []\n index = 0\n has_rollup = false\n\n if results_cache.empty?\n debug(\"No results\\n\")\n exit_code = Nagios::UNKNOWN\n exit_message = [\"Invalid SNMP community string specified or snmp is disabled\"]\n else\n\n # concrete subclasses implement checks method\n checks.each do |check|\n unless results = results_cache[check[:name]]\n debug(\"No results for check %s\\n\" % check[:name])\n next\n end\n\n # Loop on possibly multiple lines of output\n results.each_line do |line|\n next unless line =~ check[:response]\n status = $1\n\n # Iterate over the expected return codes from a check.\n # line_exit_code,line_message = check[:codes][status]\n check[:codes].keys.each do |code|\n # Might want to support regex codes.\n # For now add support for 'any' value.\n next unless status == code || code == :any\n\n # Map to a nagios code\n # check[:codes][code] maps to a pair of ( nagios_code, message )\n line_exit_code = check[:codes][code][0]\n\n # Does it matter that index = 0?\n # Yes, currently rollup check must be first\n if index == 0 && check[:rollup]\n # Base the overall exit code only on the first check if it is marked as rollup.\n exit_code = line_exit_code\n exit_message = [\"OK\"] if exit_code == Nagios::OK\n has_rollup = true\n else\n\n # Sub checks only affect the message but not the exit code for rollups\n unless has_rollup\n exit_code = Status.worst_case(line_exit_code, exit_code)\n end\n\n # Only affect the message if not OK\n if exit_code != Nagios::OK && line_exit_code != Nagios::OK\n\n # Here, instead of the message being static, we generalized this\n # to call a custom function by symbol name, sending it the check value.\n # Main application thus far is to blow up a bit string.\n line_exit_message = build_message(check[:codes][code][1], status)\n prefix = \"\"\n\n unless check[:display].nil? || check[:display].empty?\n prefix = \"%s:\" % check[:display]\n end\n unless line_exit_message.empty?\n exit_message << \"%s%s\" % [prefix, line_exit_message]\n end\n end\n\n end\n end\n end\n index += 1\n end\n end\n # In case no checks ran or other pathological\n # cases lead to no assignments\n exit_code ||= Nagios::UNKNOWN\n if exit_message.empty?\n if exit_code == Nagios::OK\n exit_message = \"OK\"\n else\n exit_message = \"Unknown\"\n end\n else\n exit_message = exit_message.uniq.join(\",\")\n end\n\n Status.new(exit_code, exit_message)\n end", "def node_hw_hash_to_hw_info(hw_hash)\n hw_hash.inject({}) do |hash, (k, v)|\n if k == 'mac'\n v.each_with_index {|v,n| hash[\"net#{n}\"] = v }\n else\n hash[k] = v\n end\n hash\n end\n end", "def node_hw_hash_to_hw_info(hw_hash)\n hw_hash.inject({}) do |hash, (k, v)|\n if k == 'mac'\n v.each_with_index {|v,n| hash[\"net#{n}\"] = v }\n else\n hash[k] = v\n end\n hash\n end\n end", "def query\n process_switch(@oid) do |oid,value|\n case oid.to_str\n when @oid[0]; @status = (value == '1' ? 'ok' : (value == '3' ? 'Critical' : 'Non-critical')) \n when @oid[1], @oid[2], @oid[3]; @txt_result += value.gsub(/;/,\"\\n\")\n when @oid[4]; @txt_result += ( value == '0' ? \"PowerSupply1: Off\\n\" : (value == '1' ? \"PowerSupply1: On\\n\" : \"PowerSupply1: Missing\\n\") )\n when @oid[5]; @txt_result += ( value == '0' ? \"PowerSupply2: Off\\n\" : (value == '1' ? \"PowerSupply2: On\\n\" : \"PowerSupply2: Missing\\n\") )\n when @oid[6]; @txt_result += ( value == '1' ? \"Have Panic Dump in Flash\\n\" : \"\" )\n else STDERR.puts \"Unknown OID '#{oid}' '#{value}'\"\n end\n end\n end", "def hash\n [host_list, total_matching, total_returned].hash\n end", "def parse_snmp_hosts(text)\n re = /host: ([^\\s]+)\\s+.*?port: (\\d+)\\s+type: (\\w+)\\s*user: (.*?)\\s+security model: (.*?)\\n/m # rubocop:disable Metrics/LineLength\n text.scan(re).map do |(host, port, type, username, auth)|\n resource_hash = { name: host, ensure: :present, port: port.to_i }\n sec_match = /^v3 (\\w+)/.match(auth)\n resource_hash[:security] = sec_match[1] if sec_match\n ver_match = /^(v\\d)/.match(auth) # first 2 characters\n resource_hash[:version] = ver_match[1] if ver_match\n resource_hash[:type] = type =~ /trap/ ? :traps : :informs\n resource_hash[:username] = username\n resource_hash\n end\n end", "def query_memstats\n send(\"QUERY_MEMSTATS\")\n response = recv\n \n # We expect to get back 4 elements only for this method\n raise CommunicationError, \"Unexpected response from QUERY_MEMSTATS: #{response.join(\":\")}\" if response.length != 4\n\n { :used_memory => response[0].to_i, :free_memory => response[1].to_i, :total_swap => response[2].to_i, :free_swap => response[3].to_i }\n end", "def parse!\n self.interface_stats = Hash.new { |hash,key| hash[key] = {} }\n \n interface_names = Hash[self.raw_output.scan(/IF-MIB::ifDescr.(\\d+) = STRING: (\\w+)/m)]\n interface_types = Hash[self.raw_output.scan(/IF-MIB::ifType.(\\d+) = INTEGER: ([a-zA-Z0-9\\(\\)]+)/)]\n mac_addresses = Hash[self.raw_output.scan(/IF-MIB::ifPhysAddress.(\\d+) = STRING: ([0-9a-f:]+)/)]\n \n link_states = Hash[self.raw_output.scan(/IF-MIB::ifOperStatus.(\\d+) = INTEGER: (\\w+)\\(\\d\\)/)]\n octets_in = Hash[self.raw_output.scan(/IF-MIB::ifInOctets.(\\d+) = Counter32: (\\d+)/)]\n octets_out = Hash[self.raw_output.scan(/IF-MIB::ifOutOctets.(\\d+) = Counter32: (\\d+)/)]\n errors_in = Hash[self.raw_output.scan(/IF-MIB::ifInErrors.(\\d+) = Counter32: (\\d+)/)]\n errors_out = Hash[self.raw_output.scan(/IF-MIB::ifOutErrors.(\\d+) = Counter32: (\\d+)/)]\n \n interface_names.keys.each do |index|\n self.interface_stats[index][:name] = interface_names[index]\n self.interface_stats[index][:type] = interface_types[index]\n self.interface_stats[index][:mac] = mac_addresses[index]\n self.interface_stats[index][:in] = octets_in[index].to_i\n self.interface_stats[index][:out] = octets_out[index].to_i\n self.interface_stats[index][:errors_in] = errors_in[index].to_i\n self.interface_stats[index][:errors_out] = errors_out[index].to_i\n self.interface_stats[index][:up] = link_states[index] == \"up\"\n end\n \n self.interface_stats\n end", "def nodetool_status()\n out = `/opt/cassandra/bin/nodetool status`\n raise 'nodetool status failed' if $? != 0\n rows = out.split(\"\\n\")\n hash = {}\n dc_exp = /Datacenter: (.*)/\n #vnode\n #-- Address Load Tokens Owns Host ID Rack\n #non-vnode\n #-- Address Load Owns Host ID Token Rack\n #node_ex = /^(?<status>[UD\\?][NLJM]) +(?<address>(?:[0-9]{1,3}\\.){3}[0-9]{1,3}) +(?<load>(\\d+\\.?\\d* (TB|GB|MB|KB|bytes))|\\?) +(?<tokens>\\d+) +(?<owns>(\\d+\\.?\\d*%|\\?)) +(?<hostid>[a-z0-9\\-]+) +(?<rack>.*)$/\n node_ex = /^([UD\\?][NLJM]) +((?:[0-9]{1,3}\\.){3}[0-9]{1,3}) +((?:\\d+\\.?\\d* (?:TB|GB|MB|KB|bytes))|\\?) +(\\d+) +(\\d+\\.?\\d*%|\\?) +([a-z0-9\\-]+) +(.*)$/\n datacenter = nil\n rows.each do |row|\n m = dc_exp.match(row)\n if m\n datacenter = m[1]\n next\n end\n m = node_ex.match(row)\n next if m == nil\n node = {'datacenter' => datacenter}\n hash[m[2]] = node\n i = 0\n %w(status address load tokens owns hostid rack).each do |name|\n node[name] = m[i += 1]\n end\n # m.names.each do |name|\n # node[name] = m[name]\n # end\n end\n return hash\n end", "def get_snmp\n\n # onvide le tableau des résultats précédents\n @deltas.clear\n # var temporaire pour détecter le changement de valeur d'index dans la liste de résultats\n tmp_index = ''\n\n # requête SNMP get :\n # la requête renvoie une ligne par index, cette ligne peut être in ou out,\n # les lignes in et out de chaque index se suivent forcément.\n response = @manager.get(@oids) \n response.each_varbind do |oid|\n # récupération de la valeur de l'index sur la ligne de résultat : chaîne après le \".\"\n index = oid.name.to_s.split('.')[1].to_s\n if (tmp_index == index) then\n # si le nom est le même que la ligne lue précédente, on vient donc de lire la 2° ligne => out\n # on supprime le dernier élément du tableau @out et on y ajoute au début la mesure out.\n # idem avec le timestamp de la mesure.\n @out[index].shift\n @out[index].push(oid.value.to_i)\n @ts[index].shift\n @ts[index].push(Time.now.to_i)\n\n # calcul du delta in et out par intervalle de ts_delta\n ts_delta = @ts[index][1] - @ts[index][0]\n out_delta = (@out[index][1] - @out[index][0]) / ts_delta\n in_delta = (@in[index][1] - @in[index][0]) / ts_delta\n\n # récupération de l'objet Interface de cet index\n iface = @interfaces[index]\n\n # création d'un hash de résultat de la mesure pour chaque index\n # et ajout de ce hash dans le tableau @port_names\n port_delta = { name: iface.name, descr: iface.descr, speed: iface.speed ,octInOut: [in_delta, out_delta] }\n @deltas.push(port_delta)\n else\n # index == tmp_index, donc on lit la première ligne d'index => in\n # on supprime le dernier élément du tableau @in et on y ajoute au début la mesure in\n @in[index].shift\n @in[index].push(oid.value.to_i)\n tmp_index = index\n end\n end\n return @deltas \n end", "def basic_info\n\t\t#Grab some basic info using OID values which should be fairly generic in nature\n\t\ttarget = \"#{@manager.config[:host]}:#{@manager.config[:port]}\"\n\t\tcstring = @manager.config[:community]\n\t\t@snmp_version = @manager.config[:version] #We need this one later for some decisions so setting to class var\n\t\tsys_name = @manager.get_value(\"sysName.0\")\n\t\tsys_descr = @manager.get_value(\"sysDescr.0\")\n\n\t\t#Print out our basic info for user\n\t\tputs \"[*] \".light_green + \"Target\".light_yellow + \": #{target}\".white\n\t\tputs \"[*] \".light_green + \"Community String\".light_yellow + \": #{cstring}\".white\n\t\tif @snmp_version\n\t\t\tputs \"[*] \".light_green + \"SNMP Version\".light_yellow + \": #{@snmp_version}\".white\n\t\telse\n\t\t\tprint_caution(\"Unable to determine SNMP Version in use?\")\n\t\tend\n\t\tif sys_name\n\t\t\tputs \"[*] \".light_green + \"System Name\".light_yellow + \": #{sys_name}\".white\n\t\telse\n\t\t\tprint_error(\"Unable to determine system name!\")\n\t\tend\n\t\tif sys_descr\n\t\t\tputs \"[*] \".light_green + \"System Description\".light_yellow + \": \\n#{sys_descr}\".white\n\t\telse\n\t\t\tprint_error(\"Unable to find system description!\")\n\t\tend\n\t\tif @sys_time\n\t\t\tputs \"[*] \".light_green + \"System Uptime\".light_yellow + \": #{@sys_time}\".white\n\t\telse\n\t\t\tprint_error(\"Unable to find system description!\")\n\t\tend\n\tend", "def statistics\n stats_hash = {}\n stats = info_cmd(\"statistics\")\n\n stats = stats.gsub!(/statistics\\s/, '').gsub!(/\\n/, '').split(\";\")\n\n stats.each do |st|\n type = \"\"\n value = nil\n\n st.split(\"=\").each_with_index do |val, i|\n type = val if i == 0\n value = val if i == 1\n end\n\n stats_hash[type] = value\n end\n\n stats_hash\n end", "def hash\n [check_id, exceptions, key, links, port, proof, protocol, since, status].hash\n end", "def query_to_hash(query)\n Hash[CGI.parse(query).map {|key,values| [key, values[0]||true]}]\n end", "def parse_snmp_users(text)\n text.split(\"\\n\\n\").map do |user_s|\n user_s.scan(/^(\\w+).*?: (.*)/).each_with_object({}) do |(h, v), m|\n key = SNMP_USER_PARAM[h.downcase.intern] || h.downcase.intern\n m[key] = case key\n when :privacy then v =~ /AES/ ? :aes128 : :des\n when :version then v.sub('v2c', 'v2').intern\n when :auth then v.downcase.intern\n when :roles then v.sub(/ \\(.*?\\)/, '')\n else v.downcase\n end\n end\n end\n end", "def info(vm)\n used_cpu = @monitor[:used_cpu]\n used_memory = @monitor[:used_memory]\n netrx = @monitor[:netrx]\n nettx = @monitor[:nettx]\n diskrdbytes = @monitor[:diskrdbytes]\n diskwrbytes = @monitor[:diskwrbytes]\n diskrdiops = @monitor[:diskrdiops]\n diskwriops = @monitor[:diskwriops]\n\n if vm[:mob]\n guest_ip = vm[:mob].guest.ipAddress\n esx_host = vm[:mob].runtime.host.name.to_s\n guest_state = vm[:mob].guest.guestState.to_s\n vmware_tools = vm[:mob].guest.toolsRunningStatus.to_s\n vm_name = vm[:mob].name.to_s\n vmtools_ver = vm[:mob].guest.toolsVersion.to_s\n vmtools_verst = vm[:mob].guest.toolsVersionStatus2.to_s\n end\n\n # if vm[:mob]\n # rp_name = vm[:mob][:rp_list]\n # .select do |item|\n # item[:ref] == vm[:mob]['resourcePool']._ref\n # end\n # .first[:name] rescue ''\n\n # rp_name = 'Resources' if rp_name.empty?\n # else\n # rp_name = @vm['resourcePool'].name\n # end\n\n str_info = ''\n\n str_info << 'GUEST_IP=' << guest_ip.to_s << \"\\n\" if guest_ip\n\n if @guest_ip_addresses && !@guest_ip_addresses.empty?\n str_info << 'GUEST_IP_ADDRESSES=\"' << @guest_ip_addresses.to_s \\\n << '\" '\n end\n\n str_info << \"#{POLL_ATTRIBUTE[:cpu]}=\" << used_cpu.to_s << \"\\n\"\n str_info << \"#{POLL_ATTRIBUTE[:memory]}=\" << used_memory.to_s << \"\\n\"\n str_info << \"#{POLL_ATTRIBUTE[:netrx]}=\" << netrx.to_s << \"\\n\"\n str_info << \"#{POLL_ATTRIBUTE[:nettx]}=\" << nettx.to_s << \"\\n\"\n\n str_info << 'DISKRDBYTES=' << diskrdbytes.to_s << \"\\n\"\n str_info << 'DISKWRBYTES=' << diskwrbytes.to_s << \"\\n\"\n str_info << 'DISKRDIOPS=' << diskrdiops.to_s << \"\\n\"\n str_info << 'DISKWRIOPS=' << diskwriops.to_s << \"\\n\"\n\n str_info << 'VCENTER_ESX_HOST=\"' << esx_host << '\" ' << \"\\n\"\n str_info << 'VCENTER_GUEST_STATE=' << guest_state << \"\\n\"\n str_info << 'VCENTER_VM_NAME=\"' << vm_name << '\" ' << \"\\n\"\n str_info << 'VCENTER_VMWARETOOLS_RUNNING_STATUS=' << vmware_tools << \"\\n\"\n str_info << 'VCENTER_VMWARETOOLS_VERSION=' << vmtools_ver << \"\\n\"\n str_info << 'VCENTER_VMWARETOOLS_VERSION_STATUS=' \\\n << vmtools_verst << \"\\n\"\n # str_info << 'VCENTER_RP_NAME=\"' << rp_name << '\" '\n\n # I need modify this Carlos improvement.\n # @vm.info_disks.each do |disk|\n # str_info << \"DISK_#{disk[0]}_ACTUAL_PATH=\\\"[\" <<\n # disk[1].ds.name << '] ' << disk[1].path << '\" '\n # end\n\n str_info\n end", "def snmp_basic(manager)\n # Grab some basic info using OID values which should be fairly generic in nature\n target = \"#{manager.config[:host]}:#{manager.config[:port]}\"\n cstring = manager.config[:community]\n snmp_version = manager.config[:version]\n sys_name = manager.get_value(\"sysName.0\")\n sys_descr = manager.get_value(\"sysDescr.0\")\n sys_time = manager.get_value(\"sysUpTime.0\")\n\n print_good(\"Target: #{target}\")\n print_good(\"Community String: #{cstring}\")\n print_good(\"Read Access: Enabled\")\n print_good(\"Write Access: Enabled\") if @wite_access\n print_good(\"Write Access: Disabled\") unless @wite_access\n if snmp_version\n print_good(\"SNMP Version: #{snmp_version}\")\n else\n print_error(\"Unable to determine SNMP Version in use?\")\n end\n if sys_name\n print_good(\"System Name: #{sys_name}\")\n else\n print_error(\"Unable to determine system name!\")\n end\n if sys_descr\n print_good(\"System Description: \\n#{sys_descr}\")\n else\n print_error(\"Unable to find system description!\")\n end\n if sys_time\n print_good(\"System Uptime: #{sys_time}\")\n else\n print_error(\"Unable to find system uptime!\")\n end\n end", "def vformat(hash = {})\n hash = hash.map { |k, v| [k.to_sym, v] }.to_h\n new_hash = {}\n new_hash[:db] = hash[:database]\n new_hash[:user] = hash[:username] unless hash[:username].nil?\n new_hash[:password] = hash[:password] unless hash[:password].nil?\n new_hash[:magic_number] = magic_number(hash[:pool], hash[:timeout])\n new_hash\nrescue NoMethodError\n {}\nend", "def hash_with_meta\n if vn then\n to_hash.merge(vn_name: $db[:network_pool].where(oid: vn).select(:name).first[:name])\n else\n to_hash\n end\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 get_hash_extended\n rc = info_search(:extended => true)\n return rc if OpenNebula.is_error?(rc)\n to_hash\n end", "def conninfo_hash\n\t\treturn self.conninfo.each_with_object({}) do |info, hash|\n\t\t\thash[ info[:keyword].to_sym ] = info[:val]\n\t\tend\n\tend", "def system_info\n si = SysInfo.new\n si.to_hash\n rescue \n {}\n end", "def digest_hash(_realm, username)\n @sequel.fetch(\"SELECT digesta1 FROM #{@table_name} WHERE username=?\", username) do |row|\n return row[:digesta1]\n end\n nil\n end", "def get_kvm_hostinfo\n guests = {}\n begin\n result = `virsh list --all`\n result.split(\"\\n\").each do |line|\n if line =~ /(\\d+)\\s+(\\S+)\\s+(\\S+)/\n guest_hostname = $2\n guests[guest_hostname] = get_kvm_guest_info(guest_hostname)\n end\n end\n rescue\n warn \"Failed to run/parse virsh command\"\n end\n return guests\n end", "def get_device_info(addr)\n open_database { |db|\n row = db.get_first_row(<<~EOQ)\n select id, addr, state, `pow-source`, descr\n from SENSOR_TABLE where addr = \"#{addr}\";\n EOQ\n\n ret = {\n :id => row[0],\n :addr => row[1],\n :state => row[2],\n :psrc => row[3],\n :descr => row[4],\n }\n\n return ret\n }\n end", "def poll(agent, snmp)\n @snmp_manager = snmp\n\n unless get_names.empty?\n throughput_in = get_throughput_in\n throughput_in.each_key { |m| agent.report_counter_metric m, \"bits/sec\", throughput_in[m] } unless throughput_in.nil?\n\n throughput_out = get_throughput_out\n throughput_out.each_key { |m| agent.report_counter_metric m, \"bits/sec\", throughput_out[m] } unless throughput_out.nil?\n\n packets_in = get_packets_in\n packets_in.each_key { |m| agent.report_counter_metric m, \"pkts/sec\", packets_in[m] } unless packets_in.nil?\n\n packets_out = get_packets_out\n packets_out.each_key { |m| agent.report_counter_metric m, \"pkts/sec\", packets_out[m] } unless packets_out.nil?\n\n mcast_in = get_mcast_in\n mcast_in.each_key { |m| agent.report_counter_metric m, \"pkts/sec\", mcast_in[m] } unless mcast_in.nil?\n\n mcast_out = get_mcast_out\n mcast_out.each_key { |m| agent.report_counter_metric m, \"pkts/sec\", mcast_out[m] } unless mcast_out.nil?\n\n errors_in = get_errors_in\n errors_in.each_key { |m| agent.report_counter_metric m, \"errors/sec\", errors_in[m] } unless errors_in.nil?\n\n errors_out = get_errors_out\n errors_out.each_key { |m| agent.report_counter_metric m, \"errors/sec\", errors_out[m] } unless errors_out.nil?\n\n drops_in = get_drops_in\n drops_in.each_key { |m| agent.report_counter_metric m, \"drops/sec\", drops_in[m] } unless drops_in.nil?\n\n drops_out = get_drops_out\n drops_out.each_key { |m| agent.report_counter_metric m, \"drops/sec\", drops_out[m] } unless drops_out.nil?\n\n collisions = get_collisions\n collisions.each_key { |m| agent.report_counter_metric m, \"collisions/sec\", collisions[m] } unless collisions.nil?\n\n status = get_status\n status.each_key { |m| agent.report_metric m, status[m][:label], status[m][:count] } unless status.nil?\n end\n end", "def describe(oid)\n nodes = [MIB[oid]]\n puts ERB.new(Net::SNMP::MIB::Templates::DESCRIBE, nil, \"-\").result(binding)\n end", "def probe_vm_monitor\n one_vms = ''\n vms = @db.select_one\n vms.each do |vm|\n one_vms << Base64.decode64(vm)\n end\n one_vms\n end", "def dissect_to_record_hashes\n end", "def hash\n [status, area, days_on_market, originating_system_name].hash\n end", "def __nrpe_snmp\n\t\t\t\tbegin\n\t\t\t\t\tgem \"snmp\"\n\t\t\t\trescue Gem::LoadError\n\t\t\t\t\t$log.debug \"No snmp library. skipping.\"\n\t\t\t\t\treturn false\n\t\t\t\tend\n\t\t\t\trequire \"snmp\"\n\n\t\t\t\tdisks = []\n\t\t\t\tmount_oid = SNMP::ObjectId.new(\"1.3.6.1.2.1.25.3.8.1.2\")\n\t\t\t\tbegin\n\t\t\t\t\tSNMP::Manager.open(:Host => @host, :Community => $snmpcommunity) do |manager|\n\t\t\t\t\t\tmanager.walk(mount_oid) do |row|\n\t\t\t\t\t\t\trow.each { |vb| disks << vb.value.to_s }\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\trescue SNMP::RequestTimeout\n\t\t\t\t\t\treturn false\n\t\t\t\tend\n\t\t\t\treturn disks\n\t\tend", "def hash\n [inventory_code, plu, name, host_id, size, category, group, master_group, price_level, clerk, location, quantity, total_ex, total_inc, counter, barcode, normal_price, item_cost, tax, tax_free, is_discount, is_refund, is_void, is_surcharge, is_promotion, reason].hash\n end", "def query_string_to_hash query_string\n Hash[*query_string.scan(/(.+?)=(.*?)(?:&|$)/).flatten].each_value {|v|\n v.gsub!('+', ' ')\n v.gsub!(/%([0-9a-f]{2})/i) { [$1.hex].pack 'C' }\n }\nend", "def info\n str_info = \"\"\n\n # CPU\n str_info << \"MODELNAME=\\\"\" << @cpuModel.to_s << \"\\\"\\n\"\n str_info << \"CPUSPEED=\" << @cpuMhz.to_s << \"\\n\"\n str_info << \"TOTALCPU=\" << @total_cpu.to_s << \"\\n\"\n str_info << \"USEDCPU=\" << @used_cpu.to_s << \"\\n\"\n str_info << \"FREECPU=\" << (@total_cpu - @used_cpu).to_s << \"\\n\"\n\n # Memory\n str_info << \"TOTALMEMORY=\" << @total_memory.to_s << \"\\n\"\n str_info << \"USEDMEMORY=\" << @used_memory.to_s << \"\\n\"\n str_info << \"FREEMEMORY=\" << (@total_memory - @used_memory).to_s << \"\\n\"\n\n # Networking\n str_info << \"NETRX=\" << @net_rx.to_s << \"\\n\"\n str_info << \"NETTX=\" << @net_tx.to_s << \"\\n\"\n\n # Datastores\n @free_ds_info.each{|k,v|\n used_space = v[:capacity].to_i - v[:free_space].to_i\n str_info << \"DS=[ID=\\\"#{k}\\\",USED_MB=#{used_space},\"\n str_info << \"TOTAL_MB=#{v[:capacity]},\"\n str_info << \"FREE_MB=#{v[:free_space]}]\\n\"\n }\n\n str_info.strip\n end", "def get_all_by_query_as_hash(query)\n map_to_hash_by_primary_key(get_all_by_query(query))\n end", "def hash\n \"#{@ipv4}#{@port}\".hash\n end", "def info2hash(device = nil)\n names = {\n \"PKGINST\" => :name,\n \"NAME\" => nil,\n \"CATEGORY\" => :category,\n \"ARCH\" => :platform,\n \"VERSION\" => :ensure,\n \"BASEDIR\" => :root,\n \"HOTLINE\" => nil,\n \"EMAIL\" => nil,\n \"VSTOCK\" => nil,\n \"VENDOR\" => :vendor,\n \"DESC\" => :description,\n \"PSTAMP\" => nil,\n \"INSTDATE\" => nil,\n \"STATUS\" => nil,\n \"FILES\" => nil\n }\n\n hash = {}\n cmd = \"#{command(:pkginfo)} -l\"\n cmd += \" -d #{device}\" if device\n cmd += \" #{@resource[:name]}\"\n\n begin\n # list out all of the packages\n execpipe(cmd) { |process|\n # we're using the long listing, so each line is a separate\n # piece of information\n process.readlines.each { |line|\n case line\n when /^$/ # ignore\n when /\\s*([A-Z]+):\\s+(.+)/\n name = $1\n value = $2\n if names.include?(name)\n hash[names[name]] = value unless names[name].nil?\n end\n when /\\s+\\d+.+/\n # nothing; we're ignoring the FILES info\n end\n }\n }\n return hash\n rescue Puppet::ExecutionFailure => detail\n return {:ensure => :absent} if detail.message =~ /information for \"#{Regexp.escape(@resource[:name])}\" was not found/\n puts detail.backtrace if Puppet[:trace]\n raise Puppet::Error, \"Unable to get information about package #{@resource[:name]} because of: #{detail}\"\n end\n end", "def hash\n dn.hash\n end", "def hash\n [apm_scanned_bytes, events_scanned_bytes, hour, logs_scanned_bytes, org_name, public_id, rum_scanned_bytes, total_scanned_bytes].hash\n end", "def hashNQS()\n @hash_nqs={}\n nqsReader=File.open(@nqsFile,\"r\")\n nqsReader.each do |line|\n cols=line.split(/\\s+/)\n \n name=cols[0]\n next if name==\"readName\"\n length=cols[1]\n dist=cols[2]\n qual=cols[3].to_i\n pass=cols[4]\n \n str_result=length+'.'+pass\n str=name+'.'+dist\n if @hash_nqs[str]==nil\n @hash_nqs[str]=str_result\n end\n end\n nqsReader.close\n $stderr.puts @hash_nqs.size\nend", "def hash\n address.hash\n end", "def dowalk(mngr,query)\n\n rows = Array.new\n\n count = 0\n\n query.each do |oid|\n start_oid = SNMP::ObjectId.new(oid)\n next_oid = start_oid\n while next_oid.subtree_of?(start_oid)\n begin\n response = mngr.get_next(next_oid)\n varbind = response.varbind_list.first\n rescue\n puts \"[-] error while quering for #{next_oid}\"\n break\n end\n break if not varbind.oid.subtree_of?(start_oid)\n next_oid = varbind.oid\n count += 1\n\n # need to make below values as variables\n # we don't want to cause high CPU on the devices\n rows.push(varbind.value)\n if count >= 100\n sleep 0.1\n puts \"[!] query count reached first limit - slowing down\" if count == 100\n end\n if count >= 1000 \n puts \"[!] query count reached second limit - stopping\"\n break\n end\n end\n end\n\n rows\nend", "def get_hash\n\t\treturn { cond_type: COND_NUM_ATTENDING, \n\t\t\tcond_met: @cond_met, num_users: @num_users }\n\tend", "def user_to_h(department_id, iph)\n {department_id: department_id,\n name: iph[\"name\"],\n office_phone: iph[\"office_phone\"].to_i,\n cell_phone: iph[\"cell_phone\"].to_i,\n email: iph[\"email\"],\n building: iph[\"building\"],\n storey: iph[\"storey\"].to_i,\n room: iph[\"room\"].to_i} \n end", "def product_hash(category, query)\n\[email protected](\"SELECT * FROM products WHERE #{category} = '#{query}'\")\nend", "def get_kvm_guest_info(guest)\n info = {}\n result = `virsh dumpxml #{guest}`\n result.split(\"\\n\").each do |line|\n if line =~ /source file='(.+)'/\n img_path = $1\n if File.exists?(img_path)\n # nVentory expects the value to be in KB\n info['vmimg_size'] = File.stat(img_path).size.to_i / 1024\n # how to calculate this?\n # info['vmspace_used'] = ???\n end\n end\n end\n return info.clone\n end", "def to_sql_hash\n { \n 'iso_time' => iso_time,\n 'date' => date,\n 'hostname' => hostname,\n 'process' => process,\n 'pid' => pid,\n 'raw_message' => raw_message\n }\n end", "def get_usage_snmp(start_hr, opts = {})\n data, _status_code, _headers = get_usage_snmp_with_http_info(start_hr, opts)\n data\n end", "def poll(container)\n info = Hash.new 0\n \n # state\n states = {'exist' => 'a', 'deleted' => 'd', 'suspended' => 'p'}\n states.default = '-'\n status = container.status\n # state can be either active or deleted\n info[:state] = states[status[0]]\n # however if there is additional status field then it may be also suspended (see vzctl status comamnd)\n info[:state] = states[status[3]] if status.size == 4\n\n # if ct is down there is nothing we can do here\n return info if info[:state] != 'a'\n\n # ONE requires usedcpu to be equal to cpu utilization on all processors\n # ex. usedcpu=200 when there are 2 fully loaded cpus\n # currently i get only average pcpu and multiply it by number of cpus\n out = (container.command \"cat /proc/cpuinfo\").split\n cpu_amount = out.find_all {|line| /processor/ =~ line}.size\n\n out = (container.command \"ps axo pcpu=\").split\n info[:usedcpu] = cpu_amount * out.inject(0.0) {|sum, current|sum + current.to_f}\n \n # net transmit & receive\n out = container.command \"cat /proc/net/dev\"\n # i'am wondering how long this shit will work\n out.each_line do |line|\n net = /\\s*(?<interface>\\w+)\\s*:\\s*(?<receive>\\d+)(\\s+\\d+){7}\\s+(?<transmit>\\d+)/.match(line)\n # omit loopback interface\n next if !net || net[:interface] == \"lo\" \n info[:netrx] += net[:receive].to_i\n info[:nettx] += net[:transmit].to_i\n end\n \n # computer container memory usage\n out = container.command \"free -k\"\n info[:usedmemory] = /Mem:\\s+\\d+\\s+(?<used>\\d+)/.match(out)[:used].to_i\n \n info\n rescue RuntimeError => e\n raise OpenVzDriverError, \"Can't get container #{container.ctid} status. Details: #{e.message}\"\n end", "def hashes(to = $stdout)\n hashes = {}\n \n ObjectSpace.each_object(Hash) do |hash|\n begin\n keys_orig = hash.keys.sort\n rescue ArgumentError\n #When unable to sort regexps...\n next\n end\n \n keys = []\n keys_orig.each do |key|\n keys << key.to_s\n end\n \n if keys.empty?\n keystr = :empty\n else\n keystr = keys.join(\":\")\n end\n \n if !hashes.key?(keystr)\n hashes[keystr] = 1\n else\n hashes[keystr] += 1\n end\n end\n \n hashes.delete_if do |key, val|\n val < 100\n end\n \n hashes = Knj::ArrayExt.hash_sort(hashes) do |h1, h2|\n h2[1] <=> h1[1]\n end\n \n to.print \"<h1>Hashes</h1>\\n\"\n to.write \"<table class=\\\"hashes list\\\">\\n\"\n to.write \"\\t<thead>\\n\"\n to.write \"\\t\\t<tr>\\n\"\n to.write \"\\t\\t\\t<th>Hash keys</th>\\n\"\n to.write \"\\t\\t\\t<th>Instances</th>\\n\"\n to.write \"\\t\\t</tr>\\n\"\n to.write \"\\t</thead>\\n\"\n to.write\"\\t<tbody>\\n\"\n \n hashes.each do |key, val|\n to.write \"\\t\\t<tr>\\n\"\n to.write \"\\t\\t\\t<td>#{Knj::Web.html(key)}</td>\\n\"\n to.write \"\\t\\t\\t<td>#{Knj::Locales.number_out(val, 0)}</td>\\n\"\n to.write \"\\t\\t</tr>\\n\"\n end\n \n to.write \"\\t</tbody>\\n\"\n to.write \"</table>\\n\"\n end", "def from_query_to_hash\n hash = CGI::parse(self)\n hash.each do |key, val|\n hash[key] = val[0] if val and val.length == 1\n end\n hash\n end", "def verify_ssh_response_in_email_delivery_database(db_host_address, db_username, db_password)\n if db_host_address == '' or db_username == '' or db_password == ''\n puts \"Inavalid Database Login credentials is given\"\n else\n sleep 10\n db_login = Mysql2::Client.new(:host => db_host_address, :username => db_username,:password=> db_password, :database => 'email_billing')\n db_output = db_login.query(\"SELECT * FROM email_billing.email_delivery WHERE MID='#{$ssh_fetched_success_log[1]}'\")\n database_output = db_output.first\n puts \"\\n#EMAIL DELIVERY DATABASE RESPONSE SHOWN ON QUERY SEARCH BASED ON SSH MESSAGE ID:\\n\"\n #CONVERTING DATABASE RESPONSE TO HASH\n unless database_output.nil? || database_output == ''\n database_ssh_to_email_address = database_output['to_email']\n database_ssh_mid = database_output['mid']\n database_ssh_mail_status = database_output['status']\n database_ssh_stime = database_output['stime']\n database_ssh_esme_address = database_output['esmeaddr']\n puts database_output\n db_login.close\n else\n puts 'Database Query is Invalid or Data is not Inserted in Email Delivery Table due to time delay'\n end\n end\nend", "def to_hash\n { :ip => ip, :netmask => netmask, :dhcp => dhcp && dhcp.to_hash }\n end", "def parse_hash_packet(data)\n hashes = []\n\n algo = data.read_string\n size = case algo\n when \"md5\" then 128\n when \"sha256\" then 256\n when \"sha384\" then 284\n when \"sha512\" then 512\n else raise NotImplementedError, \"unsupported algorithm: #{algo}\"\n end\n\n while !data.eof? do\n hashes << data.read(size)\n end\n\n { :algo => algo, :hashes => hashes }\n end", "def hash\n @data[:asin].to_s.hash\n end", "def nt_query_information_process(h, ord, buf)\r\n lenp = [0].pack(\"L\")\r\n if CALLS[\"ntdll!NtQueryInformationProcess:LLPLP=L\"].call(h, ord, buf, buf.size, lenp) == 0\r\n len = lenp.unpack(\"L\").first\r\n return buf[0..(len-1)]\r\n end\r\n nil\r\n end", "def info\n info = Hash.new\n output = @filer.invoke(\"system-get-info\")\n if(output.results_errno() != 0)\n r = output.results_reason()\n raise \"Failed : \\n\" + r\n else \n output.children_get[0].children_get.each do |naelem|\n info[naelem.name] = naelem.content\n end\n end\n info\n end", "def med_stats_hash(_assessed_data); end", "def get_router_ipaddr()\n SNMP::Manager.open(\n :Host => RouterIP,\n :Community => SNMPpw,\n :Timeout => 60,\n :Retries => 5\n ) do |manager|\n # XXX Timeout on the next line (or the one below) will kick us out.\n response = manager.get([\"ip.21.1.7.0.0.0.0\"])\n response.each_varbind do |vb|\n default_route = \"#{vb.value.to_s}\"\n # puts \"ip.21.1.7.#{default_route}\"\n response = manager.get([\"ip.21.1.7.#{default_route}\"])\n response.each_varbind do |vb|\n my_ipaddr = \"#{vb.value.to_s}\"\n # puts my_ipaddr\n return my_ipaddr\n end\n end\n end\nend", "def get_dell_chassis_info\n ENV['PATH'] = \"#{ENV['PATH']}:/opt/dell/srvadmin/bin/\"\n chassis = {}\n result = nil\n begin\n #result = `omreport modularenclosure -fmt ssv`\n #result.split(\"\\n\").each do |line|\n # if line =~ /Service Tag/\n # chassis[:service_tag] = line.split(\";\")[1].strip\n # break\n # end\n #end\n timeout(5) do\n result = `omreport chassis info -fmt ssv`\n end\n result.split(\"\\n\").each do |line|\n if line =~ /Server Module Location;Slot (\\d+)/\n chassis[:slot_num] = $1.to_i\n elsif line =~ /Chassis Service Tag/\n chassis[:service_tag] = line.split(\";\")[1].strip\n end\n end\n # if no slot_number then the blade isn't really in a chassis/blade enclosure\n # such as the case with Dell PowerEdge 1950\n return {} if chassis[:slot_num].nil?\n rescue Timeout::Error\n warn \"Timed out when trying to run omreport\"\n rescue\n warn \"Failed to run/parse Dell's omreport command\"\n end\n return chassis\n end", "def get_string_to_hash(info)\r\n\t\treturn \"#{info['id']}|#{info['prev_hash']}|#{info['transaction'].join(':')}|#{info['ts'][:sec]}.#{info['ts'][:nsec]}\".strip\r\n\tend", "def ps_to_hash(ps)\n result = {}\n\n ps.each_pair do |k,v|\n if k == :uid\n begin\n result[:username] = Etc.getpwuid(v).name\n rescue Exception => e\n logger.debug(\"Could not get username for #{v}: #{e}\")\n result[:username] = v\n end\n end\n\n result[k] = v\n end\n\n result\n end", "def hash\n [class_id, object_type, hardware_status, hcl_cimc_version, hcl_driver_name, hcl_driver_version, hcl_firmware_version, hcl_model, inv_cimc_version, inv_driver_name, inv_driver_version, inv_firmware_version, inv_model, reason, software_status, status, component, hcl_status].hash\n end", "def info\n @lock.synchronize do\n hwaddr = self.hwaddr\n unless @meta_cache && @meta_cache[:hwaddr] == hwaddr\n @meta_cache = Meta.connection do\n raise Errors::MetaBadResponse unless Meta.interface(hwaddr, '', not_found: nil)\n {\n hwaddr: hwaddr,\n interface_id: Meta.interface(hwaddr, 'interface-id'),\n subnet_id: Meta.interface(hwaddr, 'subnet-id'),\n subnet_cidr: Meta.interface(hwaddr, 'subnet-ipv4-cidr-block')\n }.freeze\n end\n end\n @meta_cache\n end\n rescue Errors::MetaConnectionFailed\n raise Errors::InvalidInterface, \"Interface #{name} could not be found in the EC2 instance meta-data\"\n end", "def get_vm_info(name)\n output = vboxmanage('showvminfo', name, '--machinereadable')\n # Split this on the '=' sign\n split_output = []\n output = output.split(\"\\n\")\n output.each do |line|\n \tsplit_output << line.split('=')\n end\n\n # Map the array to a hash\n info_hash = Hash[split_output.map {|key, value| [key, value]}]\n\n # Remove any literal quotes\n info_hash.each do |key, value|\n \tinfo_hash[key] = value.tr(\"\\\"\",\"\")\n end\n\n info_hash\n end", "def hash_with_meta\n to_hash.merge(leased: VLANLease.where(pool_id: id).count)\n end", "def hash\n [class_id, object_type, admin_evac_state, admin_inband_interface_state, alarm_summary, available_memory, device_mo_id, dn, ethernet_mode, ethernet_switching_mode, fault_summary, fc_mode, fc_switching_mode, firmware, inband_ip_address, inband_ip_gateway, inband_ip_mask, inband_vlan, ipv4_address, management_mode, model, name, num_ether_ports, num_ether_ports_configured, num_ether_ports_link_up, num_expansion_modules, num_fc_ports, num_fc_ports_configured, num_fc_ports_link_up, oper_evac_state, operability, out_of_band_ip_address, out_of_band_ip_gateway, out_of_band_ip_mask, out_of_band_ipv4_address, out_of_band_ipv4_gateway, out_of_band_ipv4_mask, out_of_band_ipv6_address, out_of_band_ipv6_gateway, out_of_band_ipv6_prefix, out_of_band_mac, presence, revision, rn, serial, source_object_type, switch_id, thermal, total_memory, vendor, version, registered_device].hash\n end", "def query\n @property_hash\n end", "def parse_status_into_hash(output)\n hash = HashWithIndifferentAccess.new\n\n output.each_line do |line|\n if line.match /(^.*) (.*)/\n hash[$1] = $2\n end\n end\n\n hash[\"volume\"] = hash[\"set vol_left\"] if hash[\"set vol_left\"]\n hash[\"position_integer\"] = hash[\"position\"]\n hash[\"position\"] = seconds_to_formatted_time(hash[\"position\"].to_i) if hash[\"position\"]\n\n hash[\"duration_integer\"] = hash[\"duration\"]\n hash[\"duration\"] = seconds_to_formatted_time(hash[\"duration\"].to_i) if hash[\"duration\"]\n\n hash[\"percent_complete\"] = (hash[\"position_integer\"].to_f / hash[\"duration_integer\"].to_f) * 100.0\n\n hash\n end", "def to_hash\n result = {}\n [[:tn, :tn], [:epg, :epg], [:cnam, :cnam], [:refId, :ref_id]].each do |garbage, pretty|\n # Make sure that this thing ain't nil\n if self.send(pretty)\n result[garbage] = self.send(pretty)\n end\n end\n result\n end", "def hash\n [ach_type, routing_number, account_number, account_type, check_number, check_type, product_code, manual_id_info, supplement_id_info, agent_id, terminal_id, registration_id, registration_date, release_type, vip_customer, session_id, terminal_state, terminal_city, ach_bill_to].hash\n end", "def get_elk_data(query)\n index = \"logstash-\" + Time.now.strftime(\"%Y.%m.%d\")\n url = \"/#{index}/#{@type}/_search\"\n\n req = Net::HTTP::Post.new( url, initheader = {'Content-Type' =>'application/json'} )\n req.body = query\n\n response = Net::HTTP.new(@host, @port).start {|http| http.request(req) }\n hits = JSON.parse(response.body)['hits']\n\n if hits.nil?\n puts response.body\n end\n\n return hits\n end", "def dump\n\t\tprint_status(\"Dumping a bunch of info from the 'mgmt' OID......\")\n\t\tdumpz=[]\n\t\[email protected]('mgmt') { |x| dumpz << x }\n\t\tif dumpz.empty?\n\t\t\tprint_error(\"No Values Found!\")\n\t\telse\n\t\t\tputs \"[*] \".light_green + \"SNMP MGMT Dump\".light_yellow + \": \".white\n\t\t\tdumpz.each do |entry|\n\t\t\t\tprint_good(\"#{entry}\")\n\t\t\tend\n\t\tend\n\tend", "def memory\n hash = {}\n page_size = 4096 # Possibly changed later\n\n begin\n optr = FFI::MemoryPointer.new(:uint64_t)\n size = FFI::MemoryPointer.new(:size_t)\n size.write_int(optr.size)\n\n if sysctlbyname('hw.memsize', optr, size, nil, 0) < 0\n raise SystemCallError.new('sysctlbyname', FFI.errno)\n end\n\n hash[:total] = optr.read_uint64\n ensure\n optr.free if optr && !optr.null?\n size.clear\n end\n\n begin\n swap = Swap.new\n size.write_int(swap.size)\n\n if sysctlbyname('vm.swapusage', swap, size, nil, 0) < 0\n raise SystemCallError.new('sysctlbyname', FFI.errno)\n end\n\n hash[:swap_total] = swap[:xsu_total]\n hash[:swap_available] = swap[:xsu_avail]\n hash[:swap_used] = swap[:xsu_used]\n page_size = swap[:xsu_pagesize]\n ensure\n size.free if size && !size.null?\n end\n\n host_self = mach_host_self()\n vmstat = VmStat.new\n count = FFI::MemoryPointer.new(:size_t)\n count.write_int(vmstat.size)\n\n rv = host_statistics64(host_self, HOST_VM_INFO64, vmstat, count)\n raise SystemCallError.new('host_statistics64', rv) if rv != 0\n\n hash[:free] = vmstat[:free_count] * page_size\n hash[:active] = vmstat[:active_count] * page_size\n hash[:inactive] = vmstat[:inactive_count] * page_size\n hash[:speculative] = vmstat[:speculative_count] * page_size\n hash[:wire] = vmstat[:wire_count] * page_size\n hash[:compressed] = vmstat[:compressor_page_count] * page_size\n\n hash\n ensure\n count.free if count && !count.null?\n end", "def test_results_to_hash\n results = [1, \" \", \"3\", \"4\", 5, 6]\n phs = @parser.results_to_hash(results, 7)\n exp_msg = 1\n exp_spc = 2\n exp_key = \"3\"\n exp_val = \"4\"\n exp_ask = 5\n exp_asv = 6\n exp_opt = 7\n assert_equal exp_msg, phs[:msg]\n assert_equal exp_spc, phs[:spc]\n assert_equal exp_key, phs[:key]\n assert_equal exp_val, phs[:val]\n assert_equal exp_ask, phs[:ask]\n assert_equal exp_asv, phs[:asv]\n assert_equal exp_opt, phs[:opt]\n end", "def info\n return 'STATE=d' if @state == 'd'\n\n if @vm.vm_info\n guest_ip = @vm.vm_info['guest.ipAddress']\n else\n guest_ip = @vm['guest.ipAddress']\n end\n\n used_cpu = @monitor[:used_cpu]\n used_memory = @monitor[:used_memory]\n netrx = @monitor[:netrx]\n nettx = @monitor[:nettx]\n diskrdbytes = @monitor[:diskrdbytes]\n diskwrbytes = @monitor[:diskwrbytes]\n diskrdiops = @monitor[:diskrdiops]\n diskwriops = @monitor[:diskwriops]\n\n if @vm.vm_info\n esx_host = @vm.vm_info[:esx_host_name].to_s\n else\n esx_host = @vm['runtime.host.name'].to_s\n end\n\n if @vm.vm_info\n guest_state = @vm.vm_info['guest.guestState'].to_s\n else\n guest_state = @vm['guest.guestState'].to_s\n end\n\n if @vm.vm_info\n vmware_tools = @vm.vm_info['guest.toolsRunningStatus'].to_s\n else\n vmware_tools = @vm['guest.toolsRunningStatus'].to_s\n end\n\n if @vm.vm_info\n vm_name = @vm.vm_info['name'].to_s\n else\n vm_name = @vm['name'].to_s\n end\n\n if @vm.vm_info\n vmtools_ver = @vm.vm_info['guest.toolsVersion'].to_s\n else\n vmtools_ver = @vm['guest.toolsVersion'].to_s\n end\n\n if @vm.vm_info\n vmtools_verst = @vm.vm_info['guest.toolsVersionStatus2'].to_s\n else\n vmtools_verst = @vm['guest.toolsVersionStatus2'].to_s\n end\n\n if @vm.vm_info\n rp_name = @vm.vm_info[:rp_list]\n .select do |item|\n item[:ref] == @vm.vm_info['resourcePool']._ref\n end\n .first[:name] rescue ''\n\n rp_name = 'Resources' if rp_name.empty?\n else\n rp_name = @vm['resourcePool'].name\n end\n\n str_info = ''\n\n str_info = 'GUEST_IP=' << guest_ip.to_s << ' ' if guest_ip\n\n if @guest_ip_addresses && !@guest_ip_addresses.empty?\n str_info << 'GUEST_IP_ADDRESSES=\"' << @guest_ip_addresses.to_s \\\n << '\" '\n end\n\n str_info << \"#{POLL_ATTRIBUTE[:state]}=\" << @state << ' '\n str_info << \"#{POLL_ATTRIBUTE[:cpu]}=\" << used_cpu.to_s << ' '\n str_info << \"#{POLL_ATTRIBUTE[:memory]}=\" << used_memory.to_s << ' '\n str_info << \"#{POLL_ATTRIBUTE[:netrx]}=\" << netrx.to_s << ' '\n str_info << \"#{POLL_ATTRIBUTE[:nettx]}=\" << nettx.to_s << ' '\n\n str_info << 'DISKRDBYTES=' << diskrdbytes.to_s << ' '\n str_info << 'DISKWRBYTES=' << diskwrbytes.to_s << ' '\n str_info << 'DISKRDIOPS=' << diskrdiops.to_s << ' '\n str_info << 'DISKWRIOPS=' << diskwriops.to_s << ' '\n\n str_info << 'VCENTER_ESX_HOST=\"' << esx_host << '\" '\n str_info << 'VCENTER_GUEST_STATE=' << guest_state << ' '\n str_info << 'VCENTER_VM_NAME=\"' << vm_name << '\" '\n str_info << 'VCENTER_VMWARETOOLS_RUNNING_STATUS=' << vmware_tools << ' '\n str_info << 'VCENTER_VMWARETOOLS_VERSION=' << vmtools_ver << ' '\n str_info << 'VCENTER_VMWARETOOLS_VERSION_STATUS=' \\\n << vmtools_verst << ' '\n str_info << 'VCENTER_RP_NAME=\"' << rp_name << '\" '\n\n # @vm.info_disks.each do |disk|\n # str_info << \"DISK_#{disk[0]}_ACTUAL_PATH=\\\"[\" <<\n # disk[1].ds.name << '] ' << disk[1].path << '\" '\n # end\n\n str_info\n end", "def get_tracking_nums()\n\n begin\n @tracking_nums = {}\n db = SQLDb.new(DB_FILE)\n db.open\n db.query(\"SELECT TrackingNum, SalesContract.ID, Name, SSNUM from SalesContract, Patient WHERE ShippingSvc = 1 AND NOT TrackingNum IS NULL AND ((ShippingSts <> 2 AND ShippingSts <> 9) OR ShippingSts IS NULL) AND SalesContract.LocatorID = Patient.ID\")\n\n rows = db.data\n \n rows.each do |row|\n \n if row[3].to_s.rstrip.length == 9 #Check for the length of the SSN\n @tracking_nums[row[0].strip().gsub(' ','').upcase]= row[1]\n process_tracking_nums(row[0], row[3], row[2])\n\n else\n log_error(\"Incorrect SSN for \" + row[2].to_s)\n end\n end\n db.close\n \n save_results()\n \n\n rescue Exception =>ex\n puts ex.to_s\n log_error(ex.to_s)\n end\n\n end", "def to_h\n info.merge(\n name: name,\n device_number: device_number,\n route_table: route_table,\n local_ips: local_ips,\n public_ips: public_ips,\n enabled: enabled?\n )\n end", "def parseping(output)\n res = Hash.new\n begin\n res[:success] = 100 - Integer(output.match(/([[:digit:]]+)% packet loss/m)[1])\n res[:rtt] = Float(output.match(/= [[:digit:]\\.]+\\/([[:digit:]\\.]+)\\//m)[1])\n rescue NoMethodError, TypeError\n # Do nothing, just fall through and return the empty hash.\n end\n res\nend", "def hash\n [authentication_type, community_name, database, domain, enumerate_sids, notes_id_password, ntlm_hash, oracle_listener_password, password, pem_key, permission_elevation, permission_elevation_password, permission_elevation_username, privacy_password, privacy_type, private_key_password, realm, service, sid, use_windows_authentication, username].hash\n end", "def getRMS(pol)\n ibobName = getiBobName(pol);\n if(ibobName.length == 0)\n return $NO_HOOKUP_INFO;\n end\n input = getInput(pol).to_i;\n #puts \"INPUT: \" +input.to_s;\n cmd = \"adcstats.rb #{ibobName}.#{@rackName}\";\n result = doCmd(cmd);\n lineCount = 0;\n result.each do |line|\n parts = line.split(/\\s+/);\n inx = parts[0];\n if((lineCount > 0) && inx.to_i == input)\n return parts[3];\n end\n lineCount = lineCount + 1;\n end\n\n return $ADCSTAT_ERROR;\n end", "def vm_info\n unless @vm\n warn 'No VM assigned to get info from'\n return\n end\n @vm = locate_vm(@vm.to_hash['VM']['ID'].to_i)\n @vm.to_hash\n end", "def snmp_user_password_hash(running_config, user_cmd)\n regexp = /#{user_cmd} .*?auth \\w+\\s+(.*?)\\s+priv \\w+\\s+(.*?)\\s/\n (auth_hash, priv_hash) = running_config.scan(regexp).first\n { auth: auth_hash, privacy: priv_hash }\n end", "def ecn_hash\n { model: @model,\n port: @port,\n area: @area,\n mac_address: @mac_address }\n end", "def get_header_section(dns_query)\n header_section = {}\n HEADER_FIELD_INDEX.each do |header, index|\n header_section[header] = dns_query[index[0], index[1]].unpack(\"n\")[0]\n end\n return header_section\n end", "def total_hash_search(hash_to_find=@hash_to_find, stop_on_success=@sos, verbose=true)\n matches={}\n while(true)\n case @hash_type\n when 'MD4'\n result = leakdb_hash_search(hash_to_find, verbose)\n if not result.nil?\n matches.store('api.leakdb.abusix.com', result)\n break if stop_on_success\n end\n when 'MD5'\n result = leakdb_hash_search(hash_to_find, verbose)\n if not result.nil?\n matches.store('api.leakdb.abusix.com', result)\n break if stop_on_success\n end\n\n result = darkbyte_hash_search(hash_to_find, verbose)\n if not result.nil?\n matches.store('md5.darkbyte.ru', result)\n break if stop_on_success\n end\n\n result = gromweb_hash_search(hash_to_find, verbose)\n if not result.nil?\n matches.store('md5.gromweb.com', result)\n break if stop_on_success\n end\n\n result = md5comcn_hash_search(hash_to_find, verbose)\n if not result.nil?\n matches.store('md5.com.cn', result)\n break if stop_on_success\n end\n\n result = md5onlinenet_hash_search(hash_to_find, verbose)\n if not result.nil?\n matches.store('md5online.net', result)\n break if stop_on_success\n end\n\n result = md5onlineorg_hash_search(hash_to_find, verbose)\n if not result.nil?\n matches.store('md5online.org', result)\n break if stop_on_success\n end\n\n result = myaddr_hash_search(hash_to_find, verbose)\n if not result.nil?\n matches.store('md5.my-addr.com', result)\n break if stop_on_success\n end\n\n result = noisette_hash_search(hash_to_find, verbose)\n if not result.nil?\n matches.store('md5.noisette.ch', result)\n break if stop_on_success\n end\n\n result = netmd5crack_hash_search(hash_to_find, verbose)\n if not result.nil?\n matches.store('netmd5crack.com', result)\n break if stop_on_success\n end\n\n result = sans_hash_search(hash_to_find, verbose)\n if not result.nil?\n matches.store('isc.sans.edu', result)\n break if stop_on_success\n end\n\n result = stringfunction_hash_search(hash_to_find, verbose)\n if not result.nil?\n matches.store('stringfunction.com', result)\n break if stop_on_success\n end\n when 'LM'\n result = it64_hash_search(hash_to_find, verbose)\n if not result.nil?\n matches.store('rainbowtables.it64.com', result)\n break if stop_on_success\n end\n\n result = leakdb_hash_search(hash_to_find, verbose)\n if not result.nil?\n matches.store('api.leakdb.abusix.com', result)\n break if stop_on_success\n end\n when 'NTLM'\n result = leakdb_hash_search(hash_to_find, verbose)\n if not result.nil?\n matches.store('api.leakdb.abusix.com', result)\n break if stop_on_success\n end\n when 'LM:NTLM'\n result = leakdb_hash_search(hash_to_find, verbose)\n if not result.nil?\n matches.store('api.leakdb.abusix.com', result)\n break if stop_on_success\n end\n when 'MYSQL'\n result = leakdb_hash_search(hash_to_find, verbose)\n if not result.nil?\n matches.store('api.leakdb.abusix.com', result)\n break if stop_on_success\n end\n when 'SHA1'\n result = leakdb_hash_search(hash_to_find, verbose)\n if not result.nil?\n matches.store('api.leakdb.abusix.com', result)\n break if stop_on_success\n end\n\n result = sans_hash_search(hash_to_find, verbose)\n if not result.nil?\n matches.store('isc.sans.edu', result)\n break if stop_on_success\n end\n\n result = stringfunction_hash_search(hash_to_find, verbose)\n if not result.nil?\n matches.store('stringfunction.com', result)\n break if stop_on_success\n end\n end\n break # tried all sites by now...\n end\n return matches\n end", "def leakdb_hash_search(hash_to_find=@hash_to_find, verbose=true)\n if @hash_type =~ /MD4|MD5|SHA1|SHA256|SHA512|LM|NT|MYSQL/\n res = @http.get(\"http://api.leakdb.abusix.com/?t=#{hash_to_find}\")\n if not res[0].nil? and res[0].strip.chomp != ''\n if res[0] =~ /plaintext=(.+)/\n plain_jane = $1.strip.chomp\n if verbose\n print_good(\"Match Found: api.leakdb.abusix.com\")\n puts \" [\".light_green + \"+\".white + \"] \".light_green + \"Hash: #{hash_to_find}\".white\n puts \" [\".light_green + \"+\".white + \"] \".light_green + \"Plain-Text: #{plain_jane.strip.chomp}\".white\n end\n return plain_jane\n end\n else\n print_error(\"No Results from: api.leakdb.abusix.com\") if verbose\n return nil\n end\n else\n print_error(\"#{@hash_type} not supported for: api.leakdb.abusix.com\") if verbose\n return nil\n end\n end", "def details\n details_hash = {}\n details_hash['total_value'] = total_value\n details_hash['address'] = @address\n details_hash\n end", "def ps_to_hash(ps)\n result = {}\n\n ps.each_pair do |k,v|\n if k == :uid\n begin\n result[:username] = Etc.getpwuid(v).name\n rescue Exception => e\n logger.debug(\"Could not get username for #{v}: #{e}\")\n result[:username] = v\n end\n end\n\n result[k] = v\n end\n\n result\n end", "def probe(link)\n output, status = call(\"plowprobe #{link} --printf '%c%n%m%n%f%n%s'\")\n return nil, status unless output\n\n lines = output.split(/\\n/)\n status = Status.from_plowshare(lines[0].to_i)\n hoster = lines[1]\n name = lines[2]\n size = lines[3].to_i\n info = {\n :size => size,\n :status => status,\n :hoster => hoster,\n :name => name,\n }\n\n return info, status\n end", "def to_hash\n h = {}\n self.all_redis_objects.each do |o|\n field = o[0]\n redis_type = o[1][:type] \n case redis_type\n when :value\n h[field] = try_a_number(self.method(field).call.value)\n when :set\n h[field] = self.method(field).call.members.map{ |x| try_a_number(x) }\n end\n end\n h\n end", "def hash\n [query, sample_rate].hash\n end", "def to_h\n hash = { 'WosUID' => uid }\n if doi.present?\n hash['doi'] = doi\n hash['doi_uri'] = doi_uri\n end\n if eissn.present?\n hash['eissn'] = eissn\n hash['eissn_uri'] = eissn_uri\n end\n if issn.present?\n hash['issn'] = issn\n hash['issn_uri'] = issn_uri\n end\n if pmid.present?\n hash['pmid'] = pmid\n hash['pmid_uri'] = pmid_uri\n end\n if wos_item_id.present?\n hash['WosItemID'] = wos_item_id\n hash['WosItemURI'] = wos_item_uri\n end\n hash\n end", "def query\n #NOTE: Prior to a fix for issue 1243, this method potentially returned a cached value\n #IF YOU CALL THIS METHOD, IT WILL CALL RPM\n #Use get(:property) to check if cached values are available\n cmd = [\"-q\", @resource[:name], \"#{self.class.nosignature}\", \"#{self.class.nodigest}\", \"--qf\", \"#{self.class::NEVRA_FORMAT}\"]\n\n begin\n output = rpm(*cmd)\n rescue Puppet::ExecutionFailure\n return nil unless @resource.allow_virtual?\n\n # rpm -q exits 1 if package not found\n # retry the query for virtual packages\n cmd << '--whatprovides'\n begin\n output = rpm(*cmd)\n rescue Puppet::ExecutionFailure\n # couldn't find a virtual package either\n return nil\n end\n end\n @property_hash.update(self.class.nevra_to_multiversion_hash(output))\n\n @property_hash.dup\n end", "def get_checksums(gf_pid, gf_identifier)\n query = \"SELECT algorithm, datetime, digest, generic_file_id \" +\n \"FROM checksums where generic_file_id = ?\"\n if @checksum_query.nil?\n @checksum_query = @db.prepare(query)\n end\n checksums = []\n result_set = @checksum_query.execute(gf_pid)\n result_set.each_hash do |row|\n cs = {}\n cs['algorithm'] = row['algorithm']\n cs['datetime'] = row['datetime']\n cs['digest'] = row['digest']\n checksums.push(cs)\n end\n checksums\n end", "def snmp\n raise ArgumentError, 'No SNMP options found for source' if @snmp_opts.nil?\n SNMP::Manager.new(@snmp_opts)\n end", "def hash\n shasum.hash\n end", "def hash\n shasum.hash\n end", "def hash\n shasum.hash\n end" ]
[ "0.6157912", "0.6037412", "0.57262534", "0.57256126", "0.57255334", "0.56743914", "0.5659326", "0.56244016", "0.5604151", "0.5479429", "0.5462078", "0.52830315", "0.5229554", "0.52291936", "0.5213674", "0.52029276", "0.51975584", "0.5140825", "0.511271", "0.50678647", "0.505101", "0.50217056", "0.5021424", "0.5017384", "0.5007787", "0.49817646", "0.49784267", "0.49663088", "0.49161008", "0.49105835", "0.49090037", "0.4904747", "0.49044764", "0.49025574", "0.4901467", "0.49008596", "0.48979026", "0.48944765", "0.48832574", "0.48784843", "0.48689178", "0.48656297", "0.48571315", "0.48488525", "0.48327035", "0.4829049", "0.48285636", "0.48276418", "0.4825608", "0.4825245", "0.48164546", "0.48060614", "0.48043966", "0.47976917", "0.4793725", "0.4793447", "0.47843018", "0.47790238", "0.4778869", "0.47781798", "0.47744134", "0.47676814", "0.47653472", "0.4764767", "0.47628835", "0.47617045", "0.47582236", "0.47577262", "0.4755421", "0.47474313", "0.47444746", "0.47435358", "0.47274357", "0.47264025", "0.4725616", "0.47240615", "0.47225592", "0.47201386", "0.47192743", "0.47059608", "0.47055817", "0.46978834", "0.4697234", "0.46952555", "0.46941558", "0.46892956", "0.46888238", "0.46883643", "0.46815297", "0.4677688", "0.46772686", "0.46729448", "0.4672315", "0.4671139", "0.46698302", "0.46686703", "0.46661383", "0.46653783", "0.46645594", "0.46645594", "0.46645594" ]
0.0
-1
Parse SNMPprovided information and alert based on thresholds.
def check_battery( host, snmp ) info = self.format_battery( snmp ) config = self.identifiers[ host ].last['config'] || {} cap_warn = config[ 'capacity_warn_at' ] || self.class.capacity_warn_at temp_warn = config[ 'temperature_warn_at' ] || self.class.temperature_warn_at in_use = info.dig( :battery, :in_use ) status = info.dig( :battery, :status ) capacity = info.dig( :battery, :capacity ) temperature = info.dig( :battery, :temperature ) warnings = [] if in_use mins = info.dig( :battery, :minutes_remaining ) || "(unknown)" warnings << "UPS on battery - %s minute(s) remaning." % [ mins ] end warnings << BATTERY_STATUS[ status ] if status != 2 warnings << "Battery remaining capacity %0.1f%% less than %0.1f percent" % [ capacity, cap_warn ] if capacity && capacity <= cap_warn warnings << "Battery temperature %dC greater than %dC" % [ temperature, temp_warn ] if temperature && temperature >= temp_warn info[ :warning ] = warnings.join( "\n" ) unless warnings.empty? self.results[ host ] = info end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parse_snmp_hosts(text)\n re = /host: ([^\\s]+)\\s+.*?port: (\\d+)\\s+type: (\\w+)\\s*user: (.*?)\\s+security model: (.*?)\\n/m # rubocop:disable Metrics/LineLength\n text.scan(re).map do |(host, port, type, username, auth)|\n resource_hash = { name: host, ensure: :present, port: port.to_i }\n sec_match = /^v3 (\\w+)/.match(auth)\n resource_hash[:security] = sec_match[1] if sec_match\n ver_match = /^(v\\d)/.match(auth) # first 2 characters\n resource_hash[:version] = ver_match[1] if ver_match\n resource_hash[:type] = type =~ /trap/ ? :traps : :informs\n resource_hash[:username] = username\n resource_hash\n end\n end", "def poll(agent, snmp)\n @snmp_manager = snmp\n\n unless get_names.empty?\n throughput_in = get_throughput_in\n throughput_in.each_key { |m| agent.report_counter_metric m, \"bits/sec\", throughput_in[m] } unless throughput_in.nil?\n\n throughput_out = get_throughput_out\n throughput_out.each_key { |m| agent.report_counter_metric m, \"bits/sec\", throughput_out[m] } unless throughput_out.nil?\n\n packets_in = get_packets_in\n packets_in.each_key { |m| agent.report_counter_metric m, \"pkts/sec\", packets_in[m] } unless packets_in.nil?\n\n packets_out = get_packets_out\n packets_out.each_key { |m| agent.report_counter_metric m, \"pkts/sec\", packets_out[m] } unless packets_out.nil?\n\n mcast_in = get_mcast_in\n mcast_in.each_key { |m| agent.report_counter_metric m, \"pkts/sec\", mcast_in[m] } unless mcast_in.nil?\n\n mcast_out = get_mcast_out\n mcast_out.each_key { |m| agent.report_counter_metric m, \"pkts/sec\", mcast_out[m] } unless mcast_out.nil?\n\n errors_in = get_errors_in\n errors_in.each_key { |m| agent.report_counter_metric m, \"errors/sec\", errors_in[m] } unless errors_in.nil?\n\n errors_out = get_errors_out\n errors_out.each_key { |m| agent.report_counter_metric m, \"errors/sec\", errors_out[m] } unless errors_out.nil?\n\n drops_in = get_drops_in\n drops_in.each_key { |m| agent.report_counter_metric m, \"drops/sec\", drops_in[m] } unless drops_in.nil?\n\n drops_out = get_drops_out\n drops_out.each_key { |m| agent.report_counter_metric m, \"drops/sec\", drops_out[m] } unless drops_out.nil?\n\n collisions = get_collisions\n collisions.each_key { |m| agent.report_counter_metric m, \"collisions/sec\", collisions[m] } unless collisions.nil?\n\n status = get_status\n status.each_key { |m| agent.report_metric m, status[m][:label], status[m][:count] } unless status.nil?\n end\n end", "def query_snmp(opts=nil)\n self.options = opts unless opts.nil?\n\n exit_code = nil\n exit_message = []\n index = 0\n has_rollup = false\n\n if results_cache.empty?\n debug(\"No results\\n\")\n exit_code = Nagios::UNKNOWN\n exit_message = [\"Invalid SNMP community string specified or snmp is disabled\"]\n else\n\n # concrete subclasses implement checks method\n checks.each do |check|\n unless results = results_cache[check[:name]]\n debug(\"No results for check %s\\n\" % check[:name])\n next\n end\n\n # Loop on possibly multiple lines of output\n results.each_line do |line|\n next unless line =~ check[:response]\n status = $1\n\n # Iterate over the expected return codes from a check.\n # line_exit_code,line_message = check[:codes][status]\n check[:codes].keys.each do |code|\n # Might want to support regex codes.\n # For now add support for 'any' value.\n next unless status == code || code == :any\n\n # Map to a nagios code\n # check[:codes][code] maps to a pair of ( nagios_code, message )\n line_exit_code = check[:codes][code][0]\n\n # Does it matter that index = 0?\n # Yes, currently rollup check must be first\n if index == 0 && check[:rollup]\n # Base the overall exit code only on the first check if it is marked as rollup.\n exit_code = line_exit_code\n exit_message = [\"OK\"] if exit_code == Nagios::OK\n has_rollup = true\n else\n\n # Sub checks only affect the message but not the exit code for rollups\n unless has_rollup\n exit_code = Status.worst_case(line_exit_code, exit_code)\n end\n\n # Only affect the message if not OK\n if exit_code != Nagios::OK && line_exit_code != Nagios::OK\n\n # Here, instead of the message being static, we generalized this\n # to call a custom function by symbol name, sending it the check value.\n # Main application thus far is to blow up a bit string.\n line_exit_message = build_message(check[:codes][code][1], status)\n prefix = \"\"\n\n unless check[:display].nil? || check[:display].empty?\n prefix = \"%s:\" % check[:display]\n end\n unless line_exit_message.empty?\n exit_message << \"%s%s\" % [prefix, line_exit_message]\n end\n end\n\n end\n end\n end\n index += 1\n end\n end\n # In case no checks ran or other pathological\n # cases lead to no assignments\n exit_code ||= Nagios::UNKNOWN\n if exit_message.empty?\n if exit_code == Nagios::OK\n exit_message = \"OK\"\n else\n exit_message = \"Unknown\"\n end\n else\n exit_message = exit_message.uniq.join(\",\")\n end\n\n Status.new(exit_code, exit_message)\n end", "def parse!\n self.interface_stats = Hash.new { |hash,key| hash[key] = {} }\n \n interface_names = Hash[self.raw_output.scan(/IF-MIB::ifDescr.(\\d+) = STRING: (\\w+)/m)]\n interface_types = Hash[self.raw_output.scan(/IF-MIB::ifType.(\\d+) = INTEGER: ([a-zA-Z0-9\\(\\)]+)/)]\n mac_addresses = Hash[self.raw_output.scan(/IF-MIB::ifPhysAddress.(\\d+) = STRING: ([0-9a-f:]+)/)]\n \n link_states = Hash[self.raw_output.scan(/IF-MIB::ifOperStatus.(\\d+) = INTEGER: (\\w+)\\(\\d\\)/)]\n octets_in = Hash[self.raw_output.scan(/IF-MIB::ifInOctets.(\\d+) = Counter32: (\\d+)/)]\n octets_out = Hash[self.raw_output.scan(/IF-MIB::ifOutOctets.(\\d+) = Counter32: (\\d+)/)]\n errors_in = Hash[self.raw_output.scan(/IF-MIB::ifInErrors.(\\d+) = Counter32: (\\d+)/)]\n errors_out = Hash[self.raw_output.scan(/IF-MIB::ifOutErrors.(\\d+) = Counter32: (\\d+)/)]\n \n interface_names.keys.each do |index|\n self.interface_stats[index][:name] = interface_names[index]\n self.interface_stats[index][:type] = interface_types[index]\n self.interface_stats[index][:mac] = mac_addresses[index]\n self.interface_stats[index][:in] = octets_in[index].to_i\n self.interface_stats[index][:out] = octets_out[index].to_i\n self.interface_stats[index][:errors_in] = errors_in[index].to_i\n self.interface_stats[index][:errors_out] = errors_out[index].to_i\n self.interface_stats[index][:up] = link_states[index] == \"up\"\n end\n \n self.interface_stats\n end", "def check_thresholds(data:)\n if data > @options[:critical].to_i\n @critical << @message\n elsif data > @options[:warning].to_i\n @warning << @message\n else\n @okays << @message\n end\n # make the final step\n build_final_output\n end", "def parse(source, output)\n source.each_line do |line|\n words = line.strip.squeeze(' \\t').split(/[ \\t\\/]/)\n if words && words[0] != \"ICMP\"\n #words.each { |x| print \"\\\"#{x}\\\"\\t\" }\n #print \"\\n\"\n if(words[8] == \"100%\") #total loss\n output << [words[0],'fault']\n elsif(words[8] != \"0%,\") #partial loss\n output << [words[0],'degraded']\n else \n output << [words[0],'ok']\n end\n end\n end\nend", "def parse_snmp_users(text)\n text.split(\"\\n\\n\").map do |user_s|\n user_s.scan(/^(\\w+).*?: (.*)/).each_with_object({}) do |(h, v), m|\n key = SNMP_USER_PARAM[h.downcase.intern] || h.downcase.intern\n m[key] = case key\n when :privacy then v =~ /AES/ ? :aes128 : :des\n when :version then v.sub('v2c', 'v2').intern\n when :auth then v.downcase.intern\n when :roles then v.sub(/ \\(.*?\\)/, '')\n else v.downcase\n end\n end\n end\n end", "def nutty_parse(thresh, want, got, v, element)\n retval = 'FAIL'\n\n # if there is a non-numeric character we have to deal with that\n # got < want\n if want =~ /^(\\d+):$/ then\n if got.to_i < $1.to_i then\n retval = '%s is below threshold value %s (%s)' % [element, $1, got]\n else\n retval = 'OK'\n end\n end\n\n # got > want\n if want =~ /^~:(\\d+)$/ then\n if got.to_i > $1.to_i then\n retval = '%s is above threshold value %s (%s)' % [element, $1, got]\n else\n retval = 'OK'\n end\n end\n\n # outside specific range\n if want =~ /^(\\d+):(\\d+)$/ then\n if got.to_i < $1.to_i or got.to_i > $2.to_i then\n retval = '%s is outside expected range [%s:%s] (%s)' % [element, $1, $2, got]\n else\n retval = 'OK'\n end\n end\n\n # inside specific range\n if want =~ /^@(\\d+):(\\d+)$/ then\n if got.to_i >= $1.to_i and got.to_i <= $2.to_i then\n retval = '%s is in value range [%s:%s] (%s)' % [element, $1, $2, got]\n else\n retval = 'OK'\n end\n end\n\n # otherwise general range\n if not want =~ /\\D/ then\n if got.to_i > want.to_i then\n retval = '%s is above threshold value %s (%s)' % [element, want, got]\n elsif got.to_i < 0 then\n retval = '%s is below 0 (%s)' % [element, got]\n else\n retval = 'OK'\n end\n end\n\n if retval == 'OK' then\n say(v, '%s threshold not exceeded.' % [thresh])\n elsif retval == 'KO' then\n say(v, '%s threshold exceeded.' % [thresh])\n else\n say(v, '\"%s\" is a strange and confusing %s value.' % [want, thresh])\n end\n\n return retval\nend", "def params_for_monitor(\n name,\n message,\n query,\n threshold,\n options = {\n escalation_message: nil,\n alert_no_data: true,\n mon_type: 'metric alert',\n renotify_interval: 60,\n no_data_timeframe: 20,\n evaluation_delay: nil\n }\n )\n options[:alert_no_data] = true unless options.key?(:alert_no_data)\n options[:mon_type] = 'metric alert' unless options.key?(:mon_type)\n options[:renotify_interval] = 60 unless options.key?(:renotify_interval)\n options[:no_data_timeframe] = 20 unless options.key?(:no_data_timeframe)\n options[:evaluation_delay] = nil unless options.key?(:evaluation_delay)\n\n # handle threshold hash\n thresh = if threshold.is_a?(Hash)\n threshold\n else\n { 'critical' => threshold }\n end\n\n monitor_data = {\n 'name' => name,\n 'type' => options[:mon_type],\n 'query' => query,\n 'message' => message,\n 'tags' => [],\n 'options' => {\n 'notify_audit' => false,\n 'locked' => false,\n 'timeout_h' => 0,\n 'silenced' => {},\n 'thresholds' => thresh,\n 'require_full_window' => false,\n 'notify_no_data' => options[:alert_no_data],\n 'renotify_interval' => options[:renotify_interval],\n 'no_data_timeframe' => options[:no_data_timeframe]\n }\n }\n unless options[:escalation_message].nil?\n monitor_data['options']['escalation_message'] = \\\n options[:escalation_message]\n end\n unless options[:evaluation_delay].nil?\n monitor_data['options']['evaluation_delay'] = options[:evaluation_delay]\n end\n monitor_data\n end", "def check_threshold\n rate = lines.length.to_f / expiry\n if rate > threshold\n alert_status\n elsif rate < threshold\n normal_status\n end\n end", "def nagios_check\n create_and_parse_cli_options\n return 1 unless check_options\n\n exit_code = Nagios::UNKNOWN\n\n begin\n # Instantiate the proper device\n device = create_device(options[:vendor], options[:model])\n # check if snmp community is correct or not for authentication\n if device.is_snmp_community_correct?(options[:community], options[:host])\n status = device.query_snmp(options)\n else\n status = Status.new(Nagios::WARNING, \"Invalid SNMP community string specified\")\n end\n exit_code = status.code\n message = status.message\n rescue StandardError => e\n message = \"%s\" % e\n exit_code = Nagios::UNKNOWN\n ensure\n puts message\n end\n exit_code\n end", "def snmp_basic(manager)\n # Grab some basic info using OID values which should be fairly generic in nature\n target = \"#{manager.config[:host]}:#{manager.config[:port]}\"\n cstring = manager.config[:community]\n snmp_version = manager.config[:version]\n sys_name = manager.get_value(\"sysName.0\")\n sys_descr = manager.get_value(\"sysDescr.0\")\n sys_time = manager.get_value(\"sysUpTime.0\")\n\n print_good(\"Target: #{target}\")\n print_good(\"Community String: #{cstring}\")\n print_good(\"Read Access: Enabled\")\n print_good(\"Write Access: Enabled\") if @wite_access\n print_good(\"Write Access: Disabled\") unless @wite_access\n if snmp_version\n print_good(\"SNMP Version: #{snmp_version}\")\n else\n print_error(\"Unable to determine SNMP Version in use?\")\n end\n if sys_name\n print_good(\"System Name: #{sys_name}\")\n else\n print_error(\"Unable to determine system name!\")\n end\n if sys_descr\n print_good(\"System Description: \\n#{sys_descr}\")\n else\n print_error(\"Unable to find system description!\")\n end\n if sys_time\n print_good(\"System Uptime: #{sys_time}\")\n else\n print_error(\"Unable to find system uptime!\")\n end\n end", "def parse_input attack_details\n attack_details_arr = attack_details.split(\":\")\n attack_details_arr.each do |attack_detail|\n tribal, direction, tribal_strength = attack_detail.split(\" - \")\n attacked?(tribal_strength.to_i, direction) ? @@attack_count += 1 : 0\n end\n rebuild_wall(attack_details_arr)\n print_outcome\n end", "def parse\n\t\tfile = File.new(@filename, \"r\")\n\t\tline = file.gets.chomp\n\t\twhile !line.nil?\n\t\t\tif line =~ /(Underflow|Overflow)/ #if exception\n\t\t\t\tline =~ /Overflow/ ? overflow = true : overflow = false\n\t\t\t\tidentifier = line[/[0-9][0-9]*/] #get exception identifier\n\t\t\t\tline = file.gets.chomp\t\t\t\t\t\n\t\t\t\tline = file.gets.chomp if line =~ /The constraints are unsat/\t\t\t\t\n\t\t\t\tline = file.gets.chomp if line =~ /KLEE: WARNING:/\t\t\t\t\n\t\t\t\t# For a given identifier, there can me multiple warnings of a potential \n\t\t\t\t# overflow/underflow, store only the last one.\n\t\t\t\t# By creating a new array, previous values are overwritten\n\t\t\t\tvalues = []\n\t\t\t\twhile line =~ /^arr[0-9]/\t#if arr value\n\t\t\t\t\tline = file.gets.chomp\n\t\t\t\t\t#~ puts \"#{identifier}: #{line}\"\t#debugging\n\t\t\t\t\tvalues.push line #store value as sring with no regard to type (rational, float, integer)\t\t\t\t\t\n\t\t\t\t\tline = file.gets.chomp\n\t\t\t\tend\n\t\t\t\tif not values.empty? #if some arr values were found, store them\t\t\t\t\t\n\t\t\t\t\toverflow ? @overflow[\"#{identifier}\"] = values : @underflow[\"#{identifier}\"] = values\n\t\t\t\tend\n\t\t\telse \n\t\t\t\tline = file.gets #if not exception warning\n\t\t\tend\n\t\tend #iterate over lines in file\n\tend", "def poll(agent, snmp)\n @snmp_manager = snmp\n @f5_agent = agent\n\n unless get_names.empty?\n get_requests\n get_conns_current\n get_conns_total\n get_packets_in\n get_packets_out\n get_throughput_in\n get_throughput_out\n get_cpu_usage_1m\n end\n end", "def perform\n result, status = execute_ping_command\n\n # we only process `successful` ping.\n return parsed(status: status) unless status == 0\n\n _, site, ip, _ = result.match(regex_ping)[0].split(\" \")\n ip.gsub!(regex_filter, \"\")\n loss = result.match(regex_loss) ? $&.to_f : 100\n\n if stat = result.match(regex_stat)\n parsed(ip: ip, site: site, loss: loss,\n max: stat[\"max\"].to_f, min: stat[\"min\"].to_f,\n avg: stat[\"avg\"].to_f, stddev: stat[\"stddev\"]&.to_f || 0.0)\n else\n parsed(ip: ip, site: site, loss: loss, status: status)\n end\n end", "def parse_energy\n \tenergy_hash = parse_hash\n \t# total energy produced\n \ttemp_array = []\n \ttemp_array = energy_hash.to_a\n \t# runtime in hours\n \t@energy_run_time = (temp_array[temp_array.length - 1][0] - temp_array[0][0])/3600.0\n \t# energy in Wh\n \t@energy_amount = (temp_array[temp_array.length - 1][1] - temp_array[0][1])\n\n \t# if the program parsed energy before power, do power now\n \t@parsed_energy = true\n \tread_file unless @parsed_power\n \toutput_report\n end", "def gather_threshold_totals\n rules.each{|field_to_validate, field_options|\n field_threshold = return_threshold(field_to_validate, field_options)\n if field_threshold\n gather_field_threshold_totals(field_to_validate, field_options)\n else\n gather_specific_validation_totals(field_to_validate, field_options)\n end\n }\n end", "def parse_conditional_drops\n \n @conditional_drops = []\n \n tmp = nil\n \n note.split(/[\\r\\n]+/).each do |l|\n case l\n when /<c_drop:[ ]*(.*)[ ](-*\\d+)>/i\n tmp = CDrop.new\n @conditional_drops.push(tmp)\n tmp.conditional_drop = [$1, $2.to_i]\n when /<c_type:[ ]*([a-z]*)[ ]*(\\d+)*>/i\n tmp.conditional_drop_type = [$1.to_sym, $2.to_i]\n when /<c_chance:[ ]*(\\d+)[%]*>/i\n tmp.conditional_drop_chance = $1.to_f\n when /<c_formula>/i\n @c_drop_formula = true\n when /<\\\\c_formula>/i\n @c_drop_formula = false\n else\n tmp.conditional_formula += l if @c_drop_formula\n end\n end\n end", "def poll(agent, snmp)\n @snmp_manager = snmp\n @f5_agent = agent\n\n unless get_names.empty?\n get_requests\n get_conns_current\n get_conns_total\n get_packets_in\n get_packets_out\n get_throughput_in\n get_throughput_out\n end\n end", "def parse_poll(instance, onevm, do_cw, cw_mon_time)\n begin\n if onevm\n if do_cw\n cloudwatch_str = cloudwatch_monitor_info(instance.instance_id,\n onevm,\n cw_mon_time)\n else\n previous_cpu = onevm[\"MONITORING/CPU\"] || 0\n previous_netrx = onevm[\"MONITORING/NETRX\"] || 0\n previous_nettx = onevm[\"MONITORING/NETTX\"] || 0\n\n cloudwatch_str = \"CPU=#{previous_cpu} NETTX=#{previous_nettx} NETRX=#{previous_netrx} \"\n end\n else\n cloudwatch_str = \"\"\n end\n\n mem = onevm[\"TEMPLATE/MEMORY\"].to_s\n mem=mem.to_i*1024\n info = \"#{POLL_ATTRIBUTE[:memory]}=#{mem} #{cloudwatch_str}\"\n\n state = \"\"\n if !instance.exists?\n state = VM_STATE[:deleted]\n else\n state = case instance.state.name\n when 'pending'\n VM_STATE[:active]\n when 'running'\n VM_STATE[:active]\n when 'shutting-down', 'terminated'\n VM_STATE[:deleted]\n else\n VM_STATE[:unknown]\n end\n end\n info << \"#{POLL_ATTRIBUTE[:state]}=#{state} \"\n\n EC2_POLL_ATTRS.map { |key|\n value = instance.send(key)\n if !value.nil? && !value.empty?\n if value.is_a?(Array)\n value = value.map {|v|\n v.group_id if v.is_a?(Aws::EC2::Types::GroupIdentifier)\n }.join(\",\")\n end\n\n info << \"AWS_#{key.to_s.upcase}=\\\\\\\"#{URI::encode(value)}\\\\\\\" \"\n end\n }\n\n info\n rescue\n # Unkown state if exception occurs retrieving information from\n # an instance\n \"#{POLL_ATTRIBUTE[:state]}=#{VM_STATE[:unknown]} \"\n end\n end", "def perform\n \n users = User.all\n \n users.each do |user|\n \n alerts = user.alerts.unarchived.enabled\n \n alerts.each do |alert|\n \n well = Well.find(alert.well_id)\n metrics = Well_Metric.all(:conditions => [\"well_id = ? AND created_at IN (?)\", well.id, (alert.last_scanned_at.to_date)..Time.now])\n \n metrics.each do |metric|\n \n \n if (alert.type == \"voltage_line_1_upper\" && metric.metric_type == \"voltage_line_1\")\n \n if(metric.value > alert.float_value)\n fault = Fault.build(:well_id => well.id,\n :user_id => user.id,\n :well_metric_id => metric.id,\n :alert_id => alert.id\n :type => alert.type)\n # SEND EMAIL/TEXT BROWSER NOTIFICATION\n end\n \n elsif (alert.type == \"voltage_line_1_lower\" && metric.metric_type == \"voltage_line_1\" )\n \n if(metric.value < alert.float_value)\n fault = Fault.build(:well_id => well.id,\n :user_id => user.id,\n :well_metric_id => metric.id,\n :alert_id => alert.id\n :type => alert.type)\n # SEND EMAIL/TEXT BROWSER NOTIFICATION\n end\n \n elsif (alert.type == \"voltage_line_2_upper\" && metric.metric_type == \"voltage_line_2\")\n \n if(metric.value > alert.float_value)\n fault = Fault.build(:well_id => well.id,\n :user_id => user.id,\n :well_metric_id => metric.id,\n :alert_id => alert.id\n :type => alert.type)\n # SEND EMAIL/TEXT BROWSER NOTIFICATION\n end\n \n elsif (alert.type == \"voltage_line_2_lower\" && metric.metric_type == \"voltage_line_2\")\n \n if(metric.value < alert.float_value)\n fault = Fault.build(:well_id => well.id,\n :user_id => user.id,\n :well_metric_id => metric.id,\n :alert_id => alert.id\n :type => alert.type)\n # SEND EMAIL/TEXT BROWSER NOTIFICATION\n end\n \n elsif (alert.type == \"current_line_1_upper\" && metric.metric_type == \"current_line_1\")\n \n if(metric.value > alert.float_value)\n fault = Fault.build(:well_id => well.id,\n :user_id => user.id,\n :well_metric_id => metric.id,\n :alert_id => alert.id\n :type => alert.type)\n # SEND EMAIL/TEXT BROWSER NOTIFICATION\n end\n \n elsif (alert.type == \"current_line_1_lower\" && metric.metric_type == \"current_line_1\")\n \n if(metric.value < alert.float_value)\n fault = Fault.build(:well_id => well.id,\n :user_id => user.id,\n :well_metric_id => metric.id,\n :alert_id => alert.id\n :type => alert.type)\n # SEND EMAIL/TEXT BROWSER NOTIFICATION\n end\n \n elsif (alert.type == \"current_line_2_upper\" && metric.metric_type == \"current_line_2\")\n \n if(metric.value > alert.float_value)\n fault = Fault.build(:well_id => well.id,\n :user_id => user.id,\n :well_metric_id => metric.id,\n :alert_id => alert.id\n :type => alert.type)\n # SEND EMAIL/TEXT BROWSER NOTIFICATION\n end\n \n elsif (alert.type == \"current_line_2_lower\" && metric.metric_type == \"current_line_2\")\n \n if(metric.value < alert.float_value)\n fault = Fault.build(:well_id => well.id,\n :user_id => user.id,\n :well_metric_id => metric.id,\n :alert_id => alert.id\n :type => alert.type)\n # SEND EMAIL/TEXT BROWSER NOTIFICATION\n end\n \n elsif (alert.type == \"water_depth_upper\" && metric.metric_type == \"water_depth\")\n \n if(metric.value > alert.float_value)\n fault = Fault.build(:well_id => well.id,\n :user_id => user.id,\n :well_metric_id => metric.id,\n :alert_id => alert.id\n :type => alert.type)\n # SEND EMAIL/TEXT BROWSER NOTIFICATION\n end\n \n elsif (alert.type == \"water_depth_lower\" && metric.metric_type == \"water_depth\")\n \n if(metric.value < alert.float_value)\n fault = Fault.build(:well_id => well.id,\n :user_id => user.id,\n :well_metric_id => metric.id,\n :alert_id => alert.id\n :type => alert.type)\n # SEND EMAIL/TEXT BROWSER NOTIFICATION\n end\n \n end\n \n alert.last_scanned_at = Time.now\n alert.save\n \n end\n end\n end\nend", "def get_eaps_status\n cmd = 'show eaps'\n regex = /\\b\\d\\s.+/\n data_splitter = /\\s+/\n\n result = get_low_level_data(cmd, regex, data_splitter)\n result.map { |e| e || '' } if !result.nil? # replaces nil values\n\n\n result.nil? ? [\"\", \"\", \"no eaps configured\", \"\", \"\", \"\", \"\", \"\"] : result\n\n # sample text\n # D2SPO10CDR01#sh eaps\n # EAPS information:\n #\n # Mode: M - Master\n # T - Transit\n #\n # Pri Sec Ctrl Protected\n # ID Domain State Mode Port Port VLAN Groups/VLANs\n # -- --------------- --------------- ---- ------ ------ ---- ------------\n # 0 gvt Links-Up T 1/25 1/26 4094 1/4093\n #\n # D2SPO10CDR01#\n end", "def check_for_alerts(intervals)\n min = @threshold\n alert = nil\n conditions = @conditions[min]\n intervals.each do |time, swell_info|\n recent = false\n conditions.each do |type, value|\n if swell_info[type] >= value\n alert = min\n recent = true\n min += 1\n return alert if min > @max_level\n conditions = @conditions[min]\n break\n end\n end\n redo if recent\n end\n alert\n end", "def processNewAlerts\n @session.alerts.each{ |alert|\n if alert.is_a? Libtorrent::TorrentAlert\n if alert.handle.valid? && alert.handle.has_metadata\n addToHashList @torrentAlerts, alert.handle.name, alert\n end\n else\n @globalAlerts.push alert\n # For now since nothing is reading the alerts, just store a max of \n # 5.\n @globalAlerts.shift if @globalAlerts.length > 5\n end\n }\n end", "def get_snmp\n\n # onvide le tableau des résultats précédents\n @deltas.clear\n # var temporaire pour détecter le changement de valeur d'index dans la liste de résultats\n tmp_index = ''\n\n # requête SNMP get :\n # la requête renvoie une ligne par index, cette ligne peut être in ou out,\n # les lignes in et out de chaque index se suivent forcément.\n response = @manager.get(@oids) \n response.each_varbind do |oid|\n # récupération de la valeur de l'index sur la ligne de résultat : chaîne après le \".\"\n index = oid.name.to_s.split('.')[1].to_s\n if (tmp_index == index) then\n # si le nom est le même que la ligne lue précédente, on vient donc de lire la 2° ligne => out\n # on supprime le dernier élément du tableau @out et on y ajoute au début la mesure out.\n # idem avec le timestamp de la mesure.\n @out[index].shift\n @out[index].push(oid.value.to_i)\n @ts[index].shift\n @ts[index].push(Time.now.to_i)\n\n # calcul du delta in et out par intervalle de ts_delta\n ts_delta = @ts[index][1] - @ts[index][0]\n out_delta = (@out[index][1] - @out[index][0]) / ts_delta\n in_delta = (@in[index][1] - @in[index][0]) / ts_delta\n\n # récupération de l'objet Interface de cet index\n iface = @interfaces[index]\n\n # création d'un hash de résultat de la mesure pour chaque index\n # et ajout de ce hash dans le tableau @port_names\n port_delta = { name: iface.name, descr: iface.descr, speed: iface.speed ,octInOut: [in_delta, out_delta] }\n @deltas.push(port_delta)\n else\n # index == tmp_index, donc on lit la première ligne d'index => in\n # on supprime le dernier élément du tableau @in et on y ajoute au début la mesure in\n @in[index].shift\n @in[index].push(oid.value.to_i)\n tmp_index = index\n end\n end\n return @deltas \n end", "def parseping(output)\n res = Hash.new\n begin\n res[:success] = 100 - Integer(output.match(/([[:digit:]]+)% packet loss/m)[1])\n res[:rtt] = Float(output.match(/= [[:digit:]\\.]+\\/([[:digit:]\\.]+)\\//m)[1])\n rescue NoMethodError, TypeError\n # Do nothing, just fall through and return the empty hash.\n end\n res\nend", "def get_site_snmp_alerts_with_http_info(id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: SiteApi.get_site_snmp_alerts ...\"\n end\n # verify the required parameter 'id' is set\n if @api_client.config.client_side_validation && id.nil?\n fail ArgumentError, \"Missing the required parameter 'id' when calling SiteApi.get_site_snmp_alerts\"\n end\n # resource path\n local_var_path = \"/api/3/sites/{id}/alerts/snmp\".sub('{' + 'id' + '}', id.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;charset=UTF-8'])\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 = []\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 => 'ResourcesSnmpAlert')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: SiteApi#get_site_snmp_alerts\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def get_site_snmp_alerts_with_http_info(id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: SiteApi.get_site_snmp_alerts ...'\n end\n # verify the required parameter 'id' is set\n if @api_client.config.client_side_validation && id.nil?\n fail ArgumentError, \"Missing the required parameter 'id' when calling SiteApi.get_site_snmp_alerts\"\n end\n # resource path\n local_var_path = '/api/3/sites/{id}/alerts/snmp'.sub('{' + 'id' + '}', id.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;charset=UTF-8'])\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 = []\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 => 'ResourcesSnmpAlert')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: SiteApi#get_site_snmp_alerts\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def read_snmp_service_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: NsxComponentAdministrationApi.read_snmp_service ...\"\n end\n # resource path\n local_var_path = \"/node/services/snmp\"\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 = ['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 => 'NodeSnmpServiceProperties')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: NsxComponentAdministrationApi#read_snmp_service\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def monitor_poll_vm\n reset_monitor\n\n return unless @vm.get_vm_id\n\n @state = state_to_c(@vm['summary.runtime.powerState'])\n\n if @state != VM_STATE[:active]\n reset_monitor\n return\n end\n\n cpu_mhz = @vm['runtime.host.summary.hardware.cpuMhz'].to_f\n\n @monitor[:used_memory] = @vm['summary.quickStats.hostMemoryUsage'] *\n 1024\n\n used_cpu = @vm['summary.quickStats.overallCpuUsage'].to_f / cpu_mhz\n used_cpu = (used_cpu * 100).to_s\n @monitor[:used_cpu] = format('%.2f', used_cpu).to_s\n\n # Check for negative values\n @monitor[:used_memory] = 0 if @monitor[:used_memory].to_i < 0\n @monitor[:used_cpu] = 0 if @monitor[:used_cpu].to_i < 0\n\n guest_ip_addresses = []\n unless @vm['guest.net'].empty?\n @vm['guest.net'].each do |net|\n next unless net.ipConfig\n next if net.ipConfig.ipAddress.empty?\n\n net.ipConfig.ipAddress.each do |ip|\n guest_ip_addresses << ip.ipAddress\n end\n end\n end\n\n @guest_ip_addresses = guest_ip_addresses.join(',')\n\n pm = @vm['_connection'].serviceInstance.content.perfManager\n\n provider = pm.provider_summary(@vm.item)\n\n refresh_rate = provider.refreshRate\n\n stats = {}\n\n if @one_vm['MONITORING/LAST_MON'] &&\n @one_vm['MONITORING/LAST_MON'].to_i != 0\n # Real time data stores max 1 hour. 1 minute has 3 samples\n interval = (Time.now.to_i -\n @one_vm['MONITORING/LAST_MON'].to_i)\n\n # If last poll was more than hour ago get 3 minutes,\n # else calculate how many samples since last poll\n if interval > 3600\n samples = 9\n else\n samples = (interval / refresh_rate) + 1\n end\n samples > 0 ? max_samples = samples : max_samples = 1\n\n stats = pm.retrieve_stats(\n [@vm.item],\n ['net.transmitted', 'net.bytesRx', 'net.bytesTx',\n 'net.received', 'virtualDisk.numberReadAveraged',\n 'virtualDisk.numberWriteAveraged', 'virtualDisk.read',\n 'virtualDisk.write'],\n interval => refresh_rate, max_samples => max_samples\n ) rescue {}\n else\n # First poll, get at least latest 3 minutes = 9 samples\n stats = pm.retrieve_stats(\n [@vm.item],\n ['net.transmitted', 'net.bytesRx', 'net.bytesTx',\n 'net.received', 'virtualDisk.numberReadAveraged',\n 'virtualDisk.numberWriteAveraged', 'virtualDisk.read',\n 'virtualDisk.write'],\n interval => refresh_rate, max_samples => 9\n ) rescue {}\n end\n\n if !stats.empty? && !stats.first[1][:metrics].empty?\n metrics = stats.first[1][:metrics]\n\n nettx_kbpersec = 0\n if metrics['net.transmitted']\n metrics['net.transmitted'].each do |sample|\n nettx_kbpersec += sample if sample > 0\n end\n end\n\n netrx_kbpersec = 0\n if metrics['net.bytesRx']\n metrics['net.bytesRx'].each do |sample|\n netrx_kbpersec += sample if sample > 0\n end\n end\n\n read_kbpersec = 0\n if metrics['virtualDisk.read']\n metrics['virtualDisk.read'].each do |sample|\n read_kbpersec += sample if sample > 0\n end\n end\n\n read_iops = 0\n if metrics['virtualDisk.numberReadAveraged']\n metrics['virtualDisk.numberReadAveraged'].each do |sample|\n read_iops += sample if sample > 0\n end\n end\n\n write_kbpersec = 0\n if metrics['virtualDisk.write']\n metrics['virtualDisk.write'].each do |sample|\n write_kbpersec += sample if sample > 0\n end\n end\n\n write_iops = 0\n if metrics['virtualDisk.numberWriteAveraged']\n metrics['virtualDisk.numberWriteAveraged'].each do |sample|\n write_iops += sample if sample > 0\n end\n end\n\n else\n nettx_kbpersec = 0\n netrx_kbpersec = 0\n read_kbpersec = 0\n read_iops = 0\n write_kbpersec = 0\n write_iops = 0\n end\n\n # Accumulate values if present\n if @one_item && @one_item['MONITORING/NETTX']\n previous_nettx = @one_item['MONITORING/NETTX'].to_i\n else\n previous_nettx = 0\n end\n\n if @one_item && @one_item['MONITORING/NETRX']\n previous_netrx = @one_item['MONITORING/NETRX'].to_i\n else\n previous_netrx = 0\n end\n\n if @one_item && @one_item['MONITORING/DISKRDIOPS']\n previous_diskrdiops = @one_item['MONITORING/DISKRDIOPS'].to_i\n else\n previous_diskrdiops = 0\n end\n\n if @one_item && @one_item['MONITORING/DISKWRIOPS']\n previous_diskwriops = @one_item['MONITORING/DISKWRIOPS'].to_i\n else\n previous_diskwriops = 0\n end\n\n if @one_item && @one_item['MONITORING/DISKRDBYTES']\n previous_diskrdbytes = @one_item['MONITORING/DISKRDBYTES'].to_i\n else\n previous_diskrdbytes = 0\n end\n\n if @one_item && @one_item['MONITORING/DISKWRBYTES']\n previous_diskwrbytes = @one_item['MONITORING/DISKWRBYTES'].to_i\n else\n previous_diskwrbytes = 0\n end\n\n @monitor[:nettx] = previous_nettx +\n (nettx_kbpersec * 1024 * refresh_rate).to_i\n @monitor[:netrx] = previous_netrx +\n (netrx_kbpersec * 1024 * refresh_rate).to_i\n\n @monitor[:diskrdiops] = previous_diskrdiops + read_iops\n @monitor[:diskwriops] = previous_diskwriops + write_iops\n @monitor[:diskrdbytes] = previous_diskrdbytes +\n (read_kbpersec * 1024 * refresh_rate).to_i\n @monitor[:diskwrbytes] = previous_diskwrbytes +\n (write_kbpersec * 1024 * refresh_rate).to_i\n end", "def monitor\n @summary = @vm.summary\n @state = state_to_c(@summary.runtime.powerState)\n\n if @state != 'a'\n @used_cpu = 0\n @used_memory = 0\n\n @net_rx = 0\n @net_tx = 0\n\n return\n end\n\n @used_memory = @summary.quickStats.hostMemoryUsage * 1024\n\n host = VIDriver::host\n cpuMhz = host.cpuMhz.to_f\n @used_cpu =\n ((@summary.quickStats.overallCpuUsage.to_f / cpuMhz) * 100).to_s\n @used_cpu = sprintf('%.2f',@used_cpu).to_s\n\n vm_stats = VIDriver::retrieve_stats([@vm],\n [\"net.packetsRx\",\"net.packetsTx\"])\n @net_rx = 0\n @net_tx = 0\n\n if vm_stats[@vm] && vm_stats[@vm][:metrics]\n if vm_stats[@vm][:metrics][\"net.packetsRx\"]\n @net_rx = vm_stats[@vm][:metrics][\"net.packetsRx\"].first\n end\n\n if vm_stats[@vm][:metrics][\"net.packetsTx\"]\n @net_tx = vm_stats[@vm][:metrics][\"net.packetsTx\"].first\n end\n end\n\n # Check for negative values\n @used_memory = 0 if @used_memory.to_i < 0\n @used_cpu = 0 if @used_cpu.to_i < 0\n @net_rx = 0 if @net_rx.to_i < 0\n @net_tx = 0 if @net_tx.to_i < 0\n end", "def analyze!\n if nova_score_above_threshold?\n APPROVE_VALUE\n else\n DENIAL_VALUE\n end\n end", "def report\n if data[:ping].nil?\n @fails += 1\n if @fails >= @alert_after\n alarm \"Miner #{@num} did not respond to status query\"\n end\n else\n @fails = 0\n if self[:mhs] < @min_speed*0.95 and upminutes > 5\n alarm \"Miner #{@num} performance is #{self[:mhs]}, should be #{@min_speed}\"\n elsif upminutes < 2\n alarm \"Miner #{@num} restarted\", \"Frog.aiff\"\n end\n end\n end", "def initialize(hits_alert_threshold: 500, threshold: 120)\n super()\n\n @alerts = []\n @queue = []\n @hits_alert_threshold = hits_alert_threshold\n @threshold = threshold\n end", "def poll_cycle\n NewRelic::PlatformLogger.debug(\"Starting poll cycle for '#{hostname}'\")\n\n # SNMP Stuff here\n snmp = SNMP::Manager.new(:host => hostname, :port => port, :community => snmp_community)\n\n #\n # Test our SNMP connection, return if we fail to connect so the entire agent doesn't quit\n #\n begin\n product_name = snmp.get_value([\"1.3.6.1.4.1.3375.2.1.4.1.0\"]).first\n NewRelic::PlatformLogger.debug(\"Found F5 device of type: '#{product_name}'\")\n rescue SNMP::RequestTimeout\n NewRelic::PlatformLogger.error(\"Unable to connect to device: '#{hostname}', skipping...\")\n snmp.close\n return\n rescue => e\n NewRelic::PlatformLogger.error(e)\n snmp.close\n return\n end\n\n\n # Platform metrics\n NewRelic::PlatformLogger.debug(\"Collecting Platform stats\")\n @platform ||= NewRelic::F5Plugin::Platform.new\n @platform.poll(self, snmp)\n\n # Device wide metrics\n NewRelic::PlatformLogger.debug(\"Collecting System stats\")\n @system ||= NewRelic::F5Plugin::Device.new\n @system.poll(self, snmp)\n\n # Device Interface metrics\n NewRelic::PlatformLogger.debug(\"Collecting Interface stats\")\n @interfaces ||= NewRelic::F5Plugin::Interfaces.new\n @interfaces.poll(self, snmp)\n\n # Node stats\n NewRelic::PlatformLogger.debug(\"Collecting Node stats\")\n @nodes ||= NewRelic::F5Plugin::Nodes.new\n @nodes.poll(self, snmp)\n\n # Collect virtual server statistics\n NewRelic::PlatformLogger.debug(\"Collecting Virtual Server stats\")\n @virtuals ||= NewRelic::F5Plugin::Virtuals.new\n @virtuals.poll(self, snmp)\n\n # Collect pool statistics\n NewRelic::PlatformLogger.debug(\"Collecting Pool stats\")\n @pools ||= NewRelic::F5Plugin::Pools.new\n @pools.poll(self, snmp)\n\n # iRule statistics\n NewRelic::PlatformLogger.debug(\"Collecting iRule stats\")\n @rules ||= NewRelic::F5Plugin::Rules.new\n @rules.poll(self, snmp)\n\n # Collect snat pool statistics\n NewRelic::PlatformLogger.debug(\"Collecting SNAT Pool stats\")\n @snatpools ||= NewRelic::F5Plugin::SnatPools.new\n @snatpools.poll(self, snmp)\n\n # Collect Client SSL Profile statistics\n NewRelic::PlatformLogger.debug(\"Collecting Client SSL Profile stats\")\n @clientssl ||= NewRelic::F5Plugin::ClientSsl.new\n @clientssl.poll(self, snmp)\n\n # Collect Global SSL statistics\n NewRelic::PlatformLogger.debug(\"Collecting Global SSL stats\")\n @globalssl ||= NewRelic::F5Plugin::GlobalSsl.new\n @globalssl.poll(self, snmp)\n\n # Cleanup snmp connection\n snmp.close\n end", "def get_site_snmp_alert_with_http_info(id, alert_id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: SiteApi.get_site_snmp_alert ...\"\n end\n # verify the required parameter 'id' is set\n if @api_client.config.client_side_validation && id.nil?\n fail ArgumentError, \"Missing the required parameter 'id' when calling SiteApi.get_site_snmp_alert\"\n end\n # verify the required parameter 'alert_id' is set\n if @api_client.config.client_side_validation && alert_id.nil?\n fail ArgumentError, \"Missing the required parameter 'alert_id' when calling SiteApi.get_site_snmp_alert\"\n end\n # resource path\n local_var_path = \"/api/3/sites/{id}/alerts/snmp/{alertId}\".sub('{' + 'id' + '}', id.to_s).sub('{' + 'alertId' + '}', alert_id.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;charset=UTF-8'])\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 = []\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 => 'SnmpAlert')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: SiteApi#get_site_snmp_alert\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def get_site_snmp_alert_with_http_info(id, alert_id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: SiteApi.get_site_snmp_alert ...'\n end\n # verify the required parameter 'id' is set\n if @api_client.config.client_side_validation && id.nil?\n fail ArgumentError, \"Missing the required parameter 'id' when calling SiteApi.get_site_snmp_alert\"\n end\n # verify the required parameter 'alert_id' is set\n if @api_client.config.client_side_validation && alert_id.nil?\n fail ArgumentError, \"Missing the required parameter 'alert_id' when calling SiteApi.get_site_snmp_alert\"\n end\n # resource path\n local_var_path = '/api/3/sites/{id}/alerts/snmp/{alertId}'.sub('{' + 'id' + '}', id.to_s).sub('{' + 'alertId' + '}', alert_id.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;charset=UTF-8'])\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 = []\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 => 'SnmpAlert')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: SiteApi#get_site_snmp_alert\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def create_site_snmp_alert_with_http_info(id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: SiteApi.create_site_snmp_alert ...\"\n end\n # verify the required parameter 'id' is set\n if @api_client.config.client_side_validation && id.nil?\n fail ArgumentError, \"Missing the required parameter 'id' when calling SiteApi.create_site_snmp_alert\"\n end\n # resource path\n local_var_path = \"/api/3/sites/{id}/alerts/snmp\".sub('{' + 'id' + '}', id.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;charset=UTF-8'])\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(opts[:'alert'])\n auth_names = []\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 => 'ReferenceWithAlertIDLink')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: SiteApi#create_site_snmp_alert\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def query\n process_switch(@oid) do |oid,value|\n case oid.to_str\n when @oid[0]; @status = (value == '1' ? 'ok' : (value == '3' ? 'Critical' : 'Non-critical')) \n when @oid[1], @oid[2], @oid[3]; @txt_result += value.gsub(/;/,\"\\n\")\n when @oid[4]; @txt_result += ( value == '0' ? \"PowerSupply1: Off\\n\" : (value == '1' ? \"PowerSupply1: On\\n\" : \"PowerSupply1: Missing\\n\") )\n when @oid[5]; @txt_result += ( value == '0' ? \"PowerSupply2: Off\\n\" : (value == '1' ? \"PowerSupply2: On\\n\" : \"PowerSupply2: Missing\\n\") )\n when @oid[6]; @txt_result += ( value == '1' ? \"Have Panic Dump in Flash\\n\" : \"\" )\n else STDERR.puts \"Unknown OID '#{oid}' '#{value}'\"\n end\n end\n end", "def create_site_snmp_alert_with_http_info(id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: SiteApi.create_site_snmp_alert ...'\n end\n # verify the required parameter 'id' is set\n if @api_client.config.client_side_validation && id.nil?\n fail ArgumentError, \"Missing the required parameter 'id' when calling SiteApi.create_site_snmp_alert\"\n end\n # resource path\n local_var_path = '/api/3/sites/{id}/alerts/snmp'.sub('{' + 'id' + '}', id.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;charset=UTF-8'])\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(opts[:'alert'])\n auth_names = []\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 => 'ReferenceWithAlertIDLink')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: SiteApi#create_site_snmp_alert\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def read_snmp_service_status_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: NsxComponentAdministrationApi.read_snmp_service_status ...\"\n end\n # resource path\n local_var_path = \"/node/services/snmp/status\"\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 = ['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 => 'NodeServiceStatusProperties')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: NsxComponentAdministrationApi#read_snmp_service_status\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def parse\n @meta = parse_meta\n @comments = parse_comments\n @sensors = parse_sensors\n @workout = parse_workout\n @intervals = parse_intervals\n @interval_samples = parse_interval_samples\n end", "def execute_alerts\n #iterate through all alerts, filtering out ones that don't match; with each of the remaining alerts, call Alert#notify_user\n # ad_options = self.options.includes(:option_value) #.includes(:option_class)\n ad_options = self.combined_options\n matching_alerts = []\n \n self.candidate_alerts.each do |alert|\n matching_alert = true\n \n unless(matches_date_or_integer_options?(alert.alert_integer_options, ad_options) &&\n matches_date_or_integer_options?(alert.alert_date_options, ad_options) && \n matches_string_or_boolean_options?(alert.alert_string_options, ad_options) &&\n matches_string_or_boolean_options?(alert.alert_boolean_options, ad_options))\n \n matching_alert = false \n end\n #debugger\n matching_alerts << alert if(matching_alert) \n end\n \n matching_alerts.each do |alert|\n alert.notify_user(self)\n end \n end", "def get_router_ipaddr()\n SNMP::Manager.open(\n :Host => RouterIP,\n :Community => SNMPpw,\n :Timeout => 60,\n :Retries => 5\n ) do |manager|\n # XXX Timeout on the next line (or the one below) will kick us out.\n response = manager.get([\"ip.21.1.7.0.0.0.0\"])\n response.each_varbind do |vb|\n default_route = \"#{vb.value.to_s}\"\n # puts \"ip.21.1.7.#{default_route}\"\n response = manager.get([\"ip.21.1.7.#{default_route}\"])\n response.each_varbind do |vb|\n my_ipaddr = \"#{vb.value.to_s}\"\n # puts my_ipaddr\n return my_ipaddr\n end\n end\n end\nend", "def create_site_snmp_alert(id, opts = {})\n data, _status_code, _headers = create_site_snmp_alert_with_http_info(id, opts)\n data\n end", "def main(raid_device)\n output_message = \"\"\n warning = 0\n critical = 0\n unknown = 0\n\n raid_device.each do |device|\n get_raid_output = %x[sudo mdadm --detail #{device}].lines.to_a\n get_raid_status = get_raid_output.grep(/\\sState\\s:\\s/).to_s.match(/:\\s(.*)\\\\n\\\"\\]/)\n\n raid_state = get_raid_status[1].strip\n\n if raid_state.empty?\n output_message.concat(\" Unable to get #{device} RAID status!\")\n unknown += 1\n end\n\n if /^(clean|active)(, (resyncing\\s\\(DELAYED\\)|checking))?$/.match(raid_state)\n output_message.concat(\" #{device} RAID OK: #{raid_state}\")\n elsif /degraded/i.match(raid_state)\n output_message.concat(\" #{device} WARNING RAID: #{raid_state}\")\n warning += 1\n elsif /fail/i.match(raid_state)\n output_message.concat(\" #{device} CRITICAL RAID: #{raid_state}\")\n critical += 1\n else\n output_message.concat(\" UNKNOWN RAID detected: #{raid_state}\")\n unknown += 1\n end\n end\n\n return { :message => output_message, :warning => warning, :critical => critical, :unknown => unknown}\nend", "def evaluate_checks\n log.info(\"Evaluating Checks: '#{@config['checks'].length}'\")\n\n @config['checks'].each do |check|\n check_name = check['check']\n check_cfg = check['cfg']\n\n collect_metrics(check_name, check_cfg).each do |metric|\n status = 0\n\n # on service it will come with \"state_required\" flag\n if check_name == 'service'\n # adding defaults in case they are not set\n check_cfg = check_cfg.merge(\n 'state' => 'active',\n 'state_required' => 1\n )\n # giving a service hint by adding it's name\n check_name = \"service_#{check_cfg['name']}\"\n status = equals(metric['value'], check_cfg['state_required'])\n else\n # normal threshold evaluation\n status = evaluate(\n metric['value'],\n check_cfg['warn'],\n check_cfg['crit']\n )\n end\n\n template_variables = metric\n template_variables['cfg'] = check_cfg\n\n append_event(\n \"check_#{check_name}\",\n @tmpl.render(check['check'], template_variables),\n status,\n metric['source']\n )\n end\n end\n end", "def threshold_params\n params.require(:threshold).permit(:sensor_id, :comparing_string, :comparing_value, :status, :action)\n end", "def load_notetags\n super\n init_custom_fields\n self.note.split(/[\\r\\n]+/).each { |line|\n case line\n when /<(.*) growth:\\s*(\\d+\\.?\\d*)>/i\n case $1.upcase\n when \"HP\"\n @growth_rate[0] = $2.to_f\n when \"MP\", \"TP\"\n @growth_rate[1] = $2.to_f\n when \"P.ATK\"\n @growth_rate[2] = $2.to_f\n when \"P.DEF\"\n @growth_rate[3] = $2.to_f\n when \"M.ATK\"\n @growth_rate[4] = $2.to_f\n when \"M.DEF\"\n @growth_rate[5] = $2.to_f\n when \"AGI\"\n @growth_rate[6] = $2.to_f\n when \"LCK\", \"LUCK\"\n @growth_rate[7] = $2.to_f\n end\n when /<max sp:\\s*(\\d+\\.?\\d*)>/i\n @msp = $1.to_i\n when /<capacities:[ ](\\d+(?:\\s*,\\s*\\d+)*)>/i\n $1.scan(/\\d+/).each { |num| \n @capacities.push(num.to_i) if num.to_i > 0 \n }\n end\n }\n end", "def check_alerts\n hits = @queue.size\n\n if hits >= @hits_alert_threshold && (@alerts.empty? || @alerts.last.kind_of?(EndHighTrafficAlert))\n @alerts << HighTrafficAlert.new(hits: hits)\n elsif hits < @hits_alert_threshold && @alerts.last.kind_of?(HighTrafficAlert)\n @alerts << EndHighTrafficAlert.new\n end\n end", "def create_site_snmp_alert(id, opts = {})\n data, _status_code, _headers = create_site_snmp_alert_with_http_info(id, opts)\n return data\n end", "def parser\n\t\t# read mail header from the file\n\t\tfile= File.open(\"header.txt\",\"r\")\n header=\"\"\n\t\tfile.each_line { |line|\n header= get_header_content(line).to_s\n check_google_apps(line)\n line=line.downcase\n\t\t\t#parser received value from mail header\n\t\t\tparser_received(line)\n parser_email(line)\n check_google_apps(line)\n\t\t}\n lower_case_header=header.downcase;\n check_microsoft_exchange(lower_case_header)\n check_lotus_notes(lower_case_header)\n check_novell_grouwpise(lower_case_header)\n check_other_apps(lower_case_header)\n check_software_conflicts()\n check_software_version_conflicts()\n get_security_software(lower_case_header)\n\tend", "def snmp\n raise ArgumentError, 'No SNMP options found for source' if @snmp_opts.nil?\n SNMP::Manager.new(@snmp_opts)\n end", "def start\n super\n @snmptrap = SNMP::TrapListener.new(:Host => @host, :Port => @port) do |manager|\n manager.on_trap_default do |trap|\n trap_events = Hash.new\n tag = @tag\n timestamp = Engine.now\n raise(\"Unknown Trap Format\", trap) unless trap.kind_of?(SNMP::SNMPv1_Trap) or trap.kind_of?(SNMP::SNMPv2_Trap)\n trap.each_varbind do |vb|\n trap_events[vb.name.to_s] = vb.value.to_s\n end\n trap_events['host'] = trap.source_ip\n if @trap_format == 'tojson'\n require 'json'\n trap_events.to_json\n end\n router.emit(tag, timestamp, trap_events)\n end\n end\n end", "def get_site_snmp_alerts(id, opts = {})\n data, _status_code, _headers = get_site_snmp_alerts_with_http_info(id, opts)\n data\n end", "def get_vm_monitor_data(vm)\n reset_monitor\n\n cpu_mhz = vm[:mob].runtime.host.summary.hardware.cpuMhz.to_f\n\n @monitor[:used_memory] = vm[:mob].summary.quickStats.hostMemoryUsage *\n 1024\n\n used_cpu = vm[:mob].summary.quickStats.overallCpuUsage.to_f / cpu_mhz\n used_cpu = (used_cpu * 100).to_s\n @monitor[:used_cpu] = format('%.2f', used_cpu).to_s\n\n # Check for negative values\n @monitor[:used_memory] = 0 if @monitor[:used_memory].to_i < 0\n @monitor[:used_cpu] = 0 if @monitor[:used_cpu].to_i < 0\n\n guest_ip_addresses = []\n unless vm[:mob].guest.net.empty?\n vm[:mob].guest.net.each do |net|\n next unless net.ipConfig\n next if net.ipConfig.ipAddress.empty?\n\n net.ipConfig.ipAddress.each do |ip|\n guest_ip_addresses << ip.ipAddress\n end\n end\n end\n @guest_ip_addresses = guest_ip_addresses.join(',')\n\n pm = vm[:mob]._connection.serviceInstance.content.perfManager\n\n provider = pm.provider_summary(vm[:mob])\n\n refresh_rate = provider.refreshRate\n\n stats = {}\n\n @one_vm = OpenNebula::VirtualMachine\n .new_with_id(vm[:id], @client)\n\n if @one_vm['MONITORING/LAST_MON'] &&\n @one_vm['MONITORING/LAST_MON'].to_i != 0\n # Real time data stores max 1 hour. 1 minute has 3 samples\n interval = (Time.now.to_i -\n @one_vm['MONITORING/LAST_MON'].to_i)\n\n # If last poll was more than hour ago get 3 minutes,\n # else calculate how many samples since last poll\n if interval > 3600\n samples = 9\n else\n samples = (interval / refresh_rate) + 1\n end\n samples > 0 ? max_samples = samples : max_samples = 1\n\n stats = pm.retrieve_stats(\n [vm[:mob]],\n ['net.transmitted', 'net.bytesRx', 'net.bytesTx',\n 'net.received', 'virtualDisk.numberReadAveraged',\n 'virtualDisk.numberWriteAveraged', 'virtualDisk.read',\n 'virtualDisk.write'],\n interval => refresh_rate, max_samples => max_samples\n ) rescue {}\n else\n # First poll, get at least latest 3 minutes = 9 samples\n stats = pm.retrieve_stats(\n [vm[:mob]],\n ['net.transmitted', 'net.bytesRx', 'net.bytesTx',\n 'net.received', 'virtualDisk.numberReadAveraged',\n 'virtualDisk.numberWriteAveraged', 'virtualDisk.read',\n 'virtualDisk.write'],\n interval => refresh_rate, max_samples => 9\n ) rescue {}\n end\n\n if !stats.empty? && !stats.first[1][:metrics].empty?\n metrics = stats.first[1][:metrics]\n\n nettx_kbpersec = 0\n if metrics['net.transmitted']\n metrics['net.transmitted'].each do |sample|\n nettx_kbpersec += sample if sample > 0\n end\n end\n\n netrx_kbpersec = 0\n if metrics['net.bytesRx']\n metrics['net.bytesRx'].each do |sample|\n netrx_kbpersec += sample if sample > 0\n end\n end\n\n read_kbpersec = 0\n if metrics['virtualDisk.read']\n metrics['virtualDisk.read'].each do |sample|\n read_kbpersec += sample if sample > 0\n end\n end\n\n read_iops = 0\n if metrics['virtualDisk.numberReadAveraged']\n metrics['virtualDisk.numberReadAveraged'].each do |sample|\n read_iops += sample if sample > 0\n end\n end\n\n write_kbpersec = 0\n if metrics['virtualDisk.write']\n metrics['virtualDisk.write'].each do |sample|\n write_kbpersec += sample if sample > 0\n end\n end\n\n write_iops = 0\n if metrics['virtualDisk.numberWriteAveraged']\n metrics['virtualDisk.numberWriteAveraged'].each do |sample|\n write_iops += sample if sample > 0\n end\n end\n\n else\n nettx_kbpersec = 0\n netrx_kbpersec = 0\n read_kbpersec = 0\n read_iops = 0\n write_kbpersec = 0\n write_iops = 0\n end\n\n # Accumulate values if present\n if @one_item && @one_item['MONITORING/NETTX']\n previous_nettx = @one_item['MONITORING/NETTX'].to_i\n else\n previous_nettx = 0\n end\n\n if @one_item && @one_item['MONITORING/NETRX']\n previous_netrx = @one_item['MONITORING/NETRX'].to_i\n else\n previous_netrx = 0\n end\n\n if @one_item && @one_item['MONITORING/DISKRDIOPS']\n previous_diskrdiops = @one_item['MONITORING/DISKRDIOPS'].to_i\n else\n previous_diskrdiops = 0\n end\n\n if @one_item && @one_item['MONITORING/DISKWRIOPS']\n previous_diskwriops = @one_item['MONITORING/DISKWRIOPS'].to_i\n else\n previous_diskwriops = 0\n end\n\n if @one_item && @one_item['MONITORING/DISKRDBYTES']\n previous_diskrdbytes = @one_item['MONITORING/DISKRDBYTES'].to_i\n else\n previous_diskrdbytes = 0\n end\n\n if @one_item && @one_item['MONITORING/DISKWRBYTES']\n previous_diskwrbytes = @one_item['MONITORING/DISKWRBYTES'].to_i\n else\n previous_diskwrbytes = 0\n end\n\n @monitor[:nettx] = previous_nettx +\n (nettx_kbpersec * 1024 * refresh_rate).to_i\n @monitor[:netrx] = previous_netrx +\n (netrx_kbpersec * 1024 * refresh_rate).to_i\n\n @monitor[:diskrdiops] = previous_diskrdiops + read_iops\n @monitor[:diskwriops] = previous_diskwriops + write_iops\n @monitor[:diskrdbytes] = previous_diskrdbytes +\n (read_kbpersec * 1024 * refresh_rate).to_i\n @monitor[:diskwrbytes] = previous_diskwrbytes +\n (write_kbpersec * 1024 * refresh_rate).to_i\n @monitor\n end", "def get_packets_in (snmp = nil)\n @packet_in_rate ||= { }\n report = { }\n snmp = @snmp_manager unless snmp\n\n get_names(snmp) if @names.empty?\n res = gather_snmp_metrics_by_name(\"Virtual Servers/Packets/In\", @names, OID_LTM_VIRTUAL_SERV_STAT_CLIENT_PKTS_IN, snmp)\n NewRelic::PlatformLogger.debug(\"Virtual Servers: Got #{res.size}/#{@names.size} Inbound Packet metrics\")\n\n unless res.nil?\n res.each_key do |metric|\n @packet_in_rate[metric] ||= NewRelic::Processor::EpochCounter.new\n report[metric] = @packet_in_rate[metric].process(res[metric] * 8)\n end\n\n sorted_report = report.sort_by { |k,v| v }.reverse\n sorted_report.each_with_index do |row, index|\n @f5_agent.report_metric row[0], \"packets/sec\", row[1]\n break if index >= (MAX_RESULTS - 1)\n end\n end\n end", "def set_site_snmp_alerts_with_http_info(id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: SiteApi.set_site_snmp_alerts ...\"\n end\n # verify the required parameter 'id' is set\n if @api_client.config.client_side_validation && id.nil?\n fail ArgumentError, \"Missing the required parameter 'id' when calling SiteApi.set_site_snmp_alerts\"\n end\n # resource path\n local_var_path = \"/api/3/sites/{id}/alerts/snmp\".sub('{' + 'id' + '}', id.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;charset=UTF-8'])\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(opts[:'alert'])\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 :return_type => 'Links')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: SiteApi#set_site_snmp_alerts\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def alert_threshold\n return @alert_threshold\n end", "def set_site_snmp_alerts_with_http_info(id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: SiteApi.set_site_snmp_alerts ...'\n end\n # verify the required parameter 'id' is set\n if @api_client.config.client_side_validation && id.nil?\n fail ArgumentError, \"Missing the required parameter 'id' when calling SiteApi.set_site_snmp_alerts\"\n end\n # resource path\n local_var_path = '/api/3/sites/{id}/alerts/snmp'.sub('{' + 'id' + '}', id.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;charset=UTF-8'])\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(opts[:'alert'])\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 :return_type => 'Links')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: SiteApi#set_site_snmp_alerts\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def ProbeRules\n return if @ATTR.size>0\n # SMBIOS Data\n bios = Convert.to_list(SCR.Read(path(\".probe.bios\")))\n\n if Builtins.size(bios) != 1\n Builtins.y2warning(\"Warning: BIOS list size is %1\", Builtins.size(bios))\n end\n\n biosinfo = Ops.get_map(bios, 0, {})\n smbios = Ops.get_list(biosinfo, \"smbios\", [])\n\n sysinfo = {}\n boardinfo = {}\n\n Builtins.foreach(smbios) do |inf|\n if Ops.get_string(inf, \"type\", \"\") == \"sysinfo\"\n sysinfo = deep_copy(inf)\n elsif Ops.get_string(inf, \"type\", \"\") == \"boardinfo\"\n boardinfo = deep_copy(inf)\n end\n end\n\n if Ops.greater_than(Builtins.size(sysinfo), 0)\n @product = Ops.get_string(sysinfo, \"product\", \"default\")\n @product_vendor = Ops.get_string(sysinfo, \"manufacturer\", \"default\")\n end\n\n if Ops.greater_than(Builtins.size(boardinfo), 0)\n @board = Ops.get_string(boardinfo, \"product\", \"default\")\n @board_vendor = Ops.get_string(boardinfo, \"manufacturer\", \"default\")\n end\n\n Ops.set(@ATTR, \"product\", @product)\n Ops.set(@ATTR, \"product_vendor\", @product_vendor)\n Ops.set(@ATTR, \"board\", @board)\n Ops.set(@ATTR, \"board_vendor\", @board_vendor)\n\n #\n # Architecture\n #\n\n @arch = Arch.architecture\n @karch = Ops.get(Kernel.GetPackages, 0, \"kernel-default\")\n\n Ops.set(@ATTR, \"arch\", @arch)\n Ops.set(@ATTR, \"karch\", @karch)\n\n #\n # Memory\n #\n\n memory = 0\n memories = Convert.to_list(SCR.Read(path(\".probe.memory\")))\n memory = Ops.get_integer(\n memories,\n [0, \"resource\", \"phys_mem\", 0, \"range\"],\n 0\n )\n @memsize = Ops.divide(memory, 1024 * 1024)\n Ops.set(@ATTR, \"memsize\", @memsize)\n\n #\n # Disk sizes\n #\n\n storage = Storage.GetTargetMap\n _PhysicalTargetMap = Builtins.filter(storage) do |k, v|\n Storage.IsRealDisk(v)\n end\n @totaldisk = 0\n @disksize = Builtins.maplist(_PhysicalTargetMap) do |k, v|\n size_in_mb = Ops.divide(Ops.get_integer(v, \"size_k\", 0), 1024)\n @totaldisk = Ops.add(@totaldisk, size_in_mb)\n { \"device\" => k, \"size\" => size_in_mb }\n end\n Builtins.y2debug(\"disksize: %1\", @disksize)\n #\n # MAC\n #\n Ops.set(@ATTR, \"mac\", @mac)\n\n #\n # Network\n #\n if Stage.initial\n @hostaddress = Convert.to_string(SCR.Read(path(\".etc.install_inf.IP\")))\n else\n @hostaddress = \"192.168.1.1\" # FIXME\n end\n Ops.set(@ATTR, \"hostaddress\", @hostaddress)\n\n #\n # Hostid (i.e. a8c00101);\n #\n Ops.set(@ATTR, \"hostid\", @hostid)\n\n Ops.set(@ATTR, \"hostname\", getHostname)\n @domain = Convert.to_string(SCR.Read(path(\".etc.install_inf.Domain\")))\n Ops.set(@ATTR, \"domain\", @domain)\n @network = Convert.to_string(SCR.Read(path(\".etc.install_inf.Network\")))\n Ops.set(@ATTR, \"network\", @network)\n @haspcmcia = Convert.to_string(\n SCR.Read(path(\".etc.install_inf.HasPCMCIA\"))\n )\n Ops.set(@ATTR, \"haspcmcia\", @haspcmcia)\n @xserver = Convert.to_string(SCR.Read(path(\".etc.install_inf.XServer\")))\n Ops.set(@ATTR, \"xserver\", @xserver)\n\n @NonLinuxPartitions = Storage.GetForeignPrimary\n @others = Builtins.size(@NonLinuxPartitions)\n\n Builtins.y2milestone(\"Other primaries: %1\", @NonLinuxPartitions)\n\n @LinuxPartitions = Storage.GetOtherLinuxPartitions\n @linux = Builtins.size(@LinuxPartitions)\n\n Builtins.y2milestone(\"Other linux parts: %1\", @LinuxPartitions)\n\n @installed_product = Product.name\n @installed_product_version = Product.version\n Ops.set(@ATTR, \"installed_product\", @installed_product)\n Ops.set(@ATTR, \"installed_product_version\", @installed_product_version)\n\n Builtins.y2milestone(\n \"Installing %1 %2\",\n @installed_product,\n @installed_product_version\n )\n Builtins.y2milestone(\"ATTR=%1\", @ATTR)\n\n nil\n end", "def check_passenger_monitoring\n passenger_plugins = [\n {\"plugin_name\"=>\"passenger\", \"plugin_type\"=>\"passenger_instances\",\"field\"=>\"value\"},\n {\"plugin_name\"=>\"passenger\", \"plugin_type\"=>\"passenger_processes\",\"field\"=>\"max\"},\n {\"plugin_name\"=>\"passenger\", \"plugin_type\"=>\"passenger_queued\",\"field\"=>\"value\"},\n {\"plugin_name\"=>\"passenger\", \"plugin_type\"=>\"passenger_requests\",\"field\"=>\"value\"}\n ]\n sleep 60 # wait for some data to be available\n @servers.each do |server|\n unless server.multicloud\n#passenger commands to generate data for collectd to return\n# for ii in 1...100\n# # how do we force there to be data?? For now just check that the graph exists - cause the\n# # bug was missing graphs.\n# end\n passenger_plugins.each do |plugin|\n monitor = obj_behavior(server, :get_sketchy_data, {'start' => -60,\n 'end' => -20,\n 'plugin_name' => plugin['plugin_name'],\n 'plugin_type' => plugin['plugin_type']})\n value = monitor['data'][\"#{plugin['field']}\"]\n puts \"Checking #{plugin['plugin_name']}-#{plugin['plugin_type']}: value #{value}\"\n raise \"No #{plugin['plugin_name']}-#{plugin['plugin_type']} data\" unless value.length > 0\n# # Need to check for that there is at least one non 0 value returned.\n# for nn in 0...value.length\n# if value[nn] > 0\n# break\n# end\n# end\n# raise \"No #{plugin['plugin_name']}-#{plugin['plugin_type']} time\" unless nn < value.length\n puts \"Monitoring is OK for #{plugin['plugin_name']}-#{plugin['plugin_type']}\"\n end\n end\n end\n end", "def parse_status(status)\n status = status.to_hex_s\n \n sw1 = status[-4..-3]\n sw2 = status[-2..-1]\n \n case sw1\n when \"67\"\n case sw2\n when \"00\" then err = \"LC_INVALID\"\n else\n raise \"Unknown sw2 #{ sw2.inspect } for sw1 #{ sw1.inspect }\"\n end\n \n when \"6a\"\n case sw2\n when \"82\" then err = \"FILE_NOT_FOUND\"\n when \"86\" then err = \"INVALID_P1_P2\"\n else\n raise \"Unknown sw2 #{ sw2.inspect } for sw1 #{ sw1.inspect }\"\n end\n \n when \"90\"\n case sw2\n when \"00\"\n err = \"NO_ERROR\"\n else\n raise \"Unknown sw2 #{ sw2.inspect } for sw1 #{ sw1.inspect }\"\n end\n \n when \"98\"\n case sw2\n when \"01\" then err = \"TIM_ERROR_TLV\"\n when \"02\" then err = \"TIM_ERROR_VALUE\"\n when \"03\" then err = \"TIM_ERROR_DATA_MISSING\"\n when \"04\" then err = \"TIM_ERROR_INVALID_CHARACTER\"\n when \"11\" then err = \"TIM_ERROR_DATE_FORMAT\"\n when \"12\" then err = \"TIM_ERROR_DATE_OUT_OF_RANGE\"\n when \"13\" then err = \"TIM_ERROR_CURRENCY\"\n when \"21\" then err = \"TIM_ERROR_TAX_VERIFICATION_FAILED\"\n when \"22\" then err = \"TIM_ERROR_NEGATIVE_TURNOVER\"\n when \"31\" then err = \"TIM_ERROR_INVALID_SIGNATURE\"\n when \"41\" then err = \"TIM_ERROR_INVALID_LIFECYCLE\"\n when \"e1\" then err = \"TIM_ERROR_MEMORY_FAILURE\"\n when \"e2\" then err = \"TIM_ERROR_DATA_CORRUPTED\"\n when \"ff\" then err = \"TIM_ERROR_NOT_SUPPORTED\"\n else\n raise \"Unknown sw2 #{ sw2.inspect } for sw1 #{ sw1.inspect }\"\n end\n \n else\n raise \"Unknown sw1 #{ sw1.inspect }\"\n end\n \n Insika.log(\"Parsed status #{ err }\")\n return err\n end", "def parse_policy\n parts = policy.split(' ')\n self.letter = parts.last\n parts = parts.first.split('-')\n self.min = parts.first.to_i\n self.max = parts.last.to_i\n end", "def fixed_ports(switch)\n out = %x(snmpwalk -v2c -c public #{switch} IF-MIB::ifType)\n lines = out.split(\"\\n\")\n # Some example lines of data:\n # IF-MIB::ifType.24 = INTEGER: ethernetCsmacd(6)\n # IF-MIB::ifType.53 = INTEGER: other(1)\n # IF-MIB::ifType.54 = INTEGER: ieee8023adLag(161)\n lines.select do |line|\n line.match(\"ethernetCsmacd\")\n end.map do |line|\n line.match(/[0-9]+/)\n end\nend", "def icmp_statistics\n super\n end", "def monitor\n summary = @host.summary\n hardware = summary.hardware\n stats = summary.quickStats\n\n @cpuModel = hardware.cpuModel\n @cpuMhz = hardware.cpuMhz\n\n @total_cpu = hardware.numCpuCores*100\n @used_cpu = (stats.overallCpuUsage.to_f / @cpuMhz.to_f) * 100\n @used_cpu = sprintf('%.2f', @used_cpu).to_f # Trim precission\n\n @total_memory = hardware.memorySize/1024\n @used_memory = stats.overallMemoryUsage*1024\n\n net = VIDriver::retrieve_stats([@host],\n [\"net.packetsRx\",\"net.packetsTx\"])\n @net_rx = 0\n @net_tx = 0\n\n if net[@host] && net[@host][:metrics]\n if net[@host][:metrics][\"net.packetsRx\"]\n @net_rx = net[@host][:metrics][\"net.packetsRx\"].first\n end\n\n if net[@host][:metrics][\"net.packetsTx\"]\n @net_tx = net[@host][:metrics][\"net.packetsTx\"].first\n end\n end\n\n # Check for negative values\n @used_memory = 0 if @used_memory.to_i < 0\n @used_cpu = 0 if @used_cpu.to_i < 0\n @net_rx = 0 if @net_rx.to_i < 0\n @net_tx = 0 if @net_tx.to_i < 0\n\n # Check free datastore space\n @free_ds_info = VIDriver::retrieve_free_ds(@host)\n end", "def parse_hms\n s0 = @scanner.pos\n s1 = match_digits!\n\n if s1 == :failed\n @scanner.pos = s0\n s0 = :failed\n elsif match_str(':') != :failed\n s3 = match_digits!\n if s3 == :failed\n @scanner.pos = s0\n s0 = :failed\n elsif match_str(':') != :failed\n s5 = match_digits!\n if s5 == :failed\n @scanner.pos = s0\n s0 = :failed\n else\n @reported_pos = s0\n s0 = { 'h' => s1.join.to_i, 'm' => s3.join.to_i, 's' => s5.join.to_i }\n end\n else\n @scanner.pos = s0\n s0 = :failed\n end\n else\n @scanner.pos = s0\n s0 = :failed\n end\n s0\n end", "def alive(alert, event, status)\n starts_at = DateTime.now - eval(event.amounts)\n ends_at = DateTime.now\n\n raw = @platform.raw_data.captured_between(starts_at, ends_at)\n if raw.count == 0 \n @status.update_attributes(status: \"ALERT!\", message: \"Platform #{@platform.name} is down, no new data for alert period of #{event.amounts}!\", end_time: DateTime.now)\n AlertMailer::alert_email(alert, \"Platform #{@platform.name} is down, no new data for alert period of #{event.amounts}!\", @platform.name).deliver\n else\n @status.update_attributes(status: \"Finished\", end_time: DateTime.now)\n end\n\tend", "def parse_vlans(config)\n values = config.scan(/vxlan vlan (\\d+) vni (\\d+)/)\n values = values.each_with_object({}) do |v, hsh|\n hsh[v.first] = { vni: v.last }\n end\n { vlans: values }\n end", "def process_monitor_results(result_array_of_hashes)\n result_array_of_hashes = result_array_of_hashes[\n 0..Settings.result_limit.to_i\n ]\n Delayed::Worker.logger.debug \"Processing #{@asq.name}\"\n Delayed::Worker.logger.debug \"Evaluating if #{@asq.alert_result_type}\n #{@asq.alert_operator} #{@asq.alert_value}\"\n\n if @asq.alert_result_type == 'rows_count'\n Delayed::Worker.logger.debug \"Row length: #{result_array_of_hashes.length}\n // Error value: #{@asq.alert_value.to_i}\"\n process_row_count(result_array_of_hashes)\n elsif @asq.alert_result_type == 'result_value'\n # Should break if we get multiple rows back\n return unless single_row?(result_array_of_hashes)\n Delayed::Worker.logger.debug 'Result to evaluate: ' \\\n \"#{result_array_of_hashes[0].values[0]} \" \\\n \"(#{result_array_of_hashes[0].values[0].class}) // \\n\" \\\n \"Error value: #{@asq.alert_value} (#{@asq.alert_value.class})\"\n\n if invalid_non_numeric_comparison?(result_array_of_hashes[0].values[0])\n @asq.operational_error([{\n 'error_source' => 'Asq',\n 'error_text' => 'Error processing results: This Asq is ' \\\n 'using a less-than or greater-than operator against a ' \\\n 'non-numeric expected result. For non-numeric results, ' \\\n 'only the == and != operators are valid.'\n }].to_json)\n else\n compare_result_value(result_array_of_hashes)\n end\n else\n @asq.operational_error([{\n 'error_source' => 'Asq',\n 'error_text' => 'Error processing results: ' \\\n 'I tried to evaluate if this Asq was in error but I ' \\\n 'couldn\\'t understand if I was supposed to look at the ' \\\n 'row count or result set.'\n }].to_json)\n end\n @asq.finish_refresh\n rescue StadardError => e\n @asq.operational_error([{\n 'error_source' => 'Asq',\n 'error_text' => \"Error when processing results: #{e}\"\n }].to_json)\n end", "def setup_metrics\n valid_passenger_versions = [3, 4]\n\n raise ConfigurationError, \"passenger_version config variable must be set\" unless defined?(passenger_version)\n raise ConfigurationError, \"Passenger version must be one of #{valid_passenger_versions}\" unless valid_passenger_versions.include?(passenger_version)\n\n\n @matches = {}\n\n @matches[:processes_max] = /max\\s+=\\s+(\\d+)/ if passenger_version.eql?(3)\n #Max pool size : 6\n @matches[:processes_max] = /Max pool size\\s+:\\s+(\\d+)/ if passenger_version.eql?(4)\n\n\n @matches[:processes_running] = /count\\s+=\\s+(\\d+)/ if passenger_version.eql?(3)\n #Processes : 6\n @matches[:processes_running] = /Processes\\s+:\\s+(\\d+)/ if passenger_version.eql?(4)\n\n\n @matches[:queue_waiting] = /Waiting on global queue:\\s+(\\d+)/ if passenger_version.eql?(3)\n #Requests in top-level queue : 0\n @matches[:queue_waiting] = /Requests in top-level queue\\s+:\\s+(\\d+)/ if passenger_version.eql?(4)\n\n end", "def basic_info\n\t\t#Grab some basic info using OID values which should be fairly generic in nature\n\t\ttarget = \"#{@manager.config[:host]}:#{@manager.config[:port]}\"\n\t\tcstring = @manager.config[:community]\n\t\t@snmp_version = @manager.config[:version] #We need this one later for some decisions so setting to class var\n\t\tsys_name = @manager.get_value(\"sysName.0\")\n\t\tsys_descr = @manager.get_value(\"sysDescr.0\")\n\n\t\t#Print out our basic info for user\n\t\tputs \"[*] \".light_green + \"Target\".light_yellow + \": #{target}\".white\n\t\tputs \"[*] \".light_green + \"Community String\".light_yellow + \": #{cstring}\".white\n\t\tif @snmp_version\n\t\t\tputs \"[*] \".light_green + \"SNMP Version\".light_yellow + \": #{@snmp_version}\".white\n\t\telse\n\t\t\tprint_caution(\"Unable to determine SNMP Version in use?\")\n\t\tend\n\t\tif sys_name\n\t\t\tputs \"[*] \".light_green + \"System Name\".light_yellow + \": #{sys_name}\".white\n\t\telse\n\t\t\tprint_error(\"Unable to determine system name!\")\n\t\tend\n\t\tif sys_descr\n\t\t\tputs \"[*] \".light_green + \"System Description\".light_yellow + \": \\n#{sys_descr}\".white\n\t\telse\n\t\t\tprint_error(\"Unable to find system description!\")\n\t\tend\n\t\tif @sys_time\n\t\t\tputs \"[*] \".light_green + \"System Uptime\".light_yellow + \": #{@sys_time}\".white\n\t\telse\n\t\t\tprint_error(\"Unable to find system description!\")\n\t\tend\n\tend", "def alert_threshold=(value)\n @alert_threshold = value\n end", "def dash_snort\n\n set_IPstatTypes_constants\n set_timeLine_constants\n\n\n dbQuery = Alertdb.select(\"priority as priority, sigid as sigid, message as message, count(*) as cnt\").\n group(:priority, :sigid, :message).order(:priority, :sigid)\n dbQuery = selectTimeIntervals(dbQuery)\n #add specific device to the query, if it exists\n if (params[:device].present?)\n dbQuery = dbQuery.where(\"srcmac = ? OR dstmac = ?\", params[:device], params[:device])\n else\n dbQuery = dbQuery.joins(:deviceinfo)\n end\n\n @hashSnortTimeIntervalData = Hash.new\n @hashSnortAlerts = Hash.new\n\n dbQuery.each do |rec|\n rec_priority = rec['priority'];\n\n arrayData = @hashSnortTimeIntervalData[rec_priority]\n if arrayData.nil? then\n arrayData = @hashSnortTimeIntervalData[rec_priority] = Array.new(@numTimeSlots, 0)\n end\n\n arrayData[rec['time'].to_i] += rec['cnt'].to_i\n\n arrayData = @hashSnortAlerts[rec['sigid']]\n if arrayData.nil? then\n arrayData = @hashSnortAlerts[rec['sigid']] = Array.new(3, 0)\n arrayData[1] = rec['message']\n arrayData[2] = rec_priority\n end\n arrayData[0] += rec['cnt'].to_i\n\n end #for each SNORT alert record...\n end", "def parse_report(result_body)\n # The routin should be provided in the inherited class\n end", "def parse_ndstatus# rubocop:disable all\n nodestatus = nodetool_cmd('status')\n nodestatus.each_line do |line|\n next if line.match(/^Datacenter:/)\n next if line.match(/^=======/)\n next if line.match(/^Status/)\n next if line.match(/State/)\n next if line.match(/^--/)\n next if line.match(/^Note/)\n\n if m = line.match(/^UN\\s\\s(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})/)# rubocop:disable all\n address = m[1]\n ndstatus_attr = {\"node.#{address}.status\" => 'UN'}\n else\n m = line.match(/(\\w+)\\s\\s(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})/)\n address = m[2]\n ndstatus = m[1]\n ndstatus_attr = {\"node.#{address}.status\" => ndstatus}\n critical ndstatus_attr.to_json\n end\n ok ndstatus_attr.to_json\n end\n end", "def parse\n @title = @service\n \n unless @header.nil?\n @text = @header\n end\n\n @message = @alert\n @fallback = @alert\n\n unless @bot.nil?\n @author_name = @bot\n unless @botlink.nil?\n @author_name = @botlink\n end\n end\n\n unless @severity.nil?\n add_field(\"Severity\", @severity)\n end\n\n unless @runbook.nil?\n add_field(\"Runbook\", @runbook)\n end\n end", "def check_aggregate(summary)\n #puts \"summary is #{summary}\"\n total, ok, silenced, stale, failing = summary.values_at(:total, :ok, :silenced, :stale, :failing)\n return 'OK', 'No servers running the check' if total.zero?\n\n eff_total = total - silenced * (config[:silenced] ? 1 : 0)\n return 'OK', 'All hosts silenced' if eff_total.zero?\n\n ok_pct = (100 * ok / eff_total.to_f).to_i\n\n # Loop through the arrays and split the hostname so we get a short hostname \n message = \"#{ok} OK out of #{eff_total} total.\"\n message << \" #{silenced} silenced.\" if config[:silenced] && silenced > 0\n message << \" #{stale.size} stale.\" unless stale.empty?\n message << \" #{ok_pct}% OK, #{config[:critical]}% threshold\"\n message << \"\\nStale hosts: #{stale.map{|host| host.split('.').first}.sort[0..10].join ','}\" unless stale.empty?\n message << \"\\nFailing hosts: #{failing.map{|host| host.split('.').first}.sort[0..10].join ','}\" unless failing.empty?\n message << \"\\nMinimum number of hosts required is #{config[:min_nodes]} and only #{ok} found\" if ok < config[:min_nodes]\n\n state = ok_pct >= config[:critical] ? 'OK' : 'CRITICAL'\n state = ok >= config[:min_nodes] ? state : 'CRITICAL'\n return state, message\n end", "def parse_summary_stats(nokogiri)\n\n summary_stats = {}\n\n # Summary Stats.\n # Example:\n # <div class=\"spaceit_pad\"><span class=\"dark_text\">Watching:</span> 12,334</div>\n # <div class=\"spaceit_pad\"><span class=\"dark_text\">Completed:</span> 59,459</div>\n # <div class=\"spaceit_pad\"><span class=\"dark_text\">On-Hold:</span> 3,419</div>\n # <div class=\"spaceit_pad\"><span class=\"dark_text\">Dropped:</span> 2,907</div>\n # <div class=\"spaceit_pad\"><span class=\"dark_text\">Plan to Watch:</span> 17,571</div>\n # <div class=\"spaceit_pad\"><span class=\"dark_text\">Total:</span> 95,692</div>\n\n left_column_nodeset = nokogiri.xpath('//div[@id=\"content\"]/table/tr/td[@class=\"borderClass\"]')\n\n if (node = left_column_nodeset.at('//span[text()=\"Reading:\"]')) && node.next\n summary_stats[:in_progress] = node.next.text.strip.gsub(',','').to_i\n end\n if (node = left_column_nodeset.at('//span[text()=\"Completed:\"]')) && node.next\n summary_stats[:completed] = node.next.text.strip.gsub(',','').to_i\n end\n if (node = left_column_nodeset.at('//span[text()=\"On-Hold:\"]')) && node.next\n summary_stats[:on_hold] = node.next.text.strip.gsub(',','').to_i\n end\n if (node = left_column_nodeset.at('//span[text()=\"Dropped:\"]')) && node.next\n summary_stats[:dropped] = node.next.text.strip.gsub(',','').to_i\n end\n if (node = left_column_nodeset.at('//span[text()=\"Plan to Read:\"]')) && node.next\n summary_stats[:planned] = node.next.text.strip.gsub(',','').to_i\n end\n if (node = left_column_nodeset.at('//span[text()=\"Total:\"]')) && node.next\n summary_stats[:total] = node.next.text.strip.gsub(',','').to_i\n end\n\n summary_stats\n end", "def parse_from_summary(data)\n # \n end", "def formulate_diagnose_reply(results, username)\n if @value > @threshold\n customised_diagnose = []\n DR_DIAGNOSE_RESULTS['data'].each do |diagnose|\n diagnose = diagnose.gsub('*', username)\n diagnose = diagnose.gsub('@', results['likely_condition'])\n diagnose = diagnose.gsub('%', results['condition_data']['treatment'].sample)\n diagnose = diagnose.gsub('~', results['condition_data']['worse_conditions'].sample)\n diagnose = diagnose.gsub('#', results['condition_data']['possible_conditions'].sample)\n customised_diagnose << diagnose\n end\n return customised_diagnose\n else\n customised_diagnose = []\n DR_DIAGNOSE['data'].each do |diagnose|\n diagnose = diagnose.gsub('*', username)\n diagnose = diagnose.gsub('@', results['likely_condition'])\n customised_diagnose << diagnose\n end\n end\n end", "def parseDemuxBustardSummary(demuxBustardSummaryXML)\n laneNumber = @fcBarcode.slice(/-\\d/)\n laneNumber.gsub!(/^-/, \"\")\n\n xmlDoc = Hpricot::XML(open(demuxBustardSummaryXML))\n\n (xmlDoc/:'ExpandedLaneSummary Read').each do |read|\n readNumber = (read/'readNumber').inner_html\n\n if readNumber.to_s.eql?(@readType.to_s)\n\n (read/'Lane').each do |lane|\n laneNum = (lane/'laneNumber').inner_html\n \n if laneNum.to_s.eql?(laneNumber.to_s)\n\n tmp = (lane/'phasingApplied').inner_html\n !isEmptyOrNull(tmp) ? @phasing = tmp : @phasing = 0\n tmp = (lane/'prephasingApplied').inner_html\n !isEmptyOrNull(tmp) ? @prePhasing = tmp : @prePhasing = 0\n end\n end\n end\n end\n\n (xmlDoc/:'LaneResultsSummary Read').each do |read|\n readNumber = (read/'readNumber').inner_html\n\n if readNumber.to_s.eql?(@readType.to_s)\n\n (read/'Lane').each do |lane|\n laneNum = (lane/'laneNumber').inner_html\n\n if laneNum.to_s.eql?(laneNumber.to_s)\n\n tmp = (lane/'oneSig/mean').inner_html\n !isEmptyOrNull(tmp) ? @firstCycleInt = tmp : @firstCycleInt = 0 \n tmp = (lane/'signal20AsPctOf1/mean').inner_html\n !isEmptyOrNull(tmp) ? @percentIntAfter20 = tmp : @percentIntAfter20 = 0\n end\n end\n end\n end\n end", "def process_eqlMemberHealthWarningConditions(hexstr)\n process_eqlMemberHealthConditions(hexstr, eqlMemberHealthWarningMessages)\n end", "def tlv_select\n info 'os10_lldp_interface::tlv select'\n begin\n lldp_interface_data = @tlv_ret[:stdout].split(\"\\n\")\n temp_data = {}\n\n lldp_interface_data.each do |data|\n if data.include? 'lldp tlv-select'\n tlv_data = data.split(' ')\n if tlv_data.length == 4\n temp_data[tlv_data[3]] = [' ']\n elsif temp_data[tlv_data[3]].nil? && tlv_data.length >= 4\n temp_data[tlv_data[3]] = [tlv_data[4]]\n elsif tlv_data[4]\n temp_data[tlv_data[3]] = temp_data[tlv_data[3]] << tlv_data[4]\n temp_data[tlv_data[3]] = temp_data[tlv_data[3]].sort\n end\n end\n end\n return temp_data\n rescue Exception => e\n err 'Exception in tlv select'\n err e.message\n err e.backtrace[0]\n raise\n end\n end", "def process_interfaces(int)\n\n # if unit is not the 4th field then this specified interface settings we don't care about\n # return to main to receive the next line or to move on to another method\n return if int.at(3) != :unit\n\n # if the primary interface (not unit) has not already been added as a key to the hash\n # go ahead and add it. Otherwise continue to process unit values.\n unless $h_interfaces.has_key?(int.at(2))\n $h_interfaces[int.at(2)] = Hash.new\n end\n\n unless $h_interfaces[int.at(2)].has_key?(int.at(4))\n $h_interfaces[int.at(2)][int.at(4)] = {\\\n :description => nil, \\\n :'address_v4_primary' => nil,\\\n :'ipv4_input_filter' => nil,\\\n :'ipv4_output_filter' => nil,\\\n :'address_v6_primary' => nil,\\\n :'ipv6_input_filter' => nil,\\\n :'ipv6_output_filter' => 'nil',\\\n :vlan => nil,\\\n :vrrp => Hash.new}\n\n $interface_count += 1\n end\n\n # IP address info\n if (int.at(6) == :inet && int.at(7) == :address) && (int.at(9) == :primary || int.at(9) == nil)\n $h_interfaces[int.at(2)][int.at(4)][:'address_v4_primary'] = int.at(8)\n end\n if (int.at(6) == :inet6 && int.at(7) == :address) && (int.at(9) == :primary || int.at(9) == nil)\n $h_interfaces[int.at(2)][int.at(4)][:'address_v6_primary'] = int.at(8)\n end\n\n # Set Interface Description\n $h_interfaces[int.at(2)][int.at(4)][:description] = int.at(6) if int.at(5) == :description\n\n # Set vlan-id\n $h_interfaces[int.at(2)][int.at(4)][:vlan] = int.at(6) if int.at(5) == :'vlan-id'\n\n # Set input/output filters\n if int.at(6) == :inet && int.at(7) == :filter && int.at(8) == :input\n $h_interfaces[int.at(2)][int.at(4)][:ipv4_input_filter] = int.at(9)\n $ipv4_uniq_inputfilter_count << int.at(9)\n end\n if int.at(6) == :inet && int.at(7) == :filter && int.at(8) == :output\n $h_interfaces[int.at(2)][int.at(4)][:ipv4_output_filter] = int.at(9)\n $ipv4_uniq_outputfilter_count << int.at(9)\n end\n if int.at(6) == :inet6 && int.at(7) == :filter && int.at(8) == :input\n $h_interfaces[int.at(2)][int.at(4)][:ipv6_input_filter] = int.at(9)\n $ipv6_uniq_inputfilter_count << int.at(9)\n end\n if int.at(6) == :inet6 && int.at(7) == :filter && int.at(8) == :output\n $h_interfaces[int.at(2)][int.at(4)][:ipv6_output_filter] = int.at(9)\n $ipv6_uniq_outputfilter_count << int.at(9)\n end\n\n # VRRP Detail\n if int.at(9) == :'vrrp-group'\n unless $h_interfaces[int.at(2)][int.at(4)][:vrrp].has_key?(int.at(10))\n $h_interfaces[int.at(2)][int.at(4)][:vrrp][int.at(10)] = {\\\n :'virtual-address' => nil,\\\n :'intf-address' => nil,\\\n :priority => nil,\\\n :'advertise-interval' => nil,\\\n :preempt => nil,\\\n :'accept-data' => nil,\\\n :'authentication-type' => nil,\\\n :'authentication-key' => nil }\n\n $vrrp_group_count += 1\n end\n\n $h_interfaces[int.at(2)][int.at(4)][:vrrp][int.at(10)][:'intf-address'] = int.at(8)\n\n # For other interface parameters, add a key for each under the interface/unit array\n case int.at(11)\n when :'virtual-address'\n $h_interfaces[int.at(2)][int.at(4)][:vrrp][int.at(10)][:'virtual-address'] = int.at(12)\n when :priority\n $h_interfaces[int.at(2)][int.at(4)][:vrrp][int.at(10)][:priority] = int.at(12)\n when :'advertise-interval'\n $h_interfaces[int.at(2)][int.at(4)][:vrrp][int.at(10)][:'advertise-interval'] = int.at(12)\n when :preempt\n $h_interfaces[int.at(2)][int.at(4)][:vrrp][int.at(10)][:preempt] = :true\n when :'accept-data'\n $h_interfaces[int.at(2)][int.at(4)][:vrrp][int.at(10)][:'accept-data'] = :true\n when :'authentication-type'\n $h_interfaces[int.at(2)][int.at(4)][:vrrp][int.at(10)][:'authentication-type'] = int.at(12)\n when :'authentication-key'\n $h_interfaces[int.at(2)][int.at(4)][:vrrp][int.at(10)][:'authentication-key'] = int.at(12)\n end\n\n end\n\nend", "def additional_info\n section = __method__\n output = get_nagios_var(\"NAGIOS_#{@state_type}OUTPUT\")\n #if match = /(?<state>\\w+ CPU) (?<metric>\\w+) (?<threshold_and_stats>.*) (?<iowait>iowait=.*%) (?<idle>idle=.*%)/.match(output)\n add_html(section, \"<b>Additional Info</b>:<br>\")\n add_text(section, \"Additional Info: \")\n if match = /(?<state>\\w+ CPU) (?<metric>iowait) (?<threshold_and_stats>.*) (?<iowait>iowait=.*%) (?<idle>idle=.*%)/.match(output)\n iowait_info = \"#{match[:state]} <b><font color='red'>#{match[:metric]}</font></b> \"\n iowait_info += \"#{match[:threshold_and_stats]} <b><font color='red'>#{match[:iowait]}</font></b> \"\n iowait_info += \"#{match[:idle]}\"\n add_html(section, iowait_info)\n elsif match = /(?<state>\\w+ CPU) (?<metric>idle) (?<threshold_and_stats>.*) (?<iowait>iowait=.*%) (?<idle>idle=.*%)/.match(output)\n iowait_info = \"#{match[:state]} <b><font color='red'>#{match[:metric]}</font></b> \"\n iowait_info += \"#{match[:threshold_and_stats]} #{match[:iowait]} \"\n iowait_info += \"<b><font color='red'>#{match[:idle]}</font></b>\"\n add_html(section, iowait_info)\n else\n add_html(section, output)\n end\n add_text(section, output) # nothing fancy to see for text\n end", "def get_site_snmp_alerts(id, opts = {})\n data, _status_code, _headers = get_site_snmp_alerts_with_http_info(id, opts)\n return data\n end", "def process(data)\n bytes = StringIO.new(String(data)).each_byte\n bytes.each do |byte|\n case byte\n when REPORT_VERSION\n @major_version = bytes.next\n @minor_version = bytes.next\n\n emit('report_version')\n\n when ANALOG_MESSAGE_RANGE\n least_significant_byte = bytes.next\n most_significant_byte = bytes.next\n\n value = least_significant_byte | (most_significant_byte << 7)\n pin = byte & 0x0F\n\n if analog_pin = analog_pins[pin]\n pins[analog_pin].value = value\n\n emit('analog-read', pin, value)\n emit(\"analog-read-#{pin}\", value)\n end\n\n when DIGITAL_MESSAGE_RANGE\n port = byte & 0x0F\n first_bitmask = bytes.next\n second_bitmask = bytes.next\n port_value = first_bitmask | (second_bitmask << 7)\n\n 8.times do |i|\n pin_number = 8 * port + i\n if pin = pins[pin_number] and pin.mode == INPUT\n value = (port_value >> (i & 0x07)) & 0x01\n pin.value = value\n emit('digital-read', pin_number, value)\n emit(\"digital-read-#{pin_number}\", value)\n end\n end\n\n when START_SYSEX\n current_buffer = [byte]\n begin\n current_buffer.push(bytes.next)\n end until current_buffer.last == END_SYSEX\n\n command = current_buffer[1]\n\n case command\n when CAPABILITY_RESPONSE\n supported_modes = 0\n n = 0\n\n current_buffer.slice(2, current_buffer.length - 3).each do |byte|\n if byte == 127\n modes = []\n # the pin modes\n [ INPUT, OUTPUT, ANALOG, PWM, SERVO ].each do |mode|\n modes.push(mode) unless (supported_modes & (1 << mode)).zero?\n end\n\n @pins.push(Pin.new(modes, OUTPUT, 0))\n\n supported_modes = 0\n n = 0\n next\n end\n\n supported_modes |= (1 << byte) if n.zero?\n\n n ^= 1\n end\n\n emit('capability_query')\n\n when ANALOG_MAPPING_RESPONSE\n pin_index = 0\n\n current_buffer.slice(2, current_buffer.length - 3).each do |byte|\n\n @pins[pin_index].analog_channel = byte\n\n @analog_pins.push(pin_index) unless byte == 127\n\n pin_index += 1\n end\n\n emit('analog_mapping_query')\n\n when PIN_STATE_RESPONSE\n pin = pins[current_buffer[2]]\n pin.mode = current_buffer[3]\n pin.value = current_buffer[4]\n\n pin.value |= (current_buffer[5] << 7) if current_buffer.size > 6\n\n pin.value |= (current_buffer[6] << 14) if current_buffer.size > 7\n\n when FIRMWARE_QUERY\n @firmware_name = current_buffer.slice(4, current_buffer.length - 5).reject { |b| b.zero? }.map(&:chr).join\n emit('firmware_query')\n\n else\n puts 'bad byte'\n end\n end\n end\n rescue StopIteration\n # do nadda\n end", "def info(vm)\n used_cpu = @monitor[:used_cpu]\n used_memory = @monitor[:used_memory]\n netrx = @monitor[:netrx]\n nettx = @monitor[:nettx]\n diskrdbytes = @monitor[:diskrdbytes]\n diskwrbytes = @monitor[:diskwrbytes]\n diskrdiops = @monitor[:diskrdiops]\n diskwriops = @monitor[:diskwriops]\n\n if vm[:mob]\n guest_ip = vm[:mob].guest.ipAddress\n esx_host = vm[:mob].runtime.host.name.to_s\n guest_state = vm[:mob].guest.guestState.to_s\n vmware_tools = vm[:mob].guest.toolsRunningStatus.to_s\n vm_name = vm[:mob].name.to_s\n vmtools_ver = vm[:mob].guest.toolsVersion.to_s\n vmtools_verst = vm[:mob].guest.toolsVersionStatus2.to_s\n end\n\n # if vm[:mob]\n # rp_name = vm[:mob][:rp_list]\n # .select do |item|\n # item[:ref] == vm[:mob]['resourcePool']._ref\n # end\n # .first[:name] rescue ''\n\n # rp_name = 'Resources' if rp_name.empty?\n # else\n # rp_name = @vm['resourcePool'].name\n # end\n\n str_info = ''\n\n str_info << 'GUEST_IP=' << guest_ip.to_s << \"\\n\" if guest_ip\n\n if @guest_ip_addresses && !@guest_ip_addresses.empty?\n str_info << 'GUEST_IP_ADDRESSES=\"' << @guest_ip_addresses.to_s \\\n << '\" '\n end\n\n str_info << \"#{POLL_ATTRIBUTE[:cpu]}=\" << used_cpu.to_s << \"\\n\"\n str_info << \"#{POLL_ATTRIBUTE[:memory]}=\" << used_memory.to_s << \"\\n\"\n str_info << \"#{POLL_ATTRIBUTE[:netrx]}=\" << netrx.to_s << \"\\n\"\n str_info << \"#{POLL_ATTRIBUTE[:nettx]}=\" << nettx.to_s << \"\\n\"\n\n str_info << 'DISKRDBYTES=' << diskrdbytes.to_s << \"\\n\"\n str_info << 'DISKWRBYTES=' << diskwrbytes.to_s << \"\\n\"\n str_info << 'DISKRDIOPS=' << diskrdiops.to_s << \"\\n\"\n str_info << 'DISKWRIOPS=' << diskwriops.to_s << \"\\n\"\n\n str_info << 'VCENTER_ESX_HOST=\"' << esx_host << '\" ' << \"\\n\"\n str_info << 'VCENTER_GUEST_STATE=' << guest_state << \"\\n\"\n str_info << 'VCENTER_VM_NAME=\"' << vm_name << '\" ' << \"\\n\"\n str_info << 'VCENTER_VMWARETOOLS_RUNNING_STATUS=' << vmware_tools << \"\\n\"\n str_info << 'VCENTER_VMWARETOOLS_VERSION=' << vmtools_ver << \"\\n\"\n str_info << 'VCENTER_VMWARETOOLS_VERSION_STATUS=' \\\n << vmtools_verst << \"\\n\"\n # str_info << 'VCENTER_RP_NAME=\"' << rp_name << '\" '\n\n # I need modify this Carlos improvement.\n # @vm.info_disks.each do |disk|\n # str_info << \"DISK_#{disk[0]}_ACTUAL_PATH=\\\"[\" <<\n # disk[1].ds.name << '] ' << disk[1].path << '\" '\n # end\n\n str_info\n end", "def parseReport(reportText)\n # First, get credit summary\n creditSummary = getCredits(reportText)\n @totalEarnedCredits = creditSummary[:totalEarned]\n @totalInProgressCredits = creditSummary[:totalInProgress]\n @totalNeededCredits = creditSummary[:totalNeeded]\n @upperDivEarnedCredits = creditSummary[:upperDivEarned]\n @upperDivInProgressCredits = creditSummary[:upperDivInProgress]\n @upperDivNeededCredits = creditSummary[:upperDivNeeded]\n\n # Get GPA summary and color red or green based on min requirements\n gpaSummary = getGPA(reportText)\n @cumulativeGPA = gpaSummary[:cumulativeGPA]\n @majorGPA = gpaSummary[:majorGPA]\n\n if @cumulativeGPA.to_i > 2\n @cumulativeGPAStatus = 'color: green'\n @cumulativeGPAIconClass = 'glyphicon glyphicon-ok'\n else\n @cumulativeGPAStatus = 'color: red'\n @cumulativeGPAIconClass = 'glyphicon glyphicon-remove'\n end\n\n if @majorGPA.to_i > 2\n @majorGPAStatus = 'color: green'\n @majorGPAIconClass = 'glyphicon glyphicon-ok'\n else\n @majorGPAStatus = 'color: red'\n @majorGPAIconClass = 'glyphicon glyphicon-remove'\n end\n\n # Get general and sub requirement status\n @genRequirementsArray = getGeneralRequirements(reportText)\n @subRequirementsArray = getSubRequirements(reportText)\n @verboseSectionsArray = getVerboseSections(reportText)\nend", "def parse_msats_detail\n # Set the details if there are any\n unless @msats_detail['MasterData'].nil?\n @tni = @msats_detail['MasterData']['TransmissionNodeIdentifier']\n @dlf = @msats_detail['MasterData']['DistributionLossFactorCode']\n @customer_classification_code = @msats_detail['MasterData']['CustomerClassificationCode']\n @customer_threshold_code = @msats_detail['MasterData']['CustomerThresholdCode']\n @jurisdiction_code = @msats_detail['MasterData']['JurisdictionCode']\n @classification_code = @msats_detail['MasterData']['NMIClassificationCode']\n @status = @msats_detail['MasterData']['Status']\n @address = @msats_detail['MasterData']['Address']\n end\n @meters ||= []\n @roles ||= {}\n @data_streams ||= []\n # Meters\n unless @msats_detail['MeterRegister'].nil?\n meters = @msats_detail['MeterRegister']['Meter']\n meters = [meters] if meters.is_a?(Hash)\n meters.reject { |x| x['Status'].nil? }.each do |meter|\n @meters << AEMO::Meter.from_hash(meter)\n end\n meters.select { |x| x['Status'].nil? }.each do |registers|\n m = @meters.find { |x| x.serial_number == registers['SerialNumber'] }\n m.registers << AEMO::Register.from_hash(\n registers['RegisterConfiguration']['Register']\n )\n end\n end\n # Roles\n unless @msats_detail['RoleAssignments'].nil?\n role_assignments = @msats_detail['RoleAssignments']['RoleAssignment']\n role_assignments = [role_assignments] if role_assignments.is_a?(Hash)\n role_assignments.each do |role|\n @roles[role['Role']] = role['Party']\n end\n end\n # DataStreams\n unless @msats_detail['DataStreams'].nil?\n data_streams = @msats_detail['DataStreams']['DataStream']\n data_streams = [data_streams] if data_streams.is_a?(Hash) # Deal with issue of only one existing\n data_streams.each do |stream|\n @data_streams << OpenStruct.new(\n suffix: stream['Suffix'],\n profile_name: stream['ProfileName'],\n averaged_daily_load: stream['AveragedDailyLoad'],\n data_stream_type: stream['DataStreamType'],\n status: stream['Status']\n )\n end\n end\n self\n end", "def diagnostics(rule_name, info)\n\n # Get to the advanced page.\n self.goto_advanced(rule_name, info)\n \n # Get to the \"Diagnostics\" page.\n begin\n @ff.link(:text, 'Diagnostics').click\n self.msg(rule_name, :info, 'Go to \\'Diagnostics\\' page', 'Done!')\n rescue\n self.msg(rule_name, :error, 'Go to \\'Diagnostics\\' page', 'Wrong!')\n return\n end\n \n # Check for the keys\n if ( info.has_key?('section') &&\n info.has_key?('subsection') &&\n info.has_key?('Destination') &&\n info.has_key?('Number of pings') ) then\n # Right,go on.\n else\n self.msg(rule_name,:error,'users','Some key NOT found.')\n return\n end \n \n # Parse the json file.\n \n # Fill in the \"Destination\" text field.\n @ff.text_field(:name,'ping_dest').set(info['Destination'])\n self.msg(rule_name,:info,'Destincation',info['Destination'])\n\n # Fill in the \"Number of pings\" text field.\n @ff.text_field(:name,'ping_num').set(info['Number of pings'])\n self.msg(rule_name,:info,'Number of pings',info['Number of pings'])\n \n # Click \"go\"\n @ff.link(:text,'Go').click\n self.msg(rule_name,:info,'Go','Clicked')\n \n # Wait for the result.\n sleep 0.5\n @ff.refresh\n @ff.wait\n \n count = 0\n while count <= 6\n \n # Ping over?\n @ff.link(:text,'Refresh').click\n if @ff.text.include?'Test Succeeded' or @ff.text.include?'Test Failed'\n self.msg(rule_name,:info,'Diagnostics Result','Generated')\n break\n end\n \n count += 1\n sleep 5\n \n end\n \n if count == 7 \n self.msg(rule_name, :error, 'diagnostics', '\\'Go\\' time out.')\n return \n end \n \n # Now, parse the ping result\n \n # Find the table.\n sTable = false\n @ff.tables.each do |t|\n if t.text.include? 'Status'\n sTable = t\n end\n end\n \n if sTable == false\n # Wrong here\n self.msg(rule_name,:error,'diagnostics','Did NOT find the target table.')\n return\n end\n \n # Find the row\n sTable.each do |row|\n \n # Find the cell\n \n # Output \"Status\"\n if row.text.include? 'Status'\n self.msg(rule_name,:info,'Status',row[2])\n end\n \n # Output \"Packets\"\n if row.text.include? 'Packets'\n self.msg(rule_name,:info,'Packets',row[2])\n end\n \n # Output \"Round Trip Time\"\n if row.text.include? 'Round Trip Time'\n self.msg(rule_name,:info,'Round Trip Time',row[2])\n end\n \n end\n \n # Output results\n self.msg(rule_name,:info,'Diagnostics','Success')\n \n # Close\n @ff.link(:text,'Close').click\n \n end", "def parse\n begin\n #regex_rules_params = \"(^#.*)\\nif([\\s\\w\\:\\\"\\.\\;\\(\\)\\,\\-]+)\\{([\\@\\<>=a-zA-Z0-9\\s\\[\\]\\_\\:\\\"\\.\\;\\(\\)\\,\\-\\/]+)\\}$\"\n #regex_rules_params2 = \"(^#.*)\\n(\\S+)(.+)\\n\\{\\n([\\s\\S]*)\\}\"\n parts = @text.scan(/(^#.*)\\n(\\S+)\\s(.+)\\n\\{\\n([\\s\\S]*)\\n\\}/)[0]\n parse_name(parts[0])\n @type = parts[1]\n\n self.disable! if parts[2] =~ /.*false #/\n #if the join is true, dont have conditions...\n if parts[2] =~ /true/\n @conditions << Condition.new(type:\"true\")\n elsif parts[2] =~ /(anyof|allof)/\n @join = parts[2][/^\\S+/]\n @conditions.concat(Condition.parse_all( parts[2].scan(/\\(([\\S\\s]+)\\)/)[0][0] ))\n else\n @conditions << Condition.new(text:parts[2])\n end\n\n @actions.concat(Action.parse_all(parts[3]))\n rescue => e\n puts e.to_s + \" - text: #{@text}\"\n end\n end", "def extrapolate(data, thresholds, max_length, cluster, annotation)\n # full_thresh is the array of thresholds that data arrays have to be created at\n # when threshold is nil, a data array at full data is created\n # therefore, full thresh has nil by default to always create data arrays at no subsampling level\n full_thresh = [nil]\n\n # add thresholds to be created at, as long as the threshold isn't bigger than the size of full data, because that would be impossible\n thresholds.each do |th|\n if max_length > th\n full_thresh << th\n end\n end\n\n # create a data array at each threshold\n full_thresh.each do |threshold|\n create_array(cluster, threshold, annotation, data)\n end\n\n end", "def get_threshold\n d = self.vspecs.select(:value).where(name: 'threshold').first\n return d != nil ? d.value : d\n end", "def parse_power\n \tpower_hash = parse_hash\n \t@max_power = power_hash.values.max\n \t@min_power = power_hash.values.min\n \t@parsed_power = true\n \tread_file unless @parsed_energy\n end", "def parse(metrics)\n # lines starting with a # are comments\n lines = metrics.split \"\\n\"\n lines.reject! { |e| e.strip.blank? }\n lines.reject! { |e| e.strip.starts_with?('#') }\n lines.map! { |l| StatusRow.new(l.split) }\n lines\n end", "def update_site_snmp_alert_with_http_info(id, alert_id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: SiteApi.update_site_snmp_alert ...\"\n end\n # verify the required parameter 'id' is set\n if @api_client.config.client_side_validation && id.nil?\n fail ArgumentError, \"Missing the required parameter 'id' when calling SiteApi.update_site_snmp_alert\"\n end\n # verify the required parameter 'alert_id' is set\n if @api_client.config.client_side_validation && alert_id.nil?\n fail ArgumentError, \"Missing the required parameter 'alert_id' when calling SiteApi.update_site_snmp_alert\"\n end\n # resource path\n local_var_path = \"/api/3/sites/{id}/alerts/snmp/{alertId}\".sub('{' + 'id' + '}', id.to_s).sub('{' + 'alertId' + '}', alert_id.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;charset=UTF-8'])\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(opts[:'alert'])\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 :return_type => 'Links')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: SiteApi#update_site_snmp_alert\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end" ]
[ "0.60059613", "0.5842377", "0.56512755", "0.5472736", "0.5254893", "0.5221036", "0.5188501", "0.51767224", "0.5044552", "0.50299484", "0.49437246", "0.49314392", "0.48781294", "0.48282015", "0.48275483", "0.4772863", "0.47685096", "0.47587496", "0.47324726", "0.47140944", "0.47103068", "0.46941152", "0.46893603", "0.46810508", "0.46805242", "0.46798074", "0.4669768", "0.46618426", "0.46585837", "0.46503264", "0.46420127", "0.4630553", "0.4626218", "0.46106517", "0.45664245", "0.45530832", "0.45528564", "0.45495647", "0.45375073", "0.45248204", "0.45171747", "0.45099372", "0.45045698", "0.4489014", "0.44728082", "0.44608268", "0.4457062", "0.44349843", "0.4434689", "0.44322306", "0.44275257", "0.44046718", "0.4398919", "0.43985012", "0.43971032", "0.4389937", "0.43894768", "0.4386463", "0.43836686", "0.43786037", "0.43727988", "0.43684047", "0.43677807", "0.43617052", "0.43606567", "0.43466365", "0.43444696", "0.43408078", "0.43359342", "0.4329499", "0.4327046", "0.43231934", "0.4321271", "0.4319509", "0.43160838", "0.43076295", "0.430665", "0.43037516", "0.4299849", "0.4296309", "0.42956424", "0.42811713", "0.4278036", "0.4276353", "0.4261636", "0.42598236", "0.42596096", "0.4253369", "0.4249809", "0.4239646", "0.42391902", "0.42333296", "0.42313343", "0.42305645", "0.42267156", "0.42171523", "0.4216828", "0.42164734", "0.42110348", "0.42025957" ]
0.42953137
81
edit GET /:locale/admin_session/edit (named path: edit_admin_session)
def test_edit_admin_session # FIXME route exists but no action in controller, remove route? #get :edit, :locale => 'en' end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update\n respond_to do |format|\n if @admin_session.update(session_params)\n format.html { redirect_to @admin_session, notice: 'Session was successfully updated.' }\n format.json { render :show, status: :ok, location: @admin_session }\n else\n format.html { render :edit }\n format.json { render json: @admin_session.errors, status: :unprocessable_entity }\n end\n end\n end", "def edit\n redirect_back_or_default(\"/\") if\n !@user&.admin && session[:real_user_id].blank?\n end", "def update\n @session = Session.find(params[:id])\n\n respond_to do |format|\n if @session.update_attributes(params[:session])\n flash[:notice] = 'Session was successfully updated.'\n format.html { \n if @session.course\n redirect_to(admin_course_session_path(@session.course, @session))\n else\n redirect_to(admin_session_path(@session))\n end\n }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @session.errors, :status => :unprocessable_entity }\n end\n end\n end", "def edit\n reset_session_key(:user, @user_id, {})\n redirect_to wizard_path('identity')\n end", "def edit\n find_admin_by_id\n end", "def edit\n user_id = params[:id].to_i > 0 ? params[:id] : session[:user_id]\n registration = nil\n if params[:id]\n redirect_to(:controller => :registration, :action=> :index) unless admin_session?\n registration = User.find(params[:id]).current_registration\n unless registration\n flash[:notice] = \"No registration to edit!\"\n redirect_to(:controller => :admin, :action=> :index)\n end\n else\n registration = User.find(session[:user_id]).current_registration\n unless registration \n flash[:notice] = \"No registration to edit!\"\n redirect_to(:controller => :registration, :action=> :index)\n end\n end\n session[:registration] = @registration = registration\n @admin_session = admin_session?\n end", "def edit\n @admin = Admin.find(params[:id])\n end", "def edit\n @admin = Admin.find(params[:id])\n end", "def edit\n @admin = Admin.find(params[:id])\n end", "def edit\n if (session[:user_id] != nil)\n @user = User.find_by(id: session[:user_id])\n else\n redirect_to login_path\n end\n end", "def set_admin\n if params[:admin] != nil\n session[:admin] = params[:admin] \n end\n end", "def edit\n \n # Pass through the specified user, making sure that it exists\n @user = User.find_by_login(params[:user_login])\n \n # Check that the current user is the specified user, or an\n # administrator\n unless @user == current_user or admin_logged_in?\n flash[:error] = 'You cannot edit the profile of another user.'\n redirect_to :controller => 'sessions', :action => 'new'\n else\n render :layout => 'dialog'\n end\n end", "def edit\n if current_user && current_user.role == \"admin\"\n @user = User.find(params[:id])\n else\n redirect_to new_user_session_path\n end \n end", "def toggle_edit_mode\r\n session[:edit_mode] ||= 0 \r\n# called without logged in \r\n if session[:edit_mode] < 1 \r\n dc_render_404 \r\n else\r\n session[:edit_mode] = (session[:edit_mode] == 1) ? 2 : 1\r\n redirect_to params[:return_to]\r\n end\r\nend", "def edit\n debugger\n flash.keep\n redirect_to(edit_user_registration_path)\n end", "def edit\n @user = User.find(session[:user_id])\n end", "def set_session\n @admin_session = AdminSession.find(params[:id])\n end", "def edit\n # --- [ Put in Session ]\n session[:page] = \"dojo\"\n # ---------------------\n @dojo = Dojo.find(params[:id])\n render \"edit\"\n end", "def update\n @session = Session.find(params[:id])\n\n respond_to do |format|\n if @session.update_attributes(params[:session])\n format.html { redirect_to @session, notice: 'Session was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @session.errors, status: :unprocessable_entity }\n end\n end\n end", "def edit\n @expression = Expression.find(params[:id])\n save_expression_instance_in_session\n prepare_edit\n end", "def update\n return if Settings.readonly \n\n respond_to do |format|\n if @session.update(session_params)\n format.html { redirect_to sessions_url, notice: 'Session was successfully updated.' }\n format.json { render :show, status: :ok, location: @session }\n else\n format.html { render :edit }\n format.json { render json: @session.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @plateau_session = PlateauSession.find(params[:id])\n\n respond_to do |format|\n if @plateau_session.update_attributes(params[:plateau_session])\n format.html { redirect_to(@plateau_session, :notice => 'Plateau session was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @plateau_session.errors, :status => :unprocessable_entity }\n end\n end\n end", "def edit\n @resource = Admin.find(params[:id])\n end", "def edit\n if logged_in?\n @user = current_user \n render :edit\n else\n flash[:error] = \"Please sign in\"\n render 'sessions/new'\n end\n end", "def update\n @session = Session.find(params[:id])\n\n respond_to do |format|\n if @session.update_attributes(params[:session])\n format.html { redirect_to @session, notice: 'Session was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @session.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @session = Session.find(params[:id])\n\n respond_to do |format|\n if @session.update_attributes(params[:session])\n format.html { redirect_to @session, notice: 'Session was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @session.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @session = Session.find(params[:id])\n\n respond_to do |format|\n if @session.update_attributes(params[:session])\n format.html { redirect_to @session, notice: 'Session was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @session.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @session = Session.find(params[:id])\n\n respond_to do |format|\n if @session.update_attributes(params[:session])\n format.html { redirect_to @session, notice: 'Session was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @session.errors, status: :unprocessable_entity }\n end\n end\n end", "def edit\n @user = Admin.find(params[:id]) \n end", "def edit_code\n if current_admin.present?\n @code = InviteCode.find(params[:id])\n else\n redirect_to new_admin_session_path and return\n end \n end", "def update\n @session = @event.sessions.find(params[:id])\n\n respond_to do |format|\n if @session.update_attributes(params[:session])\n format.html { redirect_to [@event, @session], notice: 'Session was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @session.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n authorize @session\n respond_to do |format|\n if @session.update(session_params)\n format.html { redirect_to @session, notice: 'Session was successfully updated.' }\n format.json { render :show, status: :ok, location: @session }\n else\n format.html { render :edit }\n format.json { render json: @session.errors, status: :unprocessable_entity }\n end\n end\n end", "def edit\n @admin = Admin.where(id: params[:id]).first\n @departments = Department.all\n if request.post?\n if Admin.updated(params)\n flash[:notice] = 'ユーザー情報を編集しました'\n redirect_to(url_for({ controller: 'super', action: 'dashboard' }))\n else\n flash[:error] = 'ユーザ-の情報編集に失敗しました'\n redirect_to(url_for({ controller: 'admin', action: 'edit', id: params[:id]}))\n end\n end\n end", "def update\n\n respond_to do |format|\n if @session.update_attributes(params[:session])\n format.html { redirect_to @session, notice: 'Session was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @session.errors, status: :unprocessable_entity }\n end\n end\n end", "def edit\n @welcome = Welcome.find(params[:id])\n @roomtype = DetailRoom.all_types\n @time = Room.all_times\n @day_list = Room.all_days\n @admin = session[:admin]\n if @admin == nil\n redirect_to rooms_path\n end\n end", "def update\n @sessionmap = Sessionmap.find(params[:id])\n\n respond_to do |format|\n if @sessionmap.update_attributes(params[:sessionmap])\n format.html { redirect_to(@sessionmap, :notice => 'Sessionmap was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @sessionmap.errors, :status => :unprocessable_entity }\n end\n end\n end", "def edit\n if params[:invitation_token]\n session[:invitation_token] = params[:invitation_token]\n end\n super\n end", "def edit\n if current_admin.present?\n @client = Client.friendly.find(params[:id])\n else\n redirect_to new_admin_session_path and return\n end\n end", "def update_sub_admin\n unless @current_admin.is_super_admin\n flash[:error]=\"You are not authorized to navigate to this page \"\n redirect_to admin_index_path\n return\n end\n\n if session[:searched_addmin_id]\n @sub_admin=Admin.find(session[:searched_addmin_id])\n else\n redirect_to admin_index_path\n end\n end", "def edit\n session[:section] = 'edit'\n @product = Product.find(params[:id])\n end", "def update\n respond_to do |format|\n if @session.update(session_params)\n format.html { redirect_to @session, notice: 'Session was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @session.errors, status: :unprocessable_entity }\n end\n end\n end", "def edit\n if session[:id] && session[:token]\n \n data_output = ::Utility.send_request_to_host_api(\"get\",DOMAIN_HOST+VERSION_API+\"/\"+USERS_TABLE+\"/\"+session[:id].to_s)\n \n if data_output[\"meta\"][\"code\"].to_i == 200\n @data_view = data_output[\"data\"]\n else\n @error = data_output[\"meta\"][\"description\"]\n end\n else\n redirect_to({action:'signin'})\n end\n \n end", "def edit\n @login = Login.find(params[:id])\n end", "def edit(id)\n records = Base.where(_id: id)\n if records.count > 0 and @user != nil and @user.admin?(@routes)\n info = Base64.encode64 records.first.id.to_s.encrypt\n\n show :edit, {views: File.join(Classiccms::ROOT, 'views/cms')}, {encrypteddata: info}\n end\n end", "def update\n respond_to do |format|\n if @session.update(session_params)\n format.html { redirect_to game_session_path(@session), notice: 'Session was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @session.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @admin = Admin.find(params[:id])\n if @admin.update(admin_params)\n redirect_to(admin_path(@admin))\n else\n render('edit')\n end\n end", "def set_edit_page\n # Definimos el nombre de la página\n @page = \"Editar cuenta\"\n @edit = params[:edit]\n end", "def edit\n # TODO: ensure is admin\n operation = params[:oper]\n if operation == 'edit'\n update\n elsif operation == 'del'\n destroy\n elsif operation == 'add'\n create\n end \n end", "def edit\n\t\t# must have admin access or be in the course\n\tend", "def edit\n\n end", "def edit \t\t\t\t\t\t\t #render user page \n \t@user = User.find(session[:user_id])\n end", "def edit\n @col2 = \"form_tips\"\n if params[:id] == 'new'\n if session[:tag_configuration]\n @tag_configuration = session[:tag_configuration]\n @tag_configuration.reset_errors_for_anonymous_session\n else\n logger.debug \"Requested /show/edit but no config in session\"\n redirect_to :action => 'new'\n return\n end\n else\n @tag_configuration = TagConfiguration.find(params[:id])\n end\n end", "def update\n return unless restrict_to_hosts\n\n respond_to do |format|\n if @session.update(session_params)\n format.html { redirect_to [@event, @session], notice: 'Session was successfully updated.' }\n format.json { render :show, status: :ok, location: [@event, @session] }\n else\n format.html { render :edit }\n format.json { render json: @session.errors, status: :unprocessable_entity }\n end\n end\n end", "def edit\n\n end", "def update\n respond_to do |format|\n if @session.update(session_params)\n format.html { redirect_to @session, notice: 'Session was successfully updated.' }\n format.json { render :show, status: :ok, location: @session }\n else\n format.html { render :edit }\n format.json { render json: @session.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @session.update(session_params)\n format.html { redirect_to @session, notice: 'Session was successfully updated.' }\n format.json { render :show, status: :ok, location: @session }\n else\n format.html { render :edit }\n format.json { render json: @session.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @session.update(session_params)\n format.html { redirect_to @session, notice: 'Session was successfully updated.' }\n format.json { render :show, status: :ok, location: @session }\n else\n format.html { render :edit }\n format.json { render json: @session.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @session.update(session_params)\n format.html { redirect_to @session, notice: 'Session was successfully updated.' }\n format.json { render :show, status: :ok, location: @session }\n else\n format.html { render :edit }\n format.json { render json: @session.errors, status: :unprocessable_entity }\n end\n end\n end", "def edit\r\n \r\n end", "def edit\n\t\t@website_admin = WebsiteAdmin.find(params[:id])\n\tend", "def update\n respond_to do |format|\n if @ergo_session.update(ergo_session_params)\n format.html { redirect_to @ergo_session, notice: 'Ergo session was successfully updated.' }\n format.json { render :show, status: :ok, location: @ergo_session }\n else\n format.html { render :edit }\n format.json { render json: @ergo_session.errors, status: :unprocessable_entity }\n end\n end\n end", "def edit\r\n end", "def edit\n user_store_url\n @user = current_user\n if params[:id] && params[:id] != \"current\" && @user.admin?\n @user = User.find(params[:id])\n end\n end", "def edit\n end", "def edit\n end", "def edit\n end", "def edit\n end", "def edit\n end", "def edit\n end", "def edit\n end", "def edit\n end", "def edit\n end", "def edit\n end", "def edit\n end", "def edit\n end", "def edit\n end", "def admin_edit\n @user = User.find(params[:id])\n end", "def admin_edit\n @user = User.find(params[:id])\n end", "def admin_login\n self.current_admin = Admin.find_by_id(session[:admin]) if session[:admin]\n end", "def edit\n\n end", "def edit\n\n end", "def edit\n\n end", "def edit\n\n end", "def edit\n\n end", "def edit\n\n end", "def edit\n\n end", "def edit\n\n end", "def edit\n\n end", "def edit\n\n end", "def edit\n\n end", "def edit\n\n end", "def edit\n\n end", "def edit\n\n end", "def edit\r\n jump_to(\"/profiles/#{session[:account_id]}/basic\")\r\n end", "def edit\n\t\tadd_breadcrumb \"Editar\"\n\t\tif @request.user_id != current_user.id\n\t\t\tredirect_to root_path, alert: \"Usted no es el creador de la solicitud, por lo que no puede modificarla. Contáctese con su administrador.\"\n\t\tend\n\tend", "def update\n respond_to do |format|\n if @admin.update(admin_params)\n format.html do \n sign_in @admin.user\n redirect_to @admin, notice: 'Admin was successfully updated.'\n end\n format.json { render :show, status: :ok, location: @admin }\n else\n format.html { render :edit }\n format.json { render json: @admin.errors, status: :unprocessable_entity }\n end\n end\n end", "def edit\n @page_title = \"Edit Translation\"\n @nav = 'user/profile'\n \n end", "def edit\n end", "def edit\n end", "def edit\n end" ]
[ "0.7054085", "0.68064123", "0.6672927", "0.6614801", "0.6589939", "0.6582252", "0.6557362", "0.6557362", "0.6557362", "0.64800197", "0.6323263", "0.62463754", "0.6240032", "0.62319636", "0.6223811", "0.62187576", "0.6200787", "0.61983234", "0.6183785", "0.61829305", "0.6177006", "0.61746854", "0.61623776", "0.6143647", "0.61364836", "0.6123302", "0.6123302", "0.61226106", "0.6121652", "0.61073", "0.6105919", "0.6103707", "0.60964787", "0.6078155", "0.6056547", "0.60528", "0.60511965", "0.60489494", "0.60339653", "0.60241306", "0.60207033", "0.60002244", "0.5991018", "0.59853107", "0.5982306", "0.5982258", "0.59773374", "0.59712267", "0.59695697", "0.596002", "0.5953826", "0.5951815", "0.5930849", "0.59296274", "0.5911469", "0.5911469", "0.5911469", "0.5911469", "0.5909607", "0.5906662", "0.59022045", "0.5901325", "0.58913815", "0.5890067", "0.5890067", "0.5890067", "0.5890067", "0.5890067", "0.5890067", "0.5890067", "0.5890067", "0.5890067", "0.5890067", "0.5890067", "0.5890067", "0.5890067", "0.5888923", "0.5888923", "0.5883331", "0.58688945", "0.58688945", "0.58688945", "0.58688945", "0.58688945", "0.58688945", "0.58688945", "0.58688945", "0.58688945", "0.58688945", "0.58688945", "0.58688945", "0.58688945", "0.58688945", "0.586843", "0.5863913", "0.58596045", "0.58534807", "0.5828308", "0.5828308", "0.5828308" ]
0.70252484
1
new GET /:locale/admin/session/new (named path: new_admin_session)
def test_new_admin_session get :new, :locale => 'en' assert_response :success end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def new\n @user = Admin.new\n\n respond_to do |format|\n format.html { render :template => \"admin/session/new\"}\n format.xml { render :xml => @user }\n end\n end", "def new\n @usuario = Usuario.new\n if current_user\n session[:admin_new] = true\n else\n session[:admin_new] = false\n end\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @usuario }\n end\n end", "def new\n reset_session_key(:user, :new, {})\n redirect_to admin_user_step_path(id: 'identity')\n end", "def new\n @admin = AdminAccount.find_by_id(session[:admin_id])\n @admin_account = AdminAccount.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @admin_account }\n end\n end", "def new\n @session = Session.new(params[:login])\n\n @page_name = \"Login\"\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @session }\n end\n end", "def create_admin_session(admin)\n session[:admin] = { :user => admin, :session_start_time => Time.now }\n end", "def create \n @admin_session = AdminSession.new(params[:admin_session]) \n if @admin_session.save \n redirect_to('/admins/index') \n else \n render layout: \"login_template\", template: \"admin_sessions/new\" \n end \n end", "def new\n if logged_in?\n redirect_to admin_url\n end\n end", "def new\n @session = Session.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @session }\n end\n end", "def new\n redirect_to members_path unless session[:admin_id].blank?\n @error = Hash.new\n @form_path = login_path\n @title = \"Ylläpitäjän sisäänkirjautuminen\"\n @password_reset_link = true\n end", "def new\n @session = Session.new('')\n end", "def new\n @session = User::Session.new\n end", "def new\n @session = Session.new\n end", "def new\n @program_language = ProgramLanguage.new\n\n @admin_log = AdminLog.new(:aid=> session[:user_id], :controller => \"program_language\", :action => \"new\")\n @admin_log.save\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @program_language }\n end\n end", "def new\n @current_admin_user = current_admin_user\n session[:menu_params] ||= {}\n @title = \"New Menu\"\n @menu = Menu.new(session[:menu_params])\n @categories = @menu.categories\n @menu.current_step = session[:menu_step]\n end", "def new\n @session = Session.new\n\n respond_to do |format|\n format.json { render json: @session }\n format.html # new.html.erb\n end\n end", "def new\n if current_user\n redirect_to root_url\n end\n @user_session = UserSession.new\n end", "def new\n @session = Session.new\n\n render 'sessions/login'\n #respond_to do |format|\n # format.html # new.html.erb\n #format.json { render json: @session }\n # end\n end", "def create_session\n session[:who_is_this] = \"admin\"\n end", "def new\r\n create\r\n# logout_keeping_session!\r\n# respond_to do |format|\r\n# format.html\r\n# end\r\n end", "def new\n @admin = AdminAccount.find_by_id(session[:admin_id])\n @user_account = UserAccount.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user_account }\n end\n end", "def new\n unless @current_admin.is_super_admin\n flash[:error]=\"You are not authorized to navigate to this page \"\n redirect_to admin_index_path\n return\n end\n @new_admin=Admin.new\n end", "def new\n @session = Session.new\n @session.machine = @machine\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @session }\n end\n end", "def new\n \t@admin = Admin.new\n end", "def new\r\n @session = Session.new\r\n @session.state = 'waiting'\r\n\r\n respond_to do |format|\r\n format.html # new.html.erb\r\n format.xml { render :xml => @session }\r\n format.json { render :json => @session }\r\n end\r\n end", "def new\n if current_user\n redirect_to(:action=>'logged_in')\n else\n @user_session = UserSession.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user_session }\n end\n end\n\n end", "def new\n\t\t@user_session = UserSession.new\n\tend", "def new\n unless has_cookies_enabled?\n flash[:error] = t 'ubiquo.auth.cookies_error'\n end\n unless ubiquo_users?\n flash.now[:notice] = t 'ubiquo.auth.create_superadmin'\n end\n if logged_in?\n redirect_to ubiquo.home_path\n end\n end", "def new_session_path(arg)\n login_path\n end", "def new\n @admin = Admin.new\n end", "def new\n @admin = Admin.new\n end", "def new\n @admin = Admin.new\n end", "def new\n @admin = Admin.new \n end", "def new\n logger.debug (flash)\n logger.debug (session)\n flash[:alert] =flash[:alert]\n redirect_to login_path\n end", "def new\n @session_type = SessionType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @session_type }\n end\n end", "def new\n @session = Session.new\n end", "def new\n @sessionmap = Sessionmap.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @sessionmap }\n end\n end", "def new_session_path(resource)\n root_path\n end", "def new\n @user_session = UserSession.new\n end", "def new\n @user_session = UserSession.new\n end", "def new\n @user_session = UserSession.new\n end", "def new\n @user_session = UserSession.new\n end", "def new\n @user_session = UserSession.new\n end", "def new\n if current_admin.present?\n @clients = Client.all\n @client = Client.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @client }\n end\n else\n redirect_to new_admin_session_path and return\n end \n end", "def test_admin_session\n # FIXME route exists but no action in controller, remove route?\n # get :show, :locale => 'en'\n end", "def new #login page\n end", "def new\n @admin_level = AdminLevel.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @admin_level }\n end\n end", "def new\n @admin_language = Language.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @admin_language }\n end\n end", "def new \n unless current_user.nil?\n redirect_to backend_root_url\n return\n end\n \n @user_session = UserSession.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user_session }\n end\n end", "def create\n @session = Session.new(params[:session])\n\n respond_to do |format|\n if @session.save\n flash[:notice] = t 'flash.notice.successfully.created', :object => Session.human_name\n format.html { redirect_to(@session) }\n format.xml { render :xml => @session, :status => :created, :location => @session }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @session.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @locale = LOCALE.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @locale }\n end\n end", "def new\n\t\traise\n\t\t@membership = Membership.create(user_id: session[:user_id], group_id: session[:false_id], admin: false)\n\t\[email protected]\n\t\traise\n\t\t#redirect_to 'groups'\n\tend", "def new\n if current_haka_user\n flash.notice = \"Olet jo kirjautunut sisään.\"\n redirect_to registrations_root_path and return\n end\n\n request = OneLogin::RubySaml::Authrequest.new\n redirect_to(request.create(saml_settings))\n end", "def create\n @admin_session = AdminSession.new\n @admin_session.adminname = session_params[:adminname]\n @admin = Admin.where(:adminname => @admin_session.adminname).first\n if @admin\n @admin = @admin.auth(params[:encrypt_password])\n @admin_session.user_id = @admin.id\n if @admin\n respond_to do |format|\n if @admin_session.save\n session[:adminname] = @admin_session.adminname\n session[:admin_session_id] = @admin_session.id.to_s\n format.html { redirect_to @admin_session, notice: 'Session was successfully created.' }\n format.json { render :show, status: :created, location: @admin_session }\n else\n format.html { render :new }\n format.json { render json: @admin_session.errors, status: :unprocessable_entity }\n end\n end\n else\n render json: '密码错误'\n end\n else\n render json: '用户名不存在'\n end\n \n end", "def new\n @user_session ||= UserSession.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @user_session }\n end\n end", "def new\n @admin = Admin.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @admin }\n end\n end", "def new\n @session = Session.new\n @speakers = active_conference.speakers\n \n respond_to do |format|\n format.html { render layout: 'admin' }\n format.json { render json: @session }\n end\n end", "def new\n if !session[:id] && !session[:token]\n redirect_to({controller:'users', action:'signin'})\n end\n end", "def new_session_path(_scope)\n new_user_session_path\n end", "def new\n @user = User.new\n session[:form] = \"register\"\n end", "def new\n unless logged_in?\n redirect_to new_login_url\n return\n end\n @play = Play.new\n\n respond_to do |format|\n format.html { render :new, :layout => 'admin' }\n format.xml { render :xml => @play }\n end\n end", "def new\n if current_user && current_user.role == \"admin\"\n @user = User.new \n else\n redirect_to new_user_session_path\n end \n end", "def new\n redirect_to(login_path)\n end", "def new\n # @user = params[:id] ? User.find(params[:id]) : nil\n @admin = Admin.new\n end", "def new\n @ykt_session = YktSession.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @ykt_session }\n end\n end", "def new_session_path(scope)\n new_user_session_path\n end", "def new\n session[:section] = 'new'\n @product = Product.new\n end", "def new\n\t\t@group_session = GroupSession.new\n\tend", "def new\n @systemadmin = Systemadmin.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @systemadmin }\n end\n end", "def create\n session[:password] = params[:password]\n flash[:notice] = \"You successfully logged in #{ \"as admin\" if admin? }\"\n redirect_to root_path\n end", "def new\n if(params[\"session\"] == 'nil')\n session[:mailid] = nil\n end\n @loginuser = Loginuser.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @loginuser }\n end\n \n end", "def new\n @user_session = UserSession.new(:email => session[:user_real_account_email])\n end", "def create\n admin = Admin.find_by_username(params[:username]).try(:authenticate, params[:password])\n @error = Hash.new\n if admin\n session[:admin_id] = admin.id\n redirect_to members_path and return\n end\n @form_path = login_path\n @title = \"Ylläpitäjän sisäänkirjautuminen\"\n @password_reset_link = true\n @error[:error] = \"Virheellinen käyttäjätunnus tai salasana\"\n render \"new\"\n end", "def create\n @admin = Admin.new(admin_params)\n if @admin.valid? && @admin.save\n redirect_to(admin_login_path)\n else\n render('new')\n end\n end", "def new_session\n IntegrationSession.new\n end", "def new\n @admin_page = Page.new\n\n respond_to do |format|\n format.html # new.html.erb\n end\n end", "def new\n redirect_to root_path if logged_in?\n end", "def new\n attempt_login\n redirect_to root_path if logged_in?\n end", "def new\n new_url = \"#{ENV['KPASS_ENDPOINT']}/members/new?app_id=#{ENV['KPASS_APP_ID']}\"\n redirect_to new_url\n end", "def new\n @admin = Admin.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @admin }\n end\n end", "def new\n @admin = Admin.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @admin }\n end\n end", "def new\n @admin = Admin.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @admin }\n end\n end", "def new\n\t\t@admin = User.new\n end", "def new\n redirect_to dashboard_path, notice: \"Logged in!\" if logged_in?\n end", "def create\n return if Settings.readonly \n\n @session = Session.new(session_params)\n\n respond_to do |format|\n if @session.save\n format.html { redirect_to sessions_url, notice: 'Session was successfully created.' }\n format.json { render :show, status: :created, location: @session }\n else\n format.html { render :new }\n format.json { render json: @session.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @categorie = Categorie.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @categorie }\n end\n session[:titre] = \"Créer une categorie\"\n end", "def new_user_session(user)\n session = new_session\n session.login!(user)\n return session\n end", "def new\n if logged_in?\n flash[:success] = t('sessions.already_logged_in')\n redirect_to root_url\n else\n use_secure_headers_override(:allow_github_form_action)\n store_location_and_locale\n end\n end", "def test_edit_admin_session\n # FIXME route exists but no action in controller, remove route?\n #get :edit, :locale => 'en'\n end", "def new\n session[:room_type_channel_mapping_params] = {}\n session[:room_type_channel_mapping_params][:channel_id] = Channel.find(params[:channel_id]).id\n session[:room_type_channel_mapping_params][:room_type_id] = RoomType.find(params[:room_type_id]).id\n\n session[:room_type_master_rate_channel_mapping_params] = {}\n \n redirect_to new_wizard_channel_room_admin_room_type_channel_mappings_path\n end", "def new_session_path(_scope)\n login_path\n end", "def new\n super\n reset_session\n end", "def new\n @user_session = UserSession.new\n\n respond_to do |format|\n format.html # new.html.haml\n format.xml { render :xml => @user_session }\n end\n end", "def new\n @title = \"Create a New Training Session\"\n session[:interval_order] = nil\n @trainingsession = Trainingsession.new\n @trainingsession.interval.build\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @trainingsession }\n end\n end", "def new\n debugger\n flash[:failure_provider] = request.env['omniauth.error.strategy'].name\n flash[:failre_type] = request.env['omniauth.error.type']\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @session }\n end\n end", "def index\n if session[:admin_id] != nil\n redirect_to admin_path(Admin.find(session[:admin_id]))\n else\n @admin = Admin.new\n end\n end", "def new_session\n open_session do |sess|\n sess.extend(SessionMethods)\n yield sess if block_given?\n end\n end", "def new\n @user_session = UserSession.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user_session }\n end\n end", "def create\n @session = Session.new(session_params)\n\n respond_to do |format|\n if @session.save\n format.html { redirect_to @session }\n format.json { render :show, status: :created, location: @session }\n else\n format.html { render :new }\n format.json { render json: @session.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n if params[:create_user] == '1' or session[:id]\n @user = User.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @user }\n end\n else\n flash[:error] = \"You will need to Sign In to view this page.\"\n redirect_to :controller => 'system', :action => 'index'\n end\n end" ]
[ "0.70117503", "0.69180125", "0.67954737", "0.67679363", "0.6726583", "0.6636874", "0.65391636", "0.65348166", "0.651468", "0.6492233", "0.64741516", "0.6468671", "0.6448151", "0.6441115", "0.6433127", "0.6397004", "0.63933915", "0.6367016", "0.6330643", "0.6290651", "0.6274631", "0.6272437", "0.6271274", "0.6225935", "0.6210962", "0.6189018", "0.61887413", "0.6187296", "0.6164627", "0.6163779", "0.6163779", "0.6163779", "0.6144377", "0.61419463", "0.61411476", "0.613602", "0.61311954", "0.6122014", "0.60822326", "0.60822326", "0.60822326", "0.60822326", "0.60822326", "0.60757536", "0.6071756", "0.60680485", "0.60523987", "0.60503983", "0.6048782", "0.60377365", "0.60296077", "0.6029543", "0.6008751", "0.5999362", "0.59970206", "0.59841704", "0.5975712", "0.59470516", "0.5941417", "0.59325534", "0.59099615", "0.5907133", "0.59065145", "0.5903072", "0.5901294", "0.5888594", "0.5888319", "0.5886673", "0.5882856", "0.5878557", "0.58722234", "0.5869999", "0.5864597", "0.5859551", "0.58537745", "0.58432615", "0.58407176", "0.5834498", "0.58344007", "0.5830943", "0.5830943", "0.5830943", "0.58227116", "0.580359", "0.5803372", "0.5801783", "0.579988", "0.57988214", "0.57981586", "0.5797735", "0.5795244", "0.5794351", "0.5794047", "0.5787836", "0.5786771", "0.5780268", "0.5768838", "0.5766757", "0.5765993", "0.5764594" ]
0.6498683
9
show GET /:locale/admin_session (named path: admin_session)
def test_admin_session # FIXME route exists but no action in controller, remove route? # get :show, :locale => 'en' end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def show\n @admin = Admin.find_by(id: session[:admin_id])\n end", "def show\n @admin_level = Admin.find(session[:admin_id]).admin_level\n end", "def admin_login\n self.current_admin = Admin.find_by_id(session[:admin]) if session[:admin]\n end", "def show\n if !session[:is_admin]\n redirect_to root_url\n end\n end", "def index\n @admin_session = AdminSession.all\n end", "def display_resource(admin)\r\n admin.login\r\n end", "def create_admin_session(admin)\n session[:admin] = { :user => admin, :session_start_time => Time.now }\n end", "def current_admin\n @admin = Admin.find_by(id: session[:admin_id])\n end", "def show\n if params[:turn_on]\n session[:admin] = true if @user&.admin && !in_admin_mode?\n elsif params[:turn_off]\n session[:admin] = nil\n end\n\n redirect_back_or_default(\"/\")\n end", "def show\n authorize! :read, @admin_language_code\n end", "def log_in(admin)\n session[:admin_id] = admin.id\n end", "def show\n @admin = AdminAccount.find_by_id(session[:admin_id])\n @admin_account = AdminAccount.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @admin_account }\n end\n end", "def set_session\n @admin_session = AdminSession.find(params[:id])\n end", "def adminlogin_from_session\n self.current_administrator = Administrator.find_by_id(session[:administrator_id]) if session[:administrator_id]\n end", "def test_edit_admin_session\n # FIXME route exists but no action in controller, remove route?\n #get :edit, :locale => 'en'\n end", "def admin?\n session[:admin] ==true\n end", "def current_user\n session[:admin]\n end", "def admin?\n session[:admin] ? true : false\n end", "def show\n @administrador = Administrador.find(session[:usuario_id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @administrador }\n end\n end", "def set_admin\n if params[:admin] != nil\n session[:admin] = params[:admin] \n end\n end", "def show\n if cookies[:admin_id]\n \n else\n redirect_to \"/\"\n end\n end", "def admin\n\t\tif !session[:admin]\n\t\t\tredirect_to root_url\n\t\tend\n\tend", "def admin?\n\t\t\tsession[:admin]\n\t\tend", "def show\n @admin = Admin.find(params[:id])\n end", "def show\n @admin = Admin.find(params[:id])\n end", "def show\n @admin = Admin.find(params[:id])\n end", "def show\n @admin = Admin.find(params[:id])\n end", "def show\n @admin = Admin.find(params[:id])\n end", "def index\n if session[:admin_id] != nil\n redirect_to admin_path(Admin.find(session[:admin_id]))\n else\n @admin = Admin.new\n end\n end", "def admin_login\n if user_is_signed_in?\n redirect_to root_path\n return\n end\n admin = Admin.authenticate(admin_params[:username], admin_params[:password])\n if admin\n session[:admin_id] = admin.id\n session[:admin_name] = admin.username\n redirect_to admin_index_path\n else\n flash.now[:error]=\"Invalid username or password \"\n render 'login'\n end\n end", "def is_admin?\n session[:is_admin]\n end", "def index\n # @admins = Admin.all\n # \n # respond_to do |format|\n # format.html # index.html.erb\n # format.xml { render :xml => @admins }\n # end\n @admin_session = AdminSession.new\n if current_admin\n redirect_to dashboards_url\n end\n end", "def index\n @admin = Admin.find_by(id: session[:admin_id])\n @admins = Admin.select_admins_to_show(@admin)\n end", "def show\n @admin = Admin.find(params[:id])\n\n end", "def show\n @admin = Admin.find params[:id]\n end", "def show\n @sessions = MyStudio::Session.all\n @emails = Admin::Customer::Email.unsent\n @studio_users = User.with_studio_role\n @unsubscribes = Unsubscribe.all\n @prospects = Prospect.all\n @sessions_ready_count = MyStudio::Session.ready_to_generate_email.count\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @admin_overview }\n end\n end", "def admin_log_in(admin)\n if student_logged_in?\n log_out\n end\n \n session[:admin_id] = admin.id\n end", "def current_admin\n\t\t@admin ||= Admin.find(session[:admin]) if session[:admin]\n\tend", "def show\n checkadmin\n end", "def current_admin\n if session[:admin_id]\n Admin.find(session[:admin_id])\n else\n false\n end\n end", "def show\n #logger.debug( cookies.inspect )\n logger.debug( \"Authorization header: #{request.headers['Authorization']}\" )\n @session = Session.get(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml\n format.json do\n render :json => {\n :session => {\n :token => @session.token,\n :link => {\n :rel => 'session',\n :uri => session_path(@session)\n }\n }\n }\n end\n end\n end", "def admin?\n\t\t\t\tsession[:admin] == true\n\t\t\tend", "def show_admin\n screen_name(\"Inicial-Admin\")\n\n distribute_ots\n\n respond_to do |format|\n format.html { render action: \"show_admin\" }\n format.json { head :ok }\n end\n end", "def is_admin?\n @user = User.find(session[:user])\n @user.is_admin?\n# @session[:user]\n# @session[:is_admin]\n end", "def session_user\n if admin_controller?\n admin_user\n else\n current_user\n end\n end", "def update\n respond_to do |format|\n if @admin_session.update(session_params)\n format.html { redirect_to @admin_session, notice: 'Session was successfully updated.' }\n format.json { render :show, status: :ok, location: @admin_session }\n else\n format.html { render :edit }\n format.json { render json: @admin_session.errors, status: :unprocessable_entity }\n end\n end\n end", "def show\n @session = Sso::Session.find(sso_session_id)\n render json: @session, serializer: Sso::SessionSerializer\n end", "def logging_out_as_admin?\n session[:logged_in_with_admin_token]\n end", "def show\n if !session[:username] || session[:username]=='admin1'\n log_out\n respond_to do |format|\n format.html { redirect_to controller: 'admin_controller', action: 'error', notice: 'In valid user access' }\n end\n end \n end", "def current_admin\n @current_admin ||= Admin.find_by(id: session[:admin_id])\n end", "def current_admin\n @current_admin ||= Admin.find_by(id: session[:admin_id])\n end", "def current_admin\n @current_admin ||= Admin.find_by(id: session[:admin_id])\n end", "def admin?\n !session[:admin].blank? and !Admin.find_by_session(session[:admin]).nil?\n end", "def show\n authorize Session\n end", "def show\n return unless restrict_to_hosts\n\n get_session_data(@session)\n end", "def logged_in_admin\n unless logged_in?\n store_location\n flash[:danger] = \"Зайдите как администратор\"\n redirect_to login_url\n end\n end", "def logged_in_admin\n unless logged_in?\n store_location\n flash[:danger] = \"Зайдите как администратор\"\n redirect_to login_url\n end\n end", "def logged_in_admin\n unless logged_in?\n store_location\n flash[:danger] = \"Зайдите как администратор\"\n redirect_to login_url\n end\n end", "def logged_in_admin\n unless logged_in?\n store_location\n flash[:danger] = \"Зайдите как администратор\"\n redirect_to login_url\n end\n end", "def logged_in_admin\n unless logged_in?\n store_location\n flash[:danger] = \"Зайдите как администратор\"\n redirect_to login_url\n end\n end", "def session_get\n nessus_rest_get(\"session\")\n end", "def admin_mode?\n\t\tsession[:admin_session] == \"true\"\n\tend", "def show\n isadmin\n end", "def set_admin\n \t@is_admin = session[:is_admin]\n end", "def admin_user\n if session[:user_id] and session[:position]\n @admin_user = AdminUser.find_by_id(session[:user_id])\n end\n end", "def show\n @admin = AdminAccount.find_by_id(session[:admin_id])\n @user_account = UserAccount.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user_account }\n end\n end", "def user_from_session\n Admin::User.find(session[:user_id]) if session[:user_id]\n end", "def show\n authorize! :read, @admin_system_admin\n end", "def show\n @admin = Admin.find(params[:id])\n @admins = Admin.all\n end", "def logged_in_admin\n unless admin?\n # show a flash message on the page\n flash[:danger] = \"Non sei autorizzato a visitare questa pagina\"\n # redirect user to home page\n redirect_to root_path\n end\n end", "def show\n @session = Session.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @session }\n end\n end", "def show\n @session = Session.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @session }\n end\n end", "def is_admin\n unless admin?\n flash[:danger]= t 'h.sessions.requireadmin'\n redirect_to(root_url)\n end\n end", "def test_new_admin_session\n get :new, :locale => 'en'\n assert_response :success\n end", "def log_in_as(user)\n session[:admin] = user.id\n end", "def show\n if params[:admin].present? and (params[:admin] == 'true')\n render :show_admin\n else\n render :show\n end\n end", "def show\n @admin_admin_user = Admin::AdminUser.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @admin_admin_user }\n end\n end", "def show\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @session }\n end\n end", "def current_admin\n if (admin_id = session[:admin_id])\n @current_admin ||= Admin.find_by(id: session[:admin_id])\n elsif (admin_id = cookies.signed[:admin_id])\n admin = Admin.find_by(id: admin_id)\n if admin && admin.authenticated?(cookies[:remember_token])\n log_admin(admin)\n @current_admin = admin\n end\n end\n\n end", "def show\n @user = current_user\n @admin = @user.admin\n unless @admin\n redirect_to :root, :alert => t(\"notice.access\")\n end\n end", "def admin_user?\n session[:user][:uid] == APP_CONFIG[:admin]\n end", "def show\n\t\trequire_admin!\n\tend", "def show\n @admin_language = Language.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @admin_language }\n end\n end", "def admin?\n app_session.admin?\n end", "def logar_admin(admin)\n session[:administrador_id] = admin ? admin.id : nil\n @admin_logado = admin || false\n end", "def current_admin\n if session[:admin_id]\n @current_admin ||= Admin.find_by(id: session[:admin_id])\n end\n end", "def show\n @admin = Admin.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @admin }\n end\n end", "def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @session }\n end\n end", "def show\n @admin_level = AdminLevel.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @admin_level }\n end\n end", "def admin? \n session[:password] == \"secret\" \n end", "def admin?\n\t\tuser_session.admin?\n\tend", "def show\n render json: @session_resource\n end", "def admin\n unless admin? || request.format.symbol == :json\n flash[:error] = \"please login as admin to view this page\"\n if authenticated?\n reset_session\n flash[:error] = \"you have been logged out - please login as admin to view this page\"\n end\n\n # Throw a 500 for create/update/delete pages -- because there's no point redirecting that.\n if ['create', 'update', 'delete'].include? params[:action]\n render json: 'You are not authorized to do that.', status: 500\n else\n session[:source] = request.path\n redirect_to '/login'\n false\n end\n end\n end", "def sign_admin(admin)\n cookies.permanent[:remember_token] = admin.remember_token\n self.current_admin = admin\n end", "def logged_in_admin\n unless logged_in?\n store_location\n flash[:danger] = \"Please log in.\"\n redirect_to admin_login_path\n end\n end", "def logout\n session.delete(:admin_password)\n redirect_to admin_login_path\n end", "def admin_logged_in?\n #if session[:logged_in] == true && (session[:host_id] == 670999089 || session[:host_id] == 753452019 || session[:host_id] == 100000182246137)\n if session[:logged_in] == true && User.find(session[:id]).admin == true\n true\n else\n false\n end\n\n end", "def valid_session\n {:user => @admin, :user_id => @admin.id}\n end", "def admin?\n if (User.find session[:user_id]).role == \"Admin\"\n true\n end\n end", "def current_admin\n if(admin_id = session[:admin_id])\n @current_admin ||= Admin.find_by(id: admin_id)\n elsif (admin_id = cookies.signed[:admin_id])\n admin = Admin.find_by_id(admin_id)\n if admin && admin.authenticated?(cookies[:admin_remember_token])\n logged_in_as_admin\n @current_admin = admin\n end\n end\n end" ]
[ "0.75633323", "0.7145599", "0.686751", "0.6754945", "0.66622984", "0.6648095", "0.6573709", "0.65021276", "0.6501548", "0.6491134", "0.6487545", "0.6471359", "0.64673877", "0.64360416", "0.64173067", "0.6382344", "0.63659334", "0.6352974", "0.6333428", "0.6330037", "0.63016397", "0.6267248", "0.62541425", "0.6253124", "0.6253124", "0.6253124", "0.6253124", "0.6253124", "0.62047184", "0.6199144", "0.61945724", "0.61926204", "0.61828816", "0.6170551", "0.6106731", "0.6096281", "0.6089513", "0.6082957", "0.60821176", "0.60625565", "0.60558724", "0.60546046", "0.6053004", "0.6018969", "0.6008348", "0.6006852", "0.5986895", "0.5979563", "0.59697413", "0.5968647", "0.5968647", "0.5968647", "0.59594834", "0.5958324", "0.5949211", "0.5933859", "0.5933859", "0.5933859", "0.5933859", "0.5933859", "0.59242725", "0.59225154", "0.5917461", "0.59161294", "0.59146047", "0.5913292", "0.59128785", "0.59083676", "0.59080964", "0.5902685", "0.5895896", "0.5895896", "0.58873534", "0.588572", "0.5884432", "0.5869345", "0.5859406", "0.5856529", "0.5852057", "0.5848688", "0.5839939", "0.5838095", "0.5837101", "0.5832585", "0.58047354", "0.5795406", "0.5786026", "0.5785429", "0.5778904", "0.5768065", "0.57598096", "0.5756792", "0.5745633", "0.57402664", "0.57342935", "0.57338965", "0.57324386", "0.571098", "0.5709921", "0.5706185" ]
0.7106847
2
code for 7 dwarves goes here (best practice)
def index if session[:count] == nil session[:count] = 0 end session[:count] += 1 @visit_count = session[:count] @products = Product.all if params[:category] @products = Category.find_by(name: params[:category]).products end if params[:sort] @products = Product.all.order(params[:sort] => params[:sort_order]) end if params[:discount] @products = Product.where("price < ?", 2) end render "index.html.erb" end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def schubert; end", "def unusual_sport; end", "def winter_paralympics_sport; end", "def winter_olympics_sport; end", "def who_we_are\r\n end", "def jack_handey; end", "def scientist; end", "def villian; end", "def weber; end", "def superweening_adorningly(counterstand_pyrenomycetales)\n end", "def stderrs; end", "def strain; end", "def suivre; end", "def king_richard_iii; end", "def lookup_new_swimmer\n \n end", "def leeway; end", "def leeway; end", "def sittinae_hooey(scrawny_appulsion, termly)\n end", "def schumann; end", "def spouse; end", "def half_wind; end", "def how_it_works\r\n end", "def coolingtower\n\n end", "def dh; end", "def SS2_7 args\r\n\r\nend", "def summer_olympics_sport; end", "def whiny; end", "def heroine; end", "def wip\n end", "def waiver\n end", "def terpene; end", "def hiddens; end", "def romeo_and_juliet; end", "def mitch_hedberg; end", "def appraisals; end", "def appraisals; end", "def summer_paralympics_sport; end", "def nasa_space_craft; end", "def witcher; end", "def invention; end", "def probers; end", "def featured(num)\n number = 0\n\n loop do\n if num % 7 != 0 && num.even?\n number += 7 \n elsif num % 7 != 0 && num.odd?\n number += 7\n else\n number += 7\n end\n break if number % 7 == 0 && number > num && number.odd?\n end\nend", "def cweek\n end", "def ninety_nine_bottles_of_beer\nend", "def ninety_nine_bottles_of_beer\nend", "def ninety_nine_bottles_of_beer\nend", "def free_helpers\n if division == 'Small Churches'\n 2\n elsif division == 'Medium Churches'\n 4\n elsif participants.coming.accepted.playing_sport.size <= 80\n 6\n else\n 8\n end\n end", "def weighIntrade()\n\n end", "def eplore\n end", "def handoff_old\n\t\t@workflows = [] #WorkFlow.where(is_active: true, is_in_use: false)\n\t\t@holidays = []\n\t\t@reason_codes = []\n\t\t@days_at_ia_approved = 0\n\t\t@days_at_ecr_inbox = 0\n\t\t@days_at_sent_to_collab = 0\n\t\t@days_at_station8_sent = 0\n\t\t@days_at_crb_started = 0\n\t\t@days_at_ecn_released = 0\n\n\t\t@pred_of_ia_approved = ''\n\t\t@pred_of_ecr_inbox = ''\n\t\t@pred_of_sent_to_collab = ''\n\t\t@pred_of_station8_sent = ''\n\t\t@pred_of_crb_started = ''\n\t\t@pred_of_ecn_released = ''\n\n\n\t\[email protected] do |holiday|\n\t @holidays << holiday\n\t end\n\n\t\tworkflows = WorkFlow.where(is_active: true, is_in_use: false)\n\t\tworkflows.each do |wk|\n\t\t\t@workflows << wk\n\t\tend\n\n\t\t@filtered_station_steps = []\n\t filtered_station_steps = @workflow.report_filter_steps.eager_load(:station_step => [:workflow_station]).order(:sequence)\n\t\tfiltered_station_steps.each do |fss|\n\t\t\t@filtered_station_steps << fss\n\t\t\tif fss.station_step_id == 1\n\t\t\t\t@days_at_ia_approved = fss.duration_days\n\t\t\t\t@pred_of_ia_approved = fss.predecessors\n\t\t\tend\n\t\t\tif fss.station_step_id == 7\n\t\t\t\t@days_at_ecr_inbox = fss.duration_days\n\t\t\t\t@pred_of_ecr_inbox = fss.predecessors\n\t\t\tend\n\t\t\tif fss.station_step_id == 5\n\t\t\t\t@days_at_sent_to_collab = fss.duration_days\n\t\t\t\t@pred_of_sent_to_collab = fss.predecessors\n\t\t\tend\n\t\t\tif fss.station_step_id == 15\n\t\t\t\t@days_at_station8_sent = fss.duration_days\n\t\t\t\t@pred_of_station8_sent = fss.predecessors\n\t\t\tend\n\t\t\tif fss.station_step_id == 17\n\t\t\t\t@days_at_crb_started = fss.duration_days\n\t\t\t\t@pred_of_crb_started = fss.predecessors\n\t\t\tend\n\t\t\tif fss.station_step_id == 19\n\t\t\t\t@pred_of_ecn_released = fss.predecessors\n\t\t\tend\n\n\t\tend\n\n\t\t@stationSteps = []\n\t\tstation_steps = StationStep.eager_load(:workflow_station)\n\t\tstation_steps.each do |stp|\n\t\t\t@stationSteps << stp\n\t\tend\n\n \tif request.post?\n \t\tparams_list = params\n \t\tsearch\n \t\tsession[:report_wildcard] = params[:wildcard]\n\t\t session[:report_exact] = params[:exact]\n\n \t\tsession[:params_search] = params_list \n \t\t\tsearch_parm = search_csv(params_list)\n \t\telse\n \t\t\tparams_list = session[:params_search]\n\t\t if session[:report_wildcard].present?\n\t\t @wildcard = session[:report_wildcard]\n\t\t end\n\t\t if session[:report_exact].present?\n\t\t @exact = session[:report_exact]\n\t\t end\n\n\t\t if params_list.present?\n \t\t\t\tsearch_parm = search_csv(params_list)\n \t\t\tend\n \t\tend\t\n\n \t\tif params_list.present?\n\t \t\tbu = search_parm[0]\n\t \t\tl1 = search_parm[1]\n\t \t\tl2 = search_parm[2]\n\t \t\tl3 = search_parm[3]\n\t\t\t\n\t\t\tif params_list[:report_include_canceled].presence\n\t \t\tinclude_cancel = true\n\t \t\t@report_include_canceled = 'report_include_canceled'\n\t \telse\n\t \t\tinclude_cancel = false\n\t \tend\n\t \tif params_list[:report_include_onhold].presence\n\t \t\tinclude_onhold = true\n\t \t\t@report_include_onhold = 'report_include_onhold'\n\t \telse\n\t \t\tinclude_onhold = false\n\t \tend\n\t\t\tif params_list[:report_include_completed].presence\n\t \t\tinclude_completed = true\n\t \t\t@report_include_completed = 'report_include_completed'\n\t \telse\n\t \t\tinclude_completed = false\n\t \tend\t\n\n\t\t\tputs \"----:#{bu}---: #{l1}---:#{l2}---:#{l3}----:#{include_cancel}----:#{include_onhold}----:#{include_completed}\"\n\t \t\t@serach_result = []\n\t \t\tserach_result = WorkFlow.handoff_report_stored_procedure(bu, l1, l2, l3, include_completed, include_cancel, include_onhold)\n \t\t\tserach_result.each do |result|\n \t\t\t\t@serach_result << result\n \t\t\tend\n\n \t\tend\n \tend", "def go_B72(events, bandsArray)\n b7_2Driver(bandsArray)\n # $_keys IS GLOBAL VARIABLE THAT DECIDES WHETHER ANY GBL WAS ENTERED INTO TEXT AREA (WHETHER TO RUN DATA)\n if $_keys == true\n clickit()\n band = bandsArray[0]\n b7_2CellTimeStamp1 = timestampB72(bandsArray)\n b7_2CellTimeStamp2 = $_hoursMinutesB72_backUp\n b7_2CellTimeStamp3 = $_hoursMinutesB72_backUp2\n alert_clickit()\n b7_2bandNumsArray = getB72bandNums(bandsArray)\n b72StoreTable($_browser)\n b72CheckTableDownload(bandsArray, b7_2CellTimeStamp1, b7_2CellTimeStamp2, b7_2CellTimeStamp3, b7_2bandNumsArray)\n browserDownloadFiles($_files_href)\n grabXlsxB72()\n b7_2Parse(events, bandsArray)\n removeTEMPB7_2()\n else\n $_browser.quit\n end\nend", "def herald; end", "def food_and_drink; end", "def gameflow\n \n end", "def w_day; end", "def preprovide_saily_kainsi(akamatsu_demoniacally)\n gibbergunyah_nutcrack(mollycot_copolymerization, capitulator_polyphylogeny, overjob)\n lid_polytonalism(pneumoenteritis_ribby)\n pricklefish(overdraft, phleboplasty_poleaxe)\n end", "def kingdom\n end", "def england\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 dish; end", "def stage; end", "def stage; end", "def doors; end", "def berlioz; end", "def high_five; end", "def circuit_breaker; end", "def whiskey_process\n end", "def mambo_no_5; end", "def sld; end", "def skier_quest; end", "def ravel; end", "def runs; end", "def bellini; end", "def featured(n)\n # The next 2 lines guarantees we start with odd multiples of 7 that is higher than n\n n += 1\n n += 1 until n.odd? && n % 7 == 0\n\n while n < 9_876_543_201\n return n if featured?(n)\n n += 14 # this hastens the loop - we only iterate odd multiples of 7\n end\n raise StandardError, \"No more featured number available\"\nend", "def hd\n \n end", "def operations; end", "def operations; end", "def night\nend", "def spice; end", "def feruchemist; end", "def wagner; end", "def starship; end", "def connect_nearby_herds\n\n end", "def sport; end", "def bring_tech_groups_back!\n warn \"Experimental code #{__method__}. Do not enable in release. #{__FILE__}:#{__LINE__}\"\n\n patch_mod_file!(\"common/institutions/00_Core.txt\") do |node|\n node.each do |name, institution|\n if name != \"feudalism\"\n institution[\"penalty\"] = 0.25\n end\n\n # Any non-Europe start really messes up with historical tech spread\n if institution[\"can_start\"]\n institution[\"can_start\"].add! \"continent\", \"europe\"\n end\n end\n\n # TODO: fix node[*][\"embracement_speed\"]\n end\n\n soft_patch_defines_lua!(\"fun_and_balance_tech\",\n [\"NCountry.EMBRACE_INSTITUTION_COST\", 2.5, 5.0],\n [\"NCountry.POWER_MAX\", 999, 3000],\n # For institution balance testing:\n # [\"NGame.END_DATE\", '\"1821.1.2\"', '\"1750.1.2\"'],\n )\n\n groups = [\n # [\"western\", 0.00, 0.00, 0.00],\n # [\"high_american\", 0.00, 0.00, 0.00],\n [\"eastern\", 0.10, 0.10, 0.20, -0.10, 0.20], # avg 15 %\n [\"ottoman\", 0.20, 0.20, 0.40, -0.20, 0.40], # avg 25 %\n [\"muslim\", 0.30, 0.30, 0.60, -0.30, 0.60], # avg 40 %\n [\"indian\", 0.40, 0.40, 0.80, -0.40, 0.80], # avg 60 %\n [\"chinese\", 0.45, 0.45, 0.90, -0.45, 0.90], # avg 60 %\n [\"east_african\", 0.45, 0.45, 0.90, -0.45, 0.90], # avg 60 %\n [\"central_african\", 0.60, 0.60, 1.20, -0.60, 1.20], # avg 80 %\n [\"sub_saharan\", 0.60, 0.60, 1.20, -0.60, 1.20], # avg 80 %\n [\"nomad_group\", 0.60, 0.60, 1.20, -0.60, 1.20], # avg 80 %\n [\"mesoamerican\", 0.75, 0.75, 1.50, -0.75, 1.50], # avg 100 %\n [\"andean\", 0.75, 0.75, 1.50, -0.75, 1.50], # avg 100 %\n [\"north_american\", 1.00, 1.00, 2.00, -0.90, 2.00], # avg 135 %\n [\"south_american\", 1.00, 1.00, 2.00, -0.90, 2.00], # avg 135 %\n ]\n\n node = PropertyList[]\n groups.each do |tech, adm, dip, mil, spread, emb|\n node.add! \"has_#{tech}\", PropertyList[\n \"potential\", PropertyList[\"technology_group\", tech],\n \"trigger\", PropertyList[\"technology_group\", tech],\n \"adm_tech_cost_modifier\", adm,\n \"dip_tech_cost_modifier\", dip,\n \"mil_tech_cost_modifier\", mil,\n \"global_institution_spread\", spread,\n \"embracement_cost\", emb,\n ]\n end\n\n create_mod_file! \"common/triggered_modifiers/01_tech_groups.txt\", node\n # TODO: localization\n end", "def bring_tech_groups_back!\n warn \"Experimental code #{__method__}. Do not enable in release. #{__FILE__}:#{__LINE__}\"\n\n patch_mod_file!(\"common/institutions/00_Core.txt\") do |node|\n node.each do |name, institution|\n if name != \"feudalism\"\n institution[\"penalty\"] = 0.25\n end\n\n # Any non-Europe start really messes up with historical tech spread\n if institution[\"can_start\"]\n institution[\"can_start\"].add! \"continent\", \"europe\"\n end\n end\n\n # TODO: fix node[*][\"embracement_speed\"]\n end\n\n soft_patch_defines_lua!(\"fun_and_balance_tech\",\n [\"NCountry.EMBRACE_INSTITUTION_COST\", 2.5, 5.0],\n [\"NCountry.POWER_MAX\", 999, 3000],\n # For institution balance testing:\n # [\"NGame.END_DATE\", '\"1821.1.2\"', '\"1750.1.2\"'],\n )\n\n groups = [\n # [\"western\", 0.00, 0.00, 0.00],\n # [\"high_american\", 0.00, 0.00, 0.00],\n [\"eastern\", 0.10, 0.10, 0.20, -0.10, 0.20], # avg 15 %\n [\"ottoman\", 0.20, 0.20, 0.40, -0.20, 0.40], # avg 25 %\n [\"muslim\", 0.30, 0.30, 0.60, -0.30, 0.60], # avg 40 %\n [\"indian\", 0.40, 0.40, 0.80, -0.40, 0.80], # avg 60 %\n [\"chinese\", 0.45, 0.45, 0.90, -0.45, 0.90], # avg 60 %\n [\"east_african\", 0.45, 0.45, 0.90, -0.45, 0.90], # avg 60 %\n [\"central_african\", 0.60, 0.60, 1.20, -0.60, 1.20], # avg 80 %\n [\"sub_saharan\", 0.60, 0.60, 1.20, -0.60, 1.20], # avg 80 %\n [\"nomad_group\", 0.60, 0.60, 1.20, -0.60, 1.20], # avg 80 %\n [\"mesoamerican\", 0.75, 0.75, 1.50, -0.75, 1.50], # avg 100 %\n [\"andean\", 0.75, 0.75, 1.50, -0.75, 1.50], # avg 100 %\n [\"north_american\", 1.00, 1.00, 2.00, -0.90, 2.00], # avg 135 %\n [\"south_american\", 1.00, 1.00, 2.00, -0.90, 2.00], # avg 135 %\n ]\n\n node = PropertyList[]\n groups.each do |tech, adm, dip, mil, spread, emb|\n node.add! \"has_#{tech}\", PropertyList[\n \"potential\", PropertyList[\"technology_group\", tech],\n \"trigger\", PropertyList[\"technology_group\", tech],\n \"adm_tech_cost_modifier\", adm,\n \"dip_tech_cost_modifier\", dip,\n \"mil_tech_cost_modifier\", mil,\n \"global_institution_spread\", spread,\n \"embracement_cost\", emb,\n ]\n end\n\n create_mod_file! \"common/triggered_modifiers/01_tech_groups.txt\", node\n # TODO: localization\n end", "def wday() end", "def method_731(base); end", "def find_people_around_football_pitch_around_jindigeling\n find_shops\nend", "def gen_washing\r\r\n end", "def meal_plan(week_time, week_day) #this is Ruby method\n if week_time == 'weekday'\n if week_day == 'breakfest'\n 'egss and cheese'\n elsif week_day == 'lunch'\n \"soup and potatos\"\n elsif week_day == 'dinner'\n \"Chicken nuggets\"\n end\n elsif week_time == 'weekend'\n if week_day == 'breakfest'\n \"French tost\"\n elsif week_day == 'lunch'\n \"2 pizza\"\n elsif week_day == 'dinner'\n \"meal stack\"\n end\n end\nend", "def bizet; end", "def eurocentric_institutions!\n warn \"Experimental code #{__method__}. Do not enable in release. #{__FILE__}:#{__LINE__}\"\n\n # Nerf dev pushing just slightly, to prevent AI Ming/Korea spawning Renaissance really early\n # 5->4\n #\n # Even more experimentally, just turn it off lol\n soft_patch_defines_lua!(\"fun_and_balance_ai_aggressiveness\",\n [\"NCountry.INSTITUTION_BONUS_FROM_IMP_DEVELOPMENT\", 5, 0],\n )\n\n # Free institutions for East Africa are not helping\n # Remove it from tier-1\n # Frontload global bonuses instead, so it's still useful\n # Tier 2-3 same as before\n patch_mod_file!(\"common/great_projects/01_monuments.txt\") do |node|\n node[\"harar_jugol\"][\"tier_1\"][\"province_modifiers\"] = PropertyList[]\n node[\"harar_jugol\"][\"tier_1\"][\"country_modifiers\"] = PropertyList[\n \"stability_cost_modifier\", -0.1,\n \"prestige_per_development_from_conversion\", 0.2,\n ]\n end\n\n # Korean Triptaka breaks the game too\n patch_mod_file!(\"common/event_modifiers/00_event_modifiers.txt\") do |node|\n node[\"tripitaka_koreana\"].delete! \"institution_growth\"\n end\n\n # Now core institution list\n patch_mod_file!(\"common/institutions/00_Core.txt\") do |node|\n factors = {}\n node.each do |name, institution|\n institution[\"embracement_speed\"].each do |_, mod|\n tooltip = mod[\"custom_trigger_tooltip\"]&.[](\"tooltip\")\n factors[[name, tooltip || rand]] = mod # if tooltip\n end\n end\n\n # First, slow down all passive spread\n [\n [\"feudalism\", \"FRIENDLY_NEIGHBOR_OR_COAST_PROVINCE_HAS_EMBRACED\"],\n [\"feudalism\", \"NEIGHBOR_NOT_OWNED_IS_FEUDAL\"],\n [\"feudalism\", \"tooltip_feudalism_embraced\"],\n\n [\"renaissance\", \"tooltip_any_friendly_coast_border_province_has_embraced_renaissance\"],\n [\"renaissance\", \"tooltip_any_neighbor_has_embraced_renaissance\"],\n [\"renaissance\", \"tooltip_renaissance_embraced\"],\n\n [\"new_world_i\", \"tooltip_any_friendly_coast_border_province_has_embraced_colonialism\"],\n [\"new_world_i\", \"tooltip_neighbor_port_province_new_world\"],\n [\"new_world_i\", \"tooltip_new_world_i_embraced\"],\n\n [\"printing_press\", \"tooltip_any_friendly_coast_border_province_has_embraced_printing_press\"],\n [\"printing_press\", \"tooltip_any_neighbor_has_embraced_printing_press\"],\n [\"printing_press\", \"tooltip_printing_press_embraced\"],\n\n [\"global_trade\", \"tooltip_neighbor_non_port_province_global_trade\"],\n [\"global_trade\", \"tooltip_neighbor_port_province_global_trade\"],\n [\"global_trade\", \"tooltip_global_trade_embraced\"],\n [\"global_trade\", \"tooltip_global_trade_embraced_other_continent\"],\n\n [\"manufactories\", \"tooltip_any_friendly_coast_border_province_has_embraced_manufactories\"],\n [\"manufactories\", \"tooltip_any_neighbor_has_embraced_manufactories\"],\n [\"manufactories\", \"tooltip_manufactories_embraced\"],\n [\"manufactories\", \"tooltip_manufactories_embraced_other_continent\"],\n\n [\"enlightenment\", \"tooltip_any_friendly_coast_border_province_has_embraced_enlightenment\"],\n [\"enlightenment\", \"tooltip_any_neighbor_has_embraced_enlightenment\"],\n [\"enlightenment\", \"tooltip_enlightenment_embraced\"],\n [\"enlightenment\", \"tooltip_enlightenment_embraced_other_continent\"],\n\n [\"industrialization\", \"tooltip_any_friendly_coast_border_province_has_embraced_industrialization\"],\n [\"industrialization\", \"tooltip_any_neighbor_has_embraced_industrialization\"],\n [\"industrialization\", \"tooltip_industrialization_embraced\"],\n [\"industrialization\", \"tooltip_industrialization_embraced_other_continent\"],\n ].each do |key|\n factors[key][\"factor\"] *= 0.5\n end\n\n # Colonialism - can only start in Europe\n node[\"new_world_i\"][\"can_start\"].add! Property[\"continent\", \"europe\"]\n\n # Gate every institution behind previous one, this prevents easy catch-up\n node[\"new_world_i\"][\"can_embrace\"] = PropertyList[\"owner\", PropertyList[\"has_institution\", \"renaissance\"]]\n node[\"printing_press\"][\"can_embrace\"] = PropertyList[\"owner\", PropertyList[\"has_institution\", \"new_world_i\"]]\n node[\"global_trade\"][\"can_embrace\"] = PropertyList[\"owner\", PropertyList[\"has_institution\", \"printing_press\"]]\n node[\"manufactories\"][\"can_embrace\"] = PropertyList[\"owner\", PropertyList[\"has_institution\", \"global_trade\"]]\n node[\"enlightenment\"][\"can_embrace\"] = PropertyList[\"owner\", PropertyList[\"has_institution\", \"manufactories\"]]\n node[\"industrialization\"][\"can_embrace\"] = PropertyList[\"owner\", PropertyList[\"has_institution\", \"enlightenment\"]]\n end\n end" ]
[ "0.5916293", "0.58770216", "0.5860818", "0.5778818", "0.57446796", "0.57159746", "0.5678462", "0.56354403", "0.56335133", "0.5614869", "0.5607277", "0.5589076", "0.5551287", "0.55388665", "0.55299103", "0.5498585", "0.5498585", "0.5438088", "0.5436617", "0.54210484", "0.54203826", "0.54126984", "0.541155", "0.54039997", "0.53933185", "0.53770167", "0.5376924", "0.5365765", "0.53657246", "0.53616536", "0.53594226", "0.53580993", "0.5351971", "0.53500664", "0.5345146", "0.5345146", "0.5337141", "0.53212345", "0.53190887", "0.5283862", "0.5251871", "0.52503306", "0.5249713", "0.5242583", "0.5242583", "0.5242583", "0.52374184", "0.52373695", "0.5236478", "0.52315074", "0.5220091", "0.52089626", "0.520839", "0.51908815", "0.5182478", "0.5165591", "0.516321", "0.515305", "0.5147886", "0.5147886", "0.5147886", "0.5147886", "0.5147886", "0.5147886", "0.5147886", "0.5147886", "0.5147886", "0.5147622", "0.51388454", "0.51388454", "0.5138228", "0.5130655", "0.512884", "0.5122597", "0.5120341", "0.5116538", "0.51161903", "0.51148903", "0.51143724", "0.51083106", "0.5095753", "0.509565", "0.50922805", "0.50869733", "0.50869733", "0.50695837", "0.5067758", "0.5064636", "0.50615853", "0.5056001", "0.5055502", "0.5051001", "0.50470954", "0.50470954", "0.5044226", "0.5041815", "0.5039545", "0.5037676", "0.5037401", "0.5032094", "0.50320154" ]
0.0
-1
rubocop:enable Metrics/AbcSize Reads current default serialization arguments.
def config @default_args || Surrealist::HashUtils::EMPTY_HASH end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def args\n @args_serializer.perform_deserialization! if @args_serializer.args.nil?\n @args_serializer.args\n end", "def serialize_default(object); object; end", "def serialization_options\n @serialization_options || self.class.serialization_options || self.class.superclass.serialization_options\n end", "def default_params\n {}\n end", "def default_parameters\n {}\n end", "def default_params\n @default_params ||= {}\n end", "def defaults\n parse({})\n end", "def default_params_encoder=(_arg0); end", "def display_serialized_params\n serialized_params.merge({\n _good_job: attributes.except('serialized_params', 'locktype', 'owns_advisory_lock'),\n })\n end", "def default_params\n @default_params ||= {\n id: nil,\n class: name.gsub(/.*::/, '').downcase,\n width: nil,\n height: nil,\n border: nil,\n borders: nil,\n border_style: nil\n }\n end", "def default_job_params\n {}\n end", "def default_job_params\n {}\n end", "def serialize(args)\n args\n end", "def required_defaults; end", "def defaults\n ActiveSupport::OrderedOptions.new\n end", "def default_job_params\n {\n }\n end", "def default_job_params\n {\n }\n end", "def default_params(default_params=nil)\n default_params and @default_params = default_params or @default_params or {}\n end", "def defaults; end", "def defaults; end", "def defaults; end", "def defaults; end", "def defaults; end", "def defaults; end", "def defaults; end", "def defaults; end", "def defaults; end", "def defaults; end", "def default_operation_params\n {}\n end", "def default_job_options\n @default_job_options ||= if Sidekiq.respond_to?(:default_job_options)\n Sidekiq.default_job_options.stringify_keys\n else\n Sidekiq.default_worker_options.stringify_keys\n end\n end", "def default_operation_params\n {\n foo: 'bar'\n }\n end", "def serializer=(_arg0); end", "def start_with_default_params!\n default_params = upper(:@@default_params) || {}\n @params.reverse_merge!(default_params)\n end", "def defaults\n super\n end", "def defaults\n {}\n end", "def defaults\n {}\n end", "def serialized_attributes\n read_inheritable_attribute(\"attr_serialized\") || { }\n end", "def params\n default_options.merge(@params)\n end", "def defaults\n {}\n end", "def default_options; {} end", "def default_options; end", "def default_options; end", "def default_options; end", "def object_serialization_options\n {:except => [:variant_id, :type, :position], :methods => [:classification, :options]}\n end", "def arguments\n self.class.dry_initializer.attributes(self)\n end", "def default_options\n {}\n end", "def default_options\n {}\n end", "def default_options\n {}\n end", "def default_options\n # {}\n end", "def default_attrs\n @default_attrs\n end", "def set_default_params params\n set_default_params_status(params)\n set_default_params_type(params)\n set_default_params_content(params)\n return params\n end", "def default_job_params\n {\n }\nend", "def compat_parameters_default_chunk_key\n \"\"\n end", "def default_params\n {\n api_key: @api_key,\n api_secret: @api_secret,\n format: @response_format\n }\n end", "def serialize_attrs\n @serialize_attrs ||= []\n end", "def default_options\n {}\n end", "def default_options\n {}\n end", "def default_options\n {}\n end", "def default_options\n {}\n end", "def initialize(*args)\n @input, @environment, @options = case args.first\n when String, IO, StringIO\n Tools.varargs(args, [args.first.class, Environment, Hash])\n else\n Tools.varargs(args, [String, Environment, Hash])\n end\n @options = self.class.const_get(:DEFAULT_OPTIONS).merge(@options || {}) \n end", "def params\n default_params.merge @params\n end", "def default_data_options\n {}\n end", "def defaults\n {\n interfaces: []\n }\n end", "def final_serialize_attrs \n if being_included?\n self.class.include_attrs | serialize_attrs\n else\n self.class.default_attrs | serialize_attrs\n end\n end", "def defaults\n self.class.defaults #.merge(@defaults || {})\n end", "def default_attributes\n data.klass.stored_attributes[:data].map(&:to_s)\n end", "def initialize *serializer_options \n @options = extract_va_options( serializer_options )\n end", "def default_options\n @default_options ||= {}\n end", "def default_attributes\n cfg_get(:default_attributes)\n end", "def missing_data_params\n default_params\n end", "def default_attributes\n cfg_get(:default_attributes)\n end", "def default_data\n end", "def default_options\n @default_options ||= {\n :output => STDOUT,\n :input => STDIN,\n :banner => true,\n :silent => false,\n :processor => Rink::LineProcessor::PureRuby.new(self),\n :rescue_errors => true,\n :defer => false,\n :allow_ruby => true,\n }\n end", "def defaults\n defaults = self[:defaults] || {}\n return defaults if defaults.any?\n options.fetch 'defaults', {}\n end", "def params\n if deserializes?\n payload=payload_object\n payload.respond_to?(:to_h) ? payload.to_h : nil\n else\n nil\n end\n end", "def default _args\n \"default _args;\" \n end", "def serialized_attributes(str = +'', additional_attributes = {})\n super(str, additional_attributes, false)\n end", "def default_options\n DEFAULT_OPTIONS\n end", "def default_config\n {}\n end", "def default_params\n {\n \"pio_appkey\" => @app_key\n }\n end", "def defaults\n []\n end", "def init_compat\n super\n\n #\n # Merge in payload compatible defaults\n #\n p = module_info['Compat']['Payload']\n\n CompatDefaults::Payload.each_pair { |k,v|\n (p[k]) ? p[k] << \" #{v}\" : p[k] = v\n }\n\n #\n # Set the default save registers if none have been explicitly\n # specified.\n #\n if (module_info['SaveRegisters'] == nil)\n module_info['SaveRegisters'] = [ 'esp', 'ebp' ]\n end\n end", "def default_settings\n {}\n end", "def default_options\n { }\n end", "def default_attributes(custom = {})\n {}\n end", "def serializable_attributes\n IDME_SERIALIZABLE_ATTRIBUTES + REQUIRED_ATTRIBUTES\n end", "def job_arguments(index = nil)\n arguments = index ? \"{arguments,#{index}}\" : '{arguments}'\n %Q(serialized_params#>'#{arguments}')\n end", "def default_options\n sync{ @opts || {} }\n end", "def default_options\n {\n color: false,\n progress: false,\n print_json: true\n }\n end", "def defaults\n {\n client: nil,\n name: '',\n }\n end", "def default_attributes\n @default_attributes ||= {}\n end", "def default_options\n @default_options ||= OpenStruct.new\n end", "def default_options # :nodoc:\n { :consume => true,\n :memoize => false,\n :offset => 0\n }\n end", "def init_default_attributes\n self.config_params ||= DEFAULT_CONFIG_PARAMS\n self.has_inventory = true\n end", "def serializer_args_hash\n result = {}\n #TODO: Should probably safety check these somewhere\n result[:entry_type] = params[:entry_type] if params[:entry_type].present? \n result[:section] = params[:section] if params[:section].present?\n return result\n end", "def defaultArguments (x = 22, y = x + 20, z = 50)\n puts \"x = \" + x.to_s\n puts \"y = \" + y.to_s\n puts \"z = \" + z.to_s\n end", "def deserialize(_argument)\n raise NotImplementedError\n end", "def defaults\n self.class.defaults\n end", "def default(value = nil)\r\n self.default_params = default_params.merge(value).freeze if value\r\n default_params\r\n end", "def default_job_params\n {\n rna_extraction_kit: QIAampDSPViralRNAMiniKit::NAME\n }\n end" ]
[ "0.6585234", "0.6388964", "0.6302947", "0.6088047", "0.6003908", "0.59347486", "0.58784777", "0.58057946", "0.5769517", "0.5755509", "0.5747322", "0.5747322", "0.57458204", "0.5738589", "0.5664444", "0.5648463", "0.5648463", "0.5633757", "0.563268", "0.563268", "0.563268", "0.563268", "0.563268", "0.563268", "0.563268", "0.563268", "0.563268", "0.563268", "0.56125885", "0.56043756", "0.558753", "0.5575022", "0.55656016", "0.5564199", "0.5546547", "0.55461556", "0.5539322", "0.5528958", "0.55137926", "0.551048", "0.55102646", "0.55102646", "0.55102646", "0.54910386", "0.5490255", "0.54869837", "0.54869837", "0.54862875", "0.54851604", "0.5482776", "0.5466869", "0.5464639", "0.5459353", "0.5456872", "0.54502547", "0.54369146", "0.5431384", "0.5431384", "0.5431384", "0.5429037", "0.5413683", "0.54109615", "0.5409594", "0.54016286", "0.53924096", "0.5387021", "0.5383925", "0.5381443", "0.5369742", "0.5362632", "0.5329403", "0.53155684", "0.5306533", "0.5305743", "0.5302041", "0.52997696", "0.52808654", "0.52718866", "0.52682084", "0.526665", "0.5266329", "0.5257931", "0.52527964", "0.5251039", "0.52495694", "0.5240433", "0.5239584", "0.5231466", "0.5229663", "0.5228066", "0.5226095", "0.52154034", "0.521327", "0.52057713", "0.52027315", "0.52015895", "0.51981777", "0.51928", "0.5185235", "0.51804984" ]
0.58779716
7
Sets default serialization arguments with a block
def configure(hash = nil, &_block) if block_given? carrier = Surrealist::Carrier.new yield(carrier) @default_args = carrier.parameters else @default_args = hash.nil? ? Surrealist::HashUtils::EMPTY_HASH : hash end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def serialize(*args, &block); end", "def serialize(*args, &block); end", "def initialize(&block)\n load_defaults!\n\n instance_eval(&block) if block_given?\n\n set_defaults!\n end", "def default_params_encoder=(_arg0); end", "def initialize\n @block_args = []\n end", "def initialize(&block)\n load_defaults!\n\n instance_eval(&block)\n end", "def initialize(&block)\n @required_options = []\n instance_exec &block\n end", "def serialize_default(object); object; end", "def serializer=(_arg0); end", "def AttributeSerializer(*args, &blk)\n if args.first.is_a?(Class)\n klass, context_name, attribs = (args.size == 3) ? args : [args[0], :default, args[1]]\n AttributeSerializer.add_context_set klass, context_name, attribs, &blk\n else\n AttributeSerializer.generate(args[1] || :default, args[0])\n end\nend", "def initialize(options={}, &block)\n set_defaults\n apply_options(options, &block)\n end", "def set_defaults( name, *args, &block )\n clear_defaults( name )\n @aliases[ name ] = args.shift if args.first.is_a? Symbol\n @defaults[ name ] = args.pop if args.last.is_a? Hash\n @callbacks[ name ] = block\n fail( ArgumentError, \"invalid defaults for #{name}\" ) unless args.empty?\n self\n end", "def initialize(args)\n args = defaults.merge(args)\n @chainring = args[:chainring]\n# ...\n end", "def post_init_block(&block)\n raise ArgumentError, \"does not accept a block\"\n end", "def block=(_arg0); end", "def block=(_arg0); end", "def default(&block)\n if block_given?\n @default = block\n else\n @default\n end\n end", "def default_compression=(_arg0); end", "def initialize(opts = {}, &block)\n @opts = opts\n @block = block\n @opts[:sync_log] ||= true\n\n raise \"block should be\" unless block\n end", "def initialize(args)\n args = defaults.merge(args)\n @chainring = args[:chainring]\nend", "def initialize args = {}\n hash_make args, Block::ARG_SPECS\n @initial_params = collect_params\n end", "def overrides(args={}, &block)\n @overrides << {:args => args, :block => block}\n self\n end", "def overrides(args={}, &block)\n @overrides << {:args => args, :block => block}\n self\n end", "def initialize(&block)\n @block = block\n end", "def initialize(&block)\n @block = block\n end", "def initialize(&block)\n @block = block\n end", "def configuration_defaults(&block)\n @configuration_defaults = block\n end", "def initialize *serializer_options \n @options = extract_va_options( serializer_options )\n end", "def set_default_options()\n @options = OpenStruct.new(\n :output_base => nil,\n :verbose => false,\n :config_file => nil,\n :samples => nil,\n :delay => 30,\n :scheduler_opts => ''\n )\nend", "def initialize(params ={}, &block)\n super\n instance_eval &block\n end", "def init (&block)\n @init_block = block\n end", "def set_default_options\n end", "def configure(&block)\n default_values!\n yield self\n end", "def initialize(name=nil, &block)\n @value = name ? { name: name } : {}\n super\n end", "def default_configuration=(_arg0); end", "def initialize(&block)\n load_defaults!\n\n @only_collections ||= Array.new\n @additional_options ||= Array.new\n @ipv6 ||= false\n @lock ||= false\n\n instance_eval(&block)\n prepare!\n end", "def post_init_block(&block)\n with(&block)\n end", "def apply_start_block_option_overrides(options)\n @requested_args.each { |option_name, option_value| options.update(option_name, option_value, add_missing: false) }\n end", "def set_default(name, *args, &block)\n set(name, *args, &block) unless exists?(name)\nend", "def set_default(name, *args, &block)\n set(name, *args, &block) unless exists?(name)\nend", "def use( opts, &block ) # :yield: self\n use! @defaults.merge( opts ), &block\n end", "def initialize(*)\n super\n apply_defaults\n end", "def set_defaults\n end", "def set_defaults\n end", "def block_params\n params.require(required_params).permit(default_permitted_attributes)\n end", "def default_to(&block)\n raise ArgumentError, _('must be passed a block') unless block_given?\n @default_to = block\n end", "def set_defaults\n\n end", "def set_defaults\n\n end", "def set_defaults\n\n end", "def set_defaults\n\n end", "def set_defaults\n\n end", "def set_defaults\n\n end", "def initialize(&block)\n configure(&block) if block_given?\n end", "def initialize args\n hash_make args, BlockState::ARG_SPECS\n end", "def default_bare=(_arg0); end", "def initialize(options={}, &block)\n super(options)\n\n block.call(self) # Allow for population of data with a block during initialization.\n end", "def initialize(identifier, default={})\n raise(ArgumentError, \"Argument 'identifier' must be a String argument to identify the option.\") unless identifier.is_a?(String)\n raise(ArgumentError, \"Optional argument 'default' must be a Hash.\") unless default.nil? || default.is_a?(Hash)\n @identifier = identifier\n @default = Marshal.dump(default) # Allows later to create deep copies.\n @options = default\n self.update(read())\nend", "def normal=(block)\n raise ArgumentError, \"normal expects a block, not a #{block.class}\" unless block.is_a?(Proc)\n @normal = block\n end", "def init_default_attributes\n self.config_params ||= DEFAULT_CONFIG_PARAMS\n self.has_inventory = true\n end", "def default(&ruby_block)\n @default_codes << ruby_block\n end", "def set_async_defaults\n @async_transport_options ||= {}\n defaults = {\n queue: \"magic_pipe\"\n }\n @async_transport_options = defaults.merge(@async_transport_options)\n end", "def initialize(attributes = {}, &block)\n super\n self.value = attributes.delete(:value) \n self.bucket = attributes.delete(:bucket)\n yield self if block_given?\n end", "def merge_attributes(block, attributes) # :nodoc:\n defaults = DEFAULT_ATTRIBUTES[nil].dup\n defaults.merge!(DEFAULT_ATTRIBUTES[block]) if block\n defaults.merge!(attributes)\n \n # register with Lazydoc\n defaults[:desc] ||= Lazydoc.register_caller(Lazydoc::Trailer, 2)\n \n defaults\n end", "def initialize(&block)\n instance_eval(&block) if block_given?\n end", "def set_block_params(item)\n if block_params.blank?\n commands.object = item\n elsif item.is_a?(Array) && item.size > 1\n # split item into block variables\n # the # of @block_params may be < the # of subitems, so put it first\n block_params.zip(item).each {|param, subitem| commands.set(param, subitem) }\n else\n # now this item is available thru the block variable\n commands.set(block_params.first, item)\n end\n end", "def initialize(&block)\n load_defaults!\n\n @level ||= false\n @rsyncable ||= false\n\n instance_eval(&block) if block_given?\n\n @cmd = \"#{utility(:gzip)}#{options}\"\n @ext = \".gz\"\n end", "def initialise(params = nil)\n super(params)\n self.compound ||= 1\n end", "def initialize(source_hash = nil, default = nil, api = nil, &blk)\n @api = api if api\n @json = source_hash\n super(source_hash, default, &blk)\n end", "def initialize(name, default_value = nil, &block)\n raise ArgumentError, \"Waw variables accept a default value or a block, but not both\"\\\n unless default_value.nil? or block.nil?\n @name, @default_value = name, (block ? block : default_value)\n end", "def initialize(&block)\n instance_eval(&block) if block_given?\n end", "def block_to_hash(default = {}, &block)\n default.merge((yield HashWithAccessors.new(default)).to_hash) if block_given?\n end", "def initialize(block, json)\n @block = block\n @elements = []\n self.data = json\n end", "def initialize opts={}, &block\n @name = opts[:name]\n @activation = opts[:activation]\n @icon = opts[:icon]\n @sound = opts[:sound]\n @block = block\n invariant\n end", "def initialize(options = {}, &block)\n\t\t \n\t\t\tyield self unless block == nil\n\t\tend", "def set_block_params(name, params)\n\t\t\tparams = {} if !params.is_a?(Hash)\n\t\t\t@vars[:block_params][name] = params\n\t\tend", "def initialize block_parser\n @block_parser = block_parser\nend", "def initialize(model, &block)\n super(model)\n\n @only_collections ||= Array.new\n @additional_options ||= Array.new\n @ipv6 ||= false\n @lock ||= false\n\n instance_eval(&block) if block_given?\n\n @mongodump_utility ||= utility(:mongodump)\n @mongo_utility ||= utility(:mongo)\n end", "def default_parameters\n {}\n end", "def set_default\n cmd = \"{\\\"id\\\":8,\\\"method\\\":\\\"set_default\\\",\\\"params\\\":[]}\\r\\n\"\n request(cmd)\n end", "def set_defaults(options = T.unsafe(nil)); end", "def set_block &b\n @block = b\n end", "def initialize task_name = :opal, &block\n @task_name = task_name\n @builder = Builder.new\n @bundle = @builder.bundle\n\n @bundle.config(:normal) { yield @bundle } if block_given?\n\n define\n end", "def default_adapter_options=(_arg0); end", "def default_adapter_options=(_arg0); end", "def default_serialized_attr(serialized, accessors)\n method_name = \"set_default_#{serialized}\"\n after_initialize method_name \n\n define_method(method_name) do\n self[serialized] = accessors if self[serialized].nil?\n end\n end", "def initialize(block_arg = nil, &block)\n @block = block || block_arg\n @run = false\n @ivars = {}\n if !@block\n raise ArgumentError, \"needs a block.\"\n end\n end", "def default_options; {} end", "def add_arg_processor(ver,&block)\n raise InvalidArity.new(\"Argument processor must accept one parameter\") if block.arity !=1\n @arg_processors[ver]=block\n @default=ver\n end", "def with_defaults(defaults); end", "def set_defaults\n super\n end", "def set_defaults\n super\n end", "def default_options=(opts); end", "def initialize(opts = {}, &block)\n @parent = opts[:parent]\n @optional_attributes = []\n instance_eval(&block)\n end", "def defaults\n super\n end", "def cxx_configuration(&block)\n @myblock = block\n @all_blocks = []\n end", "def init(&block)\n @inits << block\n end", "def init(&block)\n @inits << block\n end", "def initialize(args)\n args = defaults.merge(args)\n @chainring = args[:chainring]\n @cog = args[:cog] \n end", "def initialize(&block)\n load_defaults!\n\n @best ||= false\n @fast ||= false\n\n instance_eval(&block) if block_given?\n\n @cmd = \"#{ utility(:lzma) }#{ options }\"\n @ext = '.lzma'\n end", "def initialize(**opt)\n super\n end" ]
[ "0.65434855", "0.65434855", "0.6362944", "0.6152541", "0.61254287", "0.6075222", "0.6064395", "0.60465366", "0.6043293", "0.6023695", "0.5982058", "0.5915093", "0.5883889", "0.5882861", "0.57608163", "0.57608163", "0.57576203", "0.57487386", "0.5737648", "0.5722403", "0.5707598", "0.57063574", "0.57063574", "0.5691344", "0.5680573", "0.5680573", "0.5679332", "0.5656711", "0.56422526", "0.5638977", "0.5622064", "0.5609758", "0.5599666", "0.5546453", "0.55381477", "0.55337405", "0.552704", "0.5524398", "0.5521851", "0.5521851", "0.5499421", "0.5493479", "0.54791516", "0.54791516", "0.5470153", "0.54688936", "0.5466269", "0.5466269", "0.5466269", "0.5466269", "0.5466269", "0.5466269", "0.54644746", "0.5457697", "0.54569423", "0.54509765", "0.54460704", "0.5424596", "0.5422991", "0.5416323", "0.5413443", "0.5405703", "0.539915", "0.5384482", "0.53806776", "0.537286", "0.53665435", "0.53573245", "0.53567743", "0.53492594", "0.53451395", "0.53378516", "0.533608", "0.5328226", "0.53220266", "0.53159857", "0.5315873", "0.53128827", "0.53087056", "0.53086346", "0.5307493", "0.5306216", "0.5292953", "0.5292953", "0.52920413", "0.5287919", "0.528721", "0.5286495", "0.5282921", "0.52658945", "0.52658945", "0.52505976", "0.5246292", "0.5244907", "0.524392", "0.5236375", "0.5236375", "0.52319175", "0.52303237", "0.5226532" ]
0.59752697
11
Checks if there is a serializer (< Surrealist::Serializer) defined for the object and delegates surrealization to it.
def __build_schema(object, **args) return args[:serializer].new(object, **args[:context].to_h).build_schema(**args) if args[:serializer] if (serializer = Surrealist::VarsHelper.find_serializer(object.class, tag: args[:for])) serializer.new(object, **args[:context].to_h).build_schema(**args) else build_schema(instance: object, **args) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def serializer(name)\n @_serializer = name <= Malba::Serializer ? name : nil\n end", "def use_serializer(serializer)\n @serializer = serializer\n end", "def serialize!(object, serializer_instance)\n serializer = serializer(object, serializer_instance)\n return unless serializer\n serializer.call(object)\n end", "def with_serializer(object, serializer); end", "def serializer\n return @serializer if defined?(@serializer)\n\n _serializer = injected_options.fetch(:serializer, serializer_class)\n\n @serializer = instantiated_serializer_for(_serializer)\n end", "def get_serializer_class\n return self.class.serializer_class || RESTFramework::NativeSerializer\n end", "def _serializer(name)\n type = types[name]\n # flatten and cache all the serializers up the tree\n @_serializers ||= all_ancestors(serializers(nil)).reverse.reduce(&:merge)\n @_serializers[name] || @_serializers[type] || ( serializers(base)[type] ||= Serializer.default(type) if type )\n end", "def serializer_class\n \"#{self.class.to_s}Serializer\".constantize\n end", "def serializers\n @serializers ||= Readthis::Serializers.new\n end", "def _serializer(name)\n self.class.send(:_serializer, name)\n end", "def serializer_for(renderable, options = {})\n serializer_by_options(options) || serializer_by_renderable(renderable)\n end", "def serializers\n self._additional_serializers # standard:disable Style/RedundantSelf\n end", "def serializer_by_options(options)\n serializer = options[:serializer]\n return unless serializer\n\n # If the given serializer is a class return it.\n return serializer if serializer.is_a? Class\n\n \"#{serializer.to_s.classify}Serializer\".safe_constantize\n end", "def with_serializer(object, serializer)\n output = nil\n filename = serializer.serialized_path(object)\n if serializer.respond_to?(:basepath)\n filename = File.join(serializer.basepath, filename)\n end\n log.capture(\"Generating #{filename}\", nil) do\n serializer.before_serialize if serializer\n output = yield\n if serializer\n serializer.serialize(object, output)\n serializer.after_serialize(output)\n end\n end\n output\n end", "def serializer=(serializer) # :nodoc:\n @serializer = serializer\n serializer_methods = serializer::SerializerMethods\n for const in serializer_methods.constants\n klass = deep_const_get(const)\n modul = serializer_methods.const_get(const)\n klass.class_eval do\n instance_methods(false).each do |m|\n m.to_s == 'to_amf' and remove_method m\n end\n include modul\n end\n end\n self.serializer_state = serializer::State\n const_set :SerializerState, self.serializer_state\n end", "def with_serializer(serializer)\n @serializer = serializer\n self\n end", "def get_serializer_class\n return self.class.serializer_class\n end", "def serializer(klass)\n @objects_serializer = klass\n end", "def method_defined?(method)\n return true if instance_methods(false).include?(method)\n return false if superclass == Surrealist::Serializer\n\n super\n end", "def active_model_serializer\n self.tire_active_model_serializer || self.class.active_model_serializer\n end", "def serialize(with: nil)\n serializer = case with\n when nil\n @_serializer || empty_serializer\n when ->(obj) { obj.is_a?(Class) && obj <= Malba::Serializer }\n with\n when Proc\n inline_extended_serializer(with)\n else\n raise ArgumentError, 'Unexpected type for with, possible types are Class or Proc'\n end\n serializer.new(self).serialize\n end", "def set_serializer(self_class, serializer_class)\n self_class.instance_variable_set(SERIALIZER_CLASS, serializer_class)\n end", "def inherited(subclass)\n object_alias = subclass.name.demodulize.chomp('Serializer').underscore\n subclass.object_as(object_alias) unless method_defined?(object_alias)\n super\n end", "def find_serializer(klass)\n klass.instance_variable_get(SERIALIZER_CLASS)\n end", "def model_class\n name.sub(/Serializer$/, '').constantize\n end", "def serializer; end", "def find_serializer(klass, tag: nil)\n tag ||= DEFAULT_TAG\n hash = klass.instance_variable_get(SERIALIZER_CLASSES)\n serializer = hash&.fetch(tag.to_sym, nil)\n Surrealist::ExceptionRaiser.raise_unknown_tag!(tag) if serializer.nil? && tag != DEFAULT_TAG\n serializer\n end", "def surrealize(**args)\n if Helper.collection?(object)\n Surrealist.surrealize_collection(object, **args.merge(context: context))\n else\n Surrealist.surrealize(instance: self, **args)\n end\n end", "def serializer(params = {})\n self.class.serializer_class.new(self, params:)\n end", "def serialize(object)\n raise_or_return(object)\n end", "def render(options)\n # Get the renderable (Object that should be rendered) from options hash.\n renderable = options[:json]\n\n # Return if renderable is blank\n return options unless renderable\n\n # Try to fetch the right serializer for given renderable.\n serializer = serializer_for(renderable, options)\n\n # When no serializer is found just pass the original options hash.\n return options unless serializer\n\n # Replace json value with new serializer\n options.merge(json: serializer.new(renderable, options))\n end", "def serializer(table)\n (table + \"Serializer\").classify.constantize\n end", "def get_serializer_for(klass, namespace = nil)\n return nil unless config.serializer_lookup_enabled\n\n return NilSerializer if klass == NilClass\n\n cache_key = ActiveSupport::Cache.expand_cache_key(klass, namespace)\n serializers_cache.fetch_or_store(cache_key) do\n # NOTE(beauby): When we drop 1.9.3 support we can lazify the map for perfs.\n lookup_chain = serializer_lookup_chain_for(klass, namespace)\n serializer_class = serializer_class_from_chain(lookup_chain)\n\n if serializer_class\n serializer_class\n elsif klass.superclass\n get_serializer_for(klass.superclass, namespace)\n end\n end\n end", "def serializer_class\n BudgetSerializer\n end", "def class_serializer(klass)\n path = klass.name.underscore\n serializer = path_to_class(path + '_serializer', Totem::Core::BaseSerializer)\n serializer.root = path\n serializer.send(:include, Totem::Core::Serializers::ActiveModelSerializer)\n serializer\nend", "def parse_json_custom(object, options)\n # p \"SerializableResource, parse_json_custom, object, options\" + object.to_s + \" \" + options.to_s\n # ActiveModelSerializers::SerializableResource.new(object).as_json\n # Able to access at serializer level as @instance_options\n ActiveModelSerializers::SerializableResource.new(object, options).as_json\n end", "def surrealize(**args)\n if object.respond_to?(:each)\n Surrealist.surrealize_collection(object, args.merge(context: context))\n else\n Surrealist.surrealize(instance: self, **args)\n end\n end", "def collection_serializer_class\n return @collection_serializer_class if defined?(@collection_serializer_class)\n\n if serializer_class.is_a?(Proc) # TODO: maybe we should do duck typing instead?\n @collection_serializer_class = injected_options[:collection_serializer]\n if @collection_serializer_class.nil?\n raise 'In case of a proc serializer, you need to specify a collection_serializer'\n end\n else\n @collection_serializer_class = serializer_class\n end\n\n @collection_serializer_class\n end", "def serializer_class\n IncomeSerializer\n end", "def includes_for_serializer\n {}\n end", "def serializer_class\n AccountSerializer\n end", "def active_model_serializer\n self.class.active_model_serializer\n end", "def active_model_serializer\n self.class.active_model_serializer\n end", "def serializer=(value)\n PaperTrail.config.serializer = value\n end", "def render_serialized(obj, serializer, opts = nil)\n render_json_dump(serialize_data(obj, serializer, opts), opts)\n end", "def deserialized?\n true\n end", "def serializer=(_arg0); end", "def add_serializer(self_class, serializer_class, tag: nil)\n tag ||= DEFAULT_TAG\n hash = self_class.instance_variable_get(SERIALIZER_CLASSES) || {}\n hash[tag.to_sym] = serializer_class\n self_class.instance_variable_set(SERIALIZER_CLASSES, hash)\n end", "def serialize(object) end", "def serialize?(argument)\n argument.is_a?(klass)\n end", "def serialize?(argument)\n argument.is_a?(klass)\n end", "def serializer_for(resource)\n if resource.respond_to?(:to_ary)\n resource.first.class.name\n else\n resource.class.name\n end\n end", "def disableSerialization \n \"disableSerialization\" \n end", "def serialize(object)\n object = MAPPINGS[object]\n object.nil? ? nil : object\n end", "def render(*args, &block)\n opts = args[0]\n if opts.is_a?(Hash) && resource = opts[:json]\n if serializer = opts.fetch(:serializer, ActiveModel::Serializer.serializer_for(resource))\n render json: serializer.new(opts[:json]) and return\n end\n end\n\n super\n end", "def object_data\n raise NotImplementedError, 'Subclass of EVSSClaimBaseSerializer must implement object_data method'\n end", "def serializer_class\n UserSerializer\n end", "def create_default_serializer_class(model, serializer_class_name)\n platform_name = totem_settings.engine.current_platform_name(model)\n error(\"Platform name for model #{model.inspect} is blank.\") if platform_name.blank?\n extend_class = totem_settings.class[platform_name.to_sym].get_class(:base_serializer)\n error(\"Unknown base serializer class for platform name #{platform_name.inspect}.\") if extend_class.blank?\n klass = Class.new(extend_class)\n namespace_name = serializer_class_name.deconstantize\n namespace = namespace_name.safe_constantize\n serializer = namespace.const_set(serializer_class_name.demodulize, klass)\n error(\"Serializer class #{serializer_class_name.inspect} could not be constantized.\") if serializer.blank?\n debug \"Created serializer #{serializer.name.inspect}\" unless is_rake_task?\n end", "def emit_serializers!( file, model )\n end", "def test_uses_given_parent\n Object.const_set(:ApplicationSerializer, Class.new)\n run_generator [\"Account\", \"--parent=MySerializer\"]\n assert_file \"app/serializers/account_serializer.rb\", /class AccountSerializer < MySerializer/\n ensure\n Object.send :remove_const, :ApplicationSerializer\n end", "def initialize(column_serializer: shrine_class.opts[:column][:serializer], **options)\n super(**options)\n @column_serializer = column_serializer\n end", "def initialize(column_serializer: shrine_class.opts[:column][:serializer], **options)\n super(**options)\n @column_serializer = column_serializer\n end", "def _render_option_json(resource, options)\n serializer = options.fetch(:serializer, ActiveModel::Serializer.serializer_for(resource))\n\n if serializer\n object = serializer.new(resource)\n adapter = options.fetch(:adapter, ActiveModel::Serializer.default_adapter)\n\n super(adapter.new(object), options)\n else\n super\n end\n end", "def serialization_options\n @serialization_options || self.class.serialization_options || self.class.superclass.serialization_options\n end", "def serialized?\n false\n end", "def serialize(object, user_options)\n object = prepare(object)\n\n return object unless @binding.representable?\n\n @binding.evaluate_option(:serialize, object) do\n marshal(object, user_options)\n end\n end", "def avro_serializer\n @avro_serializer ||= Hash.new(PassthroughSerializer)\n end", "def serialize(method = :to_json)\n super\n end", "def shutdown\n @serializer.shutdown\n end", "def stockInformation\n ActiveModel::SerializableResource.new(object.stock, each_serializer: StockSerializer)\nend", "def is_object()\n res = super(context,self)\n return res\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n end", "def safe_reify\n reify\n rescue ActiveRecord::SubclassNotFound\n raise unless monkey_patch_safe_reify?\n\n # https://github.com/paper-trail-gem/paper_trail/blob/1fe26c9e445b0bcb2f7c20a5791ec01003632517/lib/paper_trail/reifier.rb#L132\n def self.object_deserialized # rubocop:disable Lint/NestedMethodDefinition\n super.dup.tap do |hsh|\n hsh['type'] = item_type\n end\n end\n\n retry\n end", "def serialize(serializer: ActiveModel::ArraySerializer, json_opts: {})\n fail 'Block required!' unless block_given?\n serializer.new(yield).as_json(json_opts)\n end", "def serialize_default(object); object; end", "def get_field_deserializers()\n return super.merge({\n \"distributeForStudentWork\" => lambda {|n| @distribute_for_student_work = n.get_boolean_value() },\n \"resource\" => lambda {|n| @resource = n.get_object_value(lambda {|pn| MicrosoftGraph::Models::EducationResource.create_from_discriminator_value(pn) }) },\n })\n end", "def generate_job_serializer(base)\n unless model_class?(base)\n return Log.debug { \"#{__method__}: ignoring #{base.class} argument\" }\n end\n base_name = base.name\n serializer = \"#{base_name}::Serializer\"\n return if safe_const_get(serializer)\n\n base.module_eval <<~HERE_DOC\n\n class #{serializer} < ActiveJob::Serializers::ObjectSerializer\n\n def serialize(item)\n super(item.fields)\n end\n\n def deserialize(hash)\n fields = hash.map { |k, v| [k.to_sym, deserialize(v)] }.to_h\n klass.new(**fields)\n end\n\n private\n\n def klass\n #{base_name}\n end\n\n end\n \n Rails.application.config.active_job.custom_serializers ||= []\n Rails.application.config.active_job.custom_serializers << #{serializer}\n\n HERE_DOC\n\n # NOTE: Under normal circumstances custom_serializers will already exist.\n # This extra check is just for the sake of executing a single file via\n # \"rails runner\" from the desktop.\n\n end", "def serializer\n ArticleSerializer\n end", "def serializer\n ArticleSerializer\n end", "def encode\n raise Errors::SerializerNotConfigured if serializer_missing?\n\n serializer.encode(self)\n end", "def serialize(_object, data); end", "def serialize(_object, data); end", "def serialize!\n end", "def serialize\n raise NotImplementedError\n end", "def serialize\n raise NotImplementedError\n end", "def serialize(object, data); end", "def serializable?(value)\n true\n end", "def as_json(options = {})\n # if application belongs to some owner we need to check if it\"s the same as\n # the one passed in the options or check if we render the client as an owner\n if (respond_to?(:owner) && owner && owner == options[:current_resource_owner]) ||\n options[:as_owner]\n # Owners can see all the client attributes, fallback to ActiveModel serialization\n super\n else\n # if application has no owner or it\"s owner doesn\"t match one from the options\n # we render only minimum set of attributes that could be exposed to a public\n only = extract_serializable_attributes(options)\n super(options.merge(only: only))\n end\n end", "def fetch_allowed_options\n _serializer_class = serializer_class\n _serializer_class = collection_serializer_class if _serializer_class.is_a?(Proc)\n\n unless _serializer_class.respond_to?(:simple_ams?)\n raise \"#{_serializer_class} does not respond to SimpleAMS methods, did you include the DSL module?\"\n end\n\n _serializer_class&.options\n end", "def find_serialized_with_caching(filters_or_source, serializer, options = {})\n if filters_or_source.is_a?(ActiveRecord::Relation)\n return cached_resources_for(filters_or_source, serializer, options)\n elsif _resource_klass._model_class.respond_to?(:all) && _resource_klass._model_class.respond_to?(:arel_table)\n records = find_records(filters_or_source, options.except(:include_directives))\n return cached_resources_for(records, serializer, options)\n else\n # :nocov:\n warn('Caching enabled on model that does not support ActiveRelation')\n # :nocov:\n end\n end", "def with_resource(resource)\n @resource = resource\n remove_instance_variable(:@serializer) if defined?(@serializer)\n clean_volatile_properties!\n\n self\n end", "def get_field_deserializers()\n return super.merge({\n \"amazonAccountId\" => lambda {|n| @amazon_account_id = n.get_string_value() },\n \"amazonResourceId\" => lambda {|n| @amazon_resource_id = n.get_string_value() },\n \"resourceName\" => lambda {|n| @resource_name = n.get_string_value() },\n \"resourceType\" => lambda {|n| @resource_type = n.get_string_value() },\n })\n end", "def get_field_deserializers()\n return super.merge({\n })\n end", "def get_field_deserializers()\n return super.merge({\n })\n end", "def get_field_deserializers()\n return super.merge({\n })\n end", "def deserialized?\n !!@deserialized\n end", "def serializer\n PaperTrail.config.serializer\n end", "def save_cache(obj)\n value = if @serializer_method\n serializer.serialize(obj.send(@serializer_method))\n elsif @serializing_block\n serializer.serialize(@serializing_block.call(obj))\n else\n serializer.serialize(obj.as_json)\n end\n\n storage.set(key(obj), value)\n value\n end", "def serialize_in(json_string, options = {})\n super(ActiveSupport::JSON.decode(json_string), options)\n end" ]
[ "0.6800968", "0.6706143", "0.669719", "0.6663395", "0.6325869", "0.62911326", "0.6170903", "0.61556405", "0.60922986", "0.60850024", "0.6050007", "0.60145956", "0.5971927", "0.5890221", "0.5873433", "0.5850773", "0.58401513", "0.5838806", "0.57777303", "0.56955296", "0.561995", "0.5575452", "0.55458087", "0.5541667", "0.55354124", "0.55329293", "0.5523636", "0.54519", "0.544266", "0.5424742", "0.541622", "0.54094034", "0.5360685", "0.5321116", "0.528598", "0.52791476", "0.5277385", "0.5270416", "0.5244612", "0.5240886", "0.52380097", "0.52376455", "0.52376455", "0.52293074", "0.5213083", "0.52123904", "0.5195711", "0.51728654", "0.5172488", "0.51638025", "0.51638025", "0.51622295", "0.5146748", "0.5125284", "0.5108843", "0.510759", "0.51001716", "0.50906414", "0.5088993", "0.5061597", "0.50595874", "0.50595874", "0.5040666", "0.5013158", "0.49996924", "0.4984733", "0.49585572", "0.4957091", "0.4948074", "0.49239194", "0.49170613", "0.4905231", "0.4905231", "0.4905231", "0.48865718", "0.48682797", "0.4860385", "0.48592168", "0.48540092", "0.48470688", "0.48470688", "0.4843693", "0.48366576", "0.48366576", "0.48291", "0.4825543", "0.4825543", "0.4818752", "0.4810941", "0.48012346", "0.47981134", "0.47977102", "0.4795173", "0.47924197", "0.47775787", "0.47775787", "0.47775787", "0.47159237", "0.47108397", "0.47049657", "0.4702945" ]
0.0
-1
Auxiliary Recursive function for fibs2
def fibs_rec2(n, i = 0, j = 1) n == 0 ? i : fibs_rec2(n-1, j, i+j) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fib2(n)\n if n < 2\n n\n else\n fib2(n - 1) + fib2(n - 2)\n end\nend", "def fib2(n)\n check = @@saved_fibs[n]\n if(check != nil)\n return check\n elsif n <= 2\n @@saved_fibs[n] = n\n return n\n else\n val = fib2(n-1) + fib2(n-2)\n @@saved_fibs[n] = val\n return val\n end\nend", "def even_fibs_recursive(num, term1 = 1, term2 = 2, sum = 2)\n \n next_term = term1 + term2\n return sum if next_term >= num\n\n sum += next_term if next_term % 2 == 0\n\n even_fibs_recursive(num, term2, next_term, sum)\n\nend", "def fibs fib1 = 0, fib2 = 1\r\n fib1, fib2 = fib2, fib1 + fib2\r\n return 0 if fib1 > 4e6\r\n fib1 % 2 == 0 ? fibs(fib1, fib2) + fib1 : fibs(fib1, fib2)\r\nend", "def fibonacci_v2(number)\n if number < 2\n number\n else\n fibonacci_v2(number - 1)\n end\nend", "def fib(n) (n<=2) ? 1 : (fib(n-2)+fib(n-1)) end", "def fibb(i)\n if i==0 \n return 0\n elsif i==1\n return 1\n else\n prev1=0\n prev2=1\n curr = 0\n #(2..i).each do |x|\n (2..i).each do #so it works w/o x as well\n #2.upto(i) do\n curr = prev1 + prev2 #3 = 1 + 2\n prev1 = prev2 # 1 := 2\n prev2 = curr # 2 := 3\n end\n end\n return curr\nend", "def recursive_fib n\n return 1 if n == 1 || n == 2\n recursive_fib(n-1) + recursive_fib(n-2)\nend", "def fib(n)\n if n == 1\n return [0]\n elsif n == 2\n return [0, 1]\n else\n one_less = fib(n-1)\n one_less << one_less[-1] + one_less[-2]\n return one_less\n end\n\nend", "def rec_fib(n)\r\n return [0] if n == 0\r\n return [0,1] if n ==1\r\n return [0,1,1] if n ==2\r\n \r\n rec_fib(n-1) << (rec_fib(n-1)[-1] + rec_fib(n-2)[-1]) \r\n\r\nend", "def fibs_rec(n)\n if n <= 2 then return n == 2 ? [0,1] : [0] end\n a = fibs_rec(n-1)\n return a << a[-1] + a[-2]\n\nend", "def recursive_fib(n)\n if n<2\n return n\n else\n return (recursive_fib(n-1)+recursive_fib(n-2))\n end \nend", "def q9_fibonacci(num)\n f1 = 0\n f2 = 1\n (num-1).times {|_|\n tmp = f2\n f2 += f1 \n f1 = tmp\n }\n f2\nend", "def fibs(i, f = [])\n for n in 0...i + 1\n n < 2? f << n : f << f[n-1] + f[n-2]\n end\n return f\nend", "def fib(n)\n return 1 if n == 2\n return 0 if n == 1\n\n fib(n-1) + fib(n-2)\nend", "def fibs_rec(num, fib = [0,1])\n if num == 1\n 0\n elsif num == fib.length\n fib\n else\n result = fib[fib.length - 2] + fib[fib.length - 1]\n fib.push(result)\n fibs_rec(num, fib)\n end\nend", "def fib(n)\n return 0 if n == 0\n return 1 if n == 1\n \n\n fib(n - 1) + fib(n - 2)\nend", "def fibs_rec(n, result = [0, 1])\n if n > 1\n result << result[-2] + result[-1]\n fibs_rec(n-1, result)\n end\n result\nend", "def fibs2(n)\n\t(0..n).map { |i| fibs_rec2(i) }\nend", "def rec_fib(n)\n return [1] if n == 1\n return [1, 1] if n == 2\n fibs = rec_fib(n - 1)\n fibs << (fibs[-1] + fibs[-2])\nend", "def fib(n)\n return [] if n < 1\n return [1] if n == 1\n return [1, 1] if n == 2\n\n prev_fib = fib(n - 1)\n num1 = prev_fib[-1]\n num2 = prev_fib[-2]\n prev_fib << num1 + num2\n prev_fib\nend", "def fib(n)\n if n < 2\n n\n else\n fib(n-1)+fib(n-2)\n end\nend", "def fib(n)\n return n if n < 2\n fib(n-1) + fib(n-2)\nend", "def fibs_rec(n)\n if n == 1\n [0]\n elsif n == 2\n [0,1]\n else\n fibs_rec(n-1) << fibs_rec(n-1)[-1] + fibs_rec(n-1)[-2]\n end\nend", "def fib(n)\n # return base cases of 0, 1\n return n if n == 0 || n == 1\n # call the function again to add the previous two numbers\n return fib(n-2)+fib(n-1)\nend", "def fibs_rec!(num, ary)\n ary[0] = 0 if ary.empty?\n return 0 if num == 0\n return ary[1] = 1 if num == 1\n ary << next_fib_term = fibs_rec!(num - 1, ary) + fibs_rec!(num - 2, [])\n next_fib_term \nend", "def fibs(n)\n return [0] if n == 1\n return [0, 1] if n == 2\n fibs = fibs(n - 1)\n fibs << fibs[-2] + fibs[-1]\nend", "def fib(n)\n if n < 2\n 1\n else\n fib(n-2) + fib(n-1)\n end\nend", "def fib(n)\n if n<2\n return n\n else\n return fib(n-2)+fib(n-1)\n end\nend", "def fib(n)\n return [] if n == 0\n return [0] if n == 1\n return [0,1] if n == 2\n \n fibs = fib(n-1)\n fibs << fib(n-1)[-1] + fib(n-1)[-2] \nend", "def fibs_rec(i)\n return i if i <= 1\n fibs_rec(i-2) + fibs_rec(i-1)\nend", "def fibonacci2(n)\n return 0 if n == 0\n return 1 if n == 1 || n == 2\n last = 0\n lastlast = 1\n current = 0\n n.times do\n current = last + lastlast\n lastlast = last\n last = current\n end\n current\nend", "def r_fib(n)\n return [1] if n == 1 \n return [1,1] if n == 2\n res = r_fib(n-1)\n res << res[-1] + res[-2]\nend", "def recursive_fib(n, a=0, b=1)\r\n if n == 0\r\n return a\r\n else\r\n recursive_fib(n - 1, b, a + b)\r\n end\r\nend", "def fib(i)\n return 0 if i == 0\n return 1 if i <= 2\n return fib(i-1) + fib(i-2)\nend", "def fib(n)\n return n if n < 2\n f0, f1 = 0, 1\n (n-1).times { f0, f1 = f1, f0+f1 }\n f1\nend", "def fib n\n return n if n < 2\n fib(n-2) + fib(n-1)\nend", "def fibs(n)\n return [] if n == 0\n return [0] if n == 1\n return [0, 1] if n == 2\n prev_fibs = fibs(n - 1)\n prev_fibs << (prev_fibs[-1] + prev_fibs[-2])\nend", "def fibonacci2(num)\n a = 0; b = 1\n array = [a,b]\n def inner(a,b,num,array)\n c = a + b\n array += [c]\n if c < num\n array = inner(b,c,num,array)\n end\n return array\n end\n array = inner(a,b,num,array)\n return array\nend", "def fib(n)\n if n == 1 || n == 2\n return 1\n end\n return fib(n-1) + fib(n-2)\nend", "def fib(n)\n if n == 1 || n == 2\n return 1\n end\n return fib(n-1) + fib(n-2)\nend", "def fibonacci(p2, p1, sum)\n next_number = p2 + p1\n return sum if next_number >= 4000000\n sum += next_number if next_number.even?\n fibonacci p1, next_number, sum\nend", "def get_nth_fib(n)\n if n == 2\n return 1\n elsif n == 1\n return 0\n else\n return get_nth_fib(n - 1) + get_nth_fib(n - 2)\n end\nend", "def fibs(n)\n return n if n <= 1\n fibs(n - 1) + fibs(n - 2)\nend", "def fibo_tr(n, acc1, acc2)\n if n == 0\n 0\n elsif n < 2\n acc2\n else\n return fibo_tr(n - 1, acc2, acc2 + acc1)\n end\nend", "def fib (x)\n y = x-2\nfib_sequence = y.times.inject(%5B0,1%5D) do |a, idx|\n a << a[-2] + a[-1]\nend", "def fib(n)\n if n <= 2\n return [0, 1].take(n)\n end\n previous_fib = fib(n-1)\n next_ele = previous_fib[-1] + previous_fib[-2]\n previous_fib << next_ele\nend", "def fib(n)\n if n == 1 || n == 2\n return 1\n end\n return fib(n - 1) + fib(n - 2)\nend", "def fib(n)\n return [0] if n == 1\n return [0, 1] if n == 2\n return [] if n == 0\n\n previous_fib = fib(n - 1)\n last_fib = previous_fib[-1] + previous_fib[-2]\n previous_fib << last_fib\nend", "def fibs(n)\n #base case\n return [0] if n == 1\n return [0, 1] if n == 2\n #inductive step\n cur_arr = fibs(n-1)\n cur_arr.push(cur_arr[-2] + cur_arr[-1])\nend", "def fib(n)\n if n == 0\n 0\n elsif n == 1 || n == 2\n 1\n else fib(n - 2) + fib(n - 1)\n end\nend", "def fib(n)\n return fib_num[n] if fib_num[n]\n\n fib_num[n - 2] = fib(n - 2) unless fib_num[n - 2]\n fib_num[n - 1] = fib(n - 1) unless fib_num[n - 1]\n\n return (fib_num[n - 2] + fib_num[n - 1])\n end", "def fib2(n)\n a = 0\n b = 1\n\n while n > 1\n c = a + b\n a = b\n b = c\n n -= 1\n end\n\n return b\nend", "def fib(n)\n return 0 if n == 0\n return 1 if n == 1\n\n return fib(n-1) + fib(n-2)\nend", "def fib n\n return n if n < 2\n fib(n - 1) + fib(n - 2)\nend", "def fib_rec(n)\n return 0 if n == 1\n return 1 if n == 2\n fib_rec(n - 1) + fib_rec(n - 2)\nend", "def fib(n)\n if n <= 2\n n\n else\n fib(n-1) + fib(n-2)\n end\nend", "def fib(n)\n if n == 0\n return [0]\n elsif n == 1\n return [0, 1]\n else\n fib(n-1) << fib(n-1)[-2] + fib(n-1)[-1]\n end\nend", "def fib(n)\n\n if n == 1 or n == 2\n return 1\n else\n return fib(n-1) + fib(n-2)\n end\n\nend", "def fibs(n)\n # fibs = [0, 1]\n # return [0] if n == 1\n # return fibs if n == 2\n\n # (n - 2).times do \n # fibs << fibs[-1] + fibs[-2]\n # end\n # return fibs\n\n return 0 if n == 1\n return 1 if n == 2\n\n return fibs(n - 1) + fibs(n - 2)\nend", "def fib(n)\n return 1 if n <= 2\n fib(n-1) + fib(n-2)\nend", "def fibs_rec(n, result = [0, 1])\n\tif n > 1\n\t\tresult << result[-2] + result[-1]\n\t\tfibs_rec(n - 1, result)\n\tend\n\tresult\nend", "def fibs(n)\nend", "def find_fib_nth(n)\n if n == 0\n 1\n elsif n == 1\n 1\n else\n return (find_fib_nth(n - 2) + find_fib_nth(n - 1))\n end\nend", "def fibs(num)\n return [] if num == 0\n return [0] if num == 1\n return [0, 1] if num == 2\n\n prev_fibs = fibs(num - 1)\n prev_fibs << prev_fibs[-1] + prev_fibs[-2]\n\n prev_fibs\nend", "def get_nth_fib(n)\n if n == 0 || n == 1\n return 0\n elsif n == 2\n return 1\n else\n return get_nth_fib(n-1) + get_nth_fib(n-2)\n end\n\nend", "def fib(n)\n return 1 if n == 1 || n == 2\n fib(n-1) + fib(n-2)\nend", "def show_fib(n)\n return 0 if n == 0\n return 1 if n == 1\n show_fib(n-1) + show_fib(n-2)\nend", "def fib_rec( n )\n $call_count += 1\n # Define the base case\n if n < 2\n return 1\n else\n # do the recursive calculation:\n return fib_rec( n - 1 ) + fib_rec( n - 2 )\n end\n\nend", "def fib(n)\n\treturn n if (n < 2)\n\treturn fib(n - 1) + fib(n - 2)\nend", "def fib(n)\n return 1 if n <= 2\n fib(n - 1) + fib(n - 2)\nend", "def iterative_fib(num)\r\n\treturn num if num < 2\r\n\tfib = [0, 1]\t\r\n\t(2..num).each do |digit|\r\n\t\tx = fib[digit - 1] + fib[digit - 2]\r\n\t\tfib << x\r\n\tend\r\n\treturn fib.last\r\nend", "def fib(n)\n return [0,1].take(n) if n <= 2\n prev = fib(n-1)\n prev << prev[-1] + prev[-2]\nend", "def iter_fib(n)\n return n if n == 0 || n == 1\n\n two_before = 0\n one_before = 1\n\n for i in 2..n\n current = two_before + one_before\n two_before = one_before\n one_before = current\n end\n one_before\nend", "def fibs_rec(n)\n\tarr = [0,1]\n\tif n == 1\n\t\treturn arr[0]\n\telsif n == 2\n\t\treturn arr\n\telse\n\t\tarr = fibs_rec(n-1)\n\t\tarr << arr[-1] + arr[-2]\n\tend\n\nend", "def fib_rec(n)\n return [0] if n == 1\n return [0, 1] if n == 2\n prev = fib_rec(n - 1)\n next_fib = prev[-1] + prev[-2]\n prev << next_fib\nend", "def even_fibonacci(n)\n\tif n == 0\n\t\treturn 0\n\telsif n == 1\n\t\treturn 2\n\telse\n\t\treturn 4*even_fibonacci(n-1)+even_fibonacci(n-2)\n\tend\nend", "def fibs_rec(n, fib_array=[0,1])\n return [0] if n == 1\n return fib_array if fib_array.length == n\n fib_array << fib_array[-1] + fib_array[-2]\n fibs_rec(n, fib_array)\nend", "def problem_two\n fibs(4_000_000).select { |n| n.even? }.reduce(&:+)\n end", "def fib(n)\n if n < 2\n \tn\n else\n num1, num2 = 0,1\n while n > 1 #since the 0 and 1 steps were already done for the n<2 case\n n-=1\n num2 = num1 + num1 = num2 #as in: num2 = old_num1 + (num1 = old_num2, returns old_num2)\n # OR\n # tmp = num2\n # num2 += num1\n # num1 = tmp\n end\n num2\n end\nend", "def fib(n)\n return 0 if n <= 0\n return 1 if n == 1\n\n fib(n - 1) + fib(n - 2)\nend", "def fib(n)\n if n == 1 || n == 2\n n\n else\n fib(n-1) + fib(n-2)\n end\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 fibs_rec(n)\n return n if n <= 1\n return fibs_rec(n-2) + fibs_rec(n-1)\nend", "def fib(n)\n return 0 if n == 0\n fib_helper(0, 1, n-1)\nend", "def faster_fib_helper(solution_arr, current, n)\n # n is negative\n if n < 0\n raise ArgumentError, \"Fib(n) error - n must be 0 or larger.\"\n\n # base cases n = 0 , n = 1\n elsif n == 0 || n == 1\n return n\n\n # the other case we check for is if current has reached n\n # this means we can end the recursion\n # and the final return value will be the sum of the previous two\n # elements in solution_arr we have been saving up until this point\n elsif current == n\n # n or current works here since they're the same value at this point\n # can do this because now the array only holds two elements at a time.\n return solution_arr[0] + solution_arr[1]\n\n # otherwise we shovel the next fib # to the back of the array\n # again, found by summing the two elements in front\n # and recusively call the helper with current incremented\n else\n # we only have current number of elements at this point\n # we have to specifically save this in solution_arr, if we do it in the function call\n # it will create a new slot instead of re-using the old one i think\n solution_arr = [solution_arr[1], solution_arr[0] + solution_arr[1]]\n return faster_fib_helper(solution_arr, current + 1, n)\n end\n\nend", "def fib(n)\n if n == 0 || n == 1\n return n\n else\n fib(n-1) + fib(n-2)\n end\nend", "def fibs_rec(n)\n n == 0 || n == 1 ? n : fibs_rec(n-1) + fibs_rec(n-2)\n fibs(n)\nend", "def sum_of_fib(n)\n return fib(n+2)-1;\nend", "def recursive_fib(num)\r\n\treturn num if num == 0 || num == 1\r\n\trecursive_fib(num - 1) + recursive_fib(num - 2)\r\nend", "def fib(n)\n return nil if n < 1\n return [0] if n == 1\n return [0, 1] if n == 2\n result = fib(n - 1)\n result.push(result[-1] + result[-2])\nend", "def fib_rec(n)\n # if n == 0\n # return 0\n # elsif n == 1\n # return 1\n # else\n # return fib_recur(n - 1) + fib_recur(n - 2)\n # end\n return [0] if n == 0\n return [0, 1] if n == 1\n [] << fib_rec(n - 1)\nend", "def fib(n)\n if (n <= 1) \n return n;\n else\n return fib(n-1)+fib(n-2);\n end\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 fib_rec(n)\n return nil if n < 1\n return [1] if n == 1\n return [1, 1] if n == 2\n current = [1, 1]\n recursive = fib_rec(n - 1)\n (recursive.length - 1).times do |el|\n current << recursive[el] + recursive[el + 1]\n end\n current\nend", "def fibs_rec(num)\n return [] if num == 0\n return [0] if num == 1\n return [0, 1] if num == 2\n\n prev_nums = fibs_rec(num - 1)\n prev_nums << prev_nums[-1] + prev_nums[-2]\nend", "def recursive_fib(number)\n _recursive_fib(number, 0, 1)\nend", "def fibs_rec(num)\n # base cases 0 and 1\n return [0] if num.zero?\n return [0, 1] if num == 1\n\n array = fibs_rec(num - 1)\n array << array[-2] + array[-1]\nend", "def fib(n, a = 0, b = 1)\n return a if n == 0\n return b if n == 1 && a == 0\n\n fib(n - 1, b, a + b)\nend", "def fib(n)\n # your implementation here\n if n==0 then\n 1\n elsif n==1 then\n 1\n else \n fib(n-2) + fib(n-1)\n end\nend" ]
[ "0.81149924", "0.7963547", "0.7920036", "0.78132284", "0.77975935", "0.7752685", "0.773212", "0.7729712", "0.7691897", "0.7683077", "0.7678424", "0.76573914", "0.76124716", "0.7605746", "0.7602062", "0.7600958", "0.7598341", "0.759583", "0.7595043", "0.75934285", "0.7582799", "0.75698936", "0.7566561", "0.75583637", "0.75505275", "0.7547786", "0.7524924", "0.7523679", "0.7519544", "0.7518521", "0.75144", "0.75107306", "0.7503899", "0.7502172", "0.7490132", "0.7487329", "0.7478234", "0.74763787", "0.7475619", "0.7473099", "0.7473099", "0.74673814", "0.74660426", "0.74656296", "0.74653816", "0.7461136", "0.7458608", "0.7458096", "0.7456909", "0.7451486", "0.7451152", "0.7449692", "0.74478894", "0.7443553", "0.7443457", "0.7440164", "0.74388814", "0.7438443", "0.74365735", "0.74348265", "0.74306136", "0.7430296", "0.7421211", "0.74208856", "0.7420693", "0.7418622", "0.7414499", "0.7408479", "0.740816", "0.74053425", "0.7405317", "0.7404536", "0.7399187", "0.73976463", "0.7397625", "0.7394595", "0.7394263", "0.7387396", "0.7382739", "0.7379457", "0.7370721", "0.7370397", "0.73687345", "0.73675483", "0.7365453", "0.73600304", "0.73589456", "0.7357395", "0.73567396", "0.7355176", "0.73537046", "0.73455846", "0.7343031", "0.73369396", "0.7335574", "0.7333071", "0.7331919", "0.73306006", "0.73297656", "0.7329416" ]
0.77920103
5
Rersive function using fibs_rec2
def fibs2(n) (0..n).map { |i| fibs_rec2(i) } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fibs_rec(num, fib = [0,1])\n if num == 1\n 0\n elsif num == fib.length\n fib\n else\n result = fib[fib.length - 2] + fib[fib.length - 1]\n fib.push(result)\n fibs_rec(num, fib)\n end\nend", "def fibs_rec(n)\n if n <= 2 then return n == 2 ? [0,1] : [0] end\n a = fibs_rec(n-1)\n return a << a[-1] + a[-2]\n\nend", "def fibs_rec(i)\n return i if i <= 1\n fibs_rec(i-2) + fibs_rec(i-1)\nend", "def fibs_rec(n, result = [0, 1])\n\tif n > 1\n\t\tresult << result[-2] + result[-1]\n\t\tfibs_rec(n - 1, result)\n\tend\n\tresult\nend", "def fibs_rec(n, result = [0, 1])\n if n > 1\n result << result[-2] + result[-1]\n fibs_rec(n-1, result)\n end\n result\nend", "def fibs_rec(n, fib_array=[0,1])\n return [0] if n == 1\n return fib_array if fib_array.length == n\n fib_array << fib_array[-1] + fib_array[-2]\n fibs_rec(n, fib_array)\nend", "def r_fib(n)\n return [1] if n == 1 \n return [1,1] if n == 2\n res = r_fib(n-1)\n res << res[-1] + res[-2]\nend", "def fibs(n)\nend", "def fibs_rec2(n, i = 0, j = 1)\n\tn == 0 ? i : fibs_rec2(n-1, j, i+j)\nend", "def fibs_rec!(num, ary)\n ary[0] = 0 if ary.empty?\n return 0 if num == 0\n return ary[1] = 1 if num == 1\n ary << next_fib_term = fibs_rec!(num - 1, ary) + fibs_rec!(num - 2, [])\n next_fib_term \nend", "def fib_rec(sequence_length)\n if sequence_length == 0\n return [0]\n elsif sequence_length == 1\n return [0,1]\n end\n\n return fib_rec(sequence_length - 1) << fib_rec(sequence_length - 1)[-1] + fib_rec(sequence_length - 2)[-1]\n\n\nend", "def fib(n)\n \nend", "def fibs_rec(n)\n if n == 1\n [0]\n elsif n == 2\n [0,1]\n else\n fibs_rec(n-1) << fibs_rec(n-1)[-1] + fibs_rec(n-1)[-2]\n end\nend", "def fibs_rec(n)\n\tarr = [0,1]\n\tif n == 1\n\t\treturn arr[0]\n\telsif n == 2\n\t\treturn arr\n\telse\n\t\tarr = fibs_rec(n-1)\n\t\tarr << arr[-1] + arr[-2]\n\tend\n\nend", "def fibs_rec(n)\n n == 0 || n == 1 ? n : fibs_rec(n-1) + fibs_rec(n-2)\n fibs(n)\nend", "def fibs_rec(n)\n\treturn n if n <= 1\n\tfibs_rec(n-1) + fibs_rec(n-2)\nend", "def fibs_rec(n)\n return n if n <= 1\n return fibs_rec(n-2) + fibs_rec(n-1)\nend", "def fibs_rec(number)\n return [0] if number.zero?\n\n return [0, 1] if number == 1\n\n result = fibs_rec(number - 1)\n result << result[-1] + result[-2]\nend", "def fib_rec(n)\n return 0 if n == 1\n return 1 if n == 2\n fib_rec(n - 1) + fib_rec(n - 2)\nend", "def fib(n)\n\nend", "def fibs_sum(n)\n\nend", "def fibs_sum(n)\n\nend", "def fibs_sum(n)\n\nend", "def fibs_sum(n)\n\nend", "def fibs_sum(n)\n\nend", "def fib(n)\n # your work here\nend", "def fibs_rec(n)\n n <= 1 ? n : fibs_rec(n - 1) + fibs_rec(n - 2)\nend", "def fib_rec(n)\n return (0..n).reduce([]) { |a, v| a << v } if n < 2\n prev = fib_rec(n - 1)\n prev << prev[-2] + prev[-1]\nend", "def fib(n)\nend", "def fib(n)\nend", "def fib2(n)\n check = @@saved_fibs[n]\n if(check != nil)\n return check\n elsif n <= 2\n @@saved_fibs[n] = n\n return n\n else\n val = fib2(n-1) + fib2(n-2)\n @@saved_fibs[n] = val\n return val\n end\nend", "def fibs_rec n\n (n < 3) ? [1]*n : fibs_rec(n - 1) << fibs_rec(n - 1)[-1] + fibs_rec(n - 1)[-2]\nend", "def rec_fib(n)\n return [1] if n == 1\n return [1, 1] if n == 2\n fibs = rec_fib(n - 1)\n fibs << (fibs[-1] + fibs[-2])\nend", "def fib_r(a, b, n)\n n == 0 ? a : fib_r(b, a + b, n - 1)\n end", "def fibs_rec(num)\n # base cases 0 and 1\n return [0] if num.zero?\n return [0, 1] if num == 1\n\n array = fibs_rec(num - 1)\n array << array[-2] + array[-1]\nend", "def fib_rec(n)\n return [0] if n == 1\n return [0, 1] if n == 2\n prev = fib_rec(n - 1)\n next_fib = prev[-1] + prev[-2]\n prev << next_fib\nend", "def fibs_rec(count)\n return [0,1,1].take(count) if count < 3\n prev_fibs = fibs_rec(count - 1)\n prev_fibs + [prev_fibs[-2] + prev_fibs[-1]]\nend", "def fibs_rec(num)\n return [] if num == 0\n return [0] if num == 1\n return [0, 1] if num == 2\n\n prev_nums = fibs_rec(num - 1)\n prev_nums << prev_nums[-1] + prev_nums[-2]\nend", "def fib (x)\n y = x-2\nfib_sequence = y.times.inject(%5B0,1%5D) do |a, idx|\n a << a[-2] + a[-1]\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_rec(n)\n # if n == 0\n # return 0\n # elsif n == 1\n # return 1\n # else\n # return fib_recur(n - 1) + fib_recur(n - 2)\n # end\n return [0] if n == 0\n return [0, 1] if n == 1\n [] << fib_rec(n - 1)\nend", "def fibonacii_rec(n)\n return [0] if n == 1\n return [0, 1] if n == 2\n fibonacii_rec(n - 1) + [fibonacii_rec(n - 1)[-1] + fibonacii_rec(n - 1)[-2]]\nend", "def rec_fib(n)\r\n return [0] if n == 0\r\n return [0,1] if n ==1\r\n return [0,1,1] if n ==2\r\n \r\n rec_fib(n-1) << (rec_fib(n-1)[-1] + rec_fib(n-2)[-1]) \r\n\r\nend", "def q9_fibonacci(num)\n f1 = 0\n f2 = 1\n (num-1).times {|_|\n tmp = f2\n f2 += f1 \n f1 = tmp\n }\n f2\nend", "def fibs(n) ; PHI**n - PHA**n ; end", "def fibo_rec(n)\n return n <= 1 ? n : fibo(n - 1) + fibo(n - 2)\nend", "def problem_two\n fibs(4_000_000).select { |n| n.even? }.reduce(&:+)\n end", "def fibs_rec(n, sequence = [0, 1])\n\tif n == 0\n\t\treturn 0\n\telsif n == 1\n\t\treturn 1\n\telse\n\t\tnew_num = sequence[-2] + sequence[-1]\n\t\tsequence << new_num\n\t\tfibs_rec(n-1, sequence)\n\tend\n\tsequence\nend", "def sum_of_fib(n)\n return fib(n+2)-1;\nend", "def recursive_fib(number)\n _recursive_fib(number, 0, 1)\nend", "def fibonacci_v2(number)\n if number < 2\n number\n else\n fibonacci_v2(number - 1)\n end\nend", "def fibo_rec(target_number)\n if target_number<1\n\t$series[0]=0\n return 0\n \n elsif target_number=1\n \t$series[1]=1\n \tfibo_rec 0\n return 1\n\n else\n\t\tans=fibo_rec(target_number-1)+(fibo_rec(target_number-2))\t\n\t\t$series[target_number]=ans\n\t\treturn ans\n\tend\n\treturn $series\nend", "def lagfib_step!(state, m)\n state << (state[0] + state[1]) % m\n state.shift\nend", "def fibGetSingle2 (n)\n (1.61803398875 ** n - -0.61803398875 ** n) / 2.2360679775\nend", "def fib(n)\n return n if n < 2\n f0, f1 = 0, 1\n (n-1).times { f0, f1 = f1, f0+f1 }\n f1\nend", "def fib_rec(n)\n return n if n <= 3\n\n return fib_rec(n-1) + fib_rec(n-2)\nend", "def fibs_rec(n)\n case n\n when 0\n return []\n when 1\n return [0]\n when 2\n return [0,1]\n else\n array = fibs_rec(n-1)\n # offset to n-3 and n-2 to acccount for 0 position start\n array.push(array[n-3] + array[n-2])\n return array\n end\nend", "def fibo context\n fibo_function = Virtual::MethodSource.create_method(:Integer,:fibo , [] )\n fibo_function.source.return_type = Virtual::Integer\n fibo_function.source.receiver = Virtual::Integer\n return fibo_function\n # result = fibo_function.return_type\n # int = fibo_function.receiver\n #\n # last = fibo_function.new_block(\"return\")\n #\n # f1 = fibo_function.new_local\n # f2 = fibo_function.new_local\n #\n # fibo_function.instance_eval do\n # cmp int , 1\n # mov( result, int , condition_code: :le)\n # ble( last ) #branch to return, rather than return (as the original)\n # mov f1 , 1 #set up initial values\n # mov f2 , 0\n # end\n #\n # loop = fibo_function.new_block(\"loop\")\n # fibo_function.insert_at loop\n #\n # fibo_function.instance_eval do #loop through\n # add f1 , f1 , f2 # f1 = f1 + f2\n # sub f2 , f1 , f2 # f2 = f1 -f2\n # sub int , int , 1 # todo: set.. should do below cmp, but doesn't , set_update_status: 1\n # cmp int , 1\n # bne( loop )\n # mov( result , f1 )\n # end\n #\n # fibo_function\n end", "def fib(n)\n n.times.each_with_object([0,1]) { |_, results| results << results[-2] + results[-1] }\nend", "def fibs(i, f = [])\n for n in 0...i + 1\n n < 2? f << n : f << f[n-1] + f[n-2]\n end\n return f\nend", "def fibonacci_rec(n)\n return [] if n == 0\n return [1] if n == 1\n return [1, 1] if n == 2\n\n fibs = fibonacci_rec(n - 1)\n last = fibs[-1]\n second_last = fibs[-2]\n\n fibs << last + second_last\nend", "def fibonacciR( n )\r\n return n if n <= 1\r\n fibonacciR( n - 1) + fibonacciR( n - 2)\r\nend", "def fibo(result)\n\treturn result if result <= 1\n\tfibo(result - 1) + fibo(result - 2)\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 fib_rec( n )\n $call_count += 1\n # Define the base case\n if n < 2\n return 1\n else\n # do the recursive calculation:\n return fib_rec( n - 1 ) + fib_rec( n - 2 )\n end\n\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 fib2(n)\n if n < 2\n n\n else\n fib2(n - 1) + fib2(n - 2)\n end\nend", "def fib(n) (n<=2) ? 1 : (fib(n-2)+fib(n-1)) end", "def iter_fib(number)\n v1 = 0\n v2 = 1\n (number-1).times.each do\n temp = v2\n v2 = v2 + v1\n v1 = temp\n end\n v2\nend", "def fiboRec(no)\n if no == 0\n return [0]\n elsif no == 1\n return fiboRec(0).push(1)\n else\n arr = fiboRec(no-1)\n return arr.push(arr[no-1] + arr[no-2])\n end\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 fibb(i)\n if i==0 \n return 0\n elsif i==1\n return 1\n else\n prev1=0\n prev2=1\n curr = 0\n #(2..i).each do |x|\n (2..i).each do #so it works w/o x as well\n #2.upto(i) do\n curr = prev1 + prev2 #3 = 1 + 2\n prev1 = prev2 # 1 := 2\n prev2 = curr # 2 := 3\n end\n end\n return curr\nend", "def fib(n)\n if n == 1\n return [0]\n elsif n == 2\n return [0, 1]\n else\n one_less = fib(n-1)\n one_less << one_less[-1] + one_less[-2]\n return one_less\n end\n\nend", "def display_fibs_rec(n)\n puts \"\\nfibs_rec(#{n}):\"\n p fibs_rec(n)\nend", "def fibonaci(n)\n\tfi= [1, 1]\n\t(n-1).times do\n\t\tfi << fi[1]+fi.shift\n\tend\n\treturn fi[0]\nend", "def fibs(n)\n #base case\n return [0] if n == 1\n return [0, 1] if n == 2\n #inductive step\n cur_arr = fibs(n-1)\n cur_arr.push(cur_arr[-2] + cur_arr[-1])\nend", "def fibo_tr(n, acc1, acc2)\n if n == 0\n 0\n elsif n < 2\n acc2\n else\n return fibo_tr(n - 1, acc2, acc2 + acc1)\n end\nend", "def fibs fib1 = 0, fib2 = 1\r\n fib1, fib2 = fib2, fib1 + fib2\r\n return 0 if fib1 > 4e6\r\n fib1 % 2 == 0 ? fibs(fib1, fib2) + fib1 : fibs(fib1, fib2)\r\nend", "def fibs_rec(n, arr = [])\n arr.unshift(n - 1 <= 1 ? n - 1 : fibo(n - 2) + fibo(n - 3))\n return n - 1 > 0 ? fibs_rec(n - 1, arr) : arr\nend", "def recur_nth_fib(n)\n nth_fib(n, { 1 => 1, 2 => 1 })[n]\nend", "def fib(n)\n return 0 if n == 0\n fib_helper(0, 1, n-1)\nend", "def fib2(i)\n (500..i).step(500) { |j| $fib[j] } if i > 500 # cache every 500\n $fib[i]\nend", "def fib(n)\n n.times.each_with_object([0,1]) { |num, obj| obj << obj[-2]+obj[-1]}\nend", "def fib(n)\n if n <= 2\n return [0, 1].take(n)\n end\n previous_fib = fib(n-1)\n next_ele = previous_fib[-1] + previous_fib[-2]\n previous_fib << next_ele\nend", "def even_fib_sum(n)\n f = ->(x){ x < 2 ? x : f[x-1] + f[x-2] }\n\n value =f[2]\n res = cnt = 0\n while value <= n\n res+=value if value.even?\n cnt+=1\n value=f[cnt]\n end\n res\nend", "def iterative_fib(num)\r\n a = 0\r\n b = 1\r\n\r\n num.to_i.times do\r\n temp = a\r\n a = b\r\n # Add up previous two numbers in sequence\r\n b = temp + b\r\n end\r\n\r\n return b\r\nend", "def fib(i)\n return 0 if i == 0\n return 1 if i <= 2\n return fib(i-1) + fib(i-2)\nend", "def fib(n)\n # return base cases of 0, 1\n return n if n == 0 || n == 1\n # call the function again to add the previous two numbers\n return fib(n-2)+fib(n-1)\nend", "def fibonacci(p2, p1, sum)\n next_number = p2 + p1\n return sum if next_number >= 4000000\n sum += next_number if next_number.even?\n fibonacci p1, next_number, sum\nend", "def fib(n)\n return [0,1].take(n) if n <= 2\n prev = fib(n-1)\n prev << prev[-1] + prev[-2]\nend", "def fib2(n)\n a = 0\n b = 1\n\n while n > 1\n c = a + b\n a = b\n b = c\n n -= 1\n end\n\n return b\nend", "def fib(n)\n return n if n < 2\n arr = [0, 1]\n (n-1).times { arr << arr.last(2).inject(:+) }\n arr.last\nend", "def fibonacci(n)\n \nend", "def fibonacci(n)\n \nend", "def fib(n)\n return fib_num[n] if fib_num[n]\n\n fib_num[n - 2] = fib(n - 2) unless fib_num[n - 2]\n fib_num[n - 1] = fib(n - 1) unless fib_num[n - 1]\n\n return (fib_num[n - 2] + fib_num[n - 1])\n end", "def fib(n)\n n.times.each_with_object([0,1]) { |num, obj| obj << obj[-2] + obj[-1] }\nend", "def fib(n)\n\n fib_seq = [0, 1]\n\n while n > 2\n fib_seq << fib_seq[fib_seq.length - 1] + fib_seq[fib_seq.length - 2]\n n -= 1\n end\n\n return fib_seq\n\nend", "def fib(n)\n return 0 if n == 0\n return 1 if n == 1\n \n\n fib(n - 1) + fib(n - 2)\nend", "def fib_rec(n)\n return nil if n < 1\n return [1] if n == 1\n return [1, 1] if n == 2\n current = [1, 1]\n recursive = fib_rec(n - 1)\n (recursive.length - 1).times do |el|\n current << recursive[el] + recursive[el + 1]\n end\n current\nend", "def sim_fib(n)\n return '0' if n == 0\n return '01' if n == 1\n\n sim_fib(n - 1) + sim_fib(n - 2)\nend" ]
[ "0.72103864", "0.7167818", "0.715184", "0.7124236", "0.71067625", "0.70858645", "0.7085737", "0.7062453", "0.70487046", "0.7035652", "0.6992201", "0.69885856", "0.69871384", "0.6986774", "0.69794714", "0.69622415", "0.69403446", "0.6925711", "0.6919367", "0.69018126", "0.68894434", "0.68894434", "0.68894434", "0.68894434", "0.68894434", "0.688097", "0.68795717", "0.6875445", "0.6869973", "0.6869973", "0.68665", "0.6865841", "0.68644696", "0.6858475", "0.68550843", "0.6841506", "0.68281096", "0.6825021", "0.6806301", "0.6794132", "0.6763699", "0.67628485", "0.674265", "0.6739971", "0.6727591", "0.67238957", "0.67169183", "0.67160225", "0.6715868", "0.6706768", "0.6704541", "0.66657287", "0.6640444", "0.6639234", "0.6637475", "0.66288525", "0.66276234", "0.6612501", "0.66046774", "0.6591234", "0.6588553", "0.6585963", "0.6584235", "0.6576393", "0.656847", "0.65647626", "0.6560749", "0.65485704", "0.65469444", "0.65461034", "0.65431905", "0.6540459", "0.65290296", "0.65256685", "0.65208334", "0.65193725", "0.65178794", "0.65147185", "0.6514214", "0.64977086", "0.6496541", "0.64941174", "0.6489177", "0.6488156", "0.64836", "0.6474605", "0.64714944", "0.6470645", "0.64684874", "0.6468159", "0.6465887", "0.64631957", "0.6459764", "0.64585054", "0.6457943", "0.64570254", "0.64563113", "0.6452832", "0.6439926", "0.64363414" ]
0.712185
4