query
stringlengths
7
9.5k
document
stringlengths
10
1.07M
negatives
listlengths
19
19
metadata
dict
get total coins value with this route => host/users/total_coins_value?:user_id=user_id
def total_coins_value json_response({:total_coins_value => @total_coins_val, :status => true, :message => 'calculated'}) end
[ "def total_value\n coins.reduce(0) do |sum, (coin_name, quantity)|\n sum + coin_value(coin_name) * quantity\n end\n end", "def get_coins\n get(\"/getcoins\")\n end", "def calculate_coins_value\n @amount = 0\n\n @coins.each do |coin|\n @amount += COINS[coin.weight]\n end\n end", "def get_user_total(user)\n self.get_user_items(user).to_a.sum(&:user_cost)\n end", "def get_inventory_value(user_id)\n value = USER_INVENTORY.where(owner_user_id: user_id).sum(:value)\n return value.nil? ? 0 : value\n end", "def total(user)\n tot = 0\n hours = Hour.where(user_id: user.id, approved: true)\n for x in 0..hours.count-1\n tot += hours[x].content\n end\n return tot\n end", "def total_contribution_by(user)\n contributions.where(user: user).with_states(:scheduled, :completed).map(&:amount).inject { |a, e| a + e } || 0\n end", "def coin_balance\n #todo calc\n coin\n end", "def return_coins\n user.increase_coins(coins)\n self.reset_coins\n end", "def balance(user_id)\n @tropo_client.get(\"users/#{user_id}/usage\")\n end", "def get_coin_value\n @coin_value = CoinValue.find(params[:coin_value_id])\n end", "def get_total(user)\n '%.3f' % (get_initial_capital(user).to_f + get_upnl(user).to_f +\n get_profit(user).to_f)\n end", "def total_value_of_shares\n total_number_of_shares * @current_value\n end", "def count\n @values = Coin.sum(:value)\n render json: @values\n end", "def user_cost\n @attributes[:user_cost]\n end", "def get_invoices_value_user_date(user, date, value)\n invoices = Invoice.where([\"invoices.return = '0' AND company_id = ? AND user_id = ? AND date_processed >= ? AND date_processed <= ?\", self.id, user.id, \"#{date} 00:00:00\", \"#{date} 23:59:59\"])\n ret = 0\n \n for invoice in invoices\n if(value == \"subtotal\")\n ret += invoice.subtotal\n elsif(value == \"tax\")\n ret += invoice.tax\n else\n ret += invoice.total\n end\n end\n \n return ret\n end", "def get_invoices_value_user_date(user, date, value)\n invoices = Invoice.where([\"invoices.return = '0' AND company_id = ? AND user_id = ? AND date_processed >= ? AND date_processed <= ?\", self.id, user.id, \"#{date} 00:00:00\", \"#{date} 23:59:59\"])\n ret = 0\n \n for invoice in invoices\n if(value == \"subtotal\")\n ret += invoice.subtotal\n elsif(value == \"tax\")\n ret += invoice.tax\n else\n ret += invoice.total\n end\n end\n \n return ret\n end", "def total\n amount\n end", "def available_crypto_balance_usd \n portafolio = Portafolio.find(params[:id])\n all_own_in_usd = []\n for i in portafolio.crypto_assets\n url = \"https://api.coincap.io/v2/assets/#{i.cryptoId}\"\n response = HTTParty.get(url)\n result = JSON.parse(response.body)\n latest_price = result.dig(\"data\", \"priceUsd\").to_f\n how_much_own = (latest_price * i.crypto_Percentage)/100\n all_own_in_usd << how_much_own\n end\n formated_ammount = all_own_in_usd.sum.round(2)\n render json: {crypto_balance_usd: formated_ammount}\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
all transactions for a specific user => host/users/user_transactions?:user_id=user_id
def user_transactions user_deposits = get_user_deposits user_withdrawals = get_user_withdrawals json_response({:user_transactions => @user_transactions, :user_deposits => user_deposits, :user_withdrawals => user_withdrawals}) end
[ "def user_transactions params = { 'offset' => 0, 'limit' => 100, 'sort' => 'desc' }\n private_request 'user_transactions', params\n end", "def get_user_transactions(**options)\n \t\t[options[:page], options[:per_page]].each do |arg|\n \t\t\tif arg && (!arg.is_a?(Integer) || arg < 1)\n \t\t\t\traise ArgumentError, \"#{arg} must be nil or an Integer >= 1\"\n \t\t\tend\n \t\tend\n\n path = transactions_path(user_id: self.user_id, options: options)\n\n begin\n trans = client.get(path)\n rescue Synapse::Error::Unauthorized\n self.authenticate()\n trans = client.get(path)\n end\n\n\n response = trans[\"trans\"].map { |trans_data| Transaction.new(trans_id: trans_data['_id'],\n payload: trans_data\n )}\n trans = Transactions.new(limit: trans[\"limit\"],\n page: trans[\"page\"],\n page_count: trans[\"page_count\"],\n trans_count: trans[\"trans_count\"],\n payload: response\n )\n\n \ttrans\n end", "def set_user_transactions\n @user_transactions = @user.transactions.where(user_id: @user.id) if @user\n end", "def show\n @transactions = Transaction.where(user_id: params[:id])\n render json: @transactions\n end", "def transactions\n @transactions = Transaction.where(\"user_id = ? AND mission_story_id = ?\", session[:user_id], params[:id])\n\n respond_to do |format|\n format.html\n format.json {render json: @transactions}\n end\n end", "def get_transactions_from_user\n # Get transactions for all accounts the user has\n transactions_sent = current_user.sent_transactions\n transactions_received = current_user.received_transactions\n return transactions_sent + transactions_received\n end", "def mytransactions\n #Quary User table in DB get all\n @users = User.all\n #Quary Transaction table in DB get all\n @transactions = Transaction.all\n end", "def get_user_coin_transactions\n user_coin_transactions = Transaction.where(user_id: @user.id, coin_id: @user_coin.id) if @user\n return user_coin_transactions;\n end", "def show\n @txn = current_user.transactions.find(params[:id])\n render json: { txn: @txn }, include: :users\n end", "def transactions(options = nil)\n request = Request.new(@client)\n path = \"/subscriptions/\" + CGI.escape(@id) + \"/transactions\"\n data = {\n\n }\n\n response = Response.new(request.get(path, data, options))\n return_values = Array.new\n \n a = Array.new\n body = response.body\n for v in body['transactions']\n tmp = Transaction(@client)\n tmp.fill_with_data(v)\n a.push(tmp)\n end\n\n return_values.push(a)\n \n\n \n return_values[0]\n end", "def transactions account_id\n data = perform_get(\"#{ACCOUNTS_PATH}/#{account_id}/transactions\")\n data[:accountTransactions] || []\n end", "def index\n @transaction = find_parent.transactions.includes(:user, :deal)\n respond_with(paginate(@transactions), :include => [:user])\n end", "def get_transactions(service)\n\t\treturn @transport.get_path(\"transactions\",service)\n\tend", "def fetch_wallets_transactions(filters = {})\n MangoPay.request(:get, url() + \"/transactions\", {}, filters)\n end", "def transactions_get_by_id id\n params = { :id => id }\n transaction = @client.query_get \"transactions/get\", params\n end", "def all(options = nil)\n request = Request.new(@client)\n path = \"/transactions\"\n data = {\n\n }\n\n response = Response.new(request.get(path, data, options))\n return_values = Array.new\n \n a = Array.new\n body = response.body\n for v in body['transactions']\n tmp = Transaction(@client)\n tmp.fill_with_data(v)\n a.push(tmp)\n end\n\n return_values.push(a)\n \n\n \n return_values[0]\n end", "def get_item_transactions(params = {})\n commit(Ebay::Requests::GetItemTransactions, params)\n end", "def get_item_transactions(params = {})\n commit(EbayTrading::Requests::GetItemTransactions, params)\n end", "def get_transactions(user_id, startTimestamp, format='json', endTimestamp=nil, limit=nil, orderByCol0=nil, orderByDir0=nil, orderByCol1=nil, orderByDir1=nil)\n @logger.debug(\"get_transaction : user_id=#{user_id} startTimestamp=#{startTimestamp} format=#{format} endTimestamp=#{endTimestamp} limit=#{limit} orderByCol0=#{orderByCol0} orderByDir0=#{orderByDir0} orderByCol1=#{orderByCol1} orderByDir1=#{orderByDir1}\")\n\n base_params = {:user_id => user_id, :action => 'get_transactions', :format => format, :offer_id => @offer_id}\n required_params = {:start_ts => startTimestamp}\n\n optional_params = Hash.new\n optional_params[:end_ts] = endTimestamp if (endTimestamp.to_i > 0) && !(endTimestamp.nil?)\n optional_params[:limit] = limit if (limit.to_i > 0) && !(limit.nil?)\n optional_params[:order_by_column_0] = orderByCol0 if !(orderByCol0.nil?)\n optional_params[:order_by_dir_0] = orderByDir0 if !(orderByDir0.nil?)\n optional_params[:order_by_column_1] = orderByCol1 if !(orderByCol1.nil?)\n optional_params[:order_by_dir_1] = orderByDir1 if !(orderByDir1.nil?)\n\n cmd_uri = _generate_uri(base_params, required_params, optional_params)\n response = _get_response(cmd_uri)\n return response\n\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Public: returns the string "We're playing tennis!" When the game_play object is named.
def to_s "We're playing tennis!" end
[ "def game_text(game)\n \"Game #{game.id} - Versus @#{game.opponent.username}\"\n end", "def game_title\n\t\t\"#{home_team} vs. #{visitor_team}\"\n\tend", "def to_s\n \"Player #{@name}\"\n end", "def name\n self[:name] || \"#{player1.name} vs. #{player2.name}\"\n end", "def name\n @game_info['name']\n end", "def current_contest_title\n \"#{JUMU_SEASON}. Wettbewerb \\\"Jugend musiziert\\\"\"\n end", "def current_player_name\n Player.find(player_turn).name unless player_turn.nil?\n end", "def cur_name\n @players[@current_player].name\n end", "def game_name()\n if @handle.ptr == nil\n raise \"this is disposed\"\n end\n result = Native.Run_game_name(@handle.ptr)\n result\n end", "def s_name\n @s_name ||= players[0]\n end", "def e_name\n @e_name ||= players[3]\n end", "def game_class(game)\n result = 'game'\n if game.ongoing? && game.whose_turn.id == user_session.current_user.id\n result += ' playable'\n end\n return result\n end", "def get_song_name\n self.song ? \"#{self.song.name}\" : \"\"\n end", "def get_full_name\n \"#{season_description} - #{team_name}: #{rank}\"\n end", "def say_name\n\t\t\"uurrgghh #{@name}\"\n\tend", "def player_name(player_id)\n player = Player.where(player_id: player_id).first\n \n if player.present?\n str = \"#{player.first_name} #{player.last_name}\"\n else\n str = 'No player name found'\n end\n \n return str\n end", "def print_play(guess)\n puts \"\\n#{@current_player.name} entered #{guess}:\"\n puts \"\\n-------------\\nCurrent word: #{@fragment}\\n-------------\\n\"\n end", "def w_name\n @w_name ||= players[1]\n end", "def n_name\n @n_name ||= players[2]\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal: This method is called to start a new game. It asks whether the user would like to play a new game. If answer is 'y' it starts a new game. If 'n' it ends the program. returns: "response not understood" if any other response is received.
def new_game puts "Would you like to play a new game (y or n)?" answer = gets.chomp.downcase if answer == 'y' @player1.points = 0 @player2.points = 0 puts "Player 1 = #{@player1}" puts "player 2 = #{@player2}" self.coin_toss_call elsif answer puts "Have a nice day." else puts "response not understood." end end
[ "def start\r\n\t\tputs \"\\nI am Negaman. Are you ready... Human?\"\r\n\t\t\r\n\t\tprint \"\\nWould you like to go first? (y/n): \"\r\n\t\tcheck = gets.chomp\r\n\r\n\t\twhile !confirm(check)\r\n\t\tcheck = gets.chomp\r\n\t\tend\r\n\r\n\t\tif check == 'n'then @currentPlayer = @player2\r\n else @currentPlayer = @player1\r\n\t\tend\r\n \r\n\t\tgameLogic\r\n\t\t\r\n\tend", "def play_again?\n puts \"Would you like to play again? Type 'yes' or 'no':\"\n answer = gets.chomp\n if answer == \"yes\"\n puts \"\\n\\n\\n\"\n new_players = [\n player1 = Player.new(\"Player 1\"),\n player2 = Player.new(\"Player 2\")\n ]\n game = Game.new(new_players)\n game.play_game\n elsif answer ==\"no\"\n puts \"Good Bye!\"\n puts\n else\n play_again?\n end\n end", "def play_game(player)\n\tgame = Game.new(player)\n\tplay_again = 'y'\n\twhile play_again == 'y'\n\t\tgame.start_session\n\t\tgame.win_ratio_output\n\t\tputs\n\t\tputs \"Do you want to play another session? (Type 'y'/'n')\"\n\t\tplay_again = gets.strip.downcase\n\t\tcheck_yes_no_input(play_again)\n\t\tgame.set_up_game_session\n\tend\nend", "def new_hand_check\n puts 'Are you ready to play? Enter ' + '(Y)es'.light_green + ' to proceed or ' + '(N)o'.light_red + ' to return to the main menu.'\n @input = STDIN.gets.chomp\n if @input.downcase == 'y' || @input.downcase == 'yes'\n @game_running = true\n elsif @input.downcase == 'n' || @input.downcase == 'no'\n @game_running = false\n else\n puts 'Please enter a valid input.'\n new_hand_check\n end\nend", "def ask_to_play\r\n\t\tputs \"Would you like to play?\"\r\n\t\tplayer_choice = gets.chomp.upcase\r\n\r\n\t\tif player_choice == \"YES\"\r\n\t\t\r\n\t\telse\r\n\t\t\tputs \"Good Bye!\"\r\n\t\t\texit\r\n\t\tend\r\n\tend", "def start_game\n puts \"What would you like to do?\"\n puts \"1. Load Saved Game\"\n puts \"2. Start New Game\"\n choice = gets.chomp\n if choice == \"1\"\n find_save_file\n elsif choice == \"2\"\n initialize\n end\n end", "def start_game\n puts\"Welcome to hold em\"\n input = 'nil'\n while input != 'n' && input != 'no'\n single_game\n puts\"would you like to play agian (y)es or (n)o\"\n input = gets.strip\n end\n end", "def done()\n\n\t\t# Anouce the end of the game\n\tputs\n\tputs \" ------- End of the game -------\"\n\tputs\n\tputs\n\t\t# prints question to ask if user want to play again \n\tputs \"Would you like to play again? y/n\"\n\t\t# captures answer from user\n\tregame = gets.chomp.to_s\n\n\t\t# analize user's answer if ys y will call method game() to start game again\n\tif regame == \"y\"\n\t\tputs \" \"\n\t\tputs \" \"\n\t\tgame()\n\n\t\t# prints thansk before end of the program\n\telse\n\t\tputs\n\t\tputs \" *** Thansk for Playing *** \"\n\t\tputs\n\t\texit\n\tend\n\nend", "def play_again\n print \"Do you want to play again?(y/n): \"\n get_choice\n start_or_end\n end", "def keep_playing\n puts \"Would you like to play another hand? Yes or no\"\n response = gets.chomp\n response.upcase!\n if response == \"YES\" || response == \"Y\"\n @flag = true\n elsif response == \"NO\" || response == \"N\"\n @flag = false\n else\n puts \"Invalid input\"\n keep_playing\n end\n end", "def player_dead\n\tputs \"Would you care to try again? (Y/N)\"\n\tplay_again = gets.chomp\n\tplay_again.downcase!\n\tif play_again == \"y\"\n\t\tgame_start\n\telse\n\t\texit\n\tend\nend", "def start\n\t\twhile @playing\n\t\t\tletter, x_coordinate, y_coordinate = @player.make_decision\n\t\t\tuntil @board.draw(letter, x_coordinate, y_coordinate)\n\t\t\t\tletter, x_coordinate, y_coordinate = @player.make_decision\n\t\t\tend\n\t\t\t@board.print_board\n\t\t\tvictory_check?\n\t\t\tif @playing\n\t\t\t\tletter, x_coordinate, y_coordinate = @computer.make_decision(@board.available_spaces)\n\t\t\t\t@board.draw(letter, x_coordinate, y_coordinate)\n\t\t\t\t@board.print_board\n\t\t\t\tvictory_check?\n\t\t\tend\n\t\tend\n\n\t\tputs \"Would you like to play again?(y/n)\"\n\t\tchoice = gets.chomp.downcase\n\t\tif choice == \"y\"\n\t\t\t@board.clear_board\n\t\t\t@playing = true\n\t\t\tstart\n\t\telse\n\t\t\tputs \"Goodbye!\"\n\t\tend\n\tend", "def start_found_game\n listen_for_challenge\n game_on\n run_game\n end", "def handle_guess(input)\n if input == false\n puts \"#{@current_user.name}: Seriously? No!\"\n lose_life(@current_user)\n elsif input == true\n puts \"#{@current_user.name}: YES! You are correct.\"\n puts \"P1: #{@players[0].lives}/3 vs P2: #{@players[1].lives}/3\"\n switch_user\n puts \"\\n\" + @@new_turn_alert\n play_game\n else\n puts \"Unhandled error\"\n end\n end", "def start_new_game\n say \"\\nStarting a new game.\"\n @client.start_new_game\n end", "def want_to_play_again?\n\t\tputs\n\t\tputs \"Do you want to play again? y or n\"\n\t\tputs\n\t\tplay_again = gets.chomp.downcase\n\t\tif play_again == \"n\"\n\t\t\t@this_turn = @max_turns + 1\n\t\telse\n\t\t\t@letters_remain = true\n\t\t\t@bad_guesses = 0\n\t\tend #if\n\tend", "def proceed?\n return true unless @verbose\n print \"(II) Proceed? <y>/n: \"\n response = gets.chomp.gsub(\"\\\\n\",\"\")\n response.downcase == 'y' || response == ''\n rescue Exception => e\n exit\n end", "def play_again_prompt\n typing_tabbed(\"txt/play_again.txt\")\n tab; print \" >> \"\n play_again = gets.chomp.downcase\n\n if play_again == 'y'\n Mastermind.new.play\n elsif play_again == \"n\"\n tab; \"Acknowledged\\n\".typing\n tab; \"--THIS DEVICE WILL SELF DESTRUCT IN 3 SECONDS--\\n\".typing\n tab; (1..3).reverse_each { |n| \"#{n}..\".typing ; sleep 0.9}\n line\n\n abort\n else\n play_again_prompt\n end\n end", "def restart_game?(input)\n if input == \"yes\"\n true\n else\n false\n end\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal: Asks player to call heads or tails, saves response. Calls toss_results if 'heads' or 'tails' is entered.
def coin_toss_call puts "Please call 'heads' or 'tails'" call = gets.chomp.downcase unless call == 'heads' || call == 'tails' puts "response not understood. Hit 't' to try again." response = gets.chomp.downcase if response == "t" self.coin_toss_call else puts "exiting game." end else self.toss_results(call) end end
[ "def toss_results(call)\n\t\t\ttoss = self.cointoss\n\t\t\ttoss_string =\"you called #{call} and the toss returned #{toss}.\"\n\t\t\tif call == toss\n\t\t\t\tputs toss_string\n\t\t\t\tputs \"you won the coin toss.\"\n\t\t\t\tputs \"You get to serve first.\"\n\t\t\t\tputs \" \"\n\t\t\t\tself.hitter2\n\t\t\t\tserver(@player1)\n\t\t\telsif call != toss\n\t\t\t\tputs toss_string\n\t\t\t\tputs \"you lost the coin toss.\"\n\t\t\t\tputs \"#{@player2} will serve first.\"\n\t\t\t\tputs \" \"\n\t\t\t\tself.hitter1\n\t\t\t\tserver(@player2)\n\t\t\telse\n\t\t\t\t\"error\"\n\t\t\tend\n\t\tend", "def coin_toss\n puts \"#{@new_game.player_1.name}, heads or tails?\"\n if @new_game.player_1.is_a?(Computer)\n call = [\"heads\", \"tails\"].sample\n puts \"#{@new_game.player_1.name} selects #{call}.\"\n else\n call = gets.chomp\n call.downcase\n # binding.pry\n end\n if call == \"heads\"\n coin = rand(1..2)\n call = 1\n if call == coin\n @new_game.player_1.go_first = true\n puts \"#{@new_game.player_1.name} won the toss.\"\n else\n @new_game.player_2.go_first = true\n puts \"#{@new_game.player_2.name} won the toss.\" \n # eval_board\n end\n elsif call == \"tails\"\n coin = rand(1..2)\n call = 2\n if call == coin\n @new_game.player_1.go_first = true\n puts \"#{@new_game.player_1.name} won the toss.\"\n else\n @new_game.player_2.go_first = true\n puts \"#{@new_game.player_2.name} won the toss.\" \n # eval_board\n end\n else\n puts \"Invalid answer\"\n coin_toss\n end\n @new_game.coin_toss\n end", "def tweet_response\n answer = gets.strip.upcase\n if answer == \"REPLIES\" && self.tweet != nil\n show_replies\n elsif answer == \"MORE\"\n self.user.five_more\n give_options\n elsif answer == \"BACK\"\n self.user.redisplay\n give_options\n elsif answer == \"NEW\"\n new_user_menu\n elsif answer.to_i > 0\n display_tweet(answer.to_i)\n else\n puts \"Uh oh!! I don't know what you're trying to say! Sorry about that.\"\n give_options\n end\n end", "def make_call(call, player=nil, position=nil)\n raise TypeError, \"Expected Call, got #{call}\" unless [Bid, Pass, Double, Redouble].include?(call.class)\n \n if player\n raise GameError, \"Player unknown to this game\" unless self.players.include?(player)\n position = self.players[player]\n end\n \n raise TypeError, \"Expected Direction, got #{position.class}\" if position.nil? or Direction[position].nil?\n \n # Validate call according to game state.\n raise GameError, \"No game in progress\" if self.auction.nil?\n raise GameError, \"Auction complete\" if self.auction.complete?\n raise GameError, \"Call made out of turn\" if self.get_turn != position\n raise GameError, \"Call cannot be made\" unless self.auction.valid_call?(call, position)\n\n self.auction.make_call(call)\n \n if self.auction.complete? and !self.auction.passed_out?\n self.state = :playing\n self.contract = self.auction.get_contract\n trump_suit = @trump_map[self.contract[:bid].strain]\n self.play = TrickPlay.new(self.contract[:declarer], trump_suit)\n elsif self.auction.passed_out?\n self.state = :finished\n end\n \n # If bidding is passed out, game is complete.\n self._add_result(self.board, contract=nil) if not self.in_progress? and self.board.deal\n\n if !self.in_progress? and self.board.deal\n # Reveal all unrevealed hands.\n Direction.each do |position|\n hand = self.board.deal.hands[position]\n self.reveal_hand(hand, position) if hand and !self.visible_hands.include?(position)\n end\n end\n end", "def answer_hint_pun\n\npun_riddle = false\nhint_counter = 0\n\n\nuntil pun_riddle\n\tmy_pun\n\n\tputs \"Can you guess what I am?\"\n\tputs \"Type [A] to answer, or [H] for a hint.\"\n\tspaces (2)\nanswer = gets.chomp.downcase\n\n\tif answer == \"a\"\n\t\tspaces(3)\t\n\t\tsystem 'figlet what am i?'\t\n\t\tmy_pun\n\t\tputs \"You think you KNOW me?! Ain't NOBODY know me.\"\n\t\tspaces(2)\n\t\tputs \"Enter your answer:\"\n\t\tuser_pun (wait_for_player)\n\t\tpun_riddle = true\n\t\t\n\telsif answer == \"h\"\n\t\tmy_pun\n\t\tspaces(2)\n\t\tif hint_counter < 2\n\t\tputs \"I don't blame you. I sound like a lunatic. I mean, I am, but that's not the answer.\"\n\t\tend\n\t\tif hint_counter < 6\n\t\t\t\n\t\t\tspaces(2)\n\t\t\tputs \"For your hint, you can ask any of these questions to find out what I am.\"\n\t\t\tspaces(1)\n\t\t\tputs \"Choose any of these yes or no questions by pressing [A], [B], [C], or [D].\"\n\t\t\tputs \"[A]: Are you an object?\"\n\t\t\tputs \"[B]: Can you be found in nature?\"\n\t\t\tputs \"[C]: Can I hold you in my hand?\"\n\t\t\tputs \"[D]: Are you alive?\"\n\t\t\tspaces(2)\n\t\t\tpuns_hints(wait_for_player)\n\t\t\thint_counter +=1\n\t\t\t\n\t\telse\n\t\t\tspaces(2)\n\t\t\tputs \"You must have gone through all the hints possible now.\"\n\t\t\tputs \"I uh... I have places to be, man.\"\n\t\t\tpun_riddle = true\n\t\tend\n\tend\n\nend\n\nend", "def ask(options={})\n check_state\n\n options[:recognizer] = @tropo_recognizer if options[:recognizer].nil?\n options[:voice] = @tropo_voice if options[:voice].nil?\n\n # Check for Asterisk sounds\n asterisk_sound_url = fetch_asterisk_sound(options[:prompt])\n if asterisk_sound_url\n prompt = asterisk_sound_url\n else\n prompt = options[:prompt]\n end\n\n response = @current_call.ask prompt, options\n if response.value == 'NO_SPEECH' || response.value == 'NO_MATCH'\n result = { :interpretation => response.value }\n else\n result = { :concept => response.choice.concept,\n :confidence => response.choice.confidence,\n :interpretation => response.choice.interpretation,\n :tag => response.choice.tag }\n end\n AGI_SUCCESS_PREFIX + result.to_json + \"\\n\"\n rescue => e\n log_error(this_method, e)\n end", "def coin_toss_intro\n self.player_turn_number = 0\n coin_toss_result = toss_coin\n player_coin_guess = human_player.intro_coin_guess\n player_coin_guess == coin_toss_result ? who_goes_first = \"Player\" : who_goes_first = \"Computer\"\n self.player_turn_number = 1 if who_goes_first == \"Player\"\n puts \"The result of the toss was #{coin_toss_result}, and you guessed #{player_coin_guess}.\"\n puts who_goes_first == \"Player\" ? \"The Player goes first!\" : \"The Computer goes first!\"\n end", "def ask(options={})\n check_state\n \n options[:args][:recognizer] = @tropo_recognizer if options[:args]['recognizer'].nil?\n options[:args][:voice] = @tropo_voice if options[:args]['voice'].nil?\n \n # Check for Asterisk sounds\n asterisk_sound_url = fetch_asterisk_sound(options[:args]['prompt'])\n if asterisk_sound_url\n prompt = asterisk_sound_url\n else\n prompt = options[:args]['prompt']\n end\n \n response = @current_call.ask prompt, options[:args]\n if response.value == 'NO_SPEECH' || response.value == 'NO_MATCH'\n result = { :interpretation => response.value }\n else\n result = { :concept => response.choice.concept,\n :confidence => response.choice.confidence,\n :interpretation => response.choice.interpretation,\n :tag => response.choice.tag }\n end\n @agi_response + result.to_json + \"\\n\"\n rescue => e\n log_error(this_method, e)\n end", "def hit_or_stay\n puts \"Would you like to hit, stay or doubledown\"\n input = gets.chomp.to_s\n input.upcase!\n @dealer.update_deck if @deck.cards_left < 1 # Rebuilds deck if empty\n if input == \"HIT\" || input == \"H\"\n @player.hand.hit\n show_player_hand\n return if @player.hand.bust # Escapes recursion if the player busts\n hit_or_stay_cont\n elsif input == \"STAY\" || input == \"S\"\n puts \"You stand\"\n elsif input == \"DOUBLEDOWN\" || input == \"D\"\n @player.hand.hit\n @player.double_down\n show_player_hand\n else\n puts \"Invalid input.\"\n hit_or_stay\n end\n end", "def printAskUserInstr(player,dealer,hand)\n puts dealer.printHands(true)\n puts player.printHands\n puts \"Player \" + player.getName + \", what would you like to do on Hand \" + hand.getName + \"?\"\n if hand.isFirstTurn and (player.getHands.length == 1)\n puts \"'dd'=doubledown 'split'=split 'surr'=surrender 'hit'=hit 'stay'=stay\"\n elsif hand.isFirstTurn and player.canSplit\n \tputs \"dd'=doubledown 'split'=split 'hit'=hit 'stay'=stay\"\n elsif hand.isFirstTurn\n puts \"dd'=doubledown 'hit'=hit 'stay'=stay\"\n else\n puts \"'hit'=hit 'stay'=stay\"\n end\nend", "def hit\n @printer = []\n @printer << \"You Hit.\"\n deal_player\n pl_total\n if session[:player].bust? || session[:player].hand_total == 21\n @action = :end\n run_dealer\n else\n @action = :choice\n end\n chat\n end", "def hitter(hitter)\n\t\t\tif $hitter == @player1\n\t\t\t\tself.hitter1\n\t\t\t\tself.rally\n\t\t\telse \n\t\t\t\tself.hitter2\n\t\t\t\tself.rally\n\t\t\tend\n\t\tend", "def asking\n call(\"ASKING\")\n end", "def prompt_hit_or_stay\n puts \"\\nWould you like to (1) hit or (2) stay?\"\n response = gets.chomp\n while response != \"1\" && response != \"2\"\n puts \"Please choose either (1) for hit or (2) for stay.\"\n response = gets.chomp\n end\n return response\n end", "def do_player_hit_stay(is_stay, players_hand, dealers_hand, deck)\n if is_stay\n return\n else\n display_hands(players_hand, dealers_hand, false)\n if get_score(players_hand) == 21\n puts \"Blackjack! You win!\"\n return \"win\"\n end\n\n puts \"Enter 'stay' to stay or 'hit' to receive another card.\"\n is_stay = gets.chomp == \"hit\" ? false : true\n \n if(!is_stay)\n deal_card(players_hand, deck)\n\n #Check if we've won or lost on hit\n if get_score(players_hand) > 21\n puts \"Bust! You lose\"\n display_hands(players_hand, dealers_hand, true)\n return \"loss\"\n elsif get_score(players_hand) == 21\n puts \"Blackjack! You win!\"\n display_hands(players_hand, dealers_hand, true)\n return \"win\"\n else #if not, loop back\n do_player_hit_stay(is_stay, players_hand, dealers_hand, deck)\n end\n end\n end\nend", "def answer_call\n call = ServiceCall.where(:status => 'waiting').order(\"updated_at\").first\n # call = calls.first\n if call\n call.status = 'connecting'\n call.user = self\n call.save\n\n # This representative is answering the call \n self.update_attributes(:status => \"connecting\")\n self.delay_check_call_status(call)\n \n Pusher.trigger(\"private-audio-#{self.id}\", 'client-connecting', nil)\n return call\n else\n return nil\n end\n end", "def coin2\n print \"Heads or tails?\"\n guess = gets.chomp\n options = [\"Heads\", \"Tails\"]\n pc_choice = options.sample\n puts \"The computer flipped #{pc_choice.upcase}\"\n \n if pc_choice == \"Heads\"\n if guess == \"Heads\"\n puts \"You guessed correctly!\"\n else\n puts \"You guess incorrectly.\"\n end\n end\n if pc_choice == \"Tails\"\n if guess == \"Tails\"\n puts \"You guessed correctly!\"\n elsif guess == \"Heads\"\n puts \"You guessed incorrectly.\"\n end\n end\nend", "def make_call call, player = nil\n assert_call(call.class)\n # Calls must be distinct.\n raise InvalidCallError, \"#{call.inspect} is invalid\" unless self.valid_call?(call)\n\n self.calls << call\n if self.complete? and not self.passed_out?\n self.contract = Contract.new(self)\n end\n true\n end", "def hit?(card_total)\n prompt_user\n player_choice = get_user_input\n if player_choice == \"h\"\n card_total = deal_card + card_total # or 'card_total += deal_card'\n elsif player_choice == \"s\"\n card_total # do not update 'card_total'\n else\n invalid_command(card_total) # other input will call #hit? again\n end\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tossresults takes a call as argument passes it to the results of a call to the cointoss method then determines a winner of the toss
def toss_results(call) toss = self.cointoss toss_string ="you called #{call} and the toss returned #{toss}." if call == toss puts toss_string puts "you won the coin toss." puts "You get to serve first." puts " " self.hitter2 server(@player1) elsif call != toss puts toss_string puts "you lost the coin toss." puts "#{@player2} will serve first." puts " " self.hitter1 server(@player2) else "error" end end
[ "def coin_toss\n puts \"#{@new_game.player_1.name}, heads or tails?\"\n if @new_game.player_1.is_a?(Computer)\n call = [\"heads\", \"tails\"].sample\n puts \"#{@new_game.player_1.name} selects #{call}.\"\n else\n call = gets.chomp\n call.downcase\n # binding.pry\n end\n if call == \"heads\"\n coin = rand(1..2)\n call = 1\n if call == coin\n @new_game.player_1.go_first = true\n puts \"#{@new_game.player_1.name} won the toss.\"\n else\n @new_game.player_2.go_first = true\n puts \"#{@new_game.player_2.name} won the toss.\" \n # eval_board\n end\n elsif call == \"tails\"\n coin = rand(1..2)\n call = 2\n if call == coin\n @new_game.player_1.go_first = true\n puts \"#{@new_game.player_1.name} won the toss.\"\n else\n @new_game.player_2.go_first = true\n puts \"#{@new_game.player_2.name} won the toss.\" \n # eval_board\n end\n else\n puts \"Invalid answer\"\n coin_toss\n end\n @new_game.coin_toss\n end", "def coin_toss_call\n\t\t\tputs \"Please call 'heads' or 'tails'\"\n\t\t\tcall = gets.chomp.downcase\n\t\t\tunless call == 'heads' || call == 'tails'\n\t\t\t\tputs \"response not understood. Hit 't' to try again.\"\n\t\t\t\tresponse = gets.chomp.downcase\n\t\t\t\tif response == \"t\"\n\t\t\t\t\tself.coin_toss_call\n\t\t\t\telse\n\t\t\t\t\tputs \"exiting game.\"\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tself.toss_results(call)\n\t\t\tend\n\t\tend", "def set_results_winner\n if @player_one_wins > @player_two_wins\n return \"\\nPlayers one is the is the winner of the set!\"\n else\n return \"\\nPlayer two is the winner of the set!\"\n end \n end", "def result(you, them, win_lose_or_draw)\n end", "def report_results(winner_name)\n @players.each do |player_name, socket|\n if player_name == winner_name\n result = \"Win\"\n else\n result = \"Loss\"\n end\n score = rand(1...5) #meaningless\n result_string = player_name.strip + \"|\" + result + \"|\" + score.to_s\n @wrapper_connection.puts(result_string)\n end\n return\n end", "def tournament_winner(competitions, results)\n champion = ''\n scores = { champion => 0 }\n competitions.each_with_index do |competition, index|\n result = results[index]\n home_team, away_team = competition\n winner = result.zero? ? away_team : home_team\n\n # initialize winner score to 0, if it is not in hash\n scores[winner] = 0 unless scores.has_key? winner\n scores[winner] = scores[winner] + 3\n\n # update overall winner if scores of current winner are more\n champion = winner if scores[champion] < scores[winner]\n end\n champion\nend", "def processResults\n passed = false\n msg = nil\n if @enteredHIGH == true && @enteredLOW == true\n passed = true \n msg = \"THREATCON_LEVEL increased and decreased with respect to the number of login failures\"\n elsif @enteredHIGH == true\n msg = \"THREATCON_LEVEL increased but did not decrease after login failures decreased\" \n elsif @enteredLOW == true\n msg = \"THREATCON_LEVEL decreased but did not increase after login failures increased\"\n else\n msg = \"THREATCON_LEVEL did not change as a result of an increase or decrease in login failures\"\n end\n saveResult(passed, \"Stress3e1\", msg)\n saveResult(passed, \"Stress3e2\", msg)\nend", "def take_turns(players)\n\t\toutcome = \"tie\"\n\t\twhile outcome == \"tie\"\n\t\t\tputs \"\\n\\nROCK * PAPER * SCISSORS * SHOOT\\n\\n\"\n\t\t\ti = 0\n\t\t\twhile i < 2\n\t\t\t\t\tputs \"\\n#{players[i].name} it is your turn\"\n\t\t\t\t\tplayers[i].move = players[i].move + players[i].enter_toss\n\t\t\t\t\ti += 1\n\t\t\tend\n\t\t\toutcome = Rule.new.determine_outcome_from_tosses(players[0].last_move, players[1].last_move)\n\t\tend\n\t\toutcome\n\tend", "def create_competition_results_for(results, race)\n competition_result = nil\n for source_result in results\n logger.debug(\"#{self.class.name} scoring result: #{source_result.event.name} | #{source_result.race.name} | #{source_result.place} | #{source_result.name} | #{source_result.team_name}\") if logger.debug?\n # e.g., MbraTeamBar scoring result: Belt Creek Omnium - Highwood TT | Master A Men | 4 | Steve Zellmer | Northern Rockies Cycling\n\n # I don't need this now: no allowance for TTT or tandem teams with members of multiple teams\n # teams = extract_teams_from(source_result)\n # logger.debug(\"#{self.class.name} teams for result: #{teams}\") if logger.debug?\n # for team in teams\n\n if member?(source_result.team, source_result.date)\n\n if first_result_for_team?(source_result, competition_result)\n # Bit of a hack here, because we split tandem team results into two results,\n # we can't guarantee that results are in team-order.\n # So 'first result' really means 'not the same as last result'\n # race here is the category in the competition\n competition_result = race.results.detect {|result| result.team == source_result.team}\n competition_result = race.results.create(:team => source_result.team) if competition_result.nil?\n end\n\n # limit to top two results for team for each source race by \n # removing the lowest score for the event after every result.\n # I do it this way because results do not arrive in postion order.\n # SQL sorting does not work as position is a varchar field.\n score = competition_result.scores.create(\n :source_result => source_result,\n :competition_result => competition_result,\n :points => points_for(source_result).to_f #/ teams.size\n )\n this_points = score.points\n logger.debug(\"#{self.class.name} competition result: #{competition_result.event.name} | #{competition_result.race.name} | #{competition_result.place} | #{competition_result.team_name}\") if logger.debug?\n # e.g., MbraTeamBar competition result: 2009 MBRA BAT | Master A Men | | Gallatin Alpine Sports/Intrinsik Architecture\n scores_for_event = competition_result.scores.select{ |s| s.source_result.event.name == source_result.event.name}\n if scores_for_event.size > 2\n competition_result.scores.delete(scores_for_event.min { |a,b| a.points <=> b.points })\n end\n end\n end\n end", "def add_results(t)\n results.each do |r|\n t.add_result(r.round, r.player_id, r.opponent_id, r.result) if r.rateable\n end\n end", "def evaluate_board_for_results\n player1_move_positions = self.moves_by_player[:player1].map{|move| [move.row, move.column]}\n player2_move_positions = self.moves_by_player[:player2].map{|move| [move.row, move.column]}\n if Game.winner_combinations.any?{|streak| streak.all?{|position| player1_move_positions.include? position}}\n self.update(:winner_identifier => self.player1_identifier)\n elsif Game.winner_combinations.any?{|streak| streak.all?{|position| player2_move_positions.include? position}}\n self.update(:winner_identifier => self.player2_identifier)\n end\n self.update(:complete => true) if self.game_over?\n end", "def results(round, first, second)\n puts \">> Round #{round} results:\"\n puts \">> #{@player1.name}: #{first}\"\n puts \">> #{@player2.name}: #{second}\"\n end", "def output_results(winner, winning_player)\n if winner\n puts \"The game is over. #{winning_player} has won!\"\n else\n puts 'Game over, no winner!!'\n end\nend", "def display_results(player, computer, result)\r\n\r\n #Display arguments passed to the method using the following template\r\n Console_Screen.cls #Clear the display area\r\n puts \"\\n\\n\\t\\t\\tRESULTS:\"\r\n puts \"\\n\\n\\t\\t\\t================================\"\r\n puts \"\\n\\n\\t\\t\\tPlayer's move: \" + player\r\n puts \"\\n\\n\\t\\t\\tComputer's move: \" + computer\r\n puts \"\\n\\n\\t\\t\\tResult: \" + result\r\n puts \"\\n\\n\\t\\t\\tGames played: #{$gameCount}\"\r\n puts \"\\n\\n\\t\\t\\tWins: #{$wins}\"\r\n puts \"\\n\\n\\t\\t\\tLosses: #{$lost}\"\r\n puts \"\\n\\n\\t\\t\\tTies: #{$tied}\"\r\n puts \"\\n\\n\\t\\t\\t================================\"\r\n puts \"\\n\\n\\n\\n\"\r\n puts \"\\a\"\r\n print \"Press Enter to continue. \"\r\n Console_Screen.pause #Pause the game\r\n\r\n end", "def successes(min = 8, reroll = 10, subtract = false)\n count = 0\n rote = false\n\n # if this result set has already been rerolled, simply count the successes\n # in the result and return the total (rather than rerolling /again/)\n if @rerolled\n @ten_result.each do |value|\n count += 1 if value >= min\n end\n\n return count\n end\n\n if reroll == 0\n reroll = 10\n rote = true\n end\n\n # this bonus dice is used for any rerolls that accrue\n bonus_dice = ::DiceRoller::Dice.new(sides = 10)\n\n # reroll failed dice once and add the results to the array\n if rote\n rote_rerolls = []\n\n @ten_result.each do |result|\n rote_rerolls << bonus_dice.roll if result < min\n end\n\n @ten_result += rote_rerolls\n end\n\n # loop through the rolled results and count successes. values greater than\n # the reroll value are rolled again.\n final_result = []\n\n @ten_result.each do |dice|\n this_dice = [dice]\n\n this_dice.each do |result|\n count += 1 if result >= min\n count -= 1 if subtract and result == 1\n\n # each pass through this loop is a rerolled dice\n if result >= reroll\n bonus_result = bonus_dice.roll\n\n # add the reroll result to the current dice's results, this will\n # reroll as appropriate\n this_dice << bonus_result\n end\n end\n\n final_result += this_dice\n end\n\n @ten_result = final_result\n @rerolled = true\n count\n end", "def analyze_results(player, computer)\r\n\r\n # Player choses ROCK\r\n if player == \"ROCK\" then\r\n return \"Player wins!\" if computer == \"SCISSORS\"\r\n return \"Tie!\" if computer == \"ROCK\" \r\n return \"Computer wins!\" if computer == \"PAPER\" \r\n end\r\n\r\n # Player choses PAPER\r\n if player == \"PAPER\" then\r\n return \"Player wins!\" if computer == \"ROCK\"\r\n return \"Tie!\" if computer == \"PAPER\" \r\n return \"Computer wins!\" if computer == \"SCISSORS\" \r\n end\r\n\r\n # Player choses SCISSORS\r\n if player == \"SCISSORS\" then\r\n return \"Player wins!\" if computer == \"PAPER\"\r\n return \"Tie!\" if computer == \"SCISSORS\" \r\n return \"Computer wins!\" if computer == \"ROCK\" \r\n end\r\n end", "def snitch_sequence(team1_roster, team2_roster, scores, teams)\n puts \"[TANNE LEGIN]\\nWait! They're closing in on the snitch!\"\n `say \"Wait! They're closing in on the snitch!\"`\n puts \"\\n\"\n puts \"[CLIFTON HAZELNUTS]\\nWho will get there?\"\n `say \"Who will get there?\"`\n puts \"\\n\"\n puts \"[TANNE LEGIN]\\nIt's gonna be close...\"\n `say \"It's gonna be close...\"`\n puts \"\\n\"\n puts \"[CLIFTON HAZELNUTS]\\nLook!\"\n `say \"Look!\"`\n puts \"\\n\"\n snitch_roll = rand(5)\n seekers = [ seeker(team1_roster), seeker(team2_roster) ]\n if snitch_roll < 2\n if scores[snitch_roll] == scores[1 - snitch_roll] - 150 && scores[0] + scores[1] > 200\n # if scores[0] == scores[1] - 150 && scores[0] + scores[1] > 100\n scores[snitch_roll] = scores[snitch_roll] + 150\n puts \"[TANNE LEGIN]\\n#{seekers[snitch_roll]} has caught the golden snitch for #{teams[snitch_roll]}! 150 points and the tie!\"\n `say \"#{seekers[snitch_roll]} has caught the golden snitch for #{teams[snitch_roll]}! 150 points and the tie!\"`\n caught = true\n elsif scores[snitch_roll] > scores[1 - snitch_roll] - 150\n # elsif scores[0] > scores[1] - 150\n scores[snitch_roll] = scores[snitch_roll] + 150\n puts \"[TANNE LEGIN]\\n#{seekers[snitch_roll]} has caught the golden snitch for #{teams[snitch_roll]}! 150 points and the win!\"\n `say \"#{seekers[snitch_roll]} has caught the golden snitch for #{teams[snitch_roll]}! 150 points and the win!\"`\n caught = true\n else\n puts \"[TANNE LEGIN]\\n#{seekers[snitch_roll]} on #{teams[snitch_roll]} blocks #{seekers[1 - snitch_roll]} from getting the golden snitch and the win for #{teams[1 - snitch_roll]}!\"\n `say \"#{seekers[snitch_roll]} on #{teams[snitch_roll]} blocks #{seekers[1 - snitch_roll]} from getting the golden snitch and the win for #{teams[1 - snitch_roll]}!\"`\n caught = false\n end\n else\n lost_snitch = [ \"The seekers have collided and fallen off their brooms! What a disaster. The snitch has vanished.\", \"They're diving for the ground. And they hit it! The snitch didn't though. On we go.\", \"Look at that! A bludger just smacked them both off the trail. The snitch escapes!\", \"They just stopped. Maybe the sun got in their eyes? That's just bad seeking, but the snitch has faded back into oblivion.\" ]\n lost_statement = lost_snitch[rand(lost_snitch.size)]\n puts \"[TANNE LEGIN]\\n#{lost_statement}\"\n `say \"#{lost_statement}\"`\n caught = false\n end\n caught\nend", "def triple_crown\n @year = params[:year]\n stats = BattingStatistic.where(year: @year, :home_runs.gt => 0, \n :runs_batted_in.gt => 0, :games_played.gt => 150)\n \n @ba_list = stats.where(batting_average: stats.max(:batting_average))\n @rbi_list = stats.where(runs_batted_in: stats.max(:runs_batted_in))\n @hr_list = stats.where(home_runs: stats.max(:home_runs))\n \n # Go throught home run list and check to see if any players are on\n # the other two lists.\n tc_winner = []\n @hr_list.each do |hrstat|\n if @ba_list.count > 1\n bastat = @ba_list.where(player_id: hrstat.player_id).first\n elsif @ba_list.count == 1\n bastat = @ba_list.first if @ba_list.first.player_id == hrstat.player_id\n else\n bastat = nil\n end\n \n if @rbi_list.count > 1\n rbistat = @rbi_list.where(player_id: hrstat.player_id).first\n elsif @rbi_list.count == 1\n rbistat = @ba_list.first if @rbi_list.first.player_id == hrstat.player_id\n else\n rbistat = nil\n end\n\n # Check to see if we have a winner\n if bastat.present? and rbistat.present?\n tc_winner << hrstat.player_id\n end\n end\n\n @player = tc_winner.present? ? Player.where(player_id: tc_winner[0]).first : nil\n @stats = stats.where(player_id: tc_winner[0]).first\n \n end", "def ot_tossups(game)\n\t\tunless (game.tossups.length - 20) > 0\n\t\t\t# no ot happened.\n\t\t\treturn \"0\\r\\n0\\r\\n0\\r\\n\"\n\t\telse\n\t\t\tteama=0\n\t\t\tteamb=0\n\t\t\tgame.tossups[20..-1].each{\n\t\t\t\tteama += 1 if tossup[:buzzes][0].any? {|b| b > 0 }\n\t\t\t\tteamb += 1 if tossup[:buzzes][1].any? {|b| b > 0 }\n\t\t\t}\n\t\t\treturn \"1\\r\\n#{teama}\\r\\n#{teamb}\\r\\n\"\n\t\tend\n\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
cointoss generates a random number between 1 and 10 and saves it in the 'number' variable. If the number generated is less than or equal to five the method returns "heads". If the random number is greater than 5 coin toss returns "tails."
def cointoss number = rand(1..10) return "heads" if number <= 5 return "tails" if number > 5 end
[ "def coin_toss\n toss = SecureRandom.random_number(2)\n if toss == 0\n HEADS_VALUE\n else\n TAILS_VALUE\n end\n end", "def coin_toss\n puts \"#{@new_game.player_1.name}, heads or tails?\"\n if @new_game.player_1.is_a?(Computer)\n call = [\"heads\", \"tails\"].sample\n puts \"#{@new_game.player_1.name} selects #{call}.\"\n else\n call = gets.chomp\n call.downcase\n # binding.pry\n end\n if call == \"heads\"\n coin = rand(1..2)\n call = 1\n if call == coin\n @new_game.player_1.go_first = true\n puts \"#{@new_game.player_1.name} won the toss.\"\n else\n @new_game.player_2.go_first = true\n puts \"#{@new_game.player_2.name} won the toss.\" \n # eval_board\n end\n elsif call == \"tails\"\n coin = rand(1..2)\n call = 2\n if call == coin\n @new_game.player_1.go_first = true\n puts \"#{@new_game.player_1.name} won the toss.\"\n else\n @new_game.player_2.go_first = true\n puts \"#{@new_game.player_2.name} won the toss.\" \n # eval_board\n end\n else\n puts \"Invalid answer\"\n coin_toss\n end\n @new_game.coin_toss\n end", "def coin_toss_call\n\t\t\tputs \"Please call 'heads' or 'tails'\"\n\t\t\tcall = gets.chomp.downcase\n\t\t\tunless call == 'heads' || call == 'tails'\n\t\t\t\tputs \"response not understood. Hit 't' to try again.\"\n\t\t\t\tresponse = gets.chomp.downcase\n\t\t\t\tif response == \"t\"\n\t\t\t\t\tself.coin_toss_call\n\t\t\t\telse\n\t\t\t\t\tputs \"exiting game.\"\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tself.toss_results(call)\n\t\t\tend\n\t\tend", "def winning_numbers(c)\n\t#c is the number of digits of the ticket entered\n\t\n\twinners = []\n\n\t5.times do\n\t\t#creates a random number with c digits and pushes that to array\n\t\twinners.push(\"#{rand(10 ** c).to_s.rjust(c, '0')}\")\n\tend\n\n\t#end up with five strings of winning numbers of c digits in an array\n\twinners\nend", "def hoop_count n\n\tn >= 10 ? \"Great, now move on to tricks\" : \"Keep at it until you get it\"\nend", "def drink_coffee(cups=1)\n\t\tcups.times do\n\t\t\t@caffeine_level += rand(0..20)\n\t\tend\n\t\tputs \"#{@name} drank #{cups} cup(s) of coffee and has a caffeiene level of #{@caffeine_level}\"\n\t\tif @caffeine_level > 200\n\t\t\tputs \"#{@name} has reached caffeine critical mass.\"\n\t\telsif @caffeine_level > 100\n\t\t\tputs \"#{@name} is excited.\"\n\t\telse\n\t\t\tputs \"#{@name} could use a Redbull.\"\n\t\tend\n\tend", "def snake_eyes\n random = Random.new\n counter = 0\n 100.times do\n first_dice = random.rand(1...6)\n second_dice = random.rand(1...6)\n if (first_dice == 1 && second_dice == 1)\n counter += 1\n end\n end\n puts counter\nend", "def less_donuts(number)\n if number < 3\n \"Good job, Homer!\"\n elsif number == 3\n \"Slow down!\"\n else number > 3\n \"Get back on your diet!\"\n end\nend", "def tenders_rand()\n\tif Random.rand(7) == 0 #achieves 1/7 probability\n\t\t\"It's Chicken Tenders Day!\" \n\telse \n\t\t\"Nope.\"\n\tend\nend", "def buzz number\n \"BUZZ\" if number % 5 == 0\n end", "def tenders_flip()\n\tif Random.rand(2) == 0 #achieves 50/50 probability\n\t\t\"It's Chicken Tenders Day!\" \n\telse \n\t\t\"Nope.\"\n\tend\nend", "def print_thrice_thrice(number)\n 3.times do\n print_thrice(number)\n end\n end", "def CoinDeterminer(num)\n coins = [1,1,1,1,1,1,5,5,5,5,5,7,7,7,7,7,7,9,9,9,9,9,9,11,11,11,11,11,11].reject{|coin| coin > num}\n \n return 1 if coins.include?(num)\n if coins.combination(2).map{|set| set.inject(:+)}.include?(num)\n return 2\n elsif coins.combination(3).map{|set| set.inject(:+)}.include?(num)\n return 3\n elsif coins.combination(4).map{|set| set.inject(:+)}.include?(num)\n return 4\n elsif coins.combination(5).map{|set| set.inject(:+)}.include?(num)\n return 5\n end\nend", "def gets_random_10\n\n count = 0\n\nwhile count < 10\n @num = rand(9)\n divider = \"=========\"\n\n\n if @num == 0\n puts divider\n puts \"#{@num}\" + \" we've got 0\"\n\n elsif @num.odd?\n @result = \"#{@num}\" + \" the number is odd\"\n puts divider\n check_if_five_exists\n elsif @num.even?\n puts divider\n @result = \"#{@num}\" + \" the number is even\"\n check_if_five_exists\n else\n puts \"I can't guess the number\"\n end\n\n count += 1\nend\nend", "def chance(c)\n return rand < c\nend", "def toss_results(call)\n\t\t\ttoss = self.cointoss\n\t\t\ttoss_string =\"you called #{call} and the toss returned #{toss}.\"\n\t\t\tif call == toss\n\t\t\t\tputs toss_string\n\t\t\t\tputs \"you won the coin toss.\"\n\t\t\t\tputs \"You get to serve first.\"\n\t\t\t\tputs \" \"\n\t\t\t\tself.hitter2\n\t\t\t\tserver(@player1)\n\t\t\telsif call != toss\n\t\t\t\tputs toss_string\n\t\t\t\tputs \"you lost the coin toss.\"\n\t\t\t\tputs \"#{@player2} will serve first.\"\n\t\t\t\tputs \" \"\n\t\t\t\tself.hitter1\n\t\t\t\tserver(@player2)\n\t\t\telse\n\t\t\t\t\"error\"\n\t\t\tend\n\t\tend", "def cheat( number )\n if number.between?(1,6)\n @number_showing = number\n else\n puts \"You are not a very smart cheater.\"\n end\n end", "def probability chance=5\n (rand(10)+1) <= chance\nend", "def bottle(n)\n if n == 1 then 'bottle' else 'bottles' end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
game action uses a random number to determine the result of ball serves. a random number between 5 and 15 is set as a net ball meaning the ball is stopped by the net and does not make it to the other court
def game_action(num) net_ball = rand(5..15) return "net" if num == net_ball return "oob" if num <= 3 return "hit" if num > 3 && num <=17 return "miss" if num > 17 end
[ "def rally\n\t\t\tnum = rand(1..20)\n\t\t\trally_case = game_action(num)\n\t\t\tcase rally_case\n\t\t\t\twhen \"oob\" \n\t\t\t\t\tputs \"oo-oo-oo-oo-oo #{$hitter} hit the ball out of bounds oo-oo-oo-oo-oo\"\n\t\t\t\t\t@current_game.wins_ball($def_num)\n\t\t\t\t\tself.game_stats\n\t\t\t\t\n\t\t\t\twhen \"miss\"\n\t\t\t\t\tputs \"mmmmmmm #{$defender} missed the ball! mmmmmmmmmm\"\n\t\t\t\t\t@current_game.wins_ball($hit_num)\n\t\t\t\t\tself.game_stats\n\t\t\t\t\t\n\t\t\t\twhen \"net\"\n\t\t\t\t\tputs \"############ #{$hitter} hit the net. ############\"\n\t\t\t\t\t@current_game.wins_ball($def_num)\n\t\t\t\t\tself.game_stats\n\t\t\t\t\t\n\t\t\t\twhen \"hit\"\n\t\t\t\t\tputs \"^o^o^o^o^o^ #{$defender} returns the ball ^o^o^o^o^o^\"\n\t\t\t\t\tputs \" \"\n\t\t\t\t\thitter($hitter)\n\t\t\t\n\t\t\t\telse\n\t\t\t\t\tputs \"#{rally} Error!!!\"\n\t\t\t\tend\n\t\t\t\t\n\t\t\tend", "def actionAI\n rand(3)\n end", "def get_rand_ball\n\t\tfor i in 0...10\n\t\t\tneeds_regen = false\n\t\t\t\n\t\t\tnew_ball = Ball.new(@random.rand(0..$win_width), @random.rand(0..$win_height), 2, 2)\n\t\t\t@balls.each do |ball|\n\t\t\t\tneeds_regen = true if new_ball.get_distance(ball) < new_ball.radius * 6\n\t\t\tend\n\t\t\t\n\t\t\treturn new_ball if !needs_regen || i == 9\n\t\tend\n\tend", "def hit_rate\n rand(100)\n end", "def battle_random_bot\n\n end", "def generateBrilliant\r\n @brilliant = true\r\n # 2- 6 max IVs\r\n maxIVs = @iv.keys.sample(2 + (rand(@iv.keys.length) - 2))\r\n maxIVs.each { |s| @iv[s] = Pokemon::IV_STAT_LIMIT }\r\n # Higher Avg Level\r\n @level += (2 + rand(5))\r\n # Knows Egg Move\r\n babyspecies = species_data.get_baby_species\r\n eggmoves = GameData::Species.get_species_form(babyspecies,form_simple).egg_moves\r\n move = eggmoves.sample\r\n learn_move(move); add_first_move(move)\r\n # Has a chance to be shiny\r\n shinyBoost = $Trainer.pokedex.number_battled_brilliant_shiny(@species)\r\n random = rand(65536)\r\n shinyChance = Settings::SHINY_POKEMON_CHANCE * shinyBoost\r\n echoln \"#{random}, #{shinyChance}\"\r\n if random < shinyChance\r\n @shiny = true\r\n self.square_shiny = true if random < (shinyChance/16)\r\n end\r\n end", "def move_type_random\r\n # Branch by random numbers 0-5\r\n case rand(6)\r\n when 0..3 # Random\r\n move_random\r\n when 4 # 1 step forward\r\n move_forward\r\n when 5 # Temporary stop\r\n @stop_count = 0\r\n end\r\n end", "def play\n 2.times {deal}\n blind_score\n if player_hand.collect{|x| x.value}.inject(:+) == 21\n bjwin\n elsif computer_hand.collect{|x| x.value}.inject(:+) == 21\n bjlose\n else\n action\n end\n end", "def move_type_random\n # Branch by random numbers 0-5\n case rand(6)\n when 0..3 # Random\n move_random\n when 4 # 1 step forward\n move_forward\n when 5 # Temporary stop\n @stop_count = 0\n end\n end", "def simulate_game(n, strategy)\n success = 0.0\n\n n.times do\n doors = [ :nothing, :nothing, :treasure ].shuffle\n guess = rand(3)\n begin\n shown = rand(3)\n end while shown == guess || doors[shown] == :treasure\n\n decision = self.send(strategy, guess, shown)\n\n if doors[decision] == :treasure\n success += 1\n end\n end\n\n success\n end", "def move_type_random\n # Branch by random numbers 0-5\n case rand(6)\n when 0..3 # Random\n move_random\n when 4 # 1 step forward\n move_forward\n when 5 # Temporary stop\n @stop_count = 0\n end\n end", "def enemy_spawned\n @enemy_chance > rand(100)\n end", "def preemptive_or_surprise\n actors_agi = $game_party.average_agi\n enemies_agi = $game_troop.average_agi\n if actors_agi >= enemies_agi\n percent_preemptive = 5\n percent_surprise = 3\n else\n percent_preemptive = 3\n percent_surprise = 5\n end\n if rand(100) < percent_preemptive\n $game_troop.preemptive = true\n elsif rand(100) < percent_surprise\n $game_troop.surprise = true\n end\n end", "def movement\n action = rand(4)\n if action == 0\n return 'towards'\n elsif action == 1\n return 'away_from'\n elsif action == 2\n return 'random'\n elsif action == 3\n return 'ignore'\n else\n puts \"RANDOM FUNCTION INCORRECT\"\n exit\n end\n end", "def defend(user, opponent)\n random = rand(100)\n chance_to_hit = opponent.hit_percent\n if chance_to_hit >= random\n #puts \"The enemy took damage\"\n defend_attack(user, opponent)\n else \n puts \"#{opponent.name} missed!\".yellow\n end \nend", "def hit\n coin = spawn :coin, :x => x, :y => y-40\n coin.collect\n\n @active = false\n @inactive_timer = HIT_RATE if has_more?\n end", "def hatch\n @status = Idle\n @target = nil\n @virility = 0\n babies = []\n rand(MaxBabiesFromEgg).to_i.times {babies << baby_salmon}\n babies\n end", "def tuna_boats()\n tuna_haul ||= (1 + rand(6)) + (1 + rand(6))\n puts \"TUNA BOAT POWER!!!\"\n @log.add(__callee__,\"Looks like Tuna Boats! The roll is #{tuna_haul}\")\n return tuna_haul\n end", "def random\n CYCLE * rand\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method switches which player is the hitter and which is returning the ball Once a player hits the ball they become the "hitter" and the other player becomes the defender. It also associates player number with "hitter" and "defender" so that the score can be tracked.
def hitter(hitter) if $hitter == @player1 self.hitter1 self.rally else self.hitter2 self.rally end end
[ "def switch_players\n \n if @current_asker == @player1\n @current_asker = @player2\n @current_responder = @player1\n else\n @current_asker = @player1\n @current_responder = @player2\n end\n\n end", "def wins_ball(winner)\n if winner == 1\n winning_player = @player1\n elsif winner == 2\n winning_player = @player2\n end\n \n winning_player.record_won_ball!\n end", "def wins_ball(winner)\n if winner == 1\n winning_player = @player1\n else\n winning_player = @player2\n end\n\n winning_player.record_won_ball!\n end", "def populate_winner\n if competitor_1_score > competitor_2_score\n self.winner_id = match.get_competitor_1.id\n elsif competitor_1_score < competitor_2_score\n self.winner_id = match.get_competitor_2.id\n else\n self.winner_id = nil\n end\n end", "def get_loser\n if self.hero_1_id != self.winner_id\n self.hero_1_id\n else \n self.hero_2_id\n end\n end", "def update_blinds\n if players.size == 2\n small_blind_player = dealer\n else\n small_blind_player = next_player(dealer)\n end\n big_blind_player = next_player(small_blind_player)\n \n @small_blind_position = @players.index(small_blind_player)\n @big_blind_position = @players.index(big_blind_player)\n end", "def defendent_identifier\n (self.challenger_identifier == self.player1_identifier) ? self.player2_identifier : self.player1_identifier\n end", "def predict_winner(hacker1, hacker2)\n if hacker1.will_defeat?(hacker2)\n debug ' hacker1 will defeat hacker2'\n hacker1\n elsif hacker2.will_defeat?(hacker1)\n debug ' hacker2 will defeat hacker1'\n hacker2\n elsif hacker1.will_probably_defeat?(hacker2)\n debug ' hacker1 will probably defeat hacker2'\n hacker1\n else # hacker2.will_probably_defeat?(hacker2) is true in this case\n debug ' hacker2 will probably defeat hacker2'\n hacker2\n end\n end", "def game_over\n if player_1.hit_points == 0\n player_1\n elsif player_2.hit_points == 0\n player_2\n end\n end", "def switch_players\n temp = @current_player\n @current_player = @opposing_player\n @opposing_player = temp\n end", "def update_winning_team_id\n return unless score_team1 == 10 || score_team2 == 10\n if score_team1 > score_team2\n self.winning_team_id = team1_id\n elsif score_team2 > score_team1\n self.winning_team_id = team2_id\n end\n end", "def switch_players\n @current_player = @current_player == @player1 ? @player2 : @player1\n end", "def wins_ball(winner)\n # this is where we increment the winner of each ball by 1 point\n if winner == 1\n @player1.record_won_ball!\n #Player.record_won_ball!(@player1)\n elsif winner == 2\n @player2.record_won_ball!\n end\n\n # TODO: Think it's gross to pass an integer instead of a player object?\n # Then reimplement this method!\n end", "def switch_leader\n # store the old party leader\n leader = player\n # iterate \"number of party members\" times\n $game_party.actors.size.times {\n # change party leader\n $game_party.add_actor($game_party.actors.shift.id)\n # until finding one who's not dead\n break if $game_party.actors[0] != nil && !$game_party.actors[0].dead?}\n # stop if party leader has not changed\n return if leader == player\n # enforce emptying moving buffer and add special command\n update_buffer(nil)\n # center screen display on new player controlled character\n center(player.x, player.y, true) if $game_system.caterpillar\n # except if charging\n unless player.charging?\n # reset player action\n player.reset_action\n # reset player action counter\n player.in_action = 0\n end\n # except if charging\n unless leader.charging?\n # reset old leader action\n leader.reset_action\n # reset old leader action counter\n leader.in_action = 0\n end\n # set flag for HUD update\n $game_temp.hud_refresh = true\n end", "def loser=(player)\n process_result(player == player_one ? 0.0 : 1.0)\n end", "def wins_ball(player_num)\n \n if player_num == 1\n player1.record_won_ball!\n \n elsif player_num == 2\n player2.record_won_ball!\n\n else\n puts \"Please enter player number.\"\n end\n end", "def second_player\n singles_player_of_team second_team\n end", "def winner\n result == 1.0 ? challenger : challenged\n end", "def invoke_player_bet\n @turn = :player_bet\n @hands = 1\n @current_hand = 1\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method initiates a new serve and calls the rally method.
def new_serve(server) puts " " puts ">>>>>>>>>>>>> #{$hitter} serves the ball >>>>>>>>>>>>>>>" puts "hit any letter to continue 'q' to quit." puts "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" result = gets.chomp.downcase if result == 'q' puts "exiting game" else self.rally end end
[ "def serve\n @server.start\n end", "def execute\n @conn = RallyConnection.new\n @conn.connect\n end", "def create\n seth_server_rest.post_rest(\"data\", self)\n self\n end", "def serve!(overlord, name, plan)\n @overlord = overlord\n @name = name\n @plan = plan\n @logger = Medusa.logger.tagged(\"#{self.class.name} - #{name}\")\n\n @logger.debug(\"I serve you my Overlord!\")\n end", "def process(*args)\n init_srv\n super\n end", "def start\n service.pool_action uuid, :create\n end", "def start\n run_server\n accept_clients\n end", "def start\r\n # create a DRb 'front' object\r\n watir_provider = Watir::Provider.new(@browser_type)\r\n architecture = Config::CONFIG['arch']\r\n hostname = ENV['SERVER_NAME'] || %x{hostname}.strip\r\n\r\n # setup the security--remember to call before DRb.start_service()\r\n DRb.install_acl(ACL.new(@acls))\r\n\r\n # start the DRb Server\r\n drb_server = DRb.start_service(\r\n \"druby://#{@drb_server_host}:#{@drb_server_port}\") \r\n\r\n # obtain DRb Server uri\r\n @drb_server_uri = drb_server.uri\r\n @log.info(\"DRb server started on : #{@drb_server_uri}\")\r\n\r\n # create a service tuple\r\n @tuple = [\r\n :WatirGrid, \r\n :WatirProvider, \r\n watir_provider, \r\n 'A watir provider', \r\n hostname,\r\n architecture,\r\n @browser_type,\r\n UUID.new.generate\r\n ] \r\n\r\n # locate the Rinda Ring Server via a UDP broadcast\r\n @log.debug(\"Attempting to find ring server on : druby://#{@ring_server_host}:#{@ring_server_port}\")\r\n ring_server = Rinda::RingFinger.new(@ring_server_host, @ring_server_port)\r\n ring_server = ring_server.lookup_ring_any\r\n @log.info(\"Ring server found on : druby://#{@ring_server_host}:#{@ring_server_port}\")\r\n\r\n # advertise this service on the primary remote tuple space\r\n ring_server.write(@tuple, @renewer)\r\n\r\n # log DRb server uri\r\n @log.info(\"New tuple registered : druby://#{@ring_server_host}:#{@ring_server_port}\")\r\n\r\n # wait for explicit stop via ctrl-c\r\n DRb.thread.join if __FILE__ == $0 \r\n end", "def new\n @timer = Timer.new\n\n respond_with(@timer)\n end", "def run_init(response)\n if response[:statuscode] != 0\n @local_error = \"run request failed: #{response[:statusmsg]}\"\n end\n @serial = @collection.serial\n end", "def create\n @rally = current_user.rallies.build(rally_params)\n\n respond_to do |format|\n if @rally.save\n format.html { redirect_to @rally, notice: 'Rally was successfully created.' }\n format.json { render :show, status: :created, location: @rally }\n else\n format.html { render :new }\n format.json { render json: @rally.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @server_rack = ServerRack.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @server_rack }\n end\n end", "def create\n #@nexttimeslot = Nexttimeslot.new(nexttimeslot_params)\n resp = Faraday.get \"https://www.honestbee.tw/api/api/next_available_timeslot?storeId=#{nexttimeslot_params['store_id']}\\\n &latitude=#{nexttimeslot_params['latitude']}&longitude=#{nexttimeslot_params['longitude']}\"\n render :json => JSON.parse(resp.body)['timeslot']\n end", "def before_create\n start_thread { start_webserver }\n start_thread { start_regserver }\n end", "def create_server\n\t\treturn Hglib::Server.new( self.path.to_s )\n\tend", "def start(params = {})\r\n # create a DRb 'front' object\r\n watir_provider = Watir::Provider.new(@driver)\r\n @log.debug(\"Watir provider is : #{watir_provider}\")\r\n architecture = Config::CONFIG['arch']\r\n hostname = ENV['SERVER_NAME'] || %x{hostname}.strip\r\n\r\n # setup the security--remember to call before DRb.start_service()\r\n DRb.install_acl(ACL.new(@acls))\r\n\r\n # start the DRb Server\r\n drb_server = DRb.start_service(\r\n \"druby://#{@drb_server_host}:#{@drb_server_port}\")\r\n\r\n # obtain DRb Server uri\r\n @drb_server_uri = drb_server.uri\r\n @log.info(\"Provider started on : #{@drb_server_uri}\")\r\n\r\n # create a service tuple\r\n @tuple = [\r\n :WatirGrid,\r\n :WatirProvider,\r\n watir_provider,\r\n 'A watir provider',\r\n hostname,\r\n architecture,\r\n @driver,\r\n @browser_type\r\n ]\r\n\r\n # locate the Rinda Ring Server via a UDP broadcast\r\n @log.debug(\"Broadcast Ring Server : druby://#{@ring_server_host}:#{@ring_server_port}\")\r\n find_ring_server\r\n\r\n # advertise this service on the primary remote tuple space\r\n @ring_server.write(@tuple, @renewer)\r\n\r\n # log DRb server uri\r\n @log.info(\"Provider registered : #{@controller_uri}\")\r\n\r\n # wait for explicit stop via ctrl-c\r\n DRb.thread.join if __FILE__ == $0\r\n end", "def serve request, response, client, vhost\n @action.call(request, response, client, vhost) unless @action.nil?\n end", "def new\n @serverrack = Serverrack.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @serverrack }\n end\n end", "def serve_clients\n clients_arrive\n say_hello_to_clients\n perform_tasks_asked_by_clients\n while_other_clients_wait_in_line\n say_goodbye_to_clients\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method alternates which player is the server and then passes the new server to the new_serve method.
def switch_serve(server) if @current_game.check_status == "#{@player1} wins" || @current_game.check_status == "#{@player2} wins" self.new_game else if $server == @player1 $server = @player2 self.hitter1 else $server = @player1 self.hitter2 end new_serve($server) end end
[ "def update_player_server!(player)\n raise Exceptions::InvalidOperation, 'Player required' unless player\n raise Exceptions::InvalidOperation, 'Invalid type' unless player.is_a? Player\n if match.first_player_server.nil?\n match.first_player_server = player\n match.save!\n elsif match.second_player_server.nil?\n match.second_player_server = player\n match.save!\n end\n end", "def accept_player_connection\n new_connection = @ref_server.accept\n\n #NOTE if players are taking a long time to respond here, other pending connections may time out\n new_player_name = nil\n while new_player_name.nil? do\n new_player_name = new_connection.gets\n end\n @players[new_player_name] = new_connection\n\n end", "def new_serve(server)\n\t\t\tputs \" \"\n\t\t\tputs \">>>>>>>>>>>>> #{$hitter} serves the ball >>>>>>>>>>>>>>>\"\n\t\t\tputs \"hit any letter to continue 'q' to quit.\"\n\t\t\tputs \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\"\n\t\t\tresult = gets.chomp.downcase\n\t\t\t\n\t\t\tif result == 'q'\n\t\t \tputs \"exiting game\"\n\n\t\t\telse\n\t\t\t\tself.rally\n\t\t\tend\n\t\tend", "def add_server server\n @station.add_server server\n end", "def put_player(player, controller = IOController.new)\n @players[player] = controller\n controller.on_player_join(player.dup.freeze)\n end", "def switch_players\n @current_player, @other_player = @other_player, @current_player\n end", "def regist_server(server)\n @server[server.uri] = server\n mutex.synchronize do\n @primary_server = server unless @primary_server\n end\n end", "def join(server, already); end", "def startNewServer\n\t\tbegin \n\t\t\t@outgoingSocket = TCPServer.new(\"\",@outgoingPort)\t\t\t\n\t\t\t#@outgoingSocket = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)\n\t\t\t@outgoingSocket.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEADDR, 1)\n\t\t\t@outgoingSocket.fcntl(Fcntl::F_SETFL, Fcntl::O_NONBLOCK)\n\t\t\t#@outgoingSocket.bind(Socket.sockaddr_in(@outgoingPort, 'localhost'))\n\t\t\t@sockets.push(@outgoingSocket)\n\t\trescue Exception => e \n\t\t\tputs debugMessage(\"Error openning torrent port. Port in use perhaps? #{e}\");\n\t\tend\n\t\t\n\t\twhile true\n\t\t\t$stdout.flush\n\t\t\tcheckForPeers()\n\t\t\tcheckPeerIntegrity()\t\t\n\t\t\t\n\t\t\tselected = select(@sockets,nil,nil, @selectTimeout)\n\t\t\tif selected == nil\n\t\t\t\tsendQueue()\n\t\t\telse\n\t\t\t\tfor socket in selected[0]\n\t\t\t\t\tif socket == @outgoingSocket\n\t\t\t\t\t\t##Dputs \"New peer attemping to connect\"\n\t\t\t\t\t\treceiveClient()\n\t\t\t\t\telsif @sockets.include?(socket)\n\t\t\t\t\t\tif socket.eof?\n\t\t\t\t\t\t\tpeer = peer_by_socket(socket)\n\t\t\t\t\t\t\t#peer.openConnection()\n\t\t\t\t\t\t\t#peer.handshake(true)\n\t\t\t\t\t\t\tremovePeer(peer, \"Connection closed by peer\")\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\treceiveMessage(socket)\n\t\t\t\t\t\tend\n\t\t\t\t\telse\n\t\t\t\t\t\tputs \"Not too sure about this error\"\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\t\tcheckDownloadStatus()\t\n\t\tend\n\tend", "def switch_player()\n\t\tif $current_player == @player1\n\t\t\t$current_player = @player2\n\t\telse \n\t\t\t$current_player = @player1\n\t\tend \n\tend", "def switch_players\n \n if @current_asker == @player1\n @current_asker = @player2\n @current_responder = @player1\n else\n @current_asker = @player1\n @current_responder = @player2\n end\n\n end", "def server\n object.player_server_id\n end", "def add_server( server )\n\t\t@servers[server.name] = server\n\t\t@server_names << server.name\n\t\t@server_names.sort! { |a,b| a.downcase <=> b.downcase }\n\t\tserver.number = @server_names.index( server.name )\n\t\tbefore = 0\n\t\t@server_names[0, server.number].each { |server_name| # iterate through all of the servers before\n\t\t\tbefore += @servers[server_name].channel_names.length + 1\n\t\t}\n\t\tshift_server_pos( server.number, 1 )\n\t\tshift_server_num( server.number, 1 )\n\t\tserver.set_position( before + 2 ) # + 2 to compensate for 0-index arrays and core being buffer 1\n\t\t@length += 1\n\tend", "def switch_player\n current_index = PLAYERS.index(@cur_player)\n @cur_player = PLAYERS[1-current_index]\n end", "def switch_players\n temp = @current_player\n @current_player = @opposing_player\n @opposing_player = temp\n end", "def switch_players\n @current_player = @current_player == @player1 ? @player2 : @player1\n end", "def listen_dserver(client)\n msg = @directoryserver.gets.chomp\n \n if(@is_new == \"1\")\n if(msg[0..5] == \"NOFILE\")\n @lookupserver = @fileserver0 #default for all new file entries\n @server_fn = \"#{@client_fn[0..@client_fn.length-5]}file.txt\"\n @client_msg.insert(5,@server_fn)\n @directoryserver.puts(\"INSERT:#{@client_fn} SERVER_FN:#{@server_fn}\")\n @lookupserver.puts(@client_msg)\n listen_fserver(client)\n # Client trying to create a new file with the same name as another\n # Implemented in this way for ease\n else\n client.puts @error0\n end\n else\n msg = msg.split(\" \")\n ip = msg[0][7..msg[0].length-1]\n port = msg[1][5..msg[1].length-1]\n @server_fn = msg[2][9..msg[2].length-1]\n @fservers[:ips].each do |other_port, other_ip|\n if(port == other_port.to_s && ip == other_ip.to_s)\n @lookupserver = @fservers[:tcps][other_port]\n end\n end\n if(@client_msg[0..4] == \"OPEN:\")\n @client_msg.insert(5,\"#{@server_fn}\")\n @lookupserver.puts(@client_msg)\n listen_fserver(client)\n elsif (@client_msg[0..5] == \"CLOSE:\")\n @client_msg.insert(6,\"#{@server_fn}\")\n @lookupserver.puts(@client_msg)\n listen_fserver(client)\n elsif (@client_msg[0..4] == \"READ:\")\n\tif @cached == true\n @lookupserver.puts(\"TIME:#{@server_fn}\")\n\t @client_msg.insert(5,\"#{@server_fn}\")\n\t check_cache_validity(client)\n\telse\n @lookupserver.puts(@client_msg)\n listen_fserver(client)\n\tend\n else #WRITE\n @lookupserver.puts(\"WRITE:#{@server_fn}\")\n @lookupserver.puts(@start_n)\n @lookupserver.puts(@contents)\n\tlisten_fserver(client)\n end\n end\n end", "def add_server server\n @servers << server\n end", "def set_current_player(player)\n\t\tself.current_player = player\n send_update\n\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is the main action of the game rally calls the game_action method to determine what has happened to the ball then it uses a case statement to return results and pick next actions
def rally num = rand(1..20) rally_case = game_action(num) case rally_case when "oob" puts "oo-oo-oo-oo-oo #{$hitter} hit the ball out of bounds oo-oo-oo-oo-oo" @current_game.wins_ball($def_num) self.game_stats when "miss" puts "mmmmmmm #{$defender} missed the ball! mmmmmmmmmm" @current_game.wins_ball($hit_num) self.game_stats when "net" puts "############ #{$hitter} hit the net. ############" @current_game.wins_ball($def_num) self.game_stats when "hit" puts "^o^o^o^o^o^ #{$defender} returns the ball ^o^o^o^o^o^" puts " " hitter($hitter) else puts "#{rally} Error!!!" end end
[ "def choose_action\n puts(\"in choose action\")\n puts(\"robot #{@robot.id} has #{@robot.foobars.size} in stock\")\n ::Actions::MineFoo.new(@robot, @manager).perform if @robot.foos.empty? #should it be the manager checking foos or every individual bots\n ::Actions::MineBar.new(@robot, @manager).perform if @robot.bars.empty? # same\n if @robot.foobars.size < 5 #assemble\n current_foo = @robot.foos.shift\n current_bar = @robot.bars.shift\n shift_from_manager_pool(current_foo, current_bar)\n action = ::Actions::Assemble.new(current_foo, current_bar, @robot, @manager)\n elsif 12 > @robot.available_funds\n action = ::Actions::Sell.new(@robot, @manager)\n elsif @robot.available_funds >= 12\n action = compare_production_improvement_ratio\n end\n action.perform\n end", "def do_action snapshot\n # HERE GOES YOUR ALGORITHM. \n\n puts\n puts \"------VIRTUAL PLAYER DATA--------\"\n puts \"v-player: NAME #{name}\"\n puts \"v-player: CARDS #{cards}\"\n puts \"v-player: REMAINING MONEY #{remaining_money}\"\n puts \"last_round_actions: #{snapshot.last_round_actions}\"\n puts \"total_biddings: #{snapshot.total_biddings}\"\n puts \"current_bet: #{snapshot.current_bet}\"\n puts \"total_players: #{snapshot.total_players}\"\n puts \"Table: cards: #{snapshot.cards_on_table}\"\n puts \"----------------------------\"\n puts\n\n action = [\"fold\", \"call\", \"call\", \"call\", \"call\", \"call\", \"call\", \"raise\", \"raise\", \"raise\"].shuffle.first\n\n if action == \"raise\"\n add_action action, 20 # algorithm decision\n return\n end\n\n add_action action\n end", "def take_action(action)\n case action\n when :look\n @print_status\n when :north\n if @current_room.doors[:n]\n @world.move_entity_north(@player)\n else\n @player.hurt(1)\n puts \"You run into a wall. Ouch! You have #{@player.hit_points} HP remaining.\"\n end\n when :east\n if @current_room.doors[:e]\n @world.move_entity_east(@player)\n else\n @player.hurt(1)\n puts \"You run into a wall. Ouch! You have #{@player.hit_points} HP remaining.\"\n end\n when :south\n if @current_room.doors[:s]\n @world.move_entity_south(@player)\n else\n @player.hurt(1)\n puts \"You run into a wall. Ouch! You have #{@player.hit_points} HP remaining.\"\n end\n when :west\n if @current_room.doors[:w]\n @world.move_entity_west(@player)\n else\n @player.hurt(1)\n puts \"You run into a wall. Ouch! You have #{@player.hit_points} HP remaining.\"\n end\n when :fight, :take\n @current_room.interact(@player)\n when :status\n @player.print_status\n end\n end", "def make_basic_action_result\n # If attack\n if @active_battler.current_action.basic == 0\n # Add log line\n $scene.log_add_line(Wep::VocAtk, @active_battler)\n # Set anaimation ID\n @animation1_id = @active_battler.animation1_id\n @animation2_id = @active_battler.animation2_id\n # If action battler is enemy\n if @active_battler.is_a?(Game_Enemy)\n if @active_battler.restriction == 3\n target = $game_troop.random_target_enemy\n elsif @active_battler.restriction == 2\n target = $game_party.random_target_actor\n else\n index = @active_battler.current_action.target_index\n target = $game_party.smooth_target_actor(index)\n end\n end\n # If action battler is actor\n if @active_battler.is_a?(Game_Actor)\n if @active_battler.restriction == 3\n target = $game_party.random_target_actor\n elsif @active_battler.restriction == 2\n target = $game_troop.random_target_enemy\n else\n index = @active_battler.current_action.target_index\n target = $game_troop.smooth_target_enemy(index)\n end\n end\n # Set array of targeted battlers\n @target_battlers = [target]\n # Apply normal attack results\n for target in @target_battlers\n target.attack_effect(@active_battler)\n end\n return\n end\n # If guard\n if @active_battler.current_action.basic == 1\n # Display \"Guard\" in help window\n # Add log line\n $scene.log_add_line(Wep::VocDef, @active_battler)\n @help_window.set_text($data_system.words.guard, 1)\n return\n end\n # If escape\n if @active_battler.is_a?(Game_Enemy) and\n @active_battler.current_action.basic == 2\n # Add log line\n # @log_window.add_special_line(Wep::VocEscaping)\n \n # Display \"Escape\" in help window\n @help_window.set_text(\"Escape\", 1)\n # Escape\n @active_battler.escape\n return\n end\n # If doing nothing\n if @active_battler.current_action.basic == 3\n # Add log line\n $scene.log_add_line(Wep::VocNothing, @active_battler)\n # Clear battler being forced into action\n $game_temp.forcing_battler = nil\n # Shift to step 1\n @phase4_step = 1\n return\n end\n end", "def make_basic_action_result\n # If attack\n if @active_battler.current_action.basic == 0\n # Set anaimation ID\n @animation1_id = @active_battler.animation1_id\n @animation2_id = @active_battler.animation2_id\n # If action battler is enemy\n if @active_battler.is_a?(Game_Enemy)\n if @active_battler.restriction == 3\n target = $game_troop.random_target_enemy\n elsif @active_battler.restriction == 2\n target = $game_party.random_target_actor\n else\n index = @active_battler.current_action.target_index\n target = $game_party.smooth_target_actor(index)\n end\n end\n # If action battler is actor\n if @active_battler.is_a?(Game_Actor)\n if @active_battler.restriction == 3\n target = $game_party.random_target_actor\n elsif @active_battler.restriction == 2\n target = $game_troop.random_target_enemy\n else\n index = @active_battler.current_action.target_index\n target = $game_troop.smooth_target_enemy(index)\n end\n end\n # Set array of targeted battlers\n @target_battlers = [target]\n # Apply normal attack results\n for target in @target_battlers\n target.attack_effect(@active_battler)\n end\n return\n end\n # If guard\n if @active_battler.current_action.basic == 1\n # Display \"Guard\" in help window\n @help_window.set_text($data_system.words.guard, 1)\n return\n end\n # If escape\n if @active_battler.is_a?(Game_Enemy) and\n @active_battler.current_action.basic == 2\n # Display \"Escape\" in help window\n @help_window.set_text(\"Escape\", 1)\n # Escape\n @active_battler.escape\n return\n end\n # If doing nothing\n if @active_battler.current_action.basic == 3\n # Clear battler being forced into action\n $game_temp.forcing_battler = nil\n # Shift to step 1\n @phase4_step = 1\n return\n end\n end", "def gameflow\n \n end", "def process_action(trigger)\n\t\t\t#process all actions with this trigger\n\t\t\ttrigger[:actions].each do |act|\n\t\t\t\tcase act.type\n\t\t\t\twhen \"SC\" #Score\n\t\t\t\t\tputs(\"\",\"You have scored \" << @score.to_s << \" points\")\n\t\t\t\twhen \"IN\" #Inventory\n\t\t\t\t\tobjCarrying = @objects[1..@objects.count].find_all {|obj| obj[:place] == 0}\n\t\t\t\t\tif objCarrying.empty?\n\t\t\t\t\t\tputs(\"\",\"You are not carrying anything.\")\n\t\t\t\t\telse\n\t\t\t\t\t\tputs(\"\",\"You are carrying : \")\n\t\t\t\t\t\tobjCarrying.each do |obj|\n\t\t\t\t\t\t\tobj[:descriptions].each do |desc|\n\t\t\t\t\t\t\t\tif eval_this(desc.condition)\n\t\t\t\t\t\t\t\t\t#check if worn\n\t\t\t\t\t\t\t\t\tworn = @wearing[@objects.find_index(obj)] == true ? \" (worn)\" : \"\"\n\t\t\t\t\t\t\t\t\tputs \"\\t\" << print_description(desc.text) << worn\n\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\twhen \"QU\" #Quit\n\t\t\t\t\tresponse = (print \"Are you sure (Y/N) ? \"; $stdin.gets.rstrip.upcase)\n\t\t\t\t\tif response == \"Y\" then\n\t\t\t\t\t\t@eogame = true\n\t\t\t\t\tend\n\t\t\t\twhen \"IS\" #Increment Score\n\t\t\t\t\t@score += act.int\n\t\t\t\twhen \"AF\" #Assign Flag\n\t\t\t\t\t@flags[act.fnum] = act.flagstatus == \"T\" ? true : false\n\t\t\t\twhen \"PR\" #Print\n\t\t\t\t\tputs(\"\",print_description(act.text))\n\t\t\t\twhen \"GO\" #Go\n\t\t\t\t\tgoodConnection = @locations[@objects[0][:place]][:connections].find do |conn|\n\t\t\t\t\t\tconn.direction == act.direction\n\t\t\t\t\tend\n\t\t\t\t\tif goodConnection\n\t\t\t\t\t\tif eval_this(goodConnection.condition)\n\t\t\t\t\t\t\t@objects[0][:place] = goodConnection.location\n\t\t\t\t\t\tend\n\t\t\t\t\telse\n\t\t\t\t\t\tputs(\"\",\"You can not go that way.\")\n\t\t\t\t\tend\n\t\t\t\twhen \"MO\" #Move Object\n\t\t\t\t\tif act.loc == 0\n\t\t\t\t\t\t@objects[act.obj][:place] = Random.rand(1..@locations.size-1) \n\t\t\t\t\telse\n\t\t\t\t\t\t@objects[act.obj][:place] = act.loc\n\t\t\t\t\tend\n\t\t\t\t\t@wearing[act.obj] = false\n\t\t\t\twhen \"GE\" #Get\n\t\t\t\t\tobj_id = assign_object(act.type)\n\t\t\t\t\tunless obj_id.nil?\n\t\t\t\t\t\tif @objects[obj_id][:place] == @objects[0][:place]\n\t\t\t\t\t\t\t@objects[obj_id][:place] = 0\n\t\t\t\t\t\t\t@score += @objects[obj_id][:value]\n\t\t\t\t\t\t\tputs(\"\",\"Taken.\")\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tputs(\"\",\"You can not see it here.\")\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\twhen \"DR\" #Drop\n\t\t\t\t\tobj_id = assign_object(act.type)\n\t\t\t\t\tunless obj_id.nil?\n\t\t\t\t\t\tif @objects[obj_id][:place] == 0\n\t\t\t\t\t\t\t@objects[obj_id][:place] = @objects[0][:place]\n\t\t\t\t\t\t\t@wearing[obj_id] = false\n\t\t\t\t\t\t\t@score -= @objects[obj_id][:value]\n\t\t\t\t\t\t\tputs(\"\",\"Dropped.\")\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tputs(\"\",\"You do not have it.\")\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\twhen \"PO\" #Put On\n\t\t\t\t\tobj_id = assign_object(act.type)\n\t\t\t\t\tunless obj_id.nil?\n\t\t\t\t\t\tif @objects[obj_id][:place] == 0\n\t\t\t\t\t\t\t@wearing[obj_id] = true\n\t\t\t\t\t\t\tputs(\"\",\"Worn.\")\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tputs(\"\",\"You do not have it.\")\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\twhen \"TO\" #Take Off\n\t\t\t\t\tobj_id = assign_object(act.type)\n\t\t\t\t\tunless obj_id.nil?\n\t\t\t\t\t\tif @wearing[obj_id] == true\n\t\t\t\t\t\t\t@wearing[obj_id] = false\n\t\t\t\t\t\t\tputs(\"\",\"Removed.\")\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tputs(\"\",\"You are not wearing it.\")\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\twhen \"EX\" #Examine\n\t\t\t\t\tobj_id = assign_object(act.type)\n\t\t\t\t\tunless obj_id.nil?\n\t\t\t\t\t\tif @objects[obj_id][:place] != 0 && @objects[obj_id][:place] != @objects[0][:place]\n\t\t\t\t\t\t\tputs(\"\",\"You see nothing special.\")\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tsuit = @objects[obj_id][:suitabilities].find {|suit| suit.action == \"EX\"}\n\t\t\t\t\t\t\t#if here suit must be found\n\t\t\t\t\t\t\tputs(\"\",print_description(suit.text))\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\twhen \"IC\" #Initialise \n\t\t\t\t\t@counting[act.cnum] = true\n\t\t\t\t\t@count[act.cnum] = act.int\n\t\t\t\twhen \"HC\" #Halt Counter\n\t\t\t\t\t@counting[act.cnum] = false\n\t\t\t\twhen \"RC\" #Resume Counter\n\t\t\t\t\t@counting[act.cnum] = true\n\t\t\t\twhen \"ZI\" #Zap In\n\t\t\t\t\t@objects[act.obj][:place] = @objects[0][:place] #current location\n\t\t\t\t\t@wearing[act.obj] = false\n\t\t\t\twhen \"ZO\" #Zap Out\n\t\t\t\t\t@objects[act.obj][:place] = -1 #nowhere\n\t\t\t\t\t@wearing[act.obj] = false\n\t\t\t\twhen \"LO\" #Load\n\t\t\t\t\tputs(\"\",\"Sorry, this feature isn't implemented...\")\n\t\t\t\twhen \"SA\" #Save\n\t\t\t\t\tputs(\"\",\"Sorry, this feature isn't implemented...\")\n\t\t\t\telse\n\t\t\t\t\traise \"unknown action type ? \" << act.type\n\t\t\t\tend\n\n\t\t\tend\n\t\tend", "def make_action_results(targets)\n #action = @active_battler.current_action\n if (@action.attack? || @action.skill?)\n make_skill_result(targets)\n elsif @action.guard? \n make_skill_result(targets) #cast skill on yourself\n elsif @action.item?\n if action.item_skill != nil\n @spell = @action.skill\n make_skill_result(targets)\n @item = nil\n else\n make_item_result(targets)\n end\n end\n end", "def do_action(action)\n \n if action.is_a?(Hash)\n action = Action.new(action)\n end\n \n update_state(action)\n \n @on_action.call(action) if @on_action\n \n responses = (0...4).map() do |i|\n @players[i].respond_to_action(action_in_view(action, i, true))\n end\n\n action_with_logs = action.merge({:logs => responses.map(){ |r| r && r.log }})\n responses = responses.map(){ |r| (!r || r.type == :none) ? nil : r.merge({:log => nil}) }\n @on_responses.call(action_with_logs, responses) if @on_responses\n\n @previous_action = action\n validate_responses(responses, action)\n return responses\n \n end", "def execute_bot_action (bot, action, map)\n case action\n when /MOVE/\n @ap -= $MOVEMENT_COST\n x = action.split(' ')[1].to_i\n y = action.split(' ')[2].to_i\n bot.move(x, y, map)\n when \"SHOOT\"\n @ap -= $SHOOT_COST\n bot.shoot(map)\n when /TURN/\n degrees = action.split(' ')[1].to_i\n @ap -= ((degrees.abs.to_i + 0.0) / $TURN_COST).ceil # Round up ap cost so 1 degree turn costs 1 ap\n bot.turn(degrees)\n when /PLACE/\n @ap -= $PLACE_COST\n @mana -= $PLACE_MANA_COST\n x = action.split(' ')[1].to_i\n y = action.split(' ')[2].to_i\n bot.place_block(map, x, y)\n when /SPAWN/\n @ap -= $SPAWN_COST\n @mana -= $SPAWN_MANA_COST\n x = action.split(' ')[1].to_i\n y = action.split(' ')[2].to_i\n spawn_bot(x, y, bot, map)\n else\n puts 'Invalid action ' + action.to_s # the to_s just to be safe in a not strong typed lang\n end\n end", "def update_state(action)\n \n @current_action = action\n @actor = action.actor if action.actor\n \n case action.type\n when :start_game\n # TODO change this by red config\n pais = (0...4).map() do |i|\n [\"m\", \"p\", \"s\"].map(){ |t| (1..9).map(){ |n| Pai.new(t, n, n == 5 && i == 0) } } +\n (1..7).map(){ |n| Pai.new(\"t\", n) }\n end\n @all_pais = pais.flatten().sort()\n when :start_kyoku\n @bakaze = action.bakaze\n @kyoku_num = action.kyoku\n @honba = action.honba\n @oya = action.oya\n @chicha ||= @oya\n @dora_markers = [action.dora_marker]\n @num_pipais = @num_initial_pipais = @all_pais.size - 13 * 4 - 14\n @first_turn = true\n when :tsumo\n @num_pipais -= 1\n if @num_initial_pipais - @num_pipais > 4\n @first_turn = false\n end\n when :chi, :pon, :daiminkan, :kakan, :ankan\n @first_turn = false\n when :dora\n @dora_markers.push(action.dora_marker)\n end\n \n for i in 0...4\n @players[i].update_state(action_in_view(action, i, false))\n end\n \n end", "def process_actions\n # First, check if we meet the endgame condition. If we do, we'll need a\n # Game-scope action to perform game-end steps\n check_game_end\n\n self.pending_actions(true)\n\n until active_actions(true).empty?\n active_actions(true).each do |action|\n check_game_end\n case action.expected_action\n when /^resolve_([[:alpha:]]+::[[:alpha:]]+)([0-9]+)(?:_([[:alnum:]_]*))?(;.*)?/\n card_type = $1\n card_id = $2\n substep = $3\n param_string = $4 || \"\"\n\n card = card_type.constantize.find(card_id)\n params = {}\n param_string.scan(/;([^;=]*)=([^;=]*)/) {|m| params[m[0].to_sym] = m[1]}\n params[:parent_act] = action.parent\n params[:this_act_id] = action.id\n params[:state] = action.state\n Game.current_act_parent = action.parent\n action.destroy\n\n if not card.respond_to? substep.to_sym\n return \"Unexpected substep #{substep} for #{card_type}\"\n end\n\n card.method(substep.to_sym).call(params)\n when /^player_([[:alpha:]_]+);player=([0-9]+)(;.*)?$/\n player = Player.find($2)\n task = $1\n param_string = $3 || \"\"\n Game.current_act_parent = action.parent\n params = {:parent_act => action.parent, :this_act_id => action.id}\n param_string.scan(/;([^;=]*)=([^;=]*)/) {|m| params[m[0].to_sym] = m[1]}\n action.destroy\n\n player.method(task.to_sym).call(params)\n when /^end_game$/\n action.destroy\n end_game\n end\n end\n end\n\n # Force each player's cards to be renumbered\n players.each do |ply|\n [:deck, :hand, :discard].each {|loc| ply.renum(loc)}\n end\n end", "def game_action(num)\n\t\t\t\n\t\t\tnet_ball = rand(5..15)\n\t\t\treturn \"net\" if num == net_ball\n\t\t\treturn \"oob\" if num <= 3\n\t\t\treturn \"hit\" if num > 3 && num <=17\n\t\t\treturn \"miss\" if num > 17\n\t\tend", "def game_menu\n system('clear')\n choices = { \"New Game\" => 1,\n \"The Awakened\" => 2,\n \"Delete Account\" => 3,\n \"Go back\" => 4}\n @@prompt.say(\"Welcome, Hero\")\n action = @@prompt.select(\"Awaken the Force\", choices)\n case action\n when 1 \n self.new_game\n when 2\n awakened_choices = {\"Tatooine\" => 1, \"Alderaan\" =>2, \"Naboo\" => 3, \"Show all results\" => 4,\"Go back\" => 5}\n awaken_action = @@prompt.select(\"Select planet to see results\", awakened_choices)\n case awaken_action\n when 1 \n Game.show_tatooine\n choice = {\"Go back\" => 1}\n action = @@prompt.select(\"\", choice)\n case action\n when 1 \n self.game_menu\n end\n when 2\n Game.show_alderaan\n choice = {\"Go back\" => 1}\n action = @@prompt.select(\"\", choice)\n case action\n when 1 \n self.game_menu\n end\n when 3\n Game.show_naboo\n choice = {\"Go back\" => 1}\n action = @@prompt.select(\"\", choice)\n case action\n when 1 \n self.game_menu\n end\n when 4\n Game.show_all_results\n choice = {\"Go back\" => 1}\n action = @@prompt.select(\"\", choice)\n case action\n when 1 \n self.game_menu\n end\n when 5\n self.game_menu\n end\n when 3\n choice = {\"Yes\" => 1, \"No\" => 2}\n action = @@prompt.select(\"Are you sure you want to delete your account?\",choice)\n case action\n when 1\n User.delete_account(@@user)\n self.display_menu\n when 2 \n self.game_menu\n end\n when 4\n self.display_menu\n\n end\n end", "def make_item_action_result\r\n # Get item\r\n @item = $data_items[@active_battler.current_action.item_id]\r\n # If unable to use due to items running out\r\n unless $game_party.item_can_use?(@item.id)\r\n # Shift to step 1\r\n @phase4_step = 1\r\n return\r\n end\r\n # If consumable\r\n if @item.consumable\r\n # Decrease used item by 1\r\n $game_party.lose_item(@item.id, 1)\r\n end\r\n # Display item name on help window\r\n @help_window.set_text(@item.name, 1)\r\n # Set animation ID\r\n @animation1_id = @item.animation1_id\r\n @animation2_id = @item.animation2_id\r\n # Set common event ID\r\n @common_event_id = @item.common_event_id\r\n # Decide on target\r\n index = @active_battler.current_action.target_index\r\n target = $game_party.smooth_target_actor(index)\r\n # Set targeted battlers\r\n set_target_battlers(@item.scope)\r\n # Apply item effect\r\n for target in @target_battlers\r\n target.item_effect(@item)\r\n end\r\n end", "def make_skill_action_result\r\n # Get skill\r\n @skill = $data_skills[@active_battler.current_action.skill_id]\r\n # If not a forcing action\r\n unless @active_battler.current_action.forcing\r\n # If unable to use due to SP running out\r\n unless @active_battler.skill_can_use?(@skill.id)\r\n # Clear battler being forced into action\r\n $game_temp.forcing_battler = nil\r\n # Shift to step 1\r\n @phase4_step = 1\r\n return\r\n end\r\n end\r\n # Use up SP\r\n @active_battler.sp -= @skill.sp_cost\r\n # Refresh status window\r\n @status_window.refresh\r\n # Show skill name on help window\r\n @help_window.set_text(@skill.name, 1)\r\n # Set animation ID\r\n @animation1_id = @skill.animation1_id\r\n @animation2_id = @skill.animation2_id\r\n # Set command event ID\r\n @common_event_id = @skill.common_event_id\r\n # Set target battlers\r\n set_target_battlers(@skill.scope)\r\n # Apply skill effect\r\n for target in @target_battlers\r\n target.skill_effect(@active_battler, @skill)\r\n end\r\n end", "def make_item_action_result\n # Get item\n @item = $data_items[@active_battler.current_action.item_id]\n # If unable to use due to items running out\n unless $game_party.item_can_use?(@item.id)\n # Shift to step 1\n @phase4_step = 1\n return\n end\n # If consumable\n if @item.consumable\n # Decrease used item by 1\n $game_party.lose_item(@item.id, 1)\n end\n # Display item name on help window\n @help_window.set_text(@item.name, 1)\n # Set animation ID\n @animation1_id = @item.animation1_id\n @animation2_id = @item.animation2_id\n # Set common event ID\n @common_event_id = @item.common_event_id\n # Decide on target\n index = @active_battler.current_action.target_index\n target = $game_party.smooth_target_actor(index)\n # Set targeted battlers\n set_target_battlers(@item.scope)\n # Apply item effect\n for target in @target_battlers\n target.item_effect(@item)\n end\n end", "def action_loop\n until @action == \"exit\" || @round != 0 && ((@round % 20) == 0 || (@round % 50 == 0))\n @round += 1\n puts \"It is day #{@round}\"\n event = rand(1..10)\n case event\n when (1..2)\n new_rival\n when (3..4)\n new_business\n when 5\n raid\n when 6\n boss_visit\n when (7..10)\n ordinary_day\n else\n raise \"Event not generated\"\n end\n puts \"___\" * 30\n @mobster.get_stats\n puts \"Press enter to end day.\"\n gets.chomp #requires player to press enter to continue\n puts \"===\" * 30\n puts \"===\" * 30\n end\nend", "def actor_command_case\n if !@actor_command_window.enabled?(@actor_command_window.item)\n if @selected_battler.inputable? and !@selected_battler.auto_battle\n Sound.play_buzzer\n else\n Sound.play_cursor\n if !dtb? and (@actor_index == $game_party.members.size - 1)\n @actor_index = -1\n end\n next_actor\n end\n return\n end\n #---\n case @actor_command_window.item\n when :attack\n Sound.play_decision\n if KreadCFG::Mimic_Class.include?(@selected_battler.class.id)\n if @last_action == nil\n @selected_battler.action.clear\n else\n @selected_battler.action = @last_action\n end\n confirm_action\n else\n @selected_battler.action.set_attack\n start_target_enemy_selection\n end\n when :skill\n Sound.play_decision\n start_skill_selection\n when :guard\n Sound.play_decision\n @selected_battler.action.set_guard\n confirm_action\n when :item\n Sound.play_decision\n start_item_selection\n when :equip\n Sound.play_decision\n call_equip_menu\n when :escape\n Sound.play_decision\n @selected_battler.action.set_escape\n confirm_action\n else\n Sound.play_decision\n @command_action = true\n @skill = @actor_command_window.skill\n determine_skill\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an input iterator to use for the request. if arguments are given, uses arguments if the input file option is given, uses file input if none of the previous are given, uses stdin
def input_iterator return arguments.each unless arguments.empty? return File.foreach(options[:input]) if options[:input] $stdin.each_line end
[ "def input_handle\n if !@options[:message].nil?\n nil\n elsif @options[:input]\n begin\n File.open(@options[:input])\n rescue Errno::ENOENT\n $stderr.puts \"no such file #{@options[:input]}\"\n exit -1\n end\n else\n $stdin\n end\n end", "def each_input\n # No block? Return an enumerator\n return enum_for(:each_input) unless block_given?\n # A block? Interrate with it\n # Process the arguments\n if ($*.empty?) then\n # No arguments, shows the help and end.\n help_short\n exit(1)\n end\n if $*[0] == \"-f\" or $*[0] == \"--file\" then\n # Work from a file, iterate on each line\n exprs = File.read($*[1])\n exprs.gsub!(/\\r\\n?/, \"\\n\")\n exprs.each_line do |line|\n yield(line)\n end\n elsif $*[0] == \"-h\" or $*[0] == \"--help\" then\n help_short\n else\n # Work directly on the arguments as an expression\n yield($*.join)\n end\n end", "def input\n option[:ifile] == '-' ? $stdin.read.force_encoding('ascii-8bit') : File.binread(option[:ifile])\n end", "def acquire_input(input_file, verbose = false)\n if input_file == '-'\n warn '[INFO] Reading from STDIN' if verbose\n $stdin.read\n else\n full_filename = File.expand_path(input_file)\n unless File.exist?(full_filename) && File.ftype(full_filename) == 'file'\n raise Exceptions::InvalidArguments, \"#{full_filename} is invalid\"\n end\n\n begin\n File.read(full_filename)\n rescue StandardError => e\n raise \"Unable to process #{relative_path}: #{e.message}\"\n end\n end\n end", "def acquire_input(input_file, verbose = false)\n if input_file == '-'\n STDERR.puts '[INFO] Reading from STDIN' if verbose\n STDIN.read\n else\n full_filename = File.expand_path(input_file)\n unless File.exist?(full_filename) && File.ftype(full_filename) == 'file'\n raise Exceptions::InvalidArguments, \"#{full_filename} is invalid\"\n end\n\n begin\n File.read(full_filename)\n rescue StandardError => e\n raise \"Unable to process #{relative_path}: #{e.message}\"\n end\n end\n end", "def each_request(options = {}, &block) # :yields: :request, request\n\n case @source_files\n when IO\n if @source_files == $stdin\n puts \"Parsing from the standard input. Press CTRL+C to finish.\" # FIXME: not here\n end\n parse_stream(@source_files, options, &block)\n when String\n parse_file(@source_files, options, &block)\n when Array\n parse_files(@source_files, options, &block)\n else\n raise \"Unknown source provided\"\n end\n end", "def process_input(file=nil)\n input = if file\n File.new(file.to_s)\n else\n STDIN\n end\n\n loop do\n text = input.read(@block_size)\n break unless text\n\n yield text\n end\n\n input.close\n return nil\n end", "def input_file\n (ARGV.empty? and $stdin.tty?) ? DATA : ARGF\nend", "def with_input_io(&bl)\n case input\n when IO, StringIO\n begin\n input.rewind unless input.pos==0\n rescue Errno::ESPIPE => ex\n end\n yield input\n when String, Path\n Path(input).open('r', &bl)\n else\n raise \"Unable to convert `#{input}` to an IO object\"\n end\n end", "def with_input_io\n case input\n when IO, StringIO\n yield input\n when String\n File.open(input, 'r'){|io| yield io}\n else\n raise \"Unable to convert #{input} to an IO object\"\n end\n end", "def stdin\n @stdin_io || @stdin_spool\n end", "def stdin\n $stdin\n end", "def stdin path\n @stdin = File.absolute_path(path)\n STDIN.reopen @stdin\n end", "def feed_stdin(str)\n old_stdin = $stdin\n $stdin = StringIO.new str\n\n yield\nensure\n $stdin = old_stdin\nend", "def stdin_reader\n @stdin_reader || Reader.send(@input_reader, $stdin)\n end", "def stdin\n $stdin\n end", "def get_input_stream(entry, &a_proc); end", "def input(*args)\n self::Input.new(*args)\n end", "def stdin_pipe\n @stdin\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the default default_batch_size of a command.
def default_batch_size raise NotImplementedError, 'This must be implemented in a subclass.' end
[ "def batch_size\n if options[:batch]\n options[:batch].to_i\n else\n default_batch_size\n end\n end", "def retrieve_batch_size_value(env)\n retrieve_integer_value('BATCH_SIZE', env)\n end", "def batch_size(value = nil)\n option(value) { |options| options.store(:batch_size, value) }\n end", "def batch_size_for(value, items = nil)\n batch = batch_option(value) or return\n batch = [batch, MAX_BATCH].min\n batch = [batch, items.size].min if (items &&= extract_items(items))\n batch unless batch < MIN_BATCH\n end", "def default_max_size\n [Setting[:histsize], self.size].min\n end", "def default_size\n @total_memory ? @total_memory * @weighting : nil\n end", "def request_limit\n if limited?\n @batch_size < @limit ? @batch_size : @limit\n else\n @batch_size\n end\n end", "def max_write_batch_size\n config[MAX_WRITE_BATCH_SIZE] || DEFAULT_MAX_WRITE_BATCH_SIZE\n end", "def default_length\n return @default_length\n end", "def batch_size\n @of\n end", "def batch_size\n @of\n end", "def default_options\n @default_options ||= { GS::BATCH => nil }\n end", "def default_max_in_memory_size\n @default_max_in_memory_size || DEFAULT_MAX_IN_MEMORY_SIZE\n end", "def default_command\n commands.find(&:default)\n end", "def get_default_size(font_id)\n end", "def get_default_command\n @default_command\n end", "def bulk_job_size\n if defined? @bulk_job_size\n @bulk_job_size\n else\n 5000\n end\n end", "def default_font_size\n (options[:default] and options[:default][:size]) ? options[:default][:size] : 40\n end", "def bulk_job_size\n if defined? @bulk_job_size\n @bulk_job_size\n else\n 5000\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the effective batch_size of a command
def batch_size if options[:batch] options[:batch].to_i else default_batch_size end end
[ "def batch_size\n @of\n end", "def batch_size\n @of\n end", "def retrieve_batch_size_value(env)\n retrieve_integer_value('BATCH_SIZE', env)\n end", "def batch_size_for(value, items = nil)\n batch = batch_option(value) or return\n batch = [batch, MAX_BATCH].min\n batch = [batch, items.size].min if (items &&= extract_items(items))\n batch unless batch < MIN_BATCH\n end", "def estimated_size overwrite_n_inputs = nil\n 148 * (overwrite_n_inputs or number_of_inputs) + 34 * number_of_outputs + 10\n end", "def request_size\n return @request_size\n end", "def instruction_size\n\t\t@ida.ua_mnem(@ea)\n\t\t@ida.cmd.size\n\tend", "def request_limit\n if limited?\n @batch_size < @limit ? @batch_size : @limit\n else\n @batch_size\n end\n end", "def blksize() end", "def batch_size(value = nil)\n option(value) { |options| options.store(:batch_size, value) }\n end", "def block_size\n @block_size\n end", "def chunk_size()\n #This is a stub, used for indexing\n end", "def warm_pool_size\n data[:warm_pool_size]\n end", "def bulk_job_size\n if defined? @bulk_job_size\n @bulk_job_size\n else\n 5000\n end\n end", "def cluster_size\n `curl -s -i -L \\\n -u #{Conn[:creds]} \\\n -H 'content-type:application/json' \\\n #{[Conn[:host_api], 'nodes'].join('/')} | grep -o \"contexts\" | wc -l`\n end", "def block_size(*) end", "def actual_size\n @actual_size\n end", "def max_command_length\n @max_command_length ||=\n if Gem.win_platform?\n # Windows is limited to 2048 since that is a worst-case scenario.\n # http://blogs.msdn.com/b/oldnewthing/archive/2003/12/10/56028.aspx\n 2048\n else\n # We fudge factor this by halving the buffer size since *nix systems\n # usually have pretty large limits, and the actual limit changes\n # depending on how much of your stack is environment variables.\n # Definitely erring on the side of overly cautious.\n `getconf ARG_MAX`.to_i / 2\n end\n end", "def chunk_size\n @connection.chunk_size\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a new batch_iterator based on the batch_size
def batch_iterator Unipept::BatchIterator.new(batch_size) end
[ "def process_in_batches(batch_size)\n raise ArgumentError if batch_size.nil? or batch_size <= 0\n \n index = 0\n \n while index < self.size\n yield self[index...index+batch_size]\n index += batch_size\n end\n end", "def batch_size(batch_size)\n operation.batch_size = batch_size\n self\n end", "def in_batches_of(size, &blk)\n size = size.to_i\n batches = (steps / size) + ((steps % size).zero? ? 0 : 1)\n\n Enumerator.new do |yielder|\n i = 0\n elements = self.each\n\n while i < batches\n batch = size.times.inject([]) do |acc, _|\n begin\n acc << blk.call(elements.next)\n rescue StopIteration\n break acc\n end\n end\n\n yielder.yield batch\n i += 1\n end\n end.lazy\n end", "def each_row_batch(batch_size = 100)\n batch = []\n each_row do |row_in|\n batch << row_in\n if batch.length >= batch_size\n yield batch\n batch = []\n end\n end\n yield batch if batch.length > 0\n end", "def in_batches(of: DEFAULT_BATCH_SIZE, &block)\n per_page = of\n\n if block_given?\n each_batch(of, &block)\n else\n Enumerator.new do |result|\n each_batch(of) do |batch|\n batch.each { |entity| result << entity }\n end\n end\n end\n end", "def next_batch\n if iter_next\n DataBatch.new(current_data, label: current_label, pad: current_pad, index: current_index)\n end\n end", "def execute_in_batches(size: 1000)\n raise ArgumentError, 'batches need a block to yield to' unless block_given?\n\n id = 0\n id_column = @manager.source.left[@clazz.primary_key]\n\n manager = Arel::SelectManager.new(@manager.as(@clazz.table_name))\n manager.project(Arel.star)\n .where(id_column.gt(Arel::Nodes::BindParam.new))\n .order(id_column)\n .take(size)\n\n statement = self.class.new(@clazz, manager, @binds + [nil])\n\n loop do\n statement.binds[statement.binds.count - 1] = Bind.new(id)\n results = statement.execute.to_a\n results.each { |r| yield r }\n\n break if results.count < size\n\n id = results.last[@clazz.primary_key]\n end\n end", "def batches(of:)\n limit = scope.limit_value\n batch_size = limit && limit < of ? limit : of\n Enumerator.new do |y|\n offset = scope.offset_value || 0\n out_of_records, count = false, 0\n\n until out_of_records\n l = limit && batch_size > limit - count ? limit - count : batch_size\n q = scope.order(model.primary_key.to_sym).offset(offset).limit(l)\n results = Query.new(q, use: @use, query_logger: @query_logger, eager_loaders: @eager_loaders).run\n\n y.yield results if results.any?\n count += results.size\n offset += results.size\n out_of_records = results.size < batch_size || (limit && count >= limit)\n end\n end\n end", "def export_in_batches(dataset:, batch_size:100)\n batch = []\n exportio = export_io(dataset: dataset)\n exportio.each_line do |row|\n batch << row\n if exportio.eof? || exportio.lineno % batch_size == 0\n yield batch\n batch = []\n end\n end\n exportio.close\n end", "def set_batch_size(size = 1)\n @batch_size = size\n end", "def find_in_batches_with_order(options={})\n return to_enum(__method__, options) unless block_given?\n options.assert_valid_keys(:batch_size)\n\n relation = self\n\n start = 0\n batch_size = options.delete(:batch_size) || 1000\n\n relation = relation.limit(batch_size)\n records = relation.offset(start).to_a\n\n while records.any?\n records_size = records.size\n\n yield records\n\n break if records_size < batch_size\n\n # get the next batch\n start += batch_size\n records = relation.offset(start + 1).to_a\n end\n end", "def in_groups_of size, options = {}, &block\n\n group = []\n\n nil_or_next_token = each_batch(options) do |batch|\n batch.each do |item|\n group << item\n if group.size == size\n yield(group)\n group = []\n end\n end\n end\n\n yield(group) unless group.empty?\n\n nil_or_next_token\n\n end", "def chunk_records(records, batch_size)\n Enumerator.new do |enum|\n chunked_records = []\n\n records.each do |record|\n if chunked_records.size == batch_size\n enum.yield(chunked_records)\n chunked_records = []\n end\n\n transformed_record = block_given? ? yield(record) : record\n chunked_records.push(transformed_record)\n end\n\n # Yield the remaining records if any\n enum.yield(chunked_records) unless chunked_records.empty?\n end\nend", "def default_batch_size\n raise NotImplementedError, 'This must be implemented in a subclass.'\n end", "def batch_size\n @of\n end", "def batch_size\n @of\n end", "def new_batch(opts={})\n Batch.new(self, opts)\n end", "def each_by_range(batch_size=DEFAULT_BATCH_SIZE)\n batches_by_range(batch_size) { |batch| batch.each { |row| yield row } }\n end", "def in_even_sized_batches(iostream, batch_size=@batch_size, &block)\n chunk = []\n iostream.each_line.each_slice(2) do |command, document|\n chunk << command\n chunk << document\n if byte_size(chunk) >= batch_size\n yield chunk\n chunk = []\n end\n end\n yield chunk if chunk.any?\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an array of regular expressions containing all the selected fields
def selected_fields return @selected_fields unless @selected_fields.nil? fields = [*options[:select]].map { |f| f.split(',') }.flatten fields.concat(required_fields) if @fasta && !fields.empty? @selected_fields = fields.map { |f| glob_to_regex(f) } end
[ "def regex_values\n @values.select do |key, value|\n value.regex?\n end.map do |key, value|\n value.name.source\n end\n end", "def build_regex(fields)\n fields_or = fields.map { |field| \"#{field}(\\\\[\\\\])?\" }.join('|')\n\n Regexp.new(\"^#{fields_or}$\")\n end", "def patterns\n #@rules.every.pattern\n @rules.map {|r| r.pattern }\n end", "def extract_regexps(line)\n r = []\n line.scan(/\\s@(rx|dfa) (?:\"((?:\\\\\"|[^\"])+)\"|([^ ]+?))(\\s|$)/) {r << $2}\n r\nend", "def filtering_patterns\n @filtering_patterns.to_a\n end", "def deep_regexps; end", "def extensions_to_regex(exts)\n return [] if exts.empty?\n [\"(#{exts.join '|'})#{QUERY_REGEX}\"]\nend", "def optional_regexp\n @form.keys.each do |elem|\n Array(@profile[:optional_regexp]).each do |regexp|\n regexp = Regexp.new(regexp)\n if elem =~ regexp\n @optional_fields << elem unless @optional_fields.include?(elem)\n end\n end\n end\n @optional_fields\n end", "def build_matched_filter( filter, fields )\n result = []\n filter.each_with_index do |filter_field,index|\n result << (filter_field == \"*!\" ? \"*\" : fields[index])\n end\n result\n end", "def required_regexp\n @form.keys.each do |elem|\n Array(@profile[:required_regexp]).each do |regexp|\n regexp = Regexp.new(regexp)\n if elem =~ regexp\n @required_fields << elem unless @required_fields.include?(elem)\n @missing_fields.push(elem) if @form[elem].to_s.empty?\n end\n end\n end\n @missing_fields\n end", "def build_regexp(list)\n r = []\n list.each do |itm|\n r << \"#{ASFSVN.source}\\['#{itm}']\"\n end\n return Regexp.union(r)\nend", "def selected_fields *names\n names.flatten.map{|name| selected_field?(name) }.compact\n end", "def build_regex\n regex = \"((\"\n days = [:monday, :tuesday, :wednesday, :thursday, :friday, :saturday, :sunday, :weekday, :weekend, :day]\n days.each do |key|\n regex += build_match_pattern(names[key]) + \"|\"\n end\n and_ptn = build_match_pattern(names[:and])\n regex.chop + \")(\\\\s*(,|#{and_ptn})?\\\\s*)?)\"\n end", "def regexp\r\n unless defined? @regexp\r\n if self.nodes.find { |i| i.type =~ /^\".+\"$/ }\r\n # It's a very special regexp if there are constant fields\r\n re_str = self.nodes.inject(\"^#{name}#{Regexp.escape(field_separator)}\") { |s, i|\r\n field_re = i.simple_regexp(field_separator, segment_separator) + Regexp.escape(field_separator) + '?'\r\n field_re = \"(#{field_re})?\" unless i.required\r\n s + field_re\r\n } + Regexp.escape(segment_separator)\r\n @regexp = Regexp.new(re_str)\r\n else\r\n # Simple match\r\n @regexp = Regexp.new(\"^#{name}#{Regexp.escape(field_separator)}[^#{Regexp.escape(segment_separator)}]*#{Regexp.escape(segment_separator)}\")\r\n end\r\n # puts sprintf(\"%s %p\", name, @regexp)\r\n end\r\n @regexp\r\n end", "def expressions \n @expressions = []\n @expressions << parse_frequency_and_interval\n @expressions << send(:\"parse_#{self.rules[:freq].downcase}\") if self.rules[:freq]\n @expressions << parse_start\n @expressions << parse_until\n @expressions.compact!\n @expressions\n end", "def get_patterns\n patterns = BASE_PATTERNS\n # add the colour keywords. generate these from the colour wheel's constants\n colours = Yay::ColourWheel::all_names.join('|')\n patterns.unshift [:colour, Regexp.new(\"\\\\b(#{colours})\\\\b\", Regexp::IGNORECASE)]\n return patterns\n end", "def make_type_search_regex_table(note_type = ALL_NOTES)\n types_regexp = []\n if note_type == ALL_NOTES\n @settings_helper.get_settings[NotesSettings::NOTE_TAGS_SETTINGS].each {|type|\n # @log.debug \"adding type |#{type[\"name\"]}|=|#{type[\"value\"]}|\"\n types_regexp.push Regexp.new(type[\"value\"], true)\n }\n else\n @settings_helper.get_settings[NotesSettings::NOTE_TAGS_SETTINGS].each{|type|\n notes_regexp.push Regexp.new(type[\"value\"], true) if type[\"name\"] == note_type\n }\n end\n return types_regexp\n end", "def bots_to_regexp\n Regexp.union(bots)\n end", "def regexp_source; end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a formatter, based on the format specified in the options
def formatter @formatter ||= Unipept::Formatter.new_for_format(options[:format]) end
[ "def formatter\n unless @formatter\n fmt = options.fetch(:formatter, :plain)\n @formatter = case fmt\n when Symbol\n klass = \"Gruf::Instrumentation::RequestLogging::Formatters::#{fmt.to_s.capitalize}\"\n fmt = klass.constantize.new\n when Class\n fmt = fmt.new\n else\n fmt\n end\n raise Gruf::Instrumentation::RequestLogging::InvalidFormatterError unless fmt.is_a?(Gruf::Instrumentation::RequestLogging::Formatters::Base)\n end\n @formatter\n end", "def formatter\n unless @formatter\n fmt = options.fetch(:formatter, :plain)\n @formatter = case fmt\n when Symbol\n prefix = 'Gruf::Interceptors::Instrumentation::RequestLogging::Formatters::'\n klass = \"#{prefix}#{fmt.to_s.capitalize}\"\n fmt = klass.constantize.new\n when Class\n fmt = fmt.new\n else\n fmt\n end\n raise InvalidFormatterError unless fmt.is_a?(Formatters::Base)\n end\n @formatter\n end", "def format(formatter = self.class.formatter, **options)\n formatter.format(self, options)\n end", "def formatter\n @formatter ||= Formatters::Default.new\n end", "def formatter fmt\n @formatter = fmt\n end", "def option_format\n option_parser.on('-f', '--format NAME', 'output format') do |name|\n options[:format] = name\n end\n end", "def get_formatters(options)\n return FORMATTER_ORDER.collect do |f|\n next unless options.include? f\n next unless options[f]\n\n get_formatter(f, options[f])\n end.compact!\n end", "def get_formatters(options)\n return FORMATTER_ORDER.collect do |f|\n next unless options.include? f\n\n get_formatter(f, options[f])\n end.compact!\n end", "def get_formatter(sym, options)\n cls_name = sym.to_s.gsub(/_(\\w)/) {|m| m[1].upcase }\n cls_name[0] = cls_name[0].upcase\n cls_name += 'Formatter'\n\n if self.class.const_defined? cls_name then\n return self.class.const_get(cls_name).new(options)\n else\n return nil\n end\n end", "def get_formatter(sym, options)\n cls_name = sym.to_s.gsub(/_(\\w)/) {|m| m[1].upcase }\n cls_name[0] = cls_name[0].upcase\n cls_name += 'Formatter'\n\n if self.class.const_defined? cls_name then\n return self.class.const_get(cls_name).new(options)\n else\n #STDERR.puts \"formatter #{cls_name} not found\"\n return nil\n end\n end", "def determine_and_set_format options\n options.format = @template_format = options.format || @template_format\n end", "def formatter\n\t\treturn ( @formatter || @default_formatter )\n\tend", "def format\n @format || parser.format\n end", "def formatter\r\n @formatter ||= SimpleFormatter.new\r\n end", "def default_formatter; end", "def get_output_formats(options); end", "def format(style = nil, option = nil)\n case style\n when 'endnote'\n return endnote\n when 'bibitem'\n return bibitem(option)\n when 'bibtex'\n return bibtex(option)\n when 'rd'\n return rd(option)\n when /^nature$/i\n return nature(option)\n when /^science$/i\n return science\n when /^genome\\s*_*biol/i\n return genome_biol\n when /^genome\\s*_*res/i\n return genome_res\n when /^nar$/i\n return nar\n when /^current/i\n return current\n when /^trends/i\n return trends\n when /^cell$/i\n return cell\n else\n return general\n end\n end", "def format(*formatters); end", "def formatter\n raise NotImplementedError\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a request body (a Hash) for set of input strings, using the options supplied by the user.
def construct_request_body(input) names = selected_fields.empty? || selected_fields.any? { |f| f.to_s.include?('name') || f.to_s.include?('.*$') } { input: input, equate_il: options[:equate] == true, extra: options[:all] == true, names: options[:all] == true && names } end
[ "def request_body\n MAPPING.keys.inject({}) do |mem, e|\n next mem unless value = send(e)\n mem.merge!(e.to_s => value.to_json)\n end\n end", "def make_request_body(opts, headers); end", "def build_request_body(header_params, form_params, body)\n # http form\n if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||\n header_params['Content-Type'] == 'multipart/form-data'\n data = {}\n form_params.each do |key, value|\n case value\n when File, Array, nil\n # let typhoeus handle File, Array and nil parameters\n data[key] = value\n else\n data[key] = value.to_s\n end\n end\n elsif body\n data = body.is_a?(String) ? body : body.to_json\n else\n data = nil\n end\n data\n end", "def build_request_body(header_params, form_params, body)\n # http form\n if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||\n header_params['Content-Type'] == 'multipart/form-data'\n data = {}\n form_params.each do |key, value|\n case value\n when ::File, ::Array, nil\n # let typhoeus handle File, Array and nil parameters\n data[key] = value\n else\n data[key] = value.to_s\n end\n end\n elsif body\n data = body.is_a?(String) ? body : body.to_json\n else\n data = nil\n end\n data\n end", "def generate_body(type, args)\n args[:'accept-language'] = args[:accept_language] if args.key?(:accept_language)\n args.select { |key, _| valid_args(type).include?(key) }\n end", "def build_create_api_body(options)\n body = {}\n\n start_time = { dateTime: options.delete(:start_time).xmlschema }\n end_time = { dateTime: options.delete(:end_time ).xmlschema }\n summary = options.delete(:summary)\n description = options.delete(:description)\n location = options.delete(:location)\n\n attendees =\n attendeeify(options.delete(:participants), 'needsAction') +\n attendeeify(options.delete(:resources), 'accepted')\n\n body[:start] = start_time\n body[:end] = end_time\n body[:summary] = summary unless summary.nil?\n body[:description] = description unless description.nil?\n body[:attendees] = attendees unless attendees.empty?\n body[:location] = location unless location.nil?\n body\n end", "def build_request_body(header_params, form_params, body)\n # http form\n if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||\n header_params['Content-Type'] == 'multipart/form-data'\n data = {}\n form_params.each do |key, value|\n case value\n when ::File, ::Array, nil\n # let httparty handle File, Array and nil parameters\n data[key] = value\n else\n data[key] = value.to_s\n end\n end\n elsif body\n data = body.is_a?(String) ? body : body.to_json\n else\n data = nil\n end\n if header_params['Content-Encoding'] == 'gzip'\n gzip = Zlib::Deflate.new(nil, Zlib::MAX_WBITS + 16)\n data = gzip.deflate(data, Zlib::FINISH)\n gzip.close\n elsif header_params['Content-Encoding'] == 'deflate'\n data = Zlib::deflate(data)\n elsif header_params['Content-Encoding'] == 'zstd1'\n data = Zstandard.deflate(data)\n end\n data\n end", "def http_options(type)\n base = self.default_request_options\n if @options.present?\n if type == :get\n base[:query] = @options\n else\n base[:head]['Content-Type'] = \"application/x-www-form-urlencoded\"\n base[:body] = body = {}\n @options.each_pair { |k,v| body[CGI.escape(k.to_s)] = CGI.escape(v) }\n end\n end\n base\n end", "def construct_request_hash; end", "def form_body\n if body.is_a?(Hash)\n body.map do |k,v|\n [AwsRequest.aws_encode(k), AwsRequest.aws_encode(v)].join(\"=\")\n end.join(\"&\")\n else\n body\n end\n end", "def prepare_request_body(params, options={})\n if (@via == :post || @via == :put)\n options[:body] = params unless params.blank?\n else\n options[:query] = params unless params.blank?\n end\n options\n end", "def request_string(options = Hash.new,&block)\n request_string_core('Enter string:', 'RequestString', options, &block)\n end", "def build_payload(options)\n body = options[:body]\n mime = options[:mime]\n if mime\n # user set mime-type, let them deal with it :)\n # fix for ruby 1.8\n if body.is_a? File\n size = body.path.size\n else\n size = body.size\n end\n elsif body.is_a? Hash\n body = Yajl.dump body\n mime = \"application/json\"\n elsif SERIALIZEABLE_TYPES.include? body.class\n if ITERABLE_TYPES.include? body.class\n if is_set_of_strings? body\n # set of strings is primitive\n mime = \"application/vnd.fluiddb.value+json\"\n else\n # we have an Array with some non-String items\n mime = \"application/json\"\n end\n else\n # primitive type\n mime = \"application/vnd.fluiddb.value+json\"\n end\n body = Yajl.dump body\n else\n raise TypeError, \"You must supply the mime-type\"\n end\n [body, mime]\n end", "def body( args )\n params[:body] ||= {}\n if args.is_a? String\n params[:body][:text] = args\n elsif args.is_a? Hash\n params[:body][:html] = args[:html] if args.include? :html\n params[:body][:text] = args[:text] if args.include? :text\n else\n raise ArgumentError.new \"Invalid argument #{args.class} to #body\"\n end\n end", "def request_parameters\n Hash[(Tumblr::Client::POST_OPTIONS | [:id, :type]).map {|key|\n [key.to_s, send(key)] if respond_to?(key) && send(key)\n }]\n end", "def build_request(request_type, path, post_content)\n request = \"#{request_type} #{path} HTTP/1.0\\r\\n\"\\\n \"From: ashleymichal@gmail.com\\r\\n\"\\\n \"User-Agent: HTTPTool/1.0\\r\\n\"\n content = \"\"\n if request_type == \"POST\"\n content_length = post_content.length\n content = post_content\n # determine content_type, content_length\n request += \"Content-Type: JSON\\r\\n\"\\\n \"Content-Length: #{content_length}\\r\\n\"\\\n end\n [request, content].join(\"\\r\\n\")\nend", "def input(question, options = {})\n bool, list, noecho = options.to_options_consumer.consume_all(:bool, :list, :noecho)\n if list\n request_from_list(question, list, noecho)\n elsif bool\n request_from_bool(question, noecho)\n else\n request_string(question, noecho)\n end\n end", "def build_request path, opts\n opts[:method] ||= :get\n raise \"The :data option can only be used if :method => :post\" if opts[:method] != :post and opts[:data]\n opts[:params] = opts[:params].nil? ? {:wt => :ruby} : opts[:params].merge(:wt => :ruby)\n query = RSolr::Uri.params_to_solr(opts[:params]) unless opts[:params].empty?\n opts[:query] = query\n if opts[:data].is_a? Hash\n opts[:data] = RSolr::Uri.params_to_solr opts[:data]\n opts[:headers] ||= {}\n opts[:headers]['Content-Type'] ||= 'application/x-www-form-urlencoded'\n end\n opts[:path] = path\n opts[:uri] = base_uri.merge(path.to_s + (query ? \"?#{query}\" : \"\")) if base_uri\n opts\n end", "def prepare_request_body\n reputation_web_service_path = URI.parse(WEBSERVICE_CONFIG['reputation_web_service_url']).path\n post_req = Net::HTTP::Post.new(reputation_web_service_path, { 'Content-Type' => 'application/json', 'charset' => 'utf-8' })\n curr_assignment_id = (params[:assignment_id].empty? ? '754' : params[:assignment_id])\n assignment_id_list_peers = get_assignment_id_list(curr_assignment_id, params[:another_assignment_id].to_i)\n\n post_req.body = generate_json_for_peer_reviews(assignment_id_list_peers, params[:round_num].to_i).to_json\n\n post_req.body[0] = '' # remove the first '{'\n add_additional_info_details post_req\n post_req.body.prepend('{')\n add_flash_messages post_req\n post_req\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves an error to a new file in the .unipept directory in the users home directory.
def save_error(message) path = error_file_path FileUtils.mkdir_p File.dirname(path) File.write(path, message) warn "API request failed! log can be found in #{path}" end
[ "def create_error_file\n FileUtils.mkdir_p(File.dirname(error_file))\n File.new(error_file, 'w')\n end", "def write_error_report_to_file(text)\n File.open(\"errorfile\", \"a\") do |er|\n er.write \"#{text}\"\n end\nend", "def map_error_output(filename)\r\n\tDir.mkdir(\"#{settings.root}/tmp\") unless File.exists?(\"#{settings.root}/tmp\")\r\n\tfile = File.new(\"#{settings.root}/tmp/#{filename}\", 'a+')\r\n\tfile.sync = true\r\n\t$stderr.reopen file\r\nend", "def record_error (error)\n\n path = get_path(error.fei)\n\n dirpath = File.dirname(path)\n\n FileUtils.mkdir_p(dirpath) unless File.exist?(dirpath)\n\n File.open(path, 'a+') do |f|\n f.puts(error.to_yaml)\n end\n end", "def add_to_errors_file(filename,output)\n self.add_to_file(filename,output)\n end", "def writeToErrorFile(line)\n File.open(@@errorFile.path, 'a') do |file|\n file.puts(line)\n line = nil\n file.close\n end\n end", "def error( message )\n @errors_found = true\n output( '### Error : ' + @file.sub(\"/\", \"\\\\\") + ' : ' + message )\n output( '' )\nend", "def save_error_log()\n CSV.open(@@log_file_location + \"error_log.csv\", \"w\") do |csv| \n csv << [\"bug_id\",\"file\",\"response_code\"]\n @errors.each do |error|\n csv << error\n end\n end\n\n puts \"Error log saved to #{@@log_file_location}error_log.csv\"\n end", "def copy_error_log_to (wfid, path)\n\n original_path = get_path(wfid)\n FileUtils.copy_file(original_path, path)\n end", "def write_failure_file_if_necessary_at_beginning\n with_optional_failures_filename do |filename|\n File.open(filename.to_s, \"w\") do |file|\n file << \"Build CRASHED; this error is written out when the build starts, and replaced when it fails or succeeds normally. This is a hard-core problem like a JVM crash of the buildsystem, or something similar, instead.\\n\"\n end\n end\n end", "def handle_error(cmd, stderr)\n summary = \"\\rError running \\`#{cmd}\\`\"\n details = readable_curr_time << \"\\n\\n\"\n details << \"**************************************************************\\n\"\n details << \"#{summary}\\n\"\n details << \"**************************************************************\\n\"\n details << stderr << \"\\n\\n\"\n File.open(@err_path, 'a') { |file| file.write(details) }\n summary\nend", "def user_error_filepath\n \"parse_logs/#{study_file.id}/user_log.txt\"\n end", "def error(message='')\n @logfile.write(\"#{Time.now}#{ERROR}#{message}\\n\")\n @logfile.rewind\n end", "def write_error (row, e)\n write_row(row,\n errors_filename,\n errors)\n write_exception(row, e)\n end", "def error_logger(e)\n File.open(\"error_log.txt\", \"a\") do |file|\n file.puts e\n end\nend", "def save_exception(error)\n app_error = ApplicationError.new\n user_email = ''\n if request.path.include?('admin') && current_admin.present?\n user = current_admin\n elsif defined?(current_user) && current_user.present?\n user = current_user\n end\n user_email = user.email if user.present?\n app_error.user_id = user.id if user.present?\n app_error.error = error.to_s + \"#{ error.backtrace[0] if error.backtrace[0].present?}\"\n app_error.url = request.url\n if app_error.save\n ApplicationMailer.error_notify(ADMIN_EMAIL, user_email, app_error.error, app_error.url).deliver_later\n end\n end", "def save_errors(config)\n # get the location of the config file, we'll use the same dir\n # and base name\n path = \"#{config.config_path}.errors\"\n if @metrics[:failed_list].empty?\n # delete any existing file if we have no errors\n File.delete(path) if File.exist?(path)\n else\n # otherwise save the errors to file\n File.write(path, @metrics[:failed_list].to_yaml)\n end\n end", "def dump_errors_to( io )\n if results.error_count > 0 then\n io.puts \"error_reason,filename\"\n results.each_error do |d|\n io.puts \"#{d['error_reason']},#{d['filename']}\"\n end\n end\n nil\n end", "def append_and_rm_err(outfile = 'out.txt', errfile = 'err.txt')\n err_contents = File.read(errfile)\n display_errors(err_contents)\n log_errors(err_contents, outfile)\n FileUtils.rm errfile\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses the json_response, wraps it in an array if needed and filters the fields based on the selected_fields
def filter_result(json_response) result = JSON[json_response] rescue [] result = [result] unless result.is_a? Array key_order = result.first.keys if result.first result = flatten_functional_fields(result) if formatter.instance_of?(Unipept::CSVFormatter) result.map! { |r| r.select! { |k, _v| selected_fields.any? { |f| f.match k } } } unless selected_fields.empty? result = inflate_functional_fields(result, key_order) if formatter.instance_of?(Unipept::CSVFormatter) && result.first result end
[ "def getCustomfields(response)\r\n\t\t\t\r\n\t\t\t\tjsonObject = JSON.parse response\r\n\t\t\t\t\r\n\t\t\t\tcustomFields = Array.new\r\n\t\t\t\t\r\n\t\t\t\tif jsonObject.has_key?(\"customfields\")\r\n\t\t\t\t\r\n\t\t\t\t\tcustomfields = jsonObject[\"customfields\"]\r\n\t\t\t\t\t\r\n\t\t\t\t\tfor i in 0...customfields.length\r\n\t\t\t\t\t\r\n\t\t\t\t\t\tcustomFields.push(jsonToCustomfield(customfields[i]))\r\n\t\t\t\t\t\t\r\n\t\t\t\t\tend\r\n\t\t\t\t\t\r\n\t\t\t\tend\r\n\t\t\t\t\r\n\t\t\t\treturn customFields\r\n\t\t\t\r\n\t\t\tend", "def filter_response_content!\n if @response_content.is_a?(Array) && !@filter_params.empty?\n attributes = {}\n @filter_params.each do |key, value|\n attributes = deep_merge(attributes, dot_notation_to_hash(key, value))\n end\n @response_content.select! do |object|\n attributes_match?(object, attributes, false)\n end\n end\n end", "def prepare_response(response)\n JSON.parse(response)\n end", "def filter_json json\n json.each do |name,hash|\n fields = hash[:fields]\n values = hash[:values]\n hash[:fields] = fields = filter_fields fields\n hash[:values] = values.keep_if do |record|\n filter_record fields,record\n end\n end\n end", "def extract_data_from_response(response)\n if response.nil?\n return []\n end\n body = nil\n begin\n body = JSON.parse(response.body)\n rescue JSON::ParserError => e\n @exception = e\n return []\n end\n if !body.is_a?(Hash) || body.nil?\n return []\n end\n body\n end", "def process_remaining_json_fields\n fields_hash.dup.each do |key, field|\n fields_hash.delete(key) if json_field?(field)\n end\n end", "def parse_response(response, **options)\n json = parse_body(response.body)\n json = json[options[:object]] if options.key?(:object)\n json.is_a?(Array) ? json.map { |a| new(a) } : new(json)\n end", "def parse_response response\n JSON.parse(response)\n end", "def getDefaultFields(response)\r\n\t\t\t\r\n\t\t\t\tjsonObject = JSON.parse response\r\n\t\t\t\t\r\n\t\t\t\tdefaultField = Defaultfield.new\r\n\t\t\t\t\r\n\t\t\t\tif jsonObject.has_key?(\"defaultfields\")\r\n\t\t\t\t\r\n\t\t\t\t\tdefaultFields = jsonObject[\"defaultfields\"]\r\n\t\t\t\t\r\n\t\t\t\t\tif defaultFields.has_key?(\"severity_details\")\r\n\t\t\t\t\r\n\t\t\t\t\t\tseveritydetails = defaultFields[\"severity_details\"]\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tseverityDetails = Array.new\r\n\t\t\t\t\t\r\n\t\t\t\t\t\tfor i in 0...severitydetails.length\r\n\t\t\t\t\t\r\n\t\t\t\t\t\t\tseverityDetails.push(jsonToHash(severity_details[i]))\r\n\t\t\t\t\t\tend\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tdefaultField.setSeverityDetails(severityDetails)\r\n\t\t\t\t\tend\r\n\t\t\t\t\t\r\n\t\t\t\t\tif defaultFields.has_key?(\"status_deatils\")\r\n\t\t\t\t\t\r\n\t\t\t\t\t\tstatusdeatils = defaultFields[\"status_deatils\"]\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tstatusDeatils = Array.new\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tfor i in 0...statusdeatils.length\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tstatusDeatils.push(jsonToHash(statusdeatils[i]))\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\tend\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tdefaultField.setStatusDeatils(statusDeatils)\r\n\t\t\t\t\tend\r\n\t\t\t\t\t\r\n\t\t\t\t\tif defaultFields.has_key?(\"module_details\")\r\n\t\t\t\t\t\r\n\t\t\t\t\t\tmoduledetails = defaultFields[\"module_details\"]\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tmoduleDetails = Array.new\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tfor i in 0...moduledetails.length\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tmoduleDetails.push(jsonToHash(moduledetails[i]))\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\tend\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tdefaultField.setModuleDetails(moduleDetails)\r\n\t\t\t\t\tend\r\n\t\t\t\t\t\r\n\t\t\t\t\tif defaultFields.has_key?(\"priority_details\")\r\n\t\t\t\t\t\r\n\t\t\t\t\t\tprioritydetails = defaultFields[\"priority_details\"]\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tpriorityDetails = Array.new\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tfor i in 0...prioritydetails.length\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tpriorityDetails.push(jsonToHash(prioritydetails[i]))\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\tend\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tdefaultField.setPriorityDetails(priorityDetails)\r\n\t\t\t\t\tend\r\n\t\t\t\t\t\r\n\t\t\t\t\tif defaultFields.has_key?(\"classification_details\")\r\n\t\t\t\t\t\r\n\t\t\t\t\t\tclassificationdetails = defaultFields[\"classification_details\"]\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tclassificationDetails = Array.new\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tfor i in 0...classificationdetails.length\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tclassificationDetails.push(jsonToHash(classificationdetails[i]))\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\tend\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tdefaultField.setClassificationDetails(classificationDetails)\r\n\t\t\t\t\tend\r\n\t\t\t\t\t\r\n\t\t\t\tend\r\n\t\t\t\t\r\n\t\t\t\treturn defaultField\r\n\t\t\tend", "def filter_results\n @json.select{|item| item[@filter_field].include?(@filter_val)}\n end", "def parse_event_fields(response)\n event_fields = attributes_to_hash(response, \"//customField\", \"id\", \"//listItem\", \"name\")\n end", "def parse_response(response)\n data = response.body\n\n data.split(ROWS_SPLITTER).inject([]) do |array, row|\n suffix, occurrences = row.split(ATTRIBUTES_SPLITTER)\n\n if occurrences.to_i > 0\n array << Models::Password.new(suffix: suffix, occurrences: occurrences.to_i)\n end\n\n array\n end\n end", "def extract_json_list(json_list, field_to_extract)\n lambda do |record, accumulator|\n values = []\n list = record[json_list]\n return unless list\n\n list.each do |val|\n values << val[field_to_extract]\n end\n accumulator.replace(values)\n end\n end", "def parse_request_result(result)\n if result.nil?\n []\n else\n json = result.read\n\n if json.nil?\n []\n else\n r = JSON.parse(json)\n\n # Add the etag to the response only for individual entities\n if result.meta['etag'] and r.class != Array\n r['etag'] = result.meta['etag']\n end\n\n r\n end\n end\n end", "def process_select_and_deny_fields\r\n only = @form['result_set']['select_fields'] || @form['result_set']['only']\r\n @records = @records.only( separated_to_symbols(only) ) if only\r\n\r\n without = @form['result_set']['deny_fields'] || @form['result_set']['without']\r\n @records = @records.without( separated_to_symbols(without) ) if without\r\nend", "def extract_data!\n # Make sure @json_response is a valid JSON Hash:\n if @json_response.instance_of?( Hash )\n @is_processed = true\n # Extract each interesting data field and store it into dedicated members:\n if @json_response['results'].first\n @formatted_address = @json_response['results'].first['formatted_address']\n @place_id = @json_response['results'].first['place_id']\n\n address_components = @json_response['results'].first['address_components']\n @postal_code_name = find_types_key_and_return_short_name( address_components, 'postal_code' )\n @country_name = find_types_key_and_return_short_name( address_components, 'country' )\n @administrative_area_level_1_name = find_types_key_and_return_short_name( address_components, 'administrative_area_level_1' )\n @administrative_area_level_2_name = find_types_key_and_return_short_name( address_components, 'administrative_area_level_2' )\n @administrative_area_level_3_name = find_types_key_and_return_short_name( address_components, 'administrative_area_level_3' )\n @locality_name = find_types_key_and_return_short_name( address_components, 'locality' )\n @route_name = find_types_key_and_return_short_name( address_components, 'route' )\n @street_number_name = find_types_key_and_return_short_name( address_components, 'street_number' )\n\n geometry = @json_response['results'].first['geometry']\n @location_lat = geometry['location']['lat']\n @location_lng = geometry['location']['lng']\n end\n end\n end", "def read_fields\n pipeline_fields = pipeline.fields\n response = Hash.new\n\n pipeline_fields.each do |full_field|\n box_field = fields.find { |bf| bf[0] == full_field.key }\n\n field_name = full_field.name\n field_value = []\n\n if box_field.present?\n field_value = case full_field.type\n when 'TAG'\n full_field.tagSettings['tags'].select { |tag| tag['key'].in? box_field[1] }.map { |f| f['tag'] }\n when 'DROPDOWN'\n full_field.dropdownSettings['items'].find { |item| item['key'] == box_field[1] }['name']\n when 'DATE'\n Time.at(box_field[1]/1000).to_date\n when 'PERSON'\n box_field[1].map { |person| \"#{person['fullName']} (#{person['email']})\" }\n else # 'TEXT_INPUT', 'CHECKBOX', or other\n box_field[1]\n end\n end\n\n response[field_name] = field_value\n end\n\n response\n end", "def parse_response(response)\n begin\n body = MultiJson.load(response.body)\n rescue Exception => e\n raise ClickSendError, e.message\n end\n end", "def filter_array_of_hashes_based_on_mandatory_fields(complete_arr_response,arr_of_mand_fields)\n $log.info \"OzoneAutomationCommon :: filter_array_of_hashes_based_on_mandatory_fields\"\n array_of_filtered_hashes = Array.new\n complete_arr_response.collect { |single_hash|\n filtered_hash = Hash.new\n arr_of_mand_fields.each do |el|\n if el == :images\n complete_arr_images_response = Array.new\n complete_arr_images_response = single_hash[el]\n img_arr_mand_fields = [:width,:height,:url]\n filtered_hash[el] = filter_array_of_hashes_based_on_mandatory_fields(complete_arr_images_response,img_arr_mand_fields)\n else\n filtered_hash[el]=single_hash[el]\n end\n end\n $log.info \"Filtered hash is ************************ #{filtered_hash}<br>\"\n array_of_filtered_hashes.push(filtered_hash) }\n array_of_filtered_hashes\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /cta_ctes GET /cta_ctes.json
def index @cta_ctes = CtaCte.all end
[ "def index\n @cta = Ctum.all\n end", "def index\n @cta = Cta.all\n end", "def census_tracts\n self.class.get('/census-tracts', @options)\n end", "def index\n @ctecs = Ctec.all\n end", "def index\n @ctos = Cto.all\n end", "def index\n @cts = Ct.all\n end", "def list_tenants_for_circle(args = {}) \n get(\"/tenantcircles.json/tenants\", args)\nend", "def create\n @cta_cte = CtaCte.new(cta_cte_params)\n\n respond_to do |format|\n if @cta_cte.save\n format.html { redirect_to @cta_cte, notice: 'Se creo correctamente.' }\n format.json { render :show, status: :created, location: @cta_cte }\n else\n format.html { render :new }\n format.json { render json: @cta_cte.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @cta = Cta.new(cta_params)\n\n respond_to do |format|\n if @cta.save\n format.html { redirect_to @cta, notice: 'cta was successfully created.' }\n format.json { render action: 'show', status: :created, location: @cta }\n else\n format.html { render action: 'new' }\n format.json { render json: @cta.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @cfcts = Cfct.all\n end", "def list_tenants_for_circles(args = {}) \n get(\"/tenants.json/circles\", args)\nend", "def index\n @tccapis = Tccapi.all\n end", "def index\n @cets = Cet.all\n end", "def census_tract(id)\n self.class.get(\"/census-tracts/#{id}\", @options)\n end", "def index\n @cts = Ct.order(\"created_at desc\")\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @cts }\n end\n end", "def index\n\n @ctacte = @local.ctactes.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @ctactes }\n end\n end", "def cft_list\n @client.make_request :get, templates_path('cft')\n end", "def index\n @cctvs = Cctv.all\n end", "def index\n @cotacts = Cotact.all\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /cta_ctes POST /cta_ctes.json
def create @cta_cte = CtaCte.new(cta_cte_params) respond_to do |format| if @cta_cte.save format.html { redirect_to @cta_cte, notice: 'Se creo correctamente.' } format.json { render :show, status: :created, location: @cta_cte } else format.html { render :new } format.json { render json: @cta_cte.errors, status: :unprocessable_entity } end end end
[ "def create\n @cta = Cta.new(cta_params)\n\n respond_to do |format|\n if @cta.save\n format.html { redirect_to @cta, notice: 'cta was successfully created.' }\n format.json { render action: 'show', status: :created, location: @cta }\n else\n format.html { render action: 'new' }\n format.json { render json: @cta.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @ct = current_user.cts.new(params[:ct])\n\n respond_to do |format|\n if @ct.save\n format.html { redirect_to @ct, notice: 'Ct was successfully created.' }\n format.json { render json: @ct, status: :created, location: @ct }\n else\n format.html { render action: \"new\" }\n format.json { render json: @ct.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @ct = Ct.new(ct_params)\n\n respond_to do |format|\n if @ct.save\n format.html { redirect_to @ct, notice: 'Ct was successfully created.' }\n format.json { render :show, status: :created, location: @ct }\n else\n format.html { render :new }\n format.json { render json: @ct.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @cta_ctes = CtaCte.all\n end", "def create\n @cfct = Cfct.new(cfct_params)\n\n respond_to do |format|\n if @cfct.save\n format.html { redirect_to @cfct, notice: 'Cfct was successfully created.' }\n format.json { render :show, status: :created, location: @cfct }\n else\n format.html { render :new }\n format.json { render json: @cfct.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @ctec = Ctec.new(ctec_params)\n\n respond_to do |format|\n if @ctec.save\n format.html { redirect_to @ctec, notice: 'Ctec was successfully created.' }\n format.json { render action: 'show', status: :created, location: @ctec }\n else\n format.html { render action: 'new' }\n format.json { render json: @ctec.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @cto = Cto.new(cto_params)\n\n respond_to do |format|\n if @cto.save\n format.html { redirect_to @cto, notice: 'Cto was successfully created.' }\n format.json { render action: 'show', status: :created, location: @cto }\n else\n format.html { render action: 'new' }\n format.json { render json: @cto.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @cta = Ctum.all\n end", "def add_tenant_circle(args = {}) \n post(\"/tenantcircles.json/\", args)\nend", "def create\n @tccapi = Tccapi.new(tccapi_params)\n\n respond_to do |format|\n if @tccapi.save\n format.html { redirect_to @tccapi, notice: 'Tccapi was successfully created.' }\n format.json { render :show, status: :created, location: @tccapi }\n else\n format.html { render :new }\n format.json { render json: @tccapi.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @tcb = Tcb.new(params[:tcb])\n\n respond_to do |format|\n if @tcb.save\n format.html { redirect_to(tcbs_url,\n :notice => \"Tcb #{@tcb.name} was successfully created.\") }\n format.json { render :json => @tcb,\n :status => :created, :location => @tcb }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @tcb.errors,\n :status => :unprocessable_entity }\n end\n end\n end", "def create\n @cctv = Cctv.new(cctv_params)\n\n respond_to do |format|\n if @cctv.save\n format.html { redirect_to @cctv, notice: 'Cctv was successfully created.' }\n format.json { render :show, status: :created, location: @cctv }\n else\n format.html { render :new }\n format.json { render json: @cctv.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @taco = Taco.new(taco_params)\n\n if @taco.save\n render json: @taco, status: :created, location: @taco\n else\n render json: @taco.errors, status: :unprocessable_entity\n end\n end", "def create\n @taco = Taco.new(taco_params)\n if @taco.save\n render status: :ok, json: @taco\n else\n render status: :unprocessable_entity, json: { message: @taco.errors.full_messages }\n end\n end", "def create\n @cotact = Cotact.new(cotact_params)\n\n respond_to do |format|\n if @cotact.save\n format.html { redirect_to @cotact, notice: 'Cotact was successfully created.' }\n format.json { render :show, status: :created, location: @cotact }\n else\n format.html { render :new }\n format.json { render json: @cotact.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @cta_cte.update(cta_cte_params)\n format.html { redirect_to @cta_cte, notice: 'Cta cte was successfully updated.' }\n format.json { render :show, status: :ok, location: @cta_cte }\n else\n format.html { render :edit }\n format.json { render json: @cta_cte.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @cta = Cta.all\n end", "def create\n @cerc = Cerc.new(params[:cerc])\n\n if @cerc.save\n render json: @cerc, status: :created, location: @cerc\n else\n render json: @cerc.errors, status: :unprocessable_entity\n end\n end", "def create\n @dtc = Dtc.new(dtc_params)\n\n respond_to do |format|\n if @dtc.save\n format.html { redirect_to @dtc, notice: 'Dtc was successfully created.' }\n format.json { render action: 'show', status: :created, location: @dtc }\n else\n format.html { render action: 'new' }\n format.json { render json: @dtc.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /cta_ctes/1 PATCH/PUT /cta_ctes/1.json
def update respond_to do |format| if @cta_cte.update(cta_cte_params) format.html { redirect_to @cta_cte, notice: 'Cta cte was successfully updated.' } format.json { render :show, status: :ok, location: @cta_cte } else format.html { render :edit } format.json { render json: @cta_cte.errors, status: :unprocessable_entity } end end end
[ "def update\n respond_to do |format|\n if @cta.update(cta_params)\n format.html { redirect_to @cta, notice: 'cta was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @cta.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_tenant_circle(args = {}) \n put(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend", "def update\n respond_to do |format|\n if @cto.update(cto_params)\n format.html { redirect_to @cto, notice: 'Cto was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @cto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @ct = current_user.cts.find(params[:id])\n\n respond_to do |format|\n if @ct.update_attributes(params[:ct])\n format.html { redirect_to @ct, notice: 'Ct was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @ct.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @cfct.update(cfct_params)\n format.html { redirect_to @cfct, notice: 'Cfct was successfully updated.' }\n format.json { render :show, status: :ok, location: @cfct }\n else\n format.html { render :edit }\n format.json { render json: @cfct.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @ctec.update(ctec_params)\n format.html { redirect_to @ctec, notice: 'Ctec was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @ctec.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @taco = Taco.find(params[:id])\n\n if @taco.update(taco_params)\n head :no_content\n else\n render json: @taco.errors, status: :unprocessable_entity\n end\n end", "def update\n @taco = Taco.find(params[:id])\n\n respond_to do |format|\n if @taco.update_attributes(params[:taco])\n format.html { redirect_to @taco, notice: 'Taco was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @taco.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @cotact.update(cotact_params)\n format.html { redirect_to @cotact, notice: 'Cotact was successfully updated.' }\n format.json { render :show, status: :ok, location: @cotact }\n else\n format.html { render :edit }\n format.json { render json: @cotact.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @tccapi.update(tccapi_params)\n format.html { redirect_to @tccapi, notice: 'Tccapi was successfully updated.' }\n format.json { render :show, status: :ok, location: @tccapi }\n else\n format.html { render :edit }\n format.json { render json: @tccapi.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @tcb = Tcb.find(params[:id])\n\n respond_to do |format|\n if @tcb.update_attributes(params[:tcb])\n format.html { redirect_to(tcbs_url,\n :notice => \"Tcb #{@tcb.name} was successfully updated.\") }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @tcb.errors,\n :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @ctantom.update(ctantom_params)\n format.html { redirect_to @ctantom, notice: 'Ctantom was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @ctantom.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @cerc = Cerc.find(params[:id])\n\n if @cerc.update_attributes(params[:cerc])\n head :no_content\n else\n render json: @cerc.errors, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @tco.update(tco_params)\n format.html { redirect_to @tco, notice: 'Tco was successfully updated.' }\n format.json { render :show, status: :ok, location: @tco }\n else\n format.html { render :edit }\n format.json { render json: @tco.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @cst = Cst.find(params[:id])\n\n respond_to do |format|\n if @cst.update_attributes(params[:cst])\n format.html { redirect_to @cst, notice: 'Cst was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @cst.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @cpt_operation.update(cpt_operation_params)\n format.html { redirect_to @cpt_operation, notice: 'Cpt operation was successfully updated.' }\n format.json { render :show, status: :ok, location: @cpt_operation }\n else\n format.html { render :edit }\n format.json { render json: @cpt_operation.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @caso = Caso.find(params[:id])\n\n respond_to do |format|\n if @caso.update_attributes(params[:caso])\n format.html { redirect_to @caso, notice: 'Caso was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @caso.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @tyc_cid.update(tyc_cid_params)\n format.html { redirect_to @tyc_cid, notice: 'Cid was successfully updated.' }\n format.json { render :show, status: :ok, location: @tyc_cid }\n else\n format.html { render :edit }\n format.json { render json: @tyc_cid.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @ccr.update(ccr_params)\n format.html { redirect_to @ccr, notice: 'Ccr was successfully updated.' }\n format.json { render :show, status: :ok, location: @ccr }\n else\n format.html { render :edit }\n format.json { render json: @ccr.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
SEND: XMPP General method for sending xmppmessages. Notce! clientparameter contains the client that is used to send the message, not the client that is receving the message
def sendMessage(args, client = @send_client) jabmsg = Jabber::Message::new(args[:receiver], args[:message]).set_type(:chat).set_id('1') begin Timeout::timeout(10) do client.send(jabmsg) puts "XMPP TO: " + args[:receiver].to_s puts "XMPP MESSAGE: " + args[:message].to_s end rescue => e puts "XMPP Exception in sending: " + e + "\n" puts "XMPP Reconnecting to server and trying again" puts " (-- line #{e.backtrace[0].to_s} )" if client == @receive_client puts "re-connecting to RECEIVE_client" connect(@receive_client) else puts "re-connecting to SEND_client" connect(@@send_client_info) end retry end end
[ "def send_message message\n message = \"#{message}\\n\"\n puts \"client << #{message}\"\n send_data message\n end", "def send_message(subject, message, recipients, adminEmail, params)\n # execute_operation(:send_message, { nickname: nickname, subject: subject, recipients: recipients, message: message, adminEmail: adminEmail params: params })\n raise RuntimeError, 'Not implemented'\n end", "def send_message(jid,text)\n m = Jabber::Message.new(jid, text)\n m.set_type :chat\n @client.send m\n end", "def send_message\n send_user_id, target_user_id, content = params[:send_user_id], params[:target_user_id], params[:conent]\n message_hash = {\n send_user_id: send_user_id,\n target_user_id: target_user_id,\n content: content\n }.keep_if{|k,v| v.present? }\n message = Message.new(message_hash)\n\n if message.save\n # push message to sockect server\n push_message({message: message})\n\n render json: {sucess: true, message_sequence: message.message_sequence, id: message.id}\n else\n render json: message.errors\n end\n end", "def send_message(message)\n client.puts message\n end", "def send_message(user)\n Log.logger.debug(\"sending message to user %s\" % user)\n m = Jabber::Message.new(user, generate_message)\n client.send(m)\n Log.logger.debug(\"sent message\")\n end", "def sendMessage *args\n options=fill_args [\n :projectid,:messagetext,:userid,:username\n ],[\n :projectid,:messagetext\n ],*args\n if options[:username]==nil && options[:userid]==nil\n raise \"Username or userid is required\"\n end\n if options[:username]!=nil && options[:userid]!=nil\n raise \"Both username and userid is not allowed\"\n end\n request \"/Message/sendMessage.json\", options\n end", "def sendChatMessage(a_to, a_text)\n# \t\tp 'JabberClient.sendChatMessage'\n\t\tsendMessage(a_to,a_text,:chat)\n\tend", "def send_message(*args)\n if args[0].kind_of? Message\n message = args[0]\n else\n message = Message.new(*args)\n end\n request = message.send :to_proto\n response = make_sync_call('SendMessage', request,\n Proto::XmppMessageResponse)\n response.status_iterator.to_a\n rescue ApiProxy::ApplicationException => ex\n case Proto::ErrorCode.value_of(ex.application_error)\n when Proto::ErrorCode::INVALID_JID\n raise ArgumentError, \"Invalid jabber ID\"\n when Proto::ErrorCode::NO_BODY\n raise ArgumentError, \"Missing message body\"\n when Proto::ErrorCode::INVALID_XML\n raise ArgumentError, \"Invalid XML body\"\n when Proto::ErrorCode::INVALID_TYPE\n raise ArgumentError, \"Invalid type #{message.type.inspect}\"\n else\n raise XMPPError, 'Unknown error sending message'\n end\n end", "def send_client_message(client, message)\n nickname = @connections[client]\n @connections.each_key do |other_client|\n unless other_client == client\n other_client.puts 'M' + @spaces + nickname + ': ' + message\n end\n end\n end", "def send_msg(data, connection)\n # TODO\n end", "def message(msg)\n @instance.client.sendClientsMessage(padID: @id, msg: msg)\n end", "def send_msg(data, connection)\n # TODO\n end", "def send_to_user(user, parameters = nil)\n result = case self[:type]\n\n when /single/\n if parameters.nil?\n if Ecircle.configure.use_priority\n Ecircle.client.\n send_priority_single_message_to_user(:singleMessageId => @id,\n :userId => user.id)\n else\n Ecircle.client.\n send_single_message_to_user(:singleMessageId => @id,\n :userId => user.id)\n end\n else\n paras = { :singleMessageId => @id,\n :userId => user.id,\n :names => parameters.keys,\n :values => parameters.values,\n }\n\n if Ecircle.configure.use_priority\n Ecircle.client.send_priority_parametrized_single_message_to_user(paras)\n else\n Ecircle.client.send_parametrized_single_message_to_user(paras)\n end\n end\n\n when /normal/\n # raise an exception because this is inconsistent: a group message without\n # group_id is not possible.\n raise MessageGroupNotDefined, \"MsgId: #{self.id}\" unless self[:group_id]\n\n Ecircle.client.\n send_group_message_to_user(:userId => user.id,\n :messageId => @id,\n :groupid => self[:group_id])\n else\n raise(MessageTypeUnknown, \"Type: #{self[:type]} unknown for \"+\n \"MsgId: #{self.id}\")\n end\n\n # strangely, if the message sending worked out, then ecircle sends nil, i.e.\n # nothing back. Else we get some sort of strange error or exception.\n result.nil? ? [true, nil] : [false, result]\n end", "def send_message(message)\n @socket.send(message << \"\\n\", 0, nil, @client)\n end", "def send_msg(data, connection)\n connection.send_msg(data)\n end", "def sendmsg(message)\n text = message.respond_to?(:sendmsg) ? message.sendmsg : message.to_s\n message = \"sendmsg\\n%s\\n\" % text\n self.respond_to?(:send_data) ? send_data(message) : message\n end", "def send(message)\n message.reply_to_address = @reply_address\n @producer.send(message)\n @send_count += 1\n end", "def sendChatMessage(a_to, a_text)\n\t\tp 'JabberClient.sendChatMessage'\n\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles xmpp2restmessages that are received.
def handleMessage(msg) if msg != nil and msg.type == :chat and msg.body #and msg.from == @@visualRESTmain #puts "#{msg.from}:" #puts "#{msg.body.strip}" puts "Validating.." begin doc = XML::Document.string(msg.body) doc.validate(@dtd) puts "..xml was valid".background(:green) rescue => e puts "..xml NOT valid!".background(:red) notification = {:receiver => msg.from, :message => "xml not valid"} sendMessage(notification, @receive_client) return end puts "Parsing.." begin method = (doc.find_first('//xmpp2rest/method')) ? doc.find_first('//xmpp2rest/method').content.to_s : nil method = method.downcase case method when 'create' Thread.new{ createResouce(doc, msg.from) } when 'read' Thread.new{ readResouce(doc, msg.from) } when 'update' Thread.new{ updateResouce(doc, msg.from) } when 'delete' Thread.new{ deleteResource(doc, msg.from) } else puts "unknown method" end rescue Exception => e puts "Problem in parsing xml-filelist: " + e.to_s puts " --line " + e.backtrace[0].to_s end end end
[ "def process_msgs\n end", "def receive_sms \n sender_tel = params[:From] || \"\"\n body = params[:Body] || \"\"\n body_tokens = body.split(\" \")\n\n logger.debug \"Received a message from tel: #{sender_tel} with body: #{body}\"\n\n if body_tokens.size == 0\n render 'process_bad_party_id.xml.erb', :content_type => 'text/xml' and return\n end\n\n @party_token = body_tokens[0].to_i\n @party = Party.find_by(token: @party_token)\n logger.debug \"Assuming party_token: #{@party_token}\"\n\n if @party.nil?\n logger.debug \"got an SMS request with a bad party token\"\n render 'process_bad_party_id.xml.erb', :content_type => 'text/xml' and return\n end\n\n if body_tokens.size == 1\n logger.debug \"got an SMS request for party status\"\n @waiting_list_pos = @party.waiting_list_position\n render 'process_sms.xml.erb', :content_type => 'text/xml' and return\n end\n\n twilio_format_phone = \"+1\" + @party.phone.gsub(/[^0-9]/, '')\n \n # for editing functions, cancel, drop, size, must be from the party phone number in the db\n if (body_tokens.size > 1) && ([\"cancel\", \"drop\", \"size\"].include?(body_tokens[1])) && (sender_tel != twilio_format_phone)\n logger.debug \"got an SMS request for to edit a party from unauthorized number (#{sender_tel} but need #{twilio_format_phone})\"\n render 'process_unauthorized_sms.xml.erb', :content_type => 'text/xml' and return\n end\n\n if (body_tokens.size == 2) && (body_tokens[1] == \"cancel\")\n logger.debug \"got an SMS request to cancel party\"\n @party.update_attributes(party_status: PartyStatus.find_by(name: \"exited\"))\n render 'process_cancel_sms.xml.erb', :content_type => 'text/xml' and return\n end\n\n ## wait on implementing this\n if (body_tokens.size == 2) && (body_tokens[1] == \"drop\")\n logger.debug \"got an SMS request to drop down party\"\n render 'process_drop_sms.xml.erb', :content_type => 'text/xml' and return\n end\n\n if (body_tokens.size == 3) && (body_tokens[1] == \"size\")\n logger.debug \"got an SMS request to change party size\"\n @old_size = @party.size\n @party.update_attributes(size: body_tokens[2].to_i) \n render 'process_change_size_sms.xml.erb', :content_type => 'text/xml' and return\n end\n\n # an invalid command\n logger.debug \"got an SMS request that was invalid\"\n render 'process_bad_sms_command.xml.erb', :content_type => 'text/xml' and return\n end", "def incoming \n response.headers[\"Content-Type\"] = \"text/plain; charset=utf-8\"\n #Read params from the text message\n \n if (params[:uid] && params[:body])\n @userid = params[:uid]\n @body = params[:body] \n sms = ZeepSms.new(:raw => @body, :login => @userid)\n end\n \n end", "def get_messages\n @connection.uid_search(@filter).each do |message|\n puts \"PROCESSING MESSAGE #{message}\"\n body=@connection.uid_fetch(message,\"RFC822\")[0].attr[\"RFC822\"]\n @processor.process(body, @options)\n @connection.uid_copy(message, 'Processed')\n\n @connection.uid_store(message,\"+FLAGS\",[:Deleted])\n end\n @connection.expunge\n #@connection.delete_all\n end", "def process_messages\n # Check status for all streams, reopen as necessary\n @streams.each { |_, stream| try { stream.keep_alive } }\n\n # Actual processing of incoming messages happens in event callbacks\n # Oбрабатываем пришедшее сообщение в интерфейсах обратного вызова\n @conn.ProcessMessage2(100)\n end", "def receive_sms\n uninitialize_sms\n body = params[:Body]\n phone_number = normalize_phone params[:From].strip\n @problem_text = body.split\n action = sms_parsing(body).downcase\n if action == \"join\"\n sms_create_account\n return\n elsif Account.find_by_phone_number(phone_number) == nil\n sms_send(params[:From], \"Please first create an account by texting the word 'join'.\")\n return\n end\n if !@sms_error\n case action\n when /^add$/,/^insert$/\n sms_create\n when /^accept$/\n sms_accept_problem\n when /^get$/\n @offset = false\n sms_get(0)\n when /^edit$/\n sms_edit\n when /^delete$/, /^destroy$/\n sms_delete\n when /^next$/\n offset = session[\"offset\"]\n if offset == nil\n sms_error(\"Sorry, there is no saved session right now. Please first text \\\"GET\\\" with @location !skill %number of texts you want to allow.\")\n else\n @offset = true\n sms_get(offset)\n end\n when /^detail$/, /^details$/, /^describe$/\n sms_detail\n when /^account$/\n forgot_acc\n when /^change$/\n sms_change_password\n when /^password$/\n forgot_password\n# when /^skill$/, /^skills$/\n# sms_skill\n when /^keywords$/, /^key$/, /^keys$/, /^help$/\n sms_keywords\n when /^explain$/\n sms_explain\n else\n if is_num?(action)\n session[:received_confirmation] = action\n sms_confirm_acc\n else\n sms_wrong_keyword\n end\n end\n end\n render :nothing => true\n end", "def listen_for_messages\n queue = @channel.queue(\"Hello\")\n queue.bind(@exchange).subscribe do |delivery_info, metadata, payload|\n data = JSON.parse(payload)\n display_message(data['user'], data['message'])\n \n#Part that after uncommenting allows to chat beetwen two \n#chat.rb apps (send and recive messages)\n #user = data.match(\" \").pre_match\n #message = data.match(\" \").post_match\n #display_message(user, message)\n end\n end", "def on_message_received\n @conn.add_handler(\"message\") do |stanza|\n yield(Message.new(stanza)) if Message.new(stanza).body\n end\n end", "def receive\n # Process msg_descriptor\n Subscriber.execute_from_descriptor(msg_descriptor)\n head :no_content\n rescue InvalidSubscriberError\n # 404: Message delivery will be retried\n head :not_found\n rescue StandardError\n # 422: Message delivery will be retried\n head :unprocessable_entity\n end", "def receive_message\n params[:incoming_number] = $1 if params[:incoming_number]=~/^1(\\d{10})$/\n params[:origin_number] = $1 if params[:origin_number]=~/^1(\\d{10})$/\n @group=Group.find_by_phone_number(params[:incoming_number])\n \n if @group\n sent_by_admin=@group.user.phone_number==params[:origin_number]\n @sending_student = @group.students.find_by_phone_number(params[:origin_number])\n @sending_person = sent_by_admin ? @group.user : @sending_student\n \n #handle the #removeme command. it's a hard-coded single test for now. if we implement more commands, we should probably generalize this\n if params[:message].match(/^\\s*#remove[\\s_]*me/) && @sending_student.present?\n @group.send_message(\"You will no longer receive messages from #{@group.title}. Sorry to see you go!\",nil,[@sending_student])\n @sending_student.update_attribute(:phone_number,nil)\n elsif @sending_person\n message = (sent_by_admin ? @group.user.display_name : @sending_student.name)+\": \"+params[:message]\n @group.send_message(message,@sending_person, sent_by_admin ? @group.students : [@group.user]) #if a student sent it, just send it to teacher. if teacher sent it, push to group\n end\n end\n \n render :text=>\"sent\", :status=>202\n #needs to return something API-like, yo\n end", "def process_msg_from_monitor ws, ws_context, msg\n if !ws_context[:registered]\n ws.close\n return\n end\n if ws_context[:type] != 'monitor'\n return\n end\n if resp_id = msg[:resp_id]\n # response from monitor\n callback = @callbacks[resp_id]\n if !callback\n return\n end\n @callbacks.delete resp_id\n callback.call msg[:err], msg[:body]\n return\n end\n # request or notify from monitor\n @console_service.execute(msg[:module_id], :master_handler, msg[:body]) { |err, res|\n if is_request? msg\n if resp = compose_response(msg, err, res)\n ws.send ['monitor', resp].to_json\n end\n else\n # notify should not have a callback\n end\n }\n end", "def getReceivedMessages\n respond_to do |format|\n format.json { render json: current_user.received_messages }\n end\n end", "def receive_message(msg)\n request_queue.shift.success(msg)\n end", "def receive message\n end", "def receive_message\n params[:incoming_number] = $1 if params[:incoming_number]=~/^1(\\d{10})$/\n params[:origin_number] = $1 if params[:origin_number]=~/^1(\\d{10})$/\n @group=current_user.groups.find_by_phone_number(params[:incoming_number])\n \n if @group\n sent_by_admin=@group.user.phone_number==params[:origin_number]\n @sending_student = @group.students.find_by_phone_number(params[:origin_number])\n @sending_person = sent_by_admin ? @group.user : @sending_student\n \n if @sending_person\n message = (sent_by_admin ? @group.user.display_name : @sending_student.name)+\": \"+params[:message]\n @group.send_message(message,@sending_person, sent_by_admin ? @group.students : [@group.user]) #if a student sent it, just send it to teacher. if teacher sent it, push to group\n end\n end\n \n render :text=>\"sent\", :status=>202\n #needs to return something API-like, yo\n end", "def handle_internal_messages(t_sock)\n t_data = read_data(t_sock)\n receive_internal_data(t_data)\n end", "def handle_messages!\n self.logger.debug { \"Starting message handler.\" }\n \n loop do\n message = nil\n\n # reads data\n self.logger.debug { \"Waiting for messages.\" }\n message = self.protocol.wait_interaction!\n \n # if nil data arrived, it means termination\n if message.nil?\n break\n end\n \n self.logger.debug { \"Message of type '#{message.type}' received.\" }\n\n # calls processing method according to incoming message\n case message.type.to_sym\n when :order\n self.handle_order(message)\n end\n \n end\n \n self.logger.debug { \"Message handler terminated.\" }\n end", "def op_receive_response_xml(params)\n return -1 unless valid?\n\n # only process when in the 'Processing' state\n unless @ticket.state == 'Processing'\n log \"Ticket state #{@ticket.state} not valid for processing responses\"\n @ticket.request_error! @last_log_message\n return -1\n end\n\n responseXML = params[:response]\n log \"Received response XML from QuickBooks\"\n\n # handle a connection error\n unless params[:hresult].blank? and params[:message].blank?\n log \"Connection error with QuickBooks: #{params[:hresult]} : #{params[:message]}\"\n\n @ticket.request_error!(@last_log_message, connection_error_hresult: params[:hresult], connection_error_message: params[:message])\n\n # also update the request if it is able to be found\n request = find_outstanding_request(responseXML)\n request.update!(response_qbxml: responseXML, state: 'Error') if request\n\n return -1\n end\n\n # find the corresponding request\n request = find_outstanding_request(responseXML)\n\n unless request\n log \"Received response back from QuickBooks but it did not correspond to any outstanding ticket request\"\n @ticket.request_error! @last_log_message\n return -1\n end\n\n log \"Found corresponding request [#{request.state}]\"\n\n # safety check. we should always get a response back for the current request\n unless request == @ticket.qb_request\n log \"Received response from QuickBooks but it references a request other than the current request\"\n @ticket.request_error! @last_log_message\n return -1\n end\n\n # process the response XML now\n unless request.consume_response_xml(responseXML)\n # this request for some reason did not succeeed. Update the request and the ticket\n log \"Request [#{request.state}] could not process the QuickBooks response: #{request.error}\"\n request.update!(response_qbxml: responseXML, state: 'Error')\n @ticket.error! @last_log_message\n return -1\n end\n\n request.update!(response_qbxml: responseXML) # This was changed for effective_qb_sync\n\n # the request has processed the response XML. if it does not have any more work to do, then detach it\n\n if request.has_more_work?\n log \"Request [#{request.state}] has more work to do on the next request\"\n else\n # detach the current request\n @ticket.update!(qb_request: nil)\n log \"Request [#{request.state}] has completed its work\"\n end\n\n work_done = @ticket.qb_requests.size\n work_left = how_much_more_work\n work_left = work_left + 1 if @ticket.qb_request # if there is still a current request we need to add that to the work_left\n\n work_left == 0 ? 100 : (work_done * 100 / (work_done + work_left))\n end", "def reply(request_msg, response_msg)\n\t\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds context from xml, adds parts to path and returns the both results
def findContext(doc, path) context = nil # If user-element is given -> context is user-based, otherwise context is system-based if doc.find_first('//xmpp2rest/user') puts "User context" username = (doc.find_first('//xmpp2rest/user').attributes.get_attribute("username")) ? doc.find_first('//xmpp2rest/user').attributes.get_attribute("username").value : nil # If username not found -> malformed uri if not username raise Exception.new("Malformed path: /user, use /user/<username> instead!") else path += "/user/#{username}" puts "..user" context = :user end # Group-context if doc.find_first('//xmpp2rest/user/group') puts "..group" groupname = (doc.find_first('//xmpp2rest/user/group').attributes.get_attribute("groupname")) ? doc.find_first('//xmpp2rest/user/group').attributes.get_attribute("groupname").value : nil # If group-context is given, but groupname not found -> malformed uri if not groupname raise Exception.new("Malformed path: ../group, use /group/<groupname> instead!") elsif doc.find_first('//xmpp2rest/user/group/user') membername = (doc.find_first('//xmpp2rest/user/group/user').attributes.get_attribute("username")) ? doc.find_first('//xmpp2rest/user/group/user').attributes.get_attribute("username").value : nil if not membername raise Exception.new("Malformed path: ../member, use ..member/<username> instead!") end puts "..member" path += "/group/#{groupname}/member/#{membername}" context = :user_group_member else path += "/group/#{groupname}" context = :user_group end end # Device-context if doc.find_first('//xmpp2rest/user/device') puts "..device" devicename = (doc.find_first('//xmpp2rest/user/device').attributes.get_attribute("devicename")) ? doc.find_first('//xmpp2rest/user/device').attributes.get_attribute("devicename").value : nil # If device-context is given, but devicename not found -> malformed uri if not devicename raise Exception.new("Malformed path: ../device, use ../device/<devicename> instead!") else path += "/device/#{devicename}" context = :user_device end end end return context, path end
[ "def find_context_xml\n\t\t@manifest.elements.each do |e|\n\t\t\te.elements.each do |e1|\n\t\t\t\tif(e1.attributes['full-path'] == 'content.xml')\n\t\t\t\t\treturn e1\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t#Throw exception if it gets this far\n\t\t\"Something has gone terribly wrong :(\"\n\tend", "def get_context_info(xml_text)\n \n xml = REXML::Document.new xml_text\n context = xml.root.get_elements(\"//CONTEXT\")\n \n return context\n end", "def on_absolute_path(ast_node, context)\n if @document.respond_to?(:root_node)\n context = XML::NodeSet.new([@document.root_node])\n else\n context = XML::NodeSet.new([@document])\n end\n\n # If the expression is just \"/\" we'll just return the current context.\n return ast_node.children.empty? ? context : on_path(ast_node, context)\n end", "def import_xml(xml)\t\t\t\n\t\t\tdoc = REXML::Document.new xml\n # Cut to the context object\n\t\t\tctx = REXML::XPath.first(doc, \".//ctx:context-object\", {\"ctx\"=>\"info:ofi/fmt:xml:xsd:ctx\"})\n\t\t\tctx.attributes.each do |attr, val|\t\t\t\t\n\t\t\t\t@admin.each do |adm, vals|\n\t\t\t\t\tself.set_administration_key(adm, val) if vals[\"label\"] == attr\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\tend\n\t\t\tend\n\t\t\tctx.to_a.each do | ent |\n\t\t\t\tif @@defined_entities.value?(ent.name())\n\t\t\t\t\tvar = @@defined_entities.keys[@@defined_entities.values.index(ent.name())]\n\t\t\t\t\tmeth = \"import_#{var}_node\"\n\t\t\t\t\tself.send(meth, ent)\n\t\t\t\telse\n\t\t\t\t\tself.import_custom_node(ent)\n\t\t\t\tend\n\t\t\tend\n end", "def context_for(context, path)\n return context.dup if !path || path == ''\n new_context = context.dup\n nodes = path.split(/[\\.\\/]/).collect(&:upcase) rescue []\n return new_context.root if nodes.empty?\n level = nodes[0] == '' ? nil : new_context.level\n\n nodes.each_with_index do |node, i|\n case\n when i.zero? && node == '' then new_context.root\n when i.zero? && node == '~' then new_context.set(schema: @user)\n when node == '-' then new_context.up\n when node == '--' then new_context.up.up\n when node =~ /^-+$/ then new_context.up.up.up\n else\n raise Context::InvalidKey if node !~ /^[a-zA-Z0-9_\\$]{,30}$/\n case new_context.level\n when nil\n @meta.find(new_context.traverse(schema: node))\n when :schema\n o = @meta.find_object(new_context.schema, node)\n new_context.traverse(object: node, object_type: o.type)\n when :object\n @meta.find(new_context.traverse(column: node))\n #TODO: Subprograms\n else raise Context::InvalidKey\n end\n end\n end\n new_context\n end", "def explore(x_path)\n @original_xml.xpath(x_path).each do |data|\n data.children.each do |node|\n \n if node.element?\n level_1 = Rymai::XmlTransformer.get_level_1(node)\n if PARENT_INDEX_REGEX.match(node.parent.path)\n if level_1 && level_2 = Rymai::XmlTransformer.get_level_2(level_1, node)\n ((@normalized_array[$2.to_i - 1]||={})[level_1]||={})[level_2] = node.child.text\n end\n end\n explore(node.path)\n end\n \n end\n end\n end", "def extract_from_relative_xpath(mods_node, template_node, xpath)\n values = {}\n mods_xpath_node = mods_node.at_xpath(xpath)\n return {} if mods_xpath_node == nil\n template_xpath_node = template_node.at_xpath(xpath)\n values.merge!(extract_self_value(mods_xpath_node, template_xpath_node))\n values.merge!(extract_attributes(mods_xpath_node, template_xpath_node))\n end", "def apply_filter(xml_orig, xpaths)\n\txml = xml_orig.dup\n\txpaths.each {|c| \n\t\txml.xpath(c[:path]).each {|x| redact(x, c[:redaction]) } \n\t}\n\treturn xml\nend", "def configure_xml(path)\n settings = load_xml(path)\n update(settings)\n return @hash\n end", "def xpathall(path,xml)\n r=[]\n XPath.each(xml,path){|x|r<<x}\n r\nend\n", "def xml_search_element(xml, path_str)\r\n #Search given xml using given string and return matching.\r\n element_xml = Nokogiri::XML.parse(xml).search(path_str)\r\n\r\n #retrieve given instance of search element body, if more than one found.\r\n $xmlelementbody = element_xml.to_a[0].to_xml\r\n end", "def setup\n xml_results = <<BEGIN\n <search:response total=\"2\" start=\"1\" page-length=\"10\" xmlns:search=\"http://marklogic.com/appservices/search\">\n <search:result index=\"1\" uri=\"/documents/discoverBook.xml\" path=\"fn:doc('/documents/discoverBook.xml')\" score=\"243\" confidence=\"0.97047\" fitness=\"1\">\n <search:snippet>\n <search:match path=\"fn:doc('/documents/discoverBook.xml')/*:book/*:bookinfo/*:title\">Discoverers <search:highlight>and</search:highlight> Explorers</search:match>\n <search:match path=\"fn:doc('/documents/discoverBook.xml')/*:book/*:chapter[1]/*:chapterinfo/*:biblioentry/*:title\">Discoverers <search:highlight>and</search:highlight> Explorers</search:match>\n </search:snippet>\n </search:result>\n <search:result index=\"2\" uri=\"/documents/a_and_c.xml\" path=\"fn:doc('/documents/a_and_c.xml')\" score=\"234\" confidence=\"0.952329\" fitness=\"1\">\n <search:snippet>\n <search:match path=\"fn:doc('/documents/a_and_c.xml')/PLAY/PERSONAE/PERSONA[10]\">Officers, Soldiers, Messengers, <search:highlight>and</search:highlight> other Attendants.</search:match>\n </search:snippet>\n </search:result>\n <search:qtext>and</search:qtext>\n <search:metrics>\n <search:query-resolution-time>PT0.009197S</search:query-resolution-time>\n <search:facet-resolution-time>PT0.000083S</search:facet-resolution-time>\n <search:snippet-resolution-time>PT0.019534S</search:snippet-resolution-time>\n <search:total-time>PT0.029033S</search:total-time>\n </search:metrics>\n</search:response>\nBEGIN\n\n xml_results_noh = <<BEGIN\n <search:response total=\"2\" start=\"1\" page-length=\"10\" xmlns:search=\"http://marklogic.com/appservices/search\">\n <search:result index=\"1\" uri=\"/documents/discoverBook.xml\" path=\"fn:doc('/documents/discoverBook.xml')\" score=\"243\" confidence=\"0.97047\" fitness=\"1\">\n <search:snippet>\n <search:match path=\"fn:doc('/documents/discoverBook.xml')/*:book/*:bookinfo/*:title\">Discoverers and Explorers</search:match>\n <search:match path=\"fn:doc('/documents/discoverBook.xml')/*:book/*:chapter[1]/*:chapterinfo/*:biblioentry/*:title\">Discoverers and Explorers</search:match>\n </search:snippet>\n </search:result>\n <search:result index=\"2\" uri=\"/documents/a_and_c.xml\" path=\"fn:doc('/documents/a_and_c.xml')\" score=\"234\" confidence=\"0.952329\" fitness=\"1\">\n <search:snippet>\n <search:match path=\"fn:doc('/documents/a_and_c.xml')/PLAY/PERSONAE/PERSONA[10]\">Officers, Soldiers, Messengers, and other Attendants.</search:match>\n </search:snippet>\n </search:result>\n <search:qtext>and</search:qtext>\n <search:metrics>\n <search:query-resolution-time>PT0.009197S</search:query-resolution-time>\n <search:facet-resolution-time>PT0.000083S</search:facet-resolution-time>\n <search:snippet-resolution-time>PT0.019534S</search:snippet-resolution-time>\n <search:total-time>PT0.029033S</search:total-time>\n </search:metrics>\n</search:response>\nBEGIN\n\n results_with_facets = <<-BEGIN\n<search:response total=\"21973\" start=\"1\" page-length=\"10\" xmlns:search=\"http://marklogic.com/appservices/search\">\n <search:result index=\"9\" uri=\"/Users/clarkrichey/Downloads/wits/wits21402.xml\" path=\"fn:doc(&quot;/Users/clarkrichey/Downloads/wits/wits21402.xml&quot;)\" score=\"196\" confidence=\"0.338805\" fitness=\"0.890659\">\n <search:snippet>\n <search:match path=\"fn:doc(&quot;/Users/clarkrichey/Downloads/wits/wits21402.xml&quot;)/*:Incident/*:Subject\">1 newspaper editor injured in letter <search:highlight>bomb</search:highlight> attack by Informal Anarchist Federation in Turin, Piemonte, Italy</search:match>\n <search:match path=\"fn:doc(&quot;/Users/clarkrichey/Downloads/wits/wits21402.xml&quot;)/*:Incident/*:EventTypeList\">\n<search:highlight>Bombing</search:highlight>\n</search:match>\n <search:match path=\"fn:doc(&quot;/Users/clarkrichey/Downloads/wits/wits21402.xml&quot;)/*:Incident/*:WeaponTypeList/*:WeaponType\">Letter <search:highlight>Bomb</search:highlight></search:match>\n </search:snippet>\n </search:result>\n <search:result index=\"10\" uri=\"/Users/clarkrichey/Downloads/wits/wits23118.xml\" path=\"fn:doc(&quot;/Users/clarkrichey/Downloads/wits/wits23118.xml&quot;)\" score=\"196\" confidence=\"0.338805\" fitness=\"0.890659\">\n <search:snippet>\n <search:match path=\"fn:doc(&quot;/Users/clarkrichey/Downloads/wits/wits23118.xml&quot;)/*:Incident/*:Subject\">1 government employee killed in <search:highlight>bombing</search:highlight> in Ghazni, Afghanistan</search:match>\n <search:match path=\"fn:doc(&quot;/Users/clarkrichey/Downloads/wits/wits23118.xml&quot;)/*:Incident/*:EventTypeList\">\n<search:highlight>Bombing</search:highlight>\n</search:match>\n </search:snippet>\n </search:result>\n <search:facet name=\"Region\">\n <search:facet-value name=\"Africa\" count=\"622\">Africa</search:facet-value>\n <search:facet-value name=\"Central and South America\" count=\"1012\">Central and South America</search:facet-value>\n <search:facet-value name=\"East Asia-Pacific\" count=\"1198\">East Asia-Pacific</search:facet-value>\n <search:facet-value name=\"Eurasia\" count=\"761\">Eurasia</search:facet-value>\n <search:facet-value name=\"Europe\" count=\"1057\">Europe</search:facet-value>\n <search:facet-value name=\"Middle East and Persian Gulf\" count=\"10374\">Middle East and Persian Gulf</search:facet-value>\n <search:facet-value name=\"North America and Caribbean\" count=\"16\">North America and Caribbean</search:facet-value>\n <search:facet-value name=\"South Asia\" count=\"6933\">South Asia</search:facet-value>\n </search:facet>\n <search:facet name=\"Country\">\n <search:facet-value name=\"England\" count=\"200\">England</search:facet-value>\n <search:facet-value name=\"Ireland\" count=\"422\">Ireland</search:facet-value>\n <search:facet-value name=\"Brazil\" count=\"10\">Brazil</search:facet-value>\n </search:facet>\n <search:qtext>bomb</search:qtext>\n <search:metrics>\n <search:query-resolution-time>PT0.420016S</search:query-resolution-time>\n <search:facet-resolution-time>PT0.002873S</search:facet-resolution-time>\n <search:snippet-resolution-time>PT0.039998S</search:snippet-resolution-time>\n <search:total-time>PT0.463759S</search:total-time>\n </search:metrics>\n</search:response>\n BEGIN\n @search_results = ActiveDocument::SearchResults.new(xml_results)\n @search_results_noh = ActiveDocument::SearchResults.new(xml_results_noh)\n @faceted_results = ActiveDocument::SearchResults.new(results_with_facets)\n end", "def get_xml_info(xml, xp)\n return '' unless block_given?\n doc = Nokogiri.XML xml\n doc.xpath(xp).map {\n |node| yield node\n }\n end", "def import_xml(xml)\n if xml.is_a?(String)\n xml.force_encoding(\"UTF-8\") if xml.respond_to? :force_encoding\n xml.scrub!\n doc = REXML::Document.new xml.gsub(/>[\\s\\t]*\\n*[\\s\\t]*</, \"><\").strip\n elsif xml.is_a?(REXML::Document)\n doc = xml\n else\n raise ArgumentError, \"Argument must be an REXML::Document or well-formed XML string\"\n end\n\n # Cut to the context object\n ctx = REXML::XPath.first(doc, \".//ctx:context-object\", {\"ctx\" => \"info:ofi/fmt:xml:xsd:ctx\"})\n\n ctx.attributes.each do |attr, val|\n @admin.each do |adm, vals|\n set_administration_key(adm, val) if vals[\"label\"] == attr\n end\n end\n ctx.to_a.each do |ent|\n if @@defined_entities.value?(ent.name)\n import_entity(ent)\n else\n import_custom_node(ent)\n end\n end\n end", "def parse_context; end", "def xpath_search(path)\n\t\t\troot.xs(path)\n\t\tend", "def process_context(doc, context)\n test_context = XPath.match(doc, context.attributes[\"select\"])\n namespaces = context.namespaces\n namespaces.delete(\"var\")\n namespaces = nil if namespaces.empty?\n variables = {}\n var_namespace = \"http://jaxen.org/test-harness/var\"\n XPath.each(context,\n \"@*[namespace-uri() = '#{var_namespace}']\") do |attribute|\n variables[attribute.name] = attribute.value\n end\n XPath.each(context, \"valueOf\") do |value|\n process_value_of(test_context, variables, namespaces, value)\n end\n XPath.each(context,\n \"test[not(@exception) or (@exception != 'true')]\") do |test|\n process_nominal_test(test_context, variables, namespaces, test)\n end\n XPath.each(context,\n \"test[@exception = 'true']\") do |test|\n process_exceptional_test(test_context, variables, namespaces, test)\n end\n end", "def set_matched_context(res)\n if res['outputContexts'].is_a?(Array)\n context = res['outputContexts'].map { |x| x['name'] }\n end\n # Dump the unnecessary projects/newagent-gjetnk/agent/sessions/avatarSessionId/contexts/ stuff\n context.map! { |c| c.split('.').last }\n # Dump anything that isn't the right kind of context, mega, system counters, etc.\n context.reject! { |e| e.include?('projects/newagent-gjetnk/agent/sessions/avatarSessionId/contexts/') }\n context\n end", "def with_context(xpath, &block)\n @local_context = xpath\n yield\n @local_context = nil\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses dev_type and password from xml
def parseDeviceData(doc, params) dev_type = (doc.find_first('//xmpp2rest/user/device/dev_type')) ? doc.find_first('//xmpp2rest/user/device/dev_type').content : nil password = (doc.find_first('//xmpp2rest/user/device/password')) ? doc.find_first('//xmpp2rest/user/device/password').content : nil if not dev_type or not password raise Exception.new("Missing elements data for creating new device!") end params.merge!({:dev_type => dev_type}) params.merge!({:password => password}) return params end
[ "def parse_xml_fields(xml)\n @xmldoc = xml\n set_field :@id, 'ID'\n set_field :@sid, 'Sid'\n set_field :@name, 'Name'\n set_field :@login_name, 'LoginName'\n set_field :@email, 'Email'\n set_field :@notes, 'Notes'\n set_field :@is_site_admin, 'IsSiteAdmin', 'Boolean'\n set_field :@is_domain_group, 'IsDomainGroup', 'Boolean'\n set_field :@flags, 'Flags'\n set_field :@site_user, 'SiteUser'\n @xmldoc = nil\n end", "def parse_user!\n login_xml = Hpricot.XML(self.login_token) \n item = (login_xml/:login).first\n self.login_type = item[\"type\"]\n self.login_id = (item/:login_id).inner_html\n self.name = (item/:name).inner_html\n self.email = (item/:email).inner_html\n self.expires_at = (item/:expires_at).inner_html\n self.auth_for = (item/:auth_for).inner_html\n return true \n end", "def parse_credentials(xml)\n doc = Hpricot::XML(xml)\n if doc.at('/BBAuthTokenLoginResponse/Success')\n # We have a successful auth response\n @wssid = doc.at('/BBAuthTokenLoginResponse/Success/WSSID').inner_text.strip\n @cookie = doc.at('/BBAuthTokenLoginResponse/Success/Cookie').inner_text.strip\n\n else\n raise YahooAuthenticationFailed, \"Yahoo authentication failed because: #{auth_error_desc(doc)} (code #{auth_error_code(doc)})\"\n end\n end", "def profile_xml(xml, values)\n ns_key = \"#{namespace_key(:profile)}\"\n xml[ns_key].Api_type values[:api_type]\n xml[ns_key].LicenceKey values[:license_key]\n xml[ns_key].LoginID values[:login_id]\n xml[ns_key].Version values[:version]\n xml\n end", "def auth(api_user, api_password)\n # <eCommerce action=\"Request\" version=\"1.1\">\n # <Requestor>\n # <ID>username</ID>\n # <Password>password</Password>\n # </Requestor>\n # </eCommerce>\n ecommerce = Element.new \"eCommerce\"\n ecommerce.attributes[\"action\"] = \"Request\"\n ecommerce.attributes[\"version\"] = \"1.1\"\n\n user = Element.new \"Requestor\"\n user_id = Element.new \"ID\"\n user_id.text = api_user \n\n user_pwd = Element.new \"Password\"\n user_pwd.text = api_password \n\n user << user_id\n user << user_pwd\n\n ecommerce << user\n @xml << ecommerce\n end", "def login_user(xml) \n login = xml.root.get_elements('User').first.text \n password = xml.root.get_elements('Password').first.text \n self.current_user = User.authenticate(login, password) \n end", "def get_account_info\n User.load_from_xml(@xml)\n end", "def get_params_from_xml(xml) \n empty = REXML::Element.new('empty') \n empty_attr = REXML::Attribute.new('empty') \n ret = {} \n root = xml.root \n \n ret.merge!('openid.mode' => \"checkid_#{$1.downcase}\") if root.xpath =~ /OpenIDCheckID(.*)/ \n if req = root.get_elements('Request').first \n ret.merge!('openid.identity' => ((req.get_elements('Identity').first || empty).text || '').strip, \n 'openid.assoc_handle' => ((req.get_elements('AssocHandle').first || empty).text || '').strip, \n 'openid.return_to' => ((req.get_elements('ReturnTo').first || empty).text || '').strip, \n 'openid.trust_root' => ((req.get_elements('TrustRoot').first || empty).text || '').strip) \n if sreg = req.get_elements('Sreg').first \n ret.merge!('openid.sreg.required' => ((sreg.attribute('required') || empty_attr).value || '').strip, \n 'openid.sreg.optional' => ((sreg.attribute('optional') || empty_attr).value || '').strip, \n 'openid.sreg.policy_url' => ((sreg.attribute('policy_url') || empty_attr).value || '').strip) \n end \n end \n return ret \n end", "def parse_xml\n parse_attributes\n parse_elements\n end", "def test_parse_valid_xml_returns_hash\n name = \"A name\"\n type = \"A type\"\n xml = \"<data><name>#{name}</name><type>#{type}</type></data>\"\n parser = ChainReactor::Parsers::XmlSimpleParser.new get_logger\n cause = parser.parse(xml,[],false)\n assert_equal name, cause['name'].first\n assert_equal type, cause['type'].first\n end", "def auth_xml=(value)\n @children['auth-xml'][:value] = value\n end", "def login \n areq = Nokogiri::XML::Builder.new { |xml|\n xml.authenticate {\n xml.credentials {\n xml.username { xml.text(@user) }\n xml.password { xml.text(@password) }\n }\n }\n }\n resp = sendrecv(areq.doc)\n begin\n if extract_value_from(\"//@status\", resp) =~ /20\\d/\n @areq = areq\n elsif extract_value_from(\"//@status\", resp) =~ /40\\d/\n disconnect()\n return false\n else\n puts \"\\n\\n***OMPAuthError*** OpenVAS response=#{resp.inspect}\\n\\n\"\n raise OMPAuthError\n end\n rescue\n puts \"\\n\\n***XMLParsingError*** OpenVAS response=#{resp.inspect}\\n\\n\"\n raise XMLParsingError\n end\n \tend", "def init_from_xml(xmlDoc)\r\n @type = xmlDoc.expanded_name\r\n xmlDoc.each_element(\"ID\") { |e| @procID = e.text }\r\n xmlDoc.each_element(\"GROUP\") { |e| @group = e.text }\r\n xmlDoc.each_element(\"PATH\") { |e| @path = e.text }\r\n xmlDoc.each_element(\"ARGSLINE\") { |e| @cmdLineArgs = e.text }\r\n xmlDoc.each_element(\"ENV\") { |e| @env = e.text }\r\n # Dump the XML description of the OML configuration into a file\r\n xmlDoc.each_element(\"OML_CONFIG\") { |config|\r\n configPath = nil\r\n config.each_element(\"omlc\") { |omlc|\r\n configPath = \"/tmp/#{omlc.attributes['exp_id']}-#{@procID}.xml\"\r\n }\r\n f = File.new(configPath, \"w+\")\r\n config.each_element {|el|\r\n f << el.to_s\r\n }\r\n f.close\r\n # Set the OML_CONFIG environment with the path to the XML file\r\n @env << \" OML_CONFIG=#{configPath} \"\r\n }\r\n end", "def load_values_from_xml(xml)\n self.class.plugin_settings.keys.each do |setting|\n value = xml.scan(/<#{setting}>(.*)<\\/#{setting}>/).flatten.first\n instance_variable_set(\"@#{setting}\", value)\n end\n end", "def get_passport_element(type, password)\n broadcast('@type' => 'getPassportElement',\n 'type' => type,\n 'password' => password)\n end", "def parse_passwd_line(line)\n x = line.split(':')\n {\n 'name' => x.at(0),\n 'password' => x.at(1),\n 'uid' => x.at(2),\n 'gid' => x.at(3),\n 'desc' => x.at(4),\n 'home' => x.at(5),\n 'shell' => x.at(6),\n }\n end", "def get_profile_info type\n login\n elements = {}\n doc = hpricot_get_url \"/editprofile.php?#{type}\"\n \n #search for all form elements on the page\n doc.search(\"//form[@id='profile_form']//input[@name!='']\") do |input|\n name = input.attributes['name']\n elements[name] = [] if elements[name].nil?\n #checked checkbox?\n if input.attributes.include?('checked')\n elements[name] << 'on'\n elsif input.attributes['value'] #regular ol' input box\n elements[name] << input.attributes['value']\n end\n end\n \n doc.search(\"//form[@id='profile_form']//select\") do |select|\n name = select.attributes['name']\n elements[name] = []\n\n #facebook uses javascript to fill in the state, for some stupid reason.\n if name =~ /region/ && doc.to_s =~ /editor_two_level_set_subselector\\(\"two_level_hometown_region\", \"(\\d+)\"\\);/\n elements[name] << $1\n else\n select.search(\"option\") do |option|\n elements[name] << option.attributes['value'] if option.attributes.include?('selected')\n end\n end\n end\n \n doc.search(\"//form[@id='profile_form']//textarea\") do |textarea|\n elements[textarea.attributes['name']] = [textarea.inner_html]\n end\n \n elements\n end", "def parse_passwd_line(line)\n x = line.split(':')\n {\n 'user' => x.at(0),\n 'password' => x.at(1),\n 'uid' => x.at(2),\n 'gid' => x.at(3),\n 'desc' => x.at(4),\n 'home' => x.at(5),\n 'shell' => x.at(6),\n }\n end", "def config_seraph_config_xml()\n seraph_xml = File.readlines(self.seraph_config_xml()).map do |line|\n if m = /(#{Regexp.quote(self.seraph_config_xml_auth_class_token())})/.match(line)\n self.debug(m[0])\n new_str = \"#{m.pre_match}#{self.cas_authenticator_class()}#{m.post_match}\"\n self.debug(new_str)\n new_str\n elsif m = /(#{Regexp.quote(self.seraph_config_xml_logout_url_token())})/.match(line)\n self.debug(m[0])\n new_str = \"#{m.pre_match}#{self.cas_server_url()}/logout#{m.post_match}\"\n self.debug(new_str)\n new_str\n else\n line\n end\n end\n \n File.open(self.seraph_config_xml(), \"w\") do |io|\n seraph_xml.each { |line| io.puts(line) }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses device's online status, and the possible status elements that are given
def parseOnlineStatus(doc, params, path) status = {} doc.find('//xmpp2rest/user/device/online/status').each do |status_element| status_key = (status_element.attributes.get_attribute("status_key")) ? status_element.attributes.get_attribute("status_key").value : nil if not status_key or status_key == "" raise Exception.new("Error in status_key -attribute. (Must be given, and cannot be empty!)") elsif not status_element.content or status_element.content == "" raise Exception.new("Status element must have content!") end if status_key == "device_location" and status_element.find_first("location/latitude") and status_element.find_first("location/longitude") and status_element.find_first("location/latitude").content and status_element.find_first("location/longitude").content location = {} location.merge!({'latitude' => status_element.find_first("location/latitude").content.to_f}) location.merge!({'longitude' => status_element.find_first("location/longitude").content.to_f}) status.merge!({:device_location => YAML.dump(location)}) elsif status_key == "uploading_file" and status_element.find_first("uploading_file") and status_element.find_first("uploading_file_hash") and status_element.find_first("uploading_file").content and status_element.find_first("uploading_file_hash").content status.merge!({'uploading_file_hash' => status_element.find_first("uploading_file_hash").content.to_s}) status.merge!({'uploading_file' => status_element.find_first("uploading_file").content.to_s}) else status_key != "device_location" and status_key != "uploading_file" and status_element.content status.merge!({status_key => status_element.content.to_s}) end end params.merge!({:status => YAML.dump(status)}) return params end
[ "def status\n {\n 'device' => :ok,\n 'no device' => :dead,\n 'offline' => :offline\n }[@state]\n end", "def status\n {\n 'device' => :ok,\n 'no device' => :dead,\n 'offline' => :offline\n }[@state]\n end", "def status\r\n \r\n got = @ndev.rpc.get_interface_information(:interface_name => @name, :media => true )\r\n phy = got.xpath('physical-interface')[0]\r\n return nil unless phy\r\n \r\n ret_h = {}\r\n ret_h[:macaddr] = phy.xpath('current-physical-address').text.strip \r\n xml_when_item(phy.xpath('description')){|i| ret_h[:description] = i.text.strip }\r\n ret_h[:oper_status] = phy.xpath('oper-status').text.strip\r\n ret_h[:admin_status] = phy.xpath('admin-status').text.strip\r\n ret_h[:mtu] = phy.xpath('mtu').text.to_i\r\n ret_h[:speed] = {:admin => phy.xpath('speed').text.strip }\r\n ret_h[:duplex] = {:admin => phy.xpath('duplex').text.strip }\r\n ret_h[:autoneg] = phy.xpath('if-auto-negotiation').text.strip \r\n \r\n if ret_h[:autoneg] == \"enabled\"\r\n autoneg = phy.xpath('ethernet-autonegotiation')[0]\r\n ret_h[:speed][:oper] = autoneg.xpath('link-partner-speed').text.strip\r\n ret_h[:duplex][:oper] = autoneg.xpath('link-partner-duplexity').text.strip\r\n end\r\n \r\n # if a block is given, then it means the caller wants to process the XML data.\r\n yield( phy ) if block_given?\r\n \r\n ret_h\r\n end", "def parse_status\n if status.blank?\n Resonad.Success(nil)\n elsif status.upcase == \"UP\"\n Resonad.Success(true)\n elsif status.upcase == \"DOWN\"\n Resonad.Success(false)\n else\n Resonad.Failure(\"Invalid Status: #{status}\")\n end\n end", "def set_online_status(status)\n case status\n when :available, :online\n @notification_server.chg \"NLN\", 0\n when :busy\n @notification_server.chg \"BSY\", 0\n when :idle\n @notification_server.chg \"IDL\", 0\n when :brb, :be_right_back\n @notification_server.chg \"BRB\", 0\n when :away\n @notification_server.chg \"AWY\", 0\n when :phone, :on_the_phone\n @notification_server.chg \"PHN\", 0\n when :lunch, :out_to_lunch\n @notification_server.chg \"LUN\", 0\n else\n raise \"Wrong online status: #{status}\"\n end\n end", "def checkDeviceStatus\n \n @user = User.find(:first, :conditions => [\"username = ? \", session[:username]]) \n @onlinelist = {}\n sql = \"SELECT devices.*, users.username from devices, users WHERE devices.user_id = users.id AND users.id = #{@user.id.to_s} ORDER BY devices.dev_name\"\n @results = Device.find_by_sql(sql)\n #@results = Device.find(:all, :conditions => [\"user_id = ?\", @user.id])\n @results.each do |dev|\n status = \"offline\"\n #puts \"#{dev.last_seen.to_s} #{device_online_timeout.to_s}\"\n if dev.last_seen > device_online_timeout\n @onlinelist.merge!(dev.id => true)\n else\n @onlinelist.merge!({dev.id => false})\n end\n end\n \n if @results and not @results.empty?\n render :update do |page|\n page['device_list'].replace_html :partial => 'devicelist' \n end\n else\n return\n end\n end", "def machine_status\n status = nil\n\n begin\n resp = @conn.get do |req|\n req.url 'status.json'\n req.options.timeout = 120\n req.options.open_timeout = 120\n end\n\n if resp.status == 200\n j = JSON.parse resp.body, symbolize_names: true\n status = j if j\n end\n rescue Faraday::ConnectionFailed\n rescue Net::ReadTimeout\n end\n\n status\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 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 get_status\n case snmp_get('1.3.6.1.2.1.25.3.5.1.1.1')\n when 1\n return 'Other'\n when 3\n return 'Idle'\n when 4\n return 'Printing'\n when 5\n return 'Warmup'\n else\n return 'Unknown'\n end\n end", "def is_online?\n devices.select{|d| d.online == true }.any?\n end", "def get_device_status optvar\n logger.debug \"Checking device status for #{optvar}\"\n return @browser.get(\"#{@locations.base}/ajax.do?operation=getDeviceById&deviceId=#{@device_id}\").body.slice(/#{optvar}:.*/).sub(\"#{optvar}:\", '').strip.gsub(/\\A'|',\\z|,\\z/,'') rescue nil\n end", "def get_device_status optvar\n logger.debug \"Checking device status for #{optvar}\"\n return @browser.get(\"#{@locations.base}/ajax.do?operation=getDeviceById&deviceId=#{@device_id}\").body.slice(/#{optvar}:.*/).sub(\"#{optvar}:\", '').strip.gsub(/\\A'|',\\z|,\\z/,'') rescue nil\n end", "def device_status_overview\n return @device_status_overview\n end", "def presence_status\n # Memoize for the life of the instance to help with sorting...\n return @presence_status unless @presence_status.nil?\n redis = Worlize::RedisConnectionPool.get_client(:presence)\n result = redis.get(\"status:#{self.guid}\")\n \n # an 'offline' status is represented by the absense of a key in Redis\n # ... why waste prescious memory on users that aren't online?\n return @presence_status = 'offline' if result.nil?\n \n statuses = [\n 'offline', # 'offline' is also optionally represented by a zero value\n 'online',\n 'idle',\n 'away',\n 'invisible'\n ]\n @presence_status = statuses[result.to_i]\n end", "def parse_status()\n status = Status.new\n status.status = first_item_content('/Response/header:Header/Status')\n status.status_msg =\n first_item_content('/Response/header:Header/StatusMsg')\n @result_item.status = status\n\n unless @result_item.status.status == Status::SUCCESS\n raise StatusError.new(\"API Error(#{@result_item.status.status}):\" +\n \"#{@result_item.status.status_msg}\")\n end\n end", "def parse_status_packet(packet); end", "def device_status_overview=(value)\n @device_status_overview = value\n end", "def check_status\n response = do_request(build_status_xml())\n status_elem = REXML::XPath.first(response,'/webthumb/jobStatus/status')\n @status = (status_elem.text || '').downcase == 'complete' ? STATUS_PICKUP : STATUS_PROCESSING\n \n if pickup?\n \n if status_elem\n @completion_time = status_elem.attributes['completionTime']\n @pickup_url = status_elem.attributes['pickup']\n @browser_width = (status_elem.attributes['browserWidth'] || \"0\").to_i\n @browser_height = (status_elem.attributes['browserHeight'] || \"0\").to_i \n end\n end\n @status\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses the userspecific metadata from xml to visualREST form. List of updated files is returned, so that xml can contain many metadata changes for different files
def parseUpdatedMetadata(doc, params, path) path += "/files" listOfUpdatedFiles = Array.new doc.find('//user/device/files/file').each do |file| fullpath = (file.attributes.get_attribute("fullpath")) ? file.attributes.get_attribute("fullpath").value : nil version = "not_found" if file.find_first('version') version = (file.find_first('version').attributes.get_attribute("num")) ? file.find_first('version').attributes.get_attribute("num").value.to_i : nil end if fullpath.to_s == "" raise Exception.new("fullpath cannot be empty") elsif fullpath[0] == '/' raise Exception.new("path cannot begin with /") elsif not version raise Exception.new("Error in version element") end temp_path = (version) == "not_found" ? path + "/#{fullpath}" : path + "/#{fullpath}" + "?version=#{version.to_s}" file.find("metadata").each do |mdata| mtype = mdata.attributes.get_attribute("metadata_type") ? mdata.attributes.get_attribute('metadata_type').value : nil mvalue = mdata.content if not mtype or not mvalue raise Exception.new("Malformed metadata element") end listOfUpdatedFiles << {:path => temp_path, :params => {:metadata_type => mtype.to_s, :metadata_value => mvalue.to_s}} end end listOfUpdatedFiles.each do |v| puts "#{v[:path]} #{v[:params][:metadata_type]} #{v[:params][:metadata_value]}" end return listOfUpdatedFiles end
[ "def files\n @mets.xpath(\"/mets:mets/mets:fileSec/mets:fileGrp[@USE='masters']/mets:file\").map do |f|\n file_info(f)\n end\n end", "def parse_list_response(xml)\n [ nodes_for(xml, 'files').collect{ |node| File.new(self, node) },\n nodes_for(xml, 'folders').collect{ |node| Folder.new(@rc, self, node) } ]\n end", "def get_files_to_upload(file_dir, dom)\n @log.info 'Figuring out which files to upload'\n\n uploaded_files = []\n\n # xpath variables\n premis_ns = { 'premis' => 'http://www.loc.gov/standards/premis' }\n mets_ns = { 'mets' => 'http://www.loc.gov/METS/' }\n checksum_xpath = 'premis:objectCharacteristics/premis:fixity/premis:messageDigest'\n original_name_xpath = 'premis:originalName'\n\n # loop over the files listed in the METS\n file_md5_list = dom.xpath('//premis:object', premis_ns)\n file_md5_list.each do |fptr|\n # file location info\n file_checksum = fptr.at_xpath(checksum_xpath, premis_ns).inner_html\n flocat_xpath = \"//mets:file[@CHECKSUM='\" + file_checksum + \"']/mets:FLocat\"\n file_location = dom.at_xpath(flocat_xpath, mets_ns)\n\n # the name of the file in the aip package and its original name\n aip_filename = file_location.attr('xlink:href')\n orig_filename = fptr.at_xpath(original_name_xpath, premis_ns).inner_html\n\n # type of file\n file_type = file_location.parent.parent.attr('USE')\n\n case file_type\n when 'THUMBNAIL'\n if @config['include_thumbnail']\n uploaded_file = upload_file(file_dir, orig_filename, aip_filename, 'thumbnail')\n uploaded_files.push(uploaded_file) unless uploaded_file.nil?\n end\n when 'ORIGINAL'\n uploaded_file = upload_file(file_dir, orig_filename, aip_filename, 'bitstream')\n uploaded_files.push(uploaded_file) unless uploaded_file.nil?\n end\n end\n\n uploaded_files\nend", "def parse(filenames, collection)\n #empty file array\n files = []\n #iterate over each filename\n filenames.each { |filename|\n #open document, parse with nokogiri\n @doc = File.open(filename) { |f| Nokogiri::XML(f) }\n #create empty file object\n file = {}\n #get relevant metadatafields\n file[\"title\"] = filter(@doc.xpath(\"//tei:title\", \"tei\" => \"http://www.tei-c.org/ns/1.0\")[0])\n file[\"author\"] = filter(@doc.at_css(\"author\"))\n file[\"pub\"] = filter(@doc.at_css(\"publisher\"))\n file[\"date\"] = @doc.at_css(\"date\").attr(\"when\")\n file[\"text\"] = filter(@doc.at_css(\"body\"))\n file[\"filename\"] = filename\n #generate link for jekyllHIDE\n file[\"link\"] = \"#{filename}\".gsub(\"TEI/\", \"\").gsub(\".xml\", \"\")\n #append file info to large array of files\n files << file\n }\n return files\n end", "def get_files_list\n @meta_info.files\n end", "def get_file_info\n Info.build_from_xml(@xml['info'])\n end", "def update_metadata(metsfile)\n\n @doc = Nokogiri::XML(File.read(metsfile))\n bitstreams = @doc.css('file')\n\n @provenance = <<-EOF.gsub(/^\\s+/, '')\n MIT Libraries updated OCW and media links to https; change made by\n Andromeda Yelton (m31@mit.edu) on %{date}\n No. of bitstreams updated: %{count}\n EOF\n\n @count = 0\n bitstreams.each do |bitstream|\n checksum = bitstream.attribute('CHECKSUM')\n bitstreampath = File.split(metsfile)[0]\n new_checksum, file_size = get_new_metadata(bitstreampath, bitstream)\n\n # You have to force both checksums to String, or else the equality test\n # will fail due to their different object types, even though the\n # representations look the same. If they differ, update the MODS and\n # PREMIS records.\n if checksum.to_s != new_checksum.to_s\n digest_node, size_node, original_name = get_premis_components(checksum)\n bitstream['CHECKSUM'] = digest_node.content = new_checksum.to_s\n bitstream['SIZE'] = size_node.content = file_size\n append_provenance(original_name, new_checksum, file_size)\n @count += 1\n end\n end\n\n date = Time.now.utc.strftime('%Y-%m-%d %H:%M:%S (UTC)')\n @provenance = @provenance % {:date => date, :count => @count}\n set_item_id(metsfile)\n File.write(metsfile, @doc.to_xml)\n end", "def run\n admin_set\n return unless errors.empty?\n metadata_files.each { |file| parse_metadata(file) }\n end", "def file_metadata\n values = map { |file_node| file_resource(file_node).file_metadata }\n values.flatten\n end", "def recents\n files = session[:user].x_files.all(:last_update.gte => (DateTime.now - 20.days), folder: false, limit: 20)\n files_list = []\n files.each do |file|\n files_list.push(file.description(session[:user])) if file.folder || (!file.folder && file.uploaded)\n end\n @result = { files: files_list, success: true }\n end", "def metadata_files\n return @metadata_files unless @metadata_files.nil?\n @metadata_files = MetadataFile.all\n @existing_files, @new_files = [], []\n @metadata_files.each do |f|\n if f.cached?\n @existing_files << f\n else\n @new_files << f\n end\n end\n end", "def offer_import_meta\n @uuid = \"\"\n if (params.has_key?(:uuid))\n @uuid = params[:uuid]\n else\n @mdo.set_message(\"No uuid. Can't move files.\", true)\n redirect_to :action => 'report'\n return;\n end\n\n orig_list = `find #{Origin} -maxdepth 1 -mindepth 1 -print`.split(\"\\n\")\n\n bgcolor = '#EEEDFD'\n color_toggle = true\n \n @f_info = [] \n orig_list.sort.each { |file|\n rh = Hash.new\n rh[:orig] = File.basename(file)\n rh[:name] = \"n/a\"\n rh[:dirs] = []\n rh[:mets] = \"\"\n if (color_toggle)\n color_toggle = false\n else\n color_toggle = true\n rh[:bgcolor] = bgcolor\n end\n @f_info.push(rh);\n }\n end", "def extract_metadata(file)\n document = parse_kramdown(file)\n toc = ::Kramdown::Converter::Toc.convert(document.root)\n toc_items = toc[0].children.select { |el| el.value.options[:level] == 2 }.map do |t| \n {:id => t.attr[:id], :text => t.value.children.first.value}\n end\n\n metadata = document.root.options[:metadata]\n metadata[:toc] = toc_items\n metadata[:converted] = document.to_html\n metadata[:technologies] = metadata[:technologies].split(\",\").collect {|tech| tech.strip}\n metadata[:images] = find_images(document.root)\n metadata[:author] = metadata[:author].split(',').first if metadata[:author]\n metadata[:commits] = commit_info @repo, Pathname.new(file)\n metadata[:current_tag] = current_tag @repo, Pathname.new(file)\n metadata[:current_branch] = current_branch @repo, Pathname.new(file)\n metadata[:github_repo_url] = repository_url @repo\n metadata[:contributors] = metadata[:commits].collect { |c| c[:author] }.uniq\n metadata[:contributors_email] = metadata[:commits].collect { |c| c[:author_email] }.uniq\n metadata[:contributors].delete(metadata[:author])\n metadata[:product] = @product if @product\n metadata[:experimental] = @experimental\n metadata\n end", "def apply_file_metadata(params)\n uploaded_file_ids = params[\"uploaded_files\"]\n return if uploaded_file_ids.nil?\n uploaded_file_ids.each do |uploaded_file_id|\n uploaded_file = find_or_create_uploaded_file(uploaded_file_id)\n next if uploaded_file.pcdm_use == \"primary\"\n apply_metadata_to_uploaded_file(uploaded_file, params)\n end\n params[\"etd\"].delete(\"supplemental_file_metadata\")\n params # return the params after processing, for ease of testing\n end", "def changeMetadata\n begin\n \n \n # Gets parameters\n typename = params[:metadata_type].to_s.strip.downcase\n value = params[:metadata_value].to_s.strip\n\n if typename == \"\"\n render :text => \"Type of metadata not given.\", :status => 404\n return\n end\n \n if value == \"\"\n render :text => \"Value of metadata not given.\", :status => 404\n return\n end\n \n # Search for the user\n @user = User.find_by_username(params[:username].to_s.strip)\n if not @user\n # If the user was not found\n return\n render :text => \"User not found.\", :status => 404\n end\n \n # Search for the device\n findDeviceOfURI\n if @device != nil\n getPathAndFilename\n @devfile = @device.devfiles.find(:first, :conditions => ['name = ? and path = ?', @filename, @path])\n if @devfile == nil\n render :text => \"File was not found.\", :status => 404\n return\n end\n else\n # If the device was not found\n render :text => \"Device was not found.\", :status => 404\n return\n end\n \n # If updating description to devfile\n if typename == \"description\"\n @devfile.update_attribute(:description, value)\n render :text => \"Metadata description updated\", :status => 201\n return\n # If updating filetype to devfile\n elsif typename == \"filetype\"\n #TODO: Check valid mime type\n \n @devfile.update_attribute(:filetype, value)\n render :text => \"Metadata filetype updated\", :status => 201\n return\n \n # If updating metadata in blob\n elsif typename == \"uploaded\" or typename == \"latitude\" or typename == \"longitude\" or typename == \"filedate\" or typename == \"file_status\"\n # Looks for right version of the file\n if params[:version] != nil\n puts \"Fetching version: \" + params[:version]\n @blob = @devfile.blobs.find(:first, :conditions => ['version = ?', params[:version]])\n if not @blob\n render :text => \"Version of the file was not found.\", :status => 404\n return\n end\n if typename == \"filedate\"\n # Create new DateTime object from given value \n newtime = DateTime.strptime(value, '%F %T')\n @blob.update_attribute(:filedate, newtime)\n render :text => \"Metadata filedate updated\", :status => 201\n return\n elsif typename == \"uploaded\" or typename == \"file_status\" \n if value == \"0\" #or intti == 1 can only be changed to non-cached\n intti = value.to_i\n puts \"foo\" \n @blob.update_attribute(:uploaded, intti)\n render :text => \"Metadata uploaded updated\", :status => 201\n return\n else\n render :text => \"Invalid metadata value\", :status => 404\n return\n end\n \n elsif typename == \"latitude\"\n latitude = value.to_f\n @blob.update_attribute(:latitude, latitude) \n render :text => \"Metadata latitude updated to #{latitude}\", :status => 201\n return \n elsif typename == \"longitude\"\n longitude = value.to_f\n @blob.update_attribute(:longitude, longitude)\n render :text => \"Metadata longitude updated to #{longitude}\", :status => 201\n return\n end\n # If version of the file was not given\n else\n render :text => \"Version of the file needed.\", :status => 404\n return\n end\n \n # Can't change metadata value from: name, path, creater_at, updated_at, privatefile, \n # size, upload_requested, thumbnail_name, version, blob_hash \n elsif typename == \"name\" or typename == \"path\" or typename == \"created_at\" or typename == \"privatefile\" or\n typename == \"size\" or typename == \"upload_requested\" or typename == \"thumbnail_name\" or\n typename == \"version\" or typename == \"blob_hash\"\n render :text => \"Can't change this metadata from devfile or blob.\", :status => 404\n return\n \n else \n # Checks that metadata type is already added\n type = MetadataType.find_by_name(typename)\n \n if not type\n # If there is not such metadata type already added\n render :text => \"Metadata type not found. Please add metadata type first.\", :status => 404\n return\n end\n \n # Checks that value is either string/float/date/datetime, according to value_type from metadata_types\n if type.value_type == \"string\"\n # String doesn't need to be checked?\n \n elsif type.value_type == \"float\"\n # Check that value has float\n if value !~ /^\\s*[+-]?((\\d+_?)*\\d+(\\.(\\d+_?)*\\d+)?|\\.(\\d+_?)*\\d+)(\\s*|([eE][+-]?(\\d+_?)*\\d+)\\s*)$/\n render :text => \"Invalid float type\", :status => 404\n return\n end\n \n elsif type.value_type == \"date\"\n # Check that value is valid date\n \n value = QueryController::transform_date(value) \n\n begin\n Date.new(value[0..3].to_i, value[5..6].to_i, value[8..9].to_i)\n rescue \n render :text => \"invalid date\", :status => 404\n return\n end\n \n elsif type.value_type == \"datetime\"\n if not QueryController::check_datetime(value)\n render :text => \"invalid datetime\", :status => 404\n return\n end\n\n else\n # Couldn't find value_type. You should never find yourself here\n render :text => \"Error adding metadata, contact support hotline\", :status => 404\n return\n end\n\n \n # \n if @devfile\n \n metadata = Metadata.find(:first, :conditions => ['metadata_type_id = ? and devfile_id = ?', type.id, @devfile.id])\n if metadata and typename != \"tag\"\n metadata.update_attribute(:value, value)\n \n \n if typename == \"context_hash\"\n \n \n context = Context.find_by_context_hash(value)\n if context \n Thread.new{\n puts \"kylla lahtee\"\n XmppHelper::notificationToContextNode(@devfile, context, \"Context content updated!\", \"content-added-to-context\") \n }\n end\n end\n \n \n render :text => \"Metadata value changed\", :status => 200\n return\n end \n if params[:version] != nil\n puts \"Fetching version: \" + params[:version]\n @blob = @devfile.blobs.find(:first, :conditions => ['version = ?', params[:version]])\n if not @blob\n render :text => \"Version of the file was not found.\", :status => 404\n return\n end\n Metadata.find_or_create_by_value_and_blob_id_and_devfile_id_and_metadata_type_id(value, @blob.id, @devfile.id, type.id)\n else \n Metadata.find_or_create_by_value_and_blob_id_and_devfile_id_and_metadata_type_id(value, nil, @devfile.id, type.id)\n end\n render :text => \"Metadata added\", :status => 201\n return\n end\n end\n \n rescue ArgumentError\n render :text => \"Invalid arguments\", :status => 409\n rescue => e\n puts \"Error in updating metadata\".background(:red)\n puts e\n end\n end", "def update_metadata\n # @todo db - refactor to use an update\n metadata = files_doc\n metadata[:length] = @file_position\n metadata[:md5] = @local_md5\n @files.save(metadata)\n end", "def parse_files()\n errors = []\n puts \"[\"\n Dir[@files_path].each do |file_name|\n begin\n xml = File.read(file_name)\n ead = Ead.new(xml)\n solr_docs = ead.to_solr(true)\n json_docs = solr_docs.map { |solr_doc| solr_doc.to_json }\n puts json_docs.join(\", \\r\\n\")\n rescue => ex\n errors << \"File: #{file_name}: #{ex}, #{ex.backtrace}\"\n end\n end\n puts \"]\"\n return errors\n end", "def extract_metadata(file)\n document = parse_kramdown(file)\n toc = ::Kramdown::Converter::Toc.convert(document.root)\n toc_items = toc[0].children.select { |el| el.value.options[:level] == 2 }.map do |t| \n {:id => t.attr[:id], :text => t.value.children.first.value}\n end\n\n metadata = document.root.options[:metadata]\n metadata[:toc] = toc_items\n metadata[:converted] = document.to_html\n metadata[:technologies] = metadata[:technologies].split(\",\")\n metadata\n end", "def processDatafiles\n sip_descriptor_node = @doc.find_first(\"//M:file[@USE='sip descriptor']\", NS_PREFIX)\n sip_descriptor_ownerid = sip_descriptor_node['OWNERID'] if sip_descriptor_node\n fileObjects = @doc.find(\"//premis:object[@xsi:type='file']\", NAMESPACES)\n \n obsolete_dfs = @doc.find(\"//mets:file[not(mets:FLocat)]\", NAMESPACES).map { |n| n['OWNERID'] }.to_set\n \n fileObjects.each do |obj| \n df = Datafile.new\n #GC.start\n #delta_stats\n \n df.fromPremis(obj, @formats, sip_descriptor_ownerid)\n unless obsolete_dfs.include? df.id\n @datafiles[df.id] = df\n @int_entity.datafiles << df\n end\n\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
General method for first sending http to visualREST and then returning the response to xmppclient that sent the xmpp2rest message
def httpAndNotify(path, params, msg_from, method) message = "" begin m = "" if method == :get m = "GET" elsif method == :post m = "POST" elsif method == :put m = "PUT" elsif method == :delete m = "DELETE" else raise Exception.new("Wrong method! use: :get, :post, :put or :delete!") end puts "HTTP #{m} to: #{@@http_host + path}" res = HttpRequest.new(method, path, params).send(@@http_host) message = "#{res.code.to_s}; #{res.body}; #{path}" rescue Exception => e puts "Error: " + e.to_s puts " -- line #{e.backtrace[0].to_s}" message = "#{e.to_s}; #{path}" end # Notifies the xmpp-client about the http-rest result puts "xmpp-response" notification = {:receiver => msg_from, :message => message} sendMessage(notification, @receive_client) end
[ "def send_request\n\n # create the connection object\n uri = URI.parse \"#{MoovAtom::API_URL}/#{@action}.#{@format}\"\n http = Net::HTTP.new uri.host, uri.port\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n # open the connection and send request\n http.start do |http|\n req = Net::HTTP::Post.new(uri.request_uri)\n req.set_form_data(all_attributes, '&')\n @response = http.request(req)\n end\n\n # parse the response if request was successful\n if @response.code == \"200\"\n case @format\n when \"json\"\n @response = JSON.parse @response.body\n when \"xml\"\n @response = REXML::Document.new @response.body\n end\n end\n\n end", "def execute\r\n\r\n begin\r\n logger.debug \"generating request\" if logger.debug?\r\n\r\n generate_request_xml\r\n self.save!\r\n\r\n logger.debug \"request: #{self.request}\" if logger.debug?\r\n\r\n req = create_base_request\r\n req.set_form_data( { :qf => 'xml', :xml => self.request} )\r\n\r\n http = Net::HTTP.new(ET_URI.host, ET_URI.port)\r\n http.use_ssl = true\r\n http.read_timeout = 300 # 5 mins\r\n res = do_http http, req\r\n\r\n logger.debug \"response: #{res.body}\" if logger.debug?\r\n\r\n case res.code\r\n when '200'\r\n self.response = res.body\r\n doc = REXML::Document.new self.response\r\n error_node = REXML::XPath.first doc.root, \"//error\"\r\n if error_node\r\n error_code = error_node.text\r\n error_description_node = REXML::XPath.first doc.root, \"//error_description\"\r\n error_description = (error_description_node ? error_description_node.text : nil)\r\n error_description_detail_node = REXML::XPath.first doc.root, \"//error_detail\"\r\n error_description_detail = (error_description_detail_node ? error_description_detail_node.text : nil)\r\n\r\n self.error_code = error_code\r\n\r\n return new_state_for_error(error_code, error_description, error_description_detail)\r\n else\r\n self.status = :et_success\r\n self.error_code = nil\r\n self.next_try_at = nil\r\n end\r\n else\r\n logger.error \"unexpected result executing message: #{res}\"\r\n return :retry\r\n end\r\n\r\n if !completed?\r\n return :retry\r\n end\r\n\r\n # save the updates to the message\r\n unless save\r\n errs = []\r\n self.errors.each do |n,v|\r\n errs << \"#{n}: #{v}\"\r\n end\r\n logger.error \"unabled to update etmessage #{self.id} after server communication: #{errs.join(';')} \"\r\n return :fail\r\n end\r\n \r\n # allow for any subclass-specific behavior after execution\r\n if :et_success == self.status\r\n if after_execute\r\n self.status = :success\r\n save!\r\n end\r\n end\r\n\r\n return :success\r\n rescue Exception => e\r\n logger.fatal \"unexpected exception encountered executing message: #{e.message}:\\n#{e.backtrace.join(\"\\n\")}\"\r\n return :retry\r\n end\r\n end", "def send!\n build! unless @post && @http\n @response = @http.request(@post)\n @response\n end", "def execute()\n uri = self.uri()\n http = Net::HTTP.new( uri.host, uri.port )\n if use_ssl\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n end\n response = http.request( request )\n response\n end", "def send\n http = EM::HttpRequest.new(@uri).post(@request_options)\n\n http.callback do\n process(http.response)\n end\n\n http.errback do\n fail(http.error)\n end\n end", "def net_http_res; end", "def send(type,data={},scope='appcelerator')\n type = convert_type(type)\n json_data = json_encode(data)\n #\n # build XML/JSON payload\n #\n xml = \"<?xml version=\\\"1.0\\\"?>\\n\"\n xml<< '<request version=\"1.0\" idle=\"0\" timestamp=\"0\" tz=\"0\">'\n xml<< \"<message requestid=\\\"1\\\" type=\\\"#{type}\\\" datatype=\\\"JSON\\\" scope=\\\"#{scope}\\\" version=\\\"1.0\\\"><![CDATA[#{json_data}]]></message>\"\n xml<< '</request>' \n xml.strip!\n \n puts \"Sending remote request with payload=> #{xml}\" if @debug\n \n #\n # build the path to the server\n #\n path = \"/#{@servicebroker}?maxwait=0&instanceid=#{@instanceid}&auth=#{@auth}&ts=#{Time.now.to_i}\"\n req = Net::HTTP::Post.new(path)\n req.body = xml\n # attempt to simulate browser\n req.set_content_type('text/xml')\n req['X-Requested-With'] = 'XMLHttpRequest'\n # send of session cookie\n req['Cookie'] = @cookies.to_s if @cookies\n \n #\n # send the POST\n #\n puts \"Sending Post[req: #{req.inspect}]\" if OPTIONS[:verbose]\n res = get_http(@url.host,@url.port) do |http|\n http.request(req)\n end\n \n # make sure we reset cookies if necessary\n get_cookies(res)\n \n response = Hash.new\n json_response = Hash.new\n \n #\n # if we get 200, we have data\n #\n if res.code.to_i == 200\n\n body = res.body\n \n puts \"received remote response => #{body}\" if @debug\n \n # currently we only support one response message in the data payload\n # extract it using simple regex\n #\n m = body.match(/<message (.*?)><!\\[CDATA\\[(.*?)\\]\\]><\\/message>/)\n \n if m and m[1] # check to see if we have a response (not required)\n #\n # split the attributes of message into hash\n #\n m[1].split(' ').map do |item|\n t = item.split('=')\n k = strip_quotes t[0]\n v = strip_quotes t[1]\n response[k]=v\n end\n json_response = json_decode(m[2])\n else\n json_response = {}\n end\n else\n puts \"received error: #{res.code} => #{res.body}\" if @debug\n end\n\n\t {:message=>convert_type(response['type']),:data=>json_response,:scope=>response['scope']||scope}\n end", "def asyncHttpCall7\n Rho::AsyncHttp.post(\n :url => \"http://10.233.85.82:9097/rhodes/secure/asyncpost.php\",\n :body => \"data1=test&data2=test2\",\n :callback => url_for(:action => :httpget_callback),\n :authentication => {\n :type => :basic,\n :username => \"wrong\",\n :password => \"wrong\"\n },\n :callback_param => \"post=complete\"\n )\n render :action => :wait\n end", "def call\n request = http_request_class.new(uri.request_uri, headers)\n request.body = body if body\n http = http_setup\n # http.set_debug_output($stdout)\n response = wait_for_completion(HttpResponse.new(http.request(request)))\n Nokogiri::XML response.body unless response.nil?\n end", "def request\n url1 = url\n return false unless valid?\n http_response = HTTParty.post(url, :format => :plain,\n :query => @params.merge({ :cmd => @cmd }),\n :headers => {\n 'ZooZ-Unique-ID' => @unique_id,\n 'ZooZ-App-Key' => @app_key,\n 'ZooZ-Response-Type' => @response_type,\n }) if @response_type.eql?('NVP')\n\n\n\n http_response = HTTParty.post(url, :format => :json,\n :body => @params.merge({ :cmd => @cmd }),\n :headers => {\n 'ZooZDeveloperId' => @developer_id,\n 'ZooZServerAPIKey' => CGI::escape(@app_key)\n }) if @response_type.eql?('JSON')\n\n response = Response.new\n response.request = self\n response.http_response = http_response\n unless response.success?\n @errors = response.errors\n return false\n end\n response\n end", "def external_communication\n response = Unirest.post \"http://office.code-runners.com:8888\",\n headers:{ \"Accept\" => \"application/json\" },\n parameters:{ :amount => amount.to_s, :tip => tip.to_s }\n p response.body\n end", "def send_command(actionName:, serviceType:, argList:, controlURL:, quiet: false )\n soapBody = \"<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?><s:Envelope s:encodingStyle=\\\"http://schemas.xmlsoap.org/soap/encoding/\\\" xmlns:s=\\\"http://schemas.xmlsoap.org/soap/envelope/\\\"><s:Body><u:#{actionName} xmlns:u=\\\"urn:schemas-nds-com:service:#{serviceType}\\\">#{argList}</u:#{actionName}></s:Body></s:Envelope>\\0xd\\0xa\"\n \n soapHeaders = { 'Host' => \"#{@skyAddress}:#{@port}\",\n 'Content-Type' => 'text/xml', \n 'SOAPAction' => \"\\\"urn:schemas-nds-com:service:#{serviceType}##{actionName}\\\"\"\n }\n\n res = Net::HTTP.new(@skyAddress, @port).start do |http|\n url = \"/#{@decoder_key}#{controlURL}\"\n response = http.post(url, soapBody, soapHeaders)\n if !quiet\n puts response.code.to_i\n puts response.body #if response.code.to_i == 200\n end\n return response\n end\n end", "def send_request(req); end", "def send_success\n end", "def make_http_request\n Net::HTTP.get_response('localhost', '/ping', 3000).body\nend", "def rpc(action, args={})\n auth_hash = {\"c\" => @company, \"u\" => @user, \"p\" => @password}\n uri = URI(\"https://#{@company}.logicmonitor.com/santaba/rpc/#{action}\")\n uri.query = URI.encode_www_form(args.merge(auth_hash))\n begin\n http = Net::HTTP.new(uri.host, 443)\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n req = Net::HTTP::Get.new(uri.request_uri)\n response = http.request(req)\n return response.body\n rescue SocketError => se\n puts \"There was an issue communicating with #{url}. Please make sure everything is correct and try again.\"\n puts se.message\n rescue Exception => e\n puts \"There was an issue.\"\n puts e.message\n end\n return nil\nend", "def send\n http = Net::HTTP.new(@uri.host, @uri.port)\n http.read_timeout = @http_timeout\n\n # Output request XML if debug flag is set\n if debug == true\n logger.info \"Request URL: #{@uri.to_s}\"\n logger.info \"Request Timeout: #{@http_timeout}\"\n logger.info \"Request headers: #{headers}\"\n logger.info \"Request body: #{body}\"\n end\n\n if @uri.port == 443\n http.use_ssl = true\n http.ssl_timeout = @http_timeout\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n end\n\n post = Net::HTTP::Post.new(@uri.path, headers)\n post.body = body\n post.content_type = 'text/xml'\n\n response = http.start { |http| http.request(post) }\n\n if debug == true\n logger.info \"Response: #{response}\"\n end\n\n if response.is_a? Net::HTTPInternalServerError\n logger.info \"#{response.class.to_s}: #{response.message}\"\n return Hashie::Mash.new({})\n end\n\n @response = Hashie::Mash.new(Response.new(self, response))\n end", "def asyncHttpCall3\n Rho::AsyncHttp.get(\n :url => \"http://10.233.85.82:9097/rhodes/secure/asyncget.php?data1=test&data2=test2\",\n :callback => (url_for :action => :httpget_callback),\n :authentication => {\n :type => :basic,\n :username => \"wrong\",\n :password => \"wrong\"\n }\n )\n render :action => :wait\n end", "def send_response\r\n if self.response.class.name == \"Proc\"\r\n return self.response.call\r\n end\r\n self.response\r\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines whether or not the 2 names match (ignoring parenthesis text)
def exact_match?(name1:, name2:) return false unless name1.present? && name2.present? a = name_without_alias(name: name1.downcase) b = name_without_alias(name: name2.downcase) a == b end
[ "def names_match s1, s2\n t1 = ''\n t2 = ''\n s1.each_char do |c|\n t1 << c if c.match /(\\d|[a-zA-Z])/\n end\n s2.each_char do |c|\n t2 << c if c.match /(\\d|[a-zA-Z])/\n end\n t1.upcase == t2.upcase\nend", "def games_have_same_name?(name1, name2)\n name1 = name1.downcase\n name2 = name2.downcase\n return true if name1 == name2\n\n levenshtein = Class.new.extend(Gem::Text).method(:levenshtein_distance)\n\n distance = levenshtein.call(name1, name2)\n return true if distance <= 2\n\n name1 = name1.gsub('&', 'and')\n name2 = name2.gsub('&', 'and')\n name1 = name1.gsub('deluxe', '').strip\n name2 = name2.gsub('deluxe', '').strip\n\n return true if name1 == name2\n\n return false\n end", "def names_match?(n1, style1, n2, style2)\n f1 = style1 == :short ? n1.first : n1.firstname\n m1 = style1 == :short ? n1.middle : n1.middlename\n l1 = style1 == :short ? n1.last : n1.lastname\n \n f2 = style2 == :short ? n2.first : n2.firstname\n m2 = style2 == :short ? n2.middle : n2.middlename\n l2 = style2 == :short ? n2.last : n2.lastname\n \n # first/last name have to be provided\n return false if l1.nil? || l2.nil? || f1.nil? || f2.nil?\n return false if l1.downcase.strip != l2.downcase.strip\n \n unless @options[:skip_match_suffix]\n s1 = n1.suffix\n s2 = n2.suffix\n return false if s1 && s2 && compare_without_dot(s1, s2) == false\n end\n \n return false if !abbr_match?(f1, f2)\n m1.nil? or m2.nil? or abbr_match?(m1, m2)\n end", "def match_first_name(first1, first2)\n initials = 0\n initials+= 1 if first1.match(/^[A-Z\\u{c0}-\\u{de}]\\.?$/)\n initials+= 1 if first2.match(/^[A-Z\\u{c0}-\\u{de}]\\.?$/)\n return initials if first1 == first2 # \"W.\" and \"W.\" or \"William\" and \"William\"\n return 0 if initials == 0 && match_alt(:first, first1, first2) # \"William\"\" and \"Bill\"\n return -1 unless initials > 0 # \"William\" and \"Patricia\"\n return initials if first1[0] == first2[0] # \"W.\" and \"William\" or \"W.\" and \"W\"\n -1\n end", "def abbr_match?(str1, str2)\n build_middlename_regexp(str1) =~ str2\n end", "def only_name_or_surname_in_common?(a, b)\n\t\t\t\t\tname_a = a[:name].strip.split(/\\s/)\n\t\t\t\t\tname_b = b[:name].strip.split(/\\s/)\n\t\t\t\t\treturn false if name_a.length != 2 || name_b.length != 2 || a[:email] == b[:email]\n\t\t\t\t\t(name_a.to_set & name_b.to_set).length == 1\n\t\t\t\tend", "def compare_to_name(name_1, name_2)\n name_1.downcase == name_2.downcase ? true : false\nend", "def match?(cop_names); end", "def similar_name(other_norm_name)\n (normalized_name.start_with?(other_norm_name) || other_norm_name.start_with?(normalized_name))\n end", "def match_name?(name)\n return true if self.name == name\n return true if aliases.include?(name)\n false\n end", "def pt_name_eql_sub_name?\r\n (patient_last_name == subscriber_last_name &&\r\n patient_first_name == subscriber_first_name &&\r\n patient_middle_initial == subscriber_middle_initial &&\r\n patient_suffix == subscriber_suffix)\r\n end", "def use_name?(*names)\n return @match.use_name?(*name)\n end", "def name_check?(input)\n (/#{input}/.match(@name.downcase) || /#{input}/.match(@last_name.downcase)) ? true : false\n end", "def name_matches?(name, match)\n if match.include? '*'\n parts = match.split '*'\n first = parts.shift\n\n # if it's a leading *, this works because start_with?(\"\") always returns true\n # and has a length of 0 so the position stays at 0, which is correct\n if name.start_with?(first)\n # check for suffix match right away, accounting for a final * which split doesn't return\n if not match.end_with? '*' and not name.end_with?(parts.pop)\n return false\n end\n\n # check any internal wildcards\n position = first.length\n parts.each do |p|\n # find the substring starting at the position end of the last match\n found = name.index(p, position)\n if found and found >= position\n position = found + p.length # end of the matched substr\n else\n return false\n end\n end\n end\n elsif name == match\n true\n end\n end", "def has_name?( other, ns=nil )\n if ns\n return (namespace() == ns and name() == other)\n elsif other.include? \":\"\n return fully_expanded_name == other\n else\n return name == other\n end\n end", "def check_names gfy_name\n names1 = Fencer.where(last_name: gfy_name)\n return names1.first if names1 and names1.count == 1\n names2 = Fencer.where(last_name: gfy_name.split(\" \")[0...-1], first_name: /^#{gfy_name.split(\" \")[-1]}/i)\n return names2.first if names2 and names2.count == 1\nend", "def output_matched?(p_name, output_names)\n output_names.detect do |o_name|\n Bogo::Utility.snake(o_name).tr('_', '') == Bogo::Utility.snake(p_name).tr('_', '')\n end\n end", "def output_matched?(p_name, output_names)\n output_names.detect do |o_name|\n Bogo::Utility.snake(o_name).tr(\"_\", \"\") == Bogo::Utility.snake(p_name).tr(\"_\", \"\")\n end\n end", "def test_compare_string_overlap_defs\n v1 = Vertex.new(\"speech\", 2, 1, 0, 0, 1, \"NN\")\n v2 = Vertex.new(\"delivering\", 2, 1, 0, 0, 1, \"VB\")\n assert_equal(1, instance.compare_strings(v1, v2, speller))#no POS is considered for hypernyms and hyponyms\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes the parenthesis portion of the name. For example: "Foo College (foo.edu)" > "Foo College"
def name_without_alias(name:) return '' if name.blank? name.split(' (')&.first&.strip end
[ "def cleanup_firstname(name)\n name.gsub(/^Dean(\\w+)/) { |s| \"DeAn#{$1}\" }\n end", "def clean_smpc_name name\n clean_text(\n name.gsub(/\\s\\(.+\\)$/, ''), # parenthesis at the end\n clean_dashes: true,\n clean_punct: true,\n )\n end", "def unparen( str )\n match = str.match(/^\\((.*?)\\)$/)\n match ? match[1] : str\n end", "def clean_name(value, **opt)\n parts = value.strip.split(/[[:space:]]+/)\n parts <<\n case (last = parts.pop)\n when /^[^.]\\.$/ then last # Assumed to be an initial\n when /^[A-Z]$/ then last + '.' # An initial missing a period.\n else clean(last, **opt) # Remove trailing punct.\n end\n parts.join(' ')\n end", "def normalize_aws_title(title)\n title.sub(/\\([^)]*\\)\\s*$/, '')\n end", "def full_name\n major.title.gsub(/\\s{2,}/, ' ') rescue major_abbr\n end", "def middle_name\n name.split[1..-2].join(' ')\n end", "def normalize_name\n @normalize_name ||= begin\n return '' if name.empty?\n\n exclude = %w[corporation institute organization university\n all and of the].join('|')\n tmp = name.dup\n tmp.gsub!(/#{exclude}/i, '')\n tmp.gsub!(/\\s+/, ' ')\n tmp.strip!\n tmp.downcase # it's not case sensitive\n end\n end", "def display_name\n return name unless subsplit?\n\n matched_name = /^(?:-|\\{.*?}\\s*)(.+)/.match(name)\n matched_name ? matched_name[1] : name\n end", "def shortened_name(name)\n name = (name.split(\"/\").map { |x| x[0].upcase + x[1..-1] }).join(\"\")\nend", "def normalize_name(name)\n if name.include?(',')\n make_name_first_then_last(name)\n else\n name\n end\n end", "def unclutter_album_name(album)\n album.gsub(/\\[[\\w\\s]+\\]/,'').strip.gsub(/\\([\\w\\s-]+\\)$/,'').strip\n end", "def clean_name(name)\n cleaned_name = I18n.transliterate(name)\n cleaned_name = cleaned_name.upcase\n # remove 'da, do, de' do nome (nao servem para nada em termos de citacoes)\n cleaned_name = cleaned_name.sub(/ \\b[\\w]{1,2}\\b /, ' ')\n # to make a trim: .gsub!(/\\s+/, \"\" )\n return cleaned_name\n end", "def short_country_name(name)\n if name.include? ' '\n temp = name.split(' ')\n temp[0][0] + temp[1][0]\n else\n name[0..2].upcase\n end\nend", "def full_name\n self.name ? \"#{self.name.split(' ')[0..-2].join(' ')}, #{self.name.split(' ')[-1]}\" : ''\n end", "def cleanup_surname(name)\n if name.length > 4\n name.gsub!(/^Mc(\\w+)/) { |s| \"Mc#{$1.capitalize}\" }\n name.gsub!(/^Mac(\\w+)/) { |s| \"Mac#{$1.capitalize}\" }\n name.gsub!(/^Mac(\\w+)/) { |s| \"Mac#{$1.capitalize}\" }\n name.gsub!(/^Osh(\\w+)/) { |s| \"O'sh#{$1}\" }\n name.gsub!(/^Van(\\w+)/) { |s| \"Van#{$1.capitalize}\" }\n name.gsub!(/^Von(\\w+)/) { |s| \"Von#{$1.capitalize}\" } \n# name.gsub!(/^Dev(\\w+)/) { |s| \"DeV#{$1}\" } \n end\n name\n end", "def clean_name(name)\n CGI.escape(name).gsub('.', '')\n end", "def clean_project_name name\n\t\t name.\n\t\t\t# replace \"_\" by \"-\"\n\t\t\tgsub('_', '-')\n\t\tname\n\tend", "def display_name(name)\n name.gsub('-', ' ').capitalize\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes any duplicates by comparing the sort names and ids
def deduplicate(records:) return [] unless records.present? && records.is_a?(Array) out = [] found = [] records.each do |rec| next if found.include?(rec[:sort_name]) || found.include?(rec[:id]) found << rec[:sort_name] found << rec[:id] if rec[:id].present? out << rec end out end
[ "def duplicate_ids()\n @traces.select{|id, traceables| traceables.length > 1}.map{|id, traceable| id}.sort\n end", "def sort_by_id\r\n # Hash#sort will convert each item to an Array of 2 elements [key, value]\r\n sort { |entry1,entry2| entry1[1].id.to_i <=> entry2[1].id.to_i }.collect { |el| el[1] }\r\n end", "def unique_by; end", "def remove_duplicates()\n self.duplicate_transactions_by_actor().each do |a, txns|\n # Spaceship operator, if my actor is of greater value than theirs, skip because they should remove the dupe\n next if (self.actor <=> a) == 1\n txns.each do |txn|\n self.counts[self.actor][\"txns\"].delete(txn)\n end\n end\n end", "def clean_up_dupes(dupes, output)\n unless dupes.empty?\n dupes.uniq.each do |sequence|\n output.delete sequence\n end\n end\n\n output\n end", "def without_duplicates(bindings); end", "def uniq_sorted_strings\n sort.map(&:to_s).uniq.delete_if(&:blank?)\n end", "def sort_and_get_uniques\n @seq_hash = @seq_hash.sort.to_h\n @seq_hash = @seq_hash.select {|seq, word| word.count == 1}\n puts \n end", "def remove_duplicate_dependencies(dependencies)\n uniq = []\n duplicated = {}\n dependencies_by_name = dependencies.group_by{|d| d.name}\n dependencies_by_name.map do |name, dependencies_same_name|\n if dependencies_same_name.size > 1\n duplicated[name] = dependencies_same_name\n uniq << merge_dependencies(dependencies_same_name)\n else\n uniq << dependencies_same_name.first\n end\n end\n [uniq, duplicated]\n end", "def organize_ids(ids); end", "def preserving_uniq(sorted)\n result = []\n elements = sorted.uniq\n sorted.each do |element|\n if elements.include?(element)\n result << element\n elements.delete(element)\n end\n end\n result\n end", "def find_dupes\n @hathi_report_filtered.find_all.with_index do |row, index|\n row if (row['local_id'] == @hathi_report_filtered.at(index + 1)&.[]('local_id')) || (row['local_id'] == @hathi_report_filtered.at(index - 1)['local_id'])\n end.compact\n end", "def sort_clear\n session[sort_name] = nil\n end", "def remove_approve_duplicates(array)\n return array.flatten.uniq.sort\n end", "def remove_duplicate_matches(matches)\r\n # Sort the items.\r\n # Sort the array without matches[0], since we need it to\r\n # stay in place no matter what.\r\n if matches.length>0\r\n matches[1..-2] = matches[1..-2].sort.uniq\r\n end\r\n matches\r\n end", "def sort!(hash)\n hash.replace(sort(hash))\n end", "def d(memo, other)\n other.each do |sort|\n unless memo.keys.include?(sort[0])\n memo << sort\n end\n end\n end", "def remove_duplicates(*cols, deleted_id_order: '<')\n condition_sql = cols.map { |col| \"#{table_name}.#{col} IS NOT NULL AND #{table_name}.#{col} = t.#{col}\" }.join(' AND ')\n query = <<-SQL\n DELETE FROM #{table_name} USING #{table_name}, #{table_name} AS t WHERE #{table_name}.id #{deleted_id_order} t.id AND #{condition_sql}\n SQL\n connection.execute(query)\n end", "def remove_dups\n first = self\n while first.next\n second = first.next\n first.next.remove if first.next.data == first.data\n while second.next\n second.next.remove if second.next.data == first.data\n second = second.next\n end\n first = first.next\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
used at filelist inorder to send file info if requested path is file
def send_file_info(last, path) if not last == nil user = current_user path = path.force_encoding("UTF-8") @file_names = "#{path.split('/').last}" + "\n" @access_url = "#{HOSTING_URL}" + "/user_files/"+ "#{user.userid}" + path.force_encoding("UTF-8") else @file_names = "error" @access_url = "" end puts_message "send_file_info end" end
[ "def has_file_server\n return @payload.get_path(\"files\"){false}\n end", "def send_to_fileserver(client, answer, msg)\n if answer.include?('ONE')\n puts \"File in server ONE\"\n @fileServer.puts msg\n fileserver_handler(client, answer)\n elsif answer.include?('TWO')\n puts \"File in server TWO\"\n #@fileServerTwo.puts msg\n fileserver_handler(client, answer)\n else\n puts \"Received #{answer}\"\n client.puts \"ERROR: File not found\"\n end\n return\n end", "def add_file_info!(request, body)\n #add content length\n request.content_length = body.respond_to?(:lstat) ? body.lstat.size : body.size \n \n #Add filename to Content-Disposition\n request['Content-Disposition'] ||= body.respond_to?(:path) ? \"filename=#{File.basename(body.path).to_s}\" : \"\"\n \n #If content type header not set, assume binary/octet-stream, since this is a file\n request['Content-Type'] ||= 'binary/octet-stream'\n end", "def process(request, response)\n req_method = request.params[Const::REQUEST_METHOD] || Const::GET\n req_path = can_serve request.params[Const::PATH_INFO]\n if not req_path\n # not found, return a 404\n response.start(404) do |head,out|\n out << \"File not found\"\n end\n else\n begin\n if File.directory? req_path\n send_dir_listing(request.params[Const::REQUEST_URI], req_path, response)\n elsif req_method == Const::HEAD\n send_file(req_path, request, response, true)\n elsif req_method == Const::GET\n send_file(req_path, request, response, false)\n else\n response.start(403) {|head,out| out.write(ONLY_HEAD_GET) }\n end\n rescue => details\n STDERR.puts \"Error sending file #{req_path}: #{details}\"\n end\n end\n end", "def get_file(client, current_path, input, client_port)\n\n\tif(!File.exist?(\"#{current_path}/files/#{input}\"))\n\t\tclient.puts \"\\nFile not available\"\n\telse\n\t\tclient.puts \"sending\"\n\n\t\tclient_serv = TCPSocket.new(\"#{client.peeraddr[3]}\", client_port)\n\t\tclient_serv.puts \"#{input}\"\n\n\t\tfile_boolean = client_serv.gets.chomp\n\t\tif(file_boolean == \"false\")\n\n\t\telse\n\t\t\tfile_sending = File.open(\"#{current_path}/files/#{input}\", \"rb\")\n\n\t\t\tfilecontent = file_sending.read\n\t\t\tclient_serv.puts(filecontent)\t \t\t\t\t\n\t\t\tclient_serv.close\n\t\t\tfile_sending.close\n\n\t\t\tputs \"File #{input} Sent\"\n\t\tend\n\tend\t\t\t\t\t\nend", "def file\n if params[:version] && !params[:version].match?(/^[1-9]\\d*$/)\n render(plain: '400 Bad Request: version parameter must be positive integer', status: :bad_request)\n return\n end\n\n obj_version = params[:version].to_i if params[:version]&.match?(/^[1-9]\\d*$/)\n location = MoabOnStorage::StorageServicesWrapper.filepath(druid, params[:category], params[:filepath], obj_version)\n if location\n send_file location\n else\n render(plain: \"404 File Not Found: #{druid}, #{params[:category]}, #{params[:filepath]}, #{params[:version]}\", status: :not_found)\n end\n rescue Moab::MoabRuntimeError => e\n render(plain: \"404 Not Found: #{e}\", status: :not_found)\n end", "def response_send_file(info)\n send_file(info[:file_path], response_binary_metadata(info))\n end", "def get_file\n uuid = params[:uuid]\n file = params[:file]\n \n # Here file only includes the basename, so no need to run basename.\n\n if ((md = file.match(/(Mets_file)/) ||\n md = file.match(Generic_xml)) &&\n File.exists?(\"#{Dest}/#{uuid}/#{Meta}/#{md[0]}\"))\n @text = IO.read(\"#{Dest}/#{uuid}/#{Meta}/#{md[0]}\")\n send_data(@text,\n :filename => md[1],\n :type => \"text/xml\",\n :disposition => \"inline\")\n elsif (file.match(Bagit_file) and File.exists?(\"#{Dest}/#{uuid}/#{Bagit_file}\"))\n @text = IO.read(\"#{Dest}/#{uuid}/#{Bagit_file}\")\n send_data(@text,\n :filename => Bagit_file,\n :type => \"application/zip\",\n :disposition => \"attachment\")\n else\n # This really needs a status message, since it will appear to\n # the user that the page just redraws.\n redirect_to :action => 'report'\n end\n end", "def file?() end", "def file\n if params[:version] && !params[:version].match?(/^[1-9]\\d*$/)\n render(plain: \"400 Bad Request: version parameter must be positive integer\", status: :bad_request)\n return\n end\n\n obj_version = params[:version].to_i if params[:version]&.match?(/^[1-9]\\d*$/)\n location = MoabStorageService.filepath(druid, params[:category], params[:filepath], obj_version)\n if location\n send_file location\n else\n render(plain: \"404 File Not Found: #{druid}, #{params[:category]}, #{params[:filepath]}, #{params[:version]}\", status: :not_found)\n end\n rescue ArgumentError => e\n render(plain: \"400 Bad Request: #{e}\", status: :bad_request)\n rescue Moab::MoabRuntimeError => e\n render(plain: \"404 Not Found: #{e}\", status: :not_found)\n end", "def process(request, response)\n if response.socket.closed?\n return\n end\n\n path_info = request.params[Mongrel::Const::PATH_INFO]\n get_or_head = @@file_only_methods.include? request.params[Mongrel::Const::REQUEST_METHOD]\n if get_or_head and @files.can_serve(path_info)\n # File exists as-is so serve it up\n @files.process(request,response)\n else\n raise \"No file... Sorry\" #TODO set 404 status 2007/04/09 by shino\n end\n end", "def single_file?\n @info['files'].nil?\n end", "def public_files\r\n\r\n if params[:cmd] == 'get'\r\n valid_path = check_file_path(File.join(Rails.public_path, params[:path].to_s))\r\n if valid_path\r\n root = File.join(@path, '*')\r\n\r\n # This part is also call in the view\r\n\r\n type_with_icon = []\r\n path_folder_icon = File.join(Rails.public_path, \"images\", \"file_icons16x16\")\r\n Dir.entries(path_folder_icon).map{|f|\r\n type_with_icon << File.basename(f, \".png\") if f != \".\" && f != \"..\"\r\n }\r\n @files = Dir[root].sort.map{|f|\r\n lstat = File.lstat(f)\r\n type = MIME::Types.type_for(f).first.try(:sub_type)\r\n type = \"txt\" if type == \"plain\"\r\n type = \"unknown\" if !type_with_icon.include?(type)\r\n hash = {\r\n :data => File.basename(f),\r\n :attr => { :rel => (lstat.directory? ? \"folder\" : (lstat.symlink? ? \"link\" : type))},\r\n :metadata => { :id => f.sub(Rails.public_path, \"\"), :name => File.basename(f) },\r\n :icon => (File.directory?(f) ? \"folder\" : \"file\")\r\n }\r\n if lstat.symlink?\r\n hash[:attr][:link] = File.readlink(f).blank? ? \"\" : File.readlink(f)\r\n elsif lstat.directory?\r\n hash[:state] = \"closed\"\r\n nbchild_and_size_tab = SystemSetting.contents_folder(f)\r\n nbchild_and_size_tab[2] = view_context.try(:number_to_human_size, nbchild_and_size_tab[2],\r\n :precision => 2, :separator => '.')\r\n hash[:attr][:nbchild_and_size] = nbchild_and_size_tab\r\n else\r\n hash[:attr][:size] = view_context.try(:number_to_human_size, File.size(f),\r\n :precision => 2, :separator => '.') if File.exists?(f)\r\n end\r\n hash\r\n }\r\n render :json => @files.to_json\r\n return\r\n else\r\n render :json => { :success => false, :error => _(\"Cannot access the path %{path}\") % {:path => @path} }\r\n return\r\n end\r\n elsif request.post?\r\n case params[:cmd]\r\n when 'rename'\r\n newpath = File.join(Rails.public_path, params[:newname])\r\n oldpath = File.join(Rails.public_path, params[:oldname])\r\n if check_file_path(oldpath) && !check_file_path(newpath)\r\n FileUtils.mv(oldpath, newpath)\r\n render :json => {:success => true}\r\n return\r\n else\r\n render :json => {:success => false, :error => _(\"Cannot rename file: %{oldpath} to %{newpath}\") %\r\n {:oldpath => oldpath, :newpath => newpath} }\r\n return\r\n end\r\n when 'newdir'\r\n if check_file_path(File.join(Rails.public_path, params[:dir])) ? false : Dir.mkdir(@path)\r\n render :json => {:success => true}\r\n return\r\n else\r\n render :json => {:success => false, :error => _(\"Cannot create directory: %{path}\") % {:path => @path} }\r\n return\r\n end\r\n when 'delete'\r\n if check_file_path(File.join(Rails.public_path, params[:file]))\r\n File.stat(@path).directory? ? Dir.delete(@path) : File.delete(@path)\r\n render :json => {:success => true}\r\n return\r\n else\r\n render :json => {:success => false, :error => _(\"Cannot delete: %{path}\") % {:path => @path} }\r\n return\r\n end\r\n when 'unzip'\r\n zip = File.join(Rails.public_path, params[:zip])\r\n dest = File.join(Rails.public_path, params[:dest])\r\n if check_file_path(zip)\r\n render :json => SystemSetting.unzip_file(zip, dest)\r\n return\r\n else\r\n render :json => {:success => false, :error => _(\"Cannot acces: %{zip} or %{dest}\") % {:zip=> zip, :dest=> dest} }\r\n return\r\n end\r\n when 'zip'\r\n if check_file_path(File.join(Rails.public_path, params[:path]))\r\n render :json => SystemSetting.zip_file(params[:folder], @path)\r\n return\r\n else\r\n render :json => {:success => false, :error => _(\"Cannot acces: %{path}\") % {:path=> @path} }\r\n return\r\n end\r\n when 'preview'\r\n path = File.join(Rails.public_path, params[:path])\r\n text_preview = ''\r\n if check_file_path(path)\r\n File.open(@path, \"r\"){|file|\r\n\r\n #conv = Iconv.new('UTF-8', 'UTF-8')\r\n\r\n 10.times{\r\n\r\n #text_preview = conv.iconv(line)\r\n\r\n text_preview << \"#{file.gets}<br/>\"\r\n }\r\n }\r\n end\r\n render :text => text_preview, :layout => false\r\n return\r\n when 'upload'\r\n if check_file_path(File.join(Rails.public_path, params[:path]))\r\n return_data = {:success => true}\r\n v = params[:form]\r\n if !v.blank? && check_file_path(@path)\r\n file = File.join(@path, v[:file].original_filename)\r\n if File.exist?(file)\r\n return_data[:success] = false\r\n return_data[:errors] = {:form => _(\"File %{file} already exists\") % {:file => file.sub(@path, '')} }\r\n else\r\n begin\r\n File.open(file, \"wb\") {|f| f.write(v[:file].read) }\r\n rescue\r\n return_data[:success] = false\r\n return_data[:errors] = {:form => _(\"File %{file} can't be uploaded\") % {:file => file.sub(@path, '')} }\r\n end\r\n end\r\n end\r\n render :action => 'upload_form', :layout => false\r\n return\r\n else\r\n render :json => {:success => false, :error => _(\"Cannot upload in the directory: %{path}\") % {:path => @path} }\r\n return\r\n end\r\n else\r\n render :json => {:error => _(\"Command unknown '%{cmd}'\") % {:cmd => params[:cmd]} }\r\n return\r\n end\r\n end\r\n render :layout => 'application_jquery'\r\n end", "def handle_file\n url_parts = environment['PATH_INFO'].split('/')\n file_path = File.join(files_dir, url_parts)\n\n if File.exists?(file_path) and path_is_subdir_of(file_path, files_dir)\n if File.readable?(file_path)\n send_file(file_path)\n else\n handle_forbidden\n end\n elsif File.exists?(file_path)\n handle_no_route\n else\n handle_no_route\n end\n end", "def file_added file_path\n puts \"File added - #{file_path} to #{@peer_id}\"\n update_file_on_index 'add', file_path\nend", "def show_files\n \n temp_dir = params[:tmp_dir]\n chunk = params[:chunk_number]\n file = params[:file]\n \n # redirect_to \"/data/#{temp_dir}/#{chunk}/#{file}\"\n \n # send_data compress(@text_output),\n # :content_type => \"application/x-gzip\",\n # :filename => @list.name.gsub(' ','_') + \".txt.gz\"\n File.exists? \"#{RAILS_ROOT}/public/data/#{temp_dir}/#{chunk}/#{file}\"\n if file =~ \"\\.PNG$\"\n send_file \"#{RAILS_ROOT}/public/data/#{temp_dir}/#{chunk}/#{file}\", :type => 'image/png', :disposition => 'inline'\n else\n send_file \"#{RAILS_ROOT}/public/data/#{temp_dir}/#{chunk}/#{file}\", :disposition => 'inline'\n end\n \n end", "def fa_request(fn, name, *_)\n ix = convert_integer(fn, \"!File number\")\n @files[ix] = {name: name.sub(/^\\*/,''), path: get_file_name(name), number: ix}\n end", "def for(file_or_dir); end", "def on_opendir(response); end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends a progress update Inputs: percentage Integer Optional description, this could be displayed to the user e.g. Resizing image
def progress(percentage, description = nil) reply({:progress => percentage, :description => description}, {:message_type => 'progress'}) end
[ "def update(percentage,text=nil)\n @progressBar.text = text.to_s if text\n @progressBar.fraction = percentage.to_f\n end", "def avanzamento_progress_bar(nome_step)\n statusbar.push(1, \"#{nome_step}\")\n progress.text = \"%.0f%%\" % @percent\n progress.fraction = @percent / 100.0\n while (Gtk.events_pending?)\n Gtk.main_iteration\n end\n @percent += @partial_progress\n end", "def set_ProgressPercentComplete(value)\n set_input(\"ProgressPercentComplete\", value)\n end", "def increment_progress\n @progress += 1\n update_progress\n end", "def percent_progress=(value)\n @percent_progress = value\n end", "def update_progress(total, done)\n percentage = total.zero? ? 100 : ((done.to_f / total) * 100).to_i\n progress(percentage)\n end", "def sync_progress\n response = block_count\n\n count = response[:count].to_i\n unchecked = response[:unchecked].to_i\n total = count + unchecked\n\n count.to_f * 100 / total.to_f\n end", "def percentage=(percentage)\n @progressBar.fraction = percentage.to_f\n end", "def progress; @progress; end", "def progress\n render :update do |page|\n @status = Mongrel::Uploads.check(params[:upload_id])\n page.upload_progress.update(@status[:size], @status[:received]) if @status\n end\n end", "def update_progress\n Platform.run_later do\n progress.set_progress patcher.progress\n end\n end", "def update_progress(file, percent_done)\n file_info = filesizes[file]\n\n current_bytes = (percent_done * file_info[:size]) / 100\n since_last = current_bytes - file_info[:transferred]\n filesizes[file][:transferred] = current_bytes\n\n increment_transferred(since_last)\n update_percent(transferred)\n end", "def progress=(value)\n @progress = value\n end", "def set_download_progress\n @downloaded_bytes = @files.inject(0) { |sum, file| sum + file.size }\n @progress = ((100 / @meta_info.total_size.to_f) * @downloaded_bytes).to_i\n PrettyLog.info(\"... #{@progress}% so far ...\")\n end", "def indicate_progress\n end", "def updateProgress(iNbrSamples)\n @NbrSamplesWritten += iNbrSamples\n $stdout.write(\"[#{(@NbrSamplesWritten*100)/@NbrSamples}%]\\015\")\n $stdout.flush\n end", "def progress=(value)\n @progress = value\n end", "def progress position, total_size = nil\n total_size ||= ARGV.size\n $PERCENTAGE_DONE = position.to_f / total_size.to_f * 100\n end", "def add_progress\n self.progress += 1\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the Site with the given UID. This method does a server request, to get additional property data.
def site(uid) site_data = request("/web_properties/#{uid}.json") Site.new self, site_data['uid'], site_data['name'] end
[ "def site\n return @site\n end", "def site\n @site ||= ::Site.find(@options[:site] || 1)\n end", "def site(id)\n s = SiteStat.find(id)\n return nil if s.user != self\n s\n end", "def get_site_data(site_id)\n @conn.get(\"/api/v1/sites/#{site_id}\")\n end", "def get_sites_uri\n @get_sites_uri ||= \"#{base_uri}/2/users/me/sites\"\n end", "def get(uid)\n raise '`get` method by ID is not supported for this resource, use `get_by_phone`.'\n end", "def my_site\n return @my_site\n end", "def get_site_details(user_id, site_id)\n\trequest_type = \"GET\"\n\turl = \"user/#{user_id}/site/#{site_id}\"\n\thash = create_hmac(request_type, url)\n\tresponse = http_send(request_type, url, hash)\nend", "def get_site\n if current_subdomain\n get_site_from_subdomain\n else\n get_site_from_params\n end\n end", "def show\n @site_attribute = @site.site_attributes.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @site_attribute }\n end\n end", "def site_id\n return @site_id\n end", "def get_project_site\n @site = \"\"\n parent.managed_repository do\n @site = Voeis::Site.get(params[:id])\n end\n respond_to do |format|\n format_response(@site, format)\n end\n end", "def site\n @site ||= ::Shop.find_by_name(\"#{ request.env['HTTP_HOST'].split('.').first() }.myshopify.com\").api_url\n end", "def find(uid)\n response = get({:uid => uid}, false)\n xml = Nokogiri::XML(response).css(\"#{defaults[:resource_name]}\")\n new(xml.first)\n end", "def get_site(state_params)\n Site.find(state_params[\"site_id\"])\n end", "def site_id\n if @stepConfiguration.configurationParams[:properties][:siteID]\n @stepConfiguration.configurationParams[:properties][:siteID][:value]\n end\n end", "def first_site_id\n res = @conn.get('/api/v1/sites')\n res['sites'].first['id']\n end", "def get_users_data(_site_info)\n s_type = 'users'\n s = _site_info[s_type]\n return s\n end", "def site_id\n return @site_id\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /likes Mostra todos os likes
def index @likes = Like.all render json: @likes, status: 200 end
[ "def index\n @api_v1_likes = Api::V1::Like.all\n end", "def index\n @likes = Like.all\n render json: @likes\n end", "def index\n @user_likes = UserLike.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @user_likes }\n end\n end", "def likes options = {}\n perform_get_with_object(\"/users/#{get_id}/likes\", options, Vimeo::Entities::Video)\n end", "def get_user_likes\n @likes_hash ||= self.facebook.get_connections(\"me\", \"likes\", {limit: 500})\n @likes ||= []\n @likes_hash.each do |like|\n @likes << like[\"name\"]\n end\n @likes\n end", "def list_item_likes(item_id, params = nil, headers = nil)\n get(\"/api/v2/items/#{item_id}/likes\", params, headers)\n end", "def like\n @article = Article.find(params[:article_id])\n current_user.articles_loved.append(@article)\n # Article.find(6).likes.count()\n # render json: \"asd\"\n end", "def index\n\n user = User.find(current_user_id)\n\n render json: user.promptlikes\n end", "def likes\n authorize! :show, @content\n if params[:kind].present?\n @users = @content.voters_for(params[:kind]).reorder('voted_at ASC').page(params[:page]).per(20)\n else\n @users = @content.voters.reorder('voted_at ASC').page(params[:page]).per(20)\n end\n render 'likes', layout: false\n end", "def liked\n get '/users/self/media/liked', auth_params\n end", "def index\n @hitcher_likes = HitcherLike.all\n end", "def moment_likes(moment_id)\n get(\"/v1/moments/#{moment_id}/likes\")\n end", "def checkin_likes(id)\n get(\"checkins/#{id}/likes\").likes\n end", "def index\n @like_system_likes = LikeSystem::Like.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @like_system_likes }\n end\n end", "def object_likes(uid, options = {})\n fetch_all = options.delete(:fetch_all)\n\n params = { \n :owner_id => user.identifier,\n :count => 1000, \n :type => \"post\", \n :item_id => uid,\n :offset => 0\n }\n params.merge!(options)\n \n if fetch_all\n return fetch_all_method_items(\"likes.getList\", params)\n end\n\n\n user.likes.getList(params)\n end", "def likes\n @page.like_count\n end", "def index\n @c_likes = CLike.all\n if params[:comment_id].present?\n like = CLike.find_by(user_id: current_user.id, comment_id: params[:comment_id])\n render json: {status: 'success', like: like, counts: CLike.where(comment_id: params[:comment_id]).count, liked: like.present?}\n end\n end", "def list_liked\n TwList.get_or_create(\"#{@account.username} # liked\")\n end", "def index\n @question_likes = QuestionLike.all\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TODO: If no original_stock_location given, return a stock item according to some priority of the regular stock locations, instead of just the first one we find.
def stock_item(variant_id, user_id = nil, original_stock_location_id = nil) return super(variant_id) unless reserved_items? raise( UserRequiredArgumentError, Spree.t(:user_id_required_for_reserved_stock_location) ) unless user_id.present? items = stock_items.where(variant_id: variant_id, user_id: user_id) items = items.where( original_stock_location_id: original_stock_location_id ) unless original_stock_location_id.blank? items.order(:id).first end
[ "def stock_item(variant_id, sub_location=nil)\n # byebug\n stock_items.where(variant_id: variant_id, sub_location: sub_location).order(:id).first\n end", "def stock_location\n @stock_location ||= Spree::StockLocation.where(default: true).first\n end", "def stock_item(variant_id)\n stock_items.where(variant_id: variant_id).order(:id).first\n end", "def spree_stock_location\n Spree::StockLocation.find_by(default: true)\n end", "def first_available_sku\n in_stock? ? skus.active.in_stock.order(price: :asc).first : skus.active.order(price: :asc).first\n end", "def stock(item_id)\n stocks.find {|st| st.item_id === item_id }\n end", "def find_stock_location(location_code)\n stock_location = Spree::StockLocation.joins(:state).find_by(Spree::State.table_name => { abbr: location_code })\n if stock_location.nil?\n Spree::DmiEvent.create_error(\"Spree couldn't find a matching stock location for code: #{location_code}\")\n end\n stock_location\n end", "def load_item!(order_item, stock)\n if !order_item.product.tracked_stock? || source.enable_gateway?\n load_item_from_infinite_stock(order_item) && return\n end\n stock_items = stock.select { |item| item.product == order_item.product }\n return false if stock_items.none?\n\n if order_item.lot_code.present?\n load_item_by_lot_code(order_item, stock_items)\n else\n load_item_from_stock(order_item, stock_items)\n end\n end", "def min_price\n if @stocks.first.opening.nil?\n @stocks.map(&:closing).min\n else\n @stocks.map(&:opening).min\n end\n end", "def default_location\n @default_location ||= Spree::StockLocation.find_by_name('default')\n end", "def price_at(date)\n found_stock = @stocks.select { |stock| stock.date == date }.first\n return nil if found_stock.nil?\n found_stock.opening unless found_stock.opening.nil?\n found_stock.closing if found_stock.opening.nil?\n end", "def get_stock(stock_ticker)\n stock = StockQuote::Stock.quote(stock_ticker)\n return stock\nend", "def get_luxire_stock\n sku = params[:luxire_stock][:parent_sku]\n @luxire_stock = LuxireStock.where(parent_sku: sku).first\n end", "def best_supplier\n self.suppliers.joins(:stock_locations => :stock_items).\n where('spree_stock_items.variant_id = spree_supplier_variants.variant_id').\n where('spree_stock_items.count_on_hand > 0').\n order('spree_supplier_variants.cost').first\n end", "def load_item_by_lot_code(order_item, stock_items)\n item = stock_items.find { |item| order_item.lot_code == item.code }\n\n # If the order item has a serial number, try lot code part only.\n if item.nil? && order_item.lot_code['-']\n lot_code_part = order_item.lot_code.split('-').first\n item = stock_items.find { |item| lot_code_part == item.code }\n end\n\n # If a match was found, load the item and return. If a partial\n # match set a lot code part above, use that, or provide nil\n # to use the code on the order item.\n if item.present?\n item.reserved += order_item.amount\n return create_item_from(order_item, lot_code_part, item.expires_at)\n end\n\n false # Failed to load the item.\n end", "def stock_locations_with_available_stock_items(variant)\n stock_locations.select { |sl| sl.available?(variant) }\n end", "def get_stock(name)\n raise TypeError, \"wrong argument type #{name.class.name} for name (expected String)\" unless name.is_a?(String)\n\n Stock.find_by(name: name)\n end", "def stock_item_or_create(variant, sub_location=nil)\n stock_item(variant, sub_location) || stock_items.create(variant_id: variant.id, sub_location: sub_location)\n end", "def available(inventory, lot_code)\n return Float::INFINITY if inventory.nil? || !tracked_stock?\n return component_stock(inventory) if bundle?\n return [\n stock(inventory, lot_code),\n component_stock(inventory)\n ].min if composite? || package?\n stock(inventory, lot_code)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
provides the institution_id from the authentication block
def auth_inst_id auth[:institution_id] end
[ "def institution\n @institution ||= Institutions.institutions[institution_code.to_sym]\n end", "def institution\n unless institution_code.blank?\n @institution ||= Institutions.institutions[institution_code.to_sym]\n end\n end", "def institution_code\n (from_aleph?) ? aleph_item.institution : super\n end", "def institution\n ::HubEdos::StudentApi::V2::StudentRecord::Institution.new(@data['institution']) if @data['institution']\n end", "def institution_param_name\n 'institution'\n end", "def id_for(institution_or_id)\n return Institution.null.id if institution_or_id.nil?\n institution_or_id.try(:id) || institution_or_id\n end", "def provider_identity\n @provider_identity ||= raw_info[\"identities\"].find {|id| id[\"provider\"] == raw_info[\"provider\"]}\n end", "def institution_param\n if params[\"#{institution_param_key}\"].present?\n params[\"#{institution_param_key}\"].to_sym\n end\n end", "def primary_institution_from_ip\n Institutions.with_ip(request.remote_ip).first unless request.nil?\n end", "def current_primary_institution\n @current_primary_institution ||= case\n when (institution_param.present? && all_institutions[institution_param])\n all_institutions[institution_param]\n when primary_institution_from_ip.present?\n primary_institution_from_ip\n when (@current_user && current_user.primary_institution)\n current_user.primary_institution\n else\n Institutions.defaults.first\n end\n end", "def institution_from_ip\n unless request.nil?\n @institution_from_ip ||= begin\n institutions_from_ip = institutions.find_all { |code, institution| institution.includes_ip? request.remote_ip }\n if institutions_from_ip.present?\n # Get first matching institution and get the last element from\n # [:NYU, Institution] array, that is, the actual Institution object\n institutions_from_ip.first.last\n end\n end\n end\n end", "def institution\n @institution ||= Institution.find(self.institution_pid)\n rescue ActiveFedora::ObjectNotFoundError => e\n logger.warn \"#{self.institution_pid} is set as the institution for #{self}, but it doesn't exist\"\n @institution = NilInstitution.new\n end", "def primary_institution_from_ip\n unless request.nil?\n @primary_institution_from_ip ||=\n Institutions.with_ip(request.remote_ip).first\n end\n end", "def institution_param\n params[institution_param_name].upcase.to_sym if params[institution_param_name].present?\n end", "def institution_id=(new_institution_id)\n\t\tif organisation.nil? then\n\t\t\tself.organisation_id = new_institution_id\n\t\tend\n\tend", "def institution\n Settings.HARVESTER.INSTITUTION.name\n end", "def institution_param_name\n 'umlaut.institution'\n end", "def current_primary_institution\n @current_primary_institution ||=\n (institution_param.nil? or all_institutions[institution_param].nil?) ?\n ((primary_institution_from_ip.nil?) ?\n ((@current_user.nil? or current_user.primary_institution.nil?) ?\n Institutions.defaults.first :\n current_user.primary_institution) :\n primary_institution_from_ip) :\n all_institutions[institution_param]\n end", "def internal_id\n return @internal_id\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
provides the user_id from the authentication block
def auth_user_id auth[:user_id] end
[ "def user_id\n instance_variable_get(:@prepared_arguments).dig(:user_id)\n end", "def user_id\n return nil unless success?\n\n @user_id\n end", "def user_id\n return @user_id\n end", "def user_id()\n # @TODO: looks for a better way to get user id\n users = client.users.all()\n for user in users\n if user.email == HARVEST_EMAIL\n return user.id\n end\n end\n return -1\n end", "def user_id\n @user_id ||= self.user ? self.user.to_global_id : nil\n end", "def user_id_for(user)\n find(user.id, user.login)\n end", "def current_user_id\n return @current_user[:id]\n end", "def user_id\n username\n end", "def hubssolib_get_user_id\n user = self.hubssolib_current_user\n user ? user.user_id : nil\n end", "def current_user_id_for_oauth\n current_user.id.to_s\n end", "def current_user_id\n info['user']['id']\n end", "def get_user_id!(params)\n get_value_for_key(params, \"user_id\")\n end", "def user_id; config[:user_id]; end", "def current_user_id\n decoded = try_decode_token\n\n unless decoded && decoded[0] && decoded[0][\"user_id\"]\n return nil\n end\n return decoded[0][\"user_id\"]\n end", "def get_user_id!(params)\n get_value_for_key!(params, \"user_id\")\n end", "def lab_user_id\n plaintext_id = \"#{@view_options[:channel]}:#{user_or_session_id}\"\n Digest::SHA1.base64digest(storage_encrypt(plaintext_id)).tr('=', '')\n end", "def userid\n user_id\n end", "def authenticate_user\n return if user_id\n\n @user_id =\n cookies.signed.permanent[:user_id] =\n request.headers[\"HTTP_X_FINGERPRINT\"] || SecureRandom.hex\n end", "def current_user_id\n return cached_user_id if cached_user_id\n return user_id_from_cookie if user_id_from_cookie\n\n new_user_id = Lacmus.generate_user_id\n @uid_hash = build_tuid_cookie(new_user_id)\n @uid_hash[:value].split('|').first.to_i\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check existence of auth params
def auth_params_exist auth.key?(:user_id) && auth.key?(:api_key) end
[ "def valid_for_params_auth?; end", "def authentication_supplied?\n params[:email] && (params[:password] || (params[:oauth] && params[:oauth][:token]))\n end", "def valid_for_params_auth?\n params_authenticatable? && valid_params_request? &&\n valid_params? && with_authentication_hash(:params_auth, params_auth_hash)\n end", "def valid_params?\n params_auth_hash.is_a?(Hash)\n end", "def is_empty_params\n\t\tif user_params[:email].blank? || user_params[:password].blank?\n\t\t\treturn error_log errors:{unauthenticated:[\"Please Provide Proper Parameters\"]}\n\t\tend\n\tend", "def auth_provided?\n !username.nil? && !password.nil?\n end", "def is_auth_required?\n @auth_required\n end", "def check_auth!\n fail ArgumentError, 'Auth must be initialized' if @auth.nil?\n end", "def auth?\n !!opts[:auth]\n end", "def auth_present?\n request.env.fetch(\"HTTP_AUTHORIZATION\", \"\") && !!request.env.fetch(\"HTTP_AUTHORIZATION\", \"\").scan(/Bearer/).flatten.first\n end", "def auth_key_present?\n !!request.env.fetch(\"HTTP_AUTHORIZATION\", \"\").scan(/Bearer/).flatten.first\n end", "def user_params_set?\n return false if params[:user].nil?\n !params[:user][:username].blank? && !params[:user][:password].blank?\n end", "def valid_auth_request?\n @valid ||= auth_request.valid?(opts)\n end", "def has_required_authentication?\n !@api_key.nil?\n end", "def valid?\n (params.include?('warden_oauth_provider') && params['warden_oauth_provider'] == config.provider_name.to_s) ||\n params.include?('oauth_token') \n end", "def auth_info\n params[auth_param] || {}\n end", "def authorized?\n @auth ||= Rack::Auth::Basic::Request.new(request.env)\n @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == [\"uber\",\"password1\"]\n end", "def required_auth\n @required_auth ||= []\n end", "def allow_params_authentication!; end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns a hash of only the search parameters that apply to the specific model being queried
def model_search_params(model, params) cols = model.column_names params.reject { |k, _v| !cols.include?(k) } end
[ "def search_attributes\n read_inheritable_attribute(:search_attributes) || []\n end", "def search_attrs_params_hash\n @search_attrs_params_hash ||= if params[:search_attrs].nil? || params[:search_attrs] == '_use_defaults_'\n @runner.using_defaults = true\n { _use_defaults_: '_use_defaults_' }\n else\n params.require(:search_attrs).permit!.to_h.dup\n end\n end", "def aml_search_params\n {\n \"first_name\" => @user_extended_detail.first_name,\n \"last_name\" => @user_extended_detail.last_name,\n \"birthdate\" => @local_cipher_obj.decrypt(@user_extended_detail.birthdate).data[:plaintext],\n \"country\" => @local_cipher_obj.decrypt(@user_extended_detail.country).data[:plaintext]\n }\n end", "def get_params_to_search(context)\n if params[:saved_search].present?\n @saved_search = SavedSearch.find_by(id: params[:saved_search], context: context)\n end\n return params[:q] if params[:use_search_params].present?\n params[:q] = @saved_search.try(:search_params) || params[:q]\n end", "def model_params\n request.params[model.params_name]\n end", "def search_params\n # TODO Configurar acá la variable params\n params[:query_name]\n end", "def searchable_attributes\n _attrs.find_all do |name, data|\n next if data[:options][:singleton]\n next if data[:options][:serialize] == false\n !data[:options].include?(:searchable) ||\n data[:options][:searchable]\n end.to_h\n end", "def model_params\n model_params_name = \"#{model_key}_params\"\n respond_to?(model_params_name, true) ? send(model_params_name) : params[model_key]\n end", "def keyword_queries\n @keyword_queries ||=\n if @params[:search_field] == config.advanced_search.url_key\n keys = config.search_fields.keys.map(&:to_sym)\n @params.slice(*keys).select { |_, v| v.present? }\n else\n {}\n end\n end", "def searchable_attributes\n key_props = self.class.primary_key_attributes\n return key_props if key_searchable?(key_props)\n key_props = self.class.secondary_key_attributes\n return key_props if key_searchable?(key_props)\n key_props = self.class.alternate_key_attributes\n return key_props if key_searchable?(key_props)\n end", "def searchable_attributes\n self.attributes.delete_if{|k,v| (self.primary_key==k.to_s || self.foreign_keys.include?(k.to_s)) }\n end", "def search_attributes\n @search_attributes ||= search_attributes_config.hash_configuration\n end", "def attributes\n self.class.search_attributes.inject({}) do |attributes, search_attribute|\n attributes.update(search_attribute => send(search_attribute))\n end\n end", "def keyword_queries\n unless(@keyword_queries)\n @keyword_queries = {}\n\n return @keyword_queries unless @params[:search_field] == ::AdvancedController.blacklight_config.advanced_search[:url_key]\n \n config.search_fields.each do | key, field_def |\n if ! @params[ key.to_sym ].blank?\n @keyword_queries[ key ] = @params[ key.to_sym ]\n end\n end\n end\n return @keyword_queries\n end", "def convert_to_search_params(params)\n HashWithIndifferentAccess.new(params).rewrite(\n :brand_id => :search_brands_id_equals,\n :source => :source_equals\n )\n end", "def get_search_params_and_query_string\n if !params[:tire_model_id].blank?\n @tire_store.tire_model_id = params[:tire_model_id]\n @search_query = \"tire_model_id=#{params[:tire_model_id].to_i}\"\n else\n if !params[:auto_options_id].blank?\n option = AutoOption.find(params[:auto_options_id])\n @tire_store.tire_size_id = option.tire_size_id if option\n elsif !params[:width].blank? && !params[:ratio].blank? && !params[:wheeldiameter].blank?\n # check and make sure the size is valid\n ts = TireSize.find_by_sizestr(\"#{params[:width].to_i}/#{params[:ratio].to_i}R#{params[:wheeldiameter].to_i}\")\n @tire_store.tire_size_id = ts.id if ts\n end\n \n if @tire_store.tire_size_id\n @search_query = \"tire_size_id=#{@tire_store.tire_size_id}\"\n \n #Don't include the manufacturer filter unless we have a valid size search going\n if !params[:tire_manufacturer_id].blank?\n @tire_store.tire_manufacturer_id_filter = params[:tire_manufacturer_id]\n @search_query += \"&tire_manufacturer_id_filter=#{params[:tire_manufacturer_id].to_i}\"\n end\n end\n end\n end", "def solr_search_params(user_params = params || {})\n solr_parameters = {}\n solr_search_params_logic.each do |method_name|\n send(method_name, solr_parameters, user_params)\n end\n\n return solr_parameters\n end", "def build_search_filters(valid_keys)\n params.clone.symbolize_keys.select{|k,v| valid_keys.include?(k) and !v.blank?}.to_hash\n end", "def process_params\n return unless params[:search].present?\n\n params[:search] = params[:search].reduce(Hash.new) do |processed_params, (filter, value)|\n if %w(city_id county_id).include? filter\n processed_params.merge(\"#{filter}_eq\" => value)\n elsif value.is_a? Array\n processed_params.merge(filter => value.map { |v| v.empty? ? nil : v }.compact)\n else\n processed_params.merge(filter => value)\n end.with_indifferent_access\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
to install specific streams and profiles: $ dnf module install modulename:stream/profile $ dnf module install perl:5.24/minimal if unspecified, they will be defaulted (see [d] param in dnf module list output)
def install # ensure we start fresh (remove existing stream) uninstall unless [:absent, :purged].include?(@property_hash[:ensure]) args = @resource[:name].dup case @resource[:ensure] when true, false, Symbol # pass else args << ":#{@resource[:ensure]}" end args << "/#{@resource[:flavor]}" if @resource[:flavor] if @resource[:enable_only] == true enable(args) else begin execute([command(:dnf), 'module', 'install', '-d', '0', '-e', self.class.error_level, '-y', args]) rescue Puppet::ExecutionFailure => e # module has no default profile and no profile was requested, so just enable the stream # DNF versions prior to 4.2.8 do not need this workaround # see https://bugzilla.redhat.com/show_bug.cgi?id=1669527 if @resource[:flavor] == nil && e.message =~ /^(?:missing|broken) groups or modules: #{Regexp.quote(@resource[:name])}$/ enable(args) else raise end end end end
[ "def install\n args = @resource[:name]\n # ensure we start fresh (remove existing stream)\n uninstall unless [:absent, :purged].include?(@property_hash[:ensure])\n case @resource[:ensure]\n when true, false, Symbol\n # pass\n else\n args << \":#{@resource[:ensure]}\"\n end\n if @resource[:flavor]\n args << \"/#{@resource[:flavor]}\"\n end\n execute([command(:dnf), 'module', 'install', '-d', '0', '-e', self.class.error_level, '-y', args])\n end", "def install!\n include_recipe 'apt'\n enable_i386_arch!\n add_repository!\n package('skype') { action :install }\n end", "def install!\n include_recipe 'freebsd::portsnap'\n package 'vlc' do\n version new_resource.version\n action :install\n end\n end", "def puppet_install(opts = {})\n # Grab facts from node\n facts = system_node.facts\n\n # Remove annoying mesg n from profile, otherwise on Debian we get:\n # stdin: is not a tty which messes with our tests later on.\n if facts['osfamily'] == 'Debian'\n log.info(\"Remove 'mesg n' from profile to stop noise\")\n system_run(\"sed -i 's/^mesg n/# mesg n/' /root/.profile\")\n end\n\n # Grab PL repository and install PL copy of puppet\n log.info \"Starting installation of puppet from PL repos\"\n if facts['osfamily'] == 'RedHat'\n if facts['operatingsystem'] == 'Fedora'\n # Fedora testing is probably the best for now\n system_run('sed -i \"0,/RE/s/enabled=0/enabled=1/\" /etc/yum.repos.d/fedora-updates-testing.repo')\n else\n if facts['operatingsystemrelease'] =~ /^6\\./\n system_run('rpm -ivh http://yum.puppetlabs.com/el/6/products/x86_64/puppetlabs-release-6-6.noarch.rpm')\n else\n system_run('rpm -ivh http://yum.puppetlabs.com/el/5/products/x86_64/puppetlabs-release-5-6.noarch.rpm')\n end\n end\n system_run('yum install -y puppet')\n elsif facts['osfamily'] == 'Debian'\n system_run(\"wget http://apt.puppetlabs.com/puppetlabs-release-#{facts['lsbdistcodename']}.deb\")\n system_run(\"dpkg -i puppetlabs-release-#{facts['lsbdistcodename']}.deb\")\n system_run('apt-get update')\n system_run('apt-get install -y puppet')\n end\n\n # Prep modules dir\n log.info(\"Preparing modules dir\")\n system_run('mkdir -p /etc/puppet/modules')\n\n # Create alias for puppet\n pp = <<-EOS\nhost { 'puppet':\n ip => '127.0.0.1',\n}\n EOS\n puppet_apply(pp)\n\n # Create hiera.yaml\n file = Tempfile.new('hierayaml')\n begin\n file.write(<<-EOS)\n---\n:logger: noop\n EOS\n file.close\n system_rcp(:sp => file.path, :dp => '/etc/puppet/hiera.yaml')\n ensure\n file.unlink\n end\n end", "def instal\n bin.install openrtp\n end", "def puppet_module_install opts = {}\n hosts.each do |host|\n scp_to host, opts[:source], File.join(host['distmoduledir'], opts[:module_name])\n end\n end", "def install!\n include_recipe 'apt'\n package 'vlc' do\n version new_resource.version\n action :install\n end\n end", "def install_in_ubuntu\n install_ppa(node['SignalFx_ppa']['collectd']['name'],\n node['SignalFx_ppa']['collectd']['uri'])\n install_ppa(node['SignalFx_ppa']['collectd_plugin']['name'],\n node['SignalFx_ppa']['collectd_plugin']['uri'])\n ubuntu_update\n install_package 'collectd'\nend", "def install_management\n # Needed to play with the configuration database.\n package 'debconf'\n package 'debconf-utils'\n\n # Keys for Debian packages.\n package 'debian-archive-keyring'\n\n # Fetch files via HTTP.\n package 'curl'\n package 'wget'\n\n package 'dpkg-dev' # Builds packages from source.\n package 'openssh-server' # SSH into the box.\n\n # For gems with native extensions.\n package 'build-essential'\n package 'g++'\n\n # Pull code from version control.\n package 'subversion'\n package 'git-core'\n\n package 'avahi-daemon' # mDNS, a.k.a. Bonjour\n package 'ddclient' # dynamic DNS\n end", "def install\n args = %W[\n --prefix=#{prefix}\n --enable-shared\n --enable-hardcoded-tables\n --cc=#{ENV.cc}\n --host-cflags=#{ENV.cflags}\n --host-ldflags=#{ENV.ldflags}\n --enable-version3\n --enable-libaom\n --enable-libopus\n --enable-libtheora\n --enable-libvorbis\n --enable-libvpx\n --enable-libxvid\n --disable-sdl2\n --disable-lzma\n --disable-libjack\n --disable-indev=jack\n --disable-filters\n --enable-filter=delogo\n --enable-filter=scale\n --enable-filter=aresample \n ]\n\n if OS.mac?\n args << \"--enable-opencl\"\n args << \"--enable-videotoolbox\"\n end\n\n args << \"--disable-htmlpages\" # doubtful anyone will look at this. The same info is accessible through the man pages.\n args << \"--enable-gpl\" if build.with? \"gpl\"\n args << \"--enable-libass\" if build.with? \"libass\"\n args << \"--enable-libcaca\" if build.with? \"libcaca\"\n args << \"--enable-libfdk-aac\" if build.with? \"fdk-aac\"\n args << \"--enable-libgsm\" if build.with? \"libgsm\"\n args << \"--enable-libmodplug\" if build.with? \"libmodplug\"\n args << \"--enable-libopenh264\" if build.with? \"openh264\"\n args << \"--enable-librsvg\" if build.with? \"librsvg\"\n args << \"--enable-librtmp\" if build.with? \"rtmp\"\n args << \"--enable-librubberband\" if build.with? \"rubberband\"\n args << \"--enable-libtesseract\" if build.with? \"tesseract\"\n args << \"--enable-libtwolame\" if build.with? \"two-lame\"\n args << \"--enable-libvidstab\" if build.with? \"libvidstab\"\n args << \"--enable-libwavpack\" if build.with? \"wavpack\"\n args << \"--enable-frei0r\" if build.with? \"frei0r\"\n args << \"--enable-libx264\" if build.with? \"x264\"\n args << \"--enable-libfontconfig\" if build.with? \"subtitle\"\n args << \"--enable-libfreetype\" if build.with? \"subtitle\"\n args << \"--disable-securetransport\" if build.with? \"disable-securetransport\"\n\n if build.with? \"openjpeg\"\n args << \"--enable-libopenjpeg\"\n args << \"--disable-decoder=jpeg2000\"\n args << \"--extra-cflags=\" + `pkg-config --cflags libopenjp2`.chomp\n end\n\n # These librares are GPL-incompatible, and require ffmpeg be built with\n # the \"--enable-nonfree\" flag, which produces unredistributable libraries\n args << \"--enable-nonfree\" if build.with?(\"fdk-aac\") || build.with?(\"openssl\")\n\n system \"./configure\", *args\n system \"make\", \"install\"\n\n # Build and install additional FFmpeg tools\n system \"make\", \"alltools\"\n bin.install Dir[\"tools/*\"].select { |f| File.executable? f }\n end", "def setUpstreamChannelModulationProfile(ch,profile)\n result = self.turnDownChannel(ch)\n @base.cmd(\"conf t\") { |c| result += c }\n @base.cmd(\"int ca1/0\") { |c| result += c }\n @base.cmd(\"cable upstream #{ch}.0 modulation-profile #{profile}\") { |c| result += c }\n @base.cmd(\"end\") { |c| result += c }\n result += self.turnUpChannel(ch)\n result\n end", "def install_in_redhat(os, version)\n install_repo_rpms(os, version)\n install_package 'collectd'\n install_package 'collectd-disk'\nend", "def install_gem; end", "def dev(name, *args)\n mod \"puppet-#{name}\", :path => \"#{ENV['HOME']}/src/puppet/modules/#{name}\"\nend", "def install\n (share+\"njs-nginx-module\").install Dir[\"*\"]\n end", "def install\n args = %w{install -q}\n if @resource[:source]\n args << \"-e\"\n if String === @resource[:ensure]\n args << \"#{@resource[:source]}@#{@resource[:ensure]}#egg=#{\n @resource[:name]}\"\n else\n args << \"#{@resource[:source]}#egg=#{@resource[:name]}\"\n end\n else\n case @resource[:ensure]\n when String\n args << \"#{@resource[:name]}==#{@resource[:ensure]}\"\n when :latest\n args << \"--upgrade\" << @resource[:name]\n else\n args << @resource[:name]\n end\n end\n lazy_pip *args\n end", "def install\r\n manifest.each do |entry|\r\n send(\"install_#{entry.type}\", entry.from, entry.to, entry.options)\r\n end\r\n end", "def install_command\n command = \"Install-Module #{@resource[:name]} -Scope AllUsers -Force\"\n command << \" -RequiredVersion #{@resource[:ensure]}\" unless [:present, :latest].include? @resource[:ensure]\n command << \" -Repository #{@resource[:source]}\" if @resource[:source]\n command << \" #{install_options(@resource[:install_options])}\" if @resource[:install_options]\n command\n end", "def install!\n each_module do |repo|\n\n print_verbose \"\\n##### processing module #{repo[:name]}...\"\n\n module_dir = File.join(module_path, repo[:name])\n\n unless File.exists?(module_dir)\n case\n when repo[:git]\n install_git module_path, repo[:name], repo[:git], repo[:ref]\n when repo[:archive]\n install_archive module_path, repo[:name], repo[:archive]\n else\n abort('only the :git and :archive provider are currently supported')\n end\n else\n print_verbose \"\\nModule #{repo[:name]} already installed in #{module_path}\"\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Configure knapsack report Setup variables Fetch latest report
def configure! ENV["KNAPSACK_TEST_FILE_PATTERN"] ||= "qa/specs/features/**/*_spec.rb" ENV["KNAPSACK_REPORT_PATH"] = report_path Knapsack.logger = QA::Runtime::Logger.logger download_report end
[ "def buyflow(testrun)\n # Pull this test runs test suite from model query\n suite = TestSuites.find(testrun['test_suites_id'])\n\n # Get the campaign data for the test run requested\n campaign_data = GRDatabase.get_campaign_data(testrun['Brand'], testrun['expectedcampaign'], testrun['Env'], testrun['DriverPlatform'], testrun['realm']).entries[0]\n\n # break the data into a Hash Object that the Campaign_Configuration variable needs for testing\n campaign_data = campaign_data.attributes\nconf_email_to_use = ''\n # Add platform as a part of the campaign Hash object\n campaign_data.merge!({'platform' => testrun['Driver']})\n if(!suite.email_random)\n if(suite.emailnotification.include?(';'))\n conf_email_to_use = suite.emailnotification.split(';')[0].strip() \n else\n conf_email_to_use = suite.emailnotification\n end\n else\n conf_email_to_use = Time.now.to_i.to_s + \".9e08e713@mailosaur.in\"\n end\n\n \n campaign_data.merge!({'ConfEmailOverride' => conf_email_to_use})\n\n # vvv OBSOLETECODE vvv\n # offers = GRDatabase.get_offer_data(user_brand, user_campaign, platform)\n\n # Check for the existance of a expected offercode\n if !testrun['ExpectedOffercode'].strip.empty?\n\n # pull it from the test run if it exists\n offer_code = testrun['ExpectedOffercode']\n else\n\n # use the default value if present, if not the offercode will be nil\n offer_code = campaign_data[\"default_offercode\"]\n end\n\n # Create a new test object which can be filled with test run data\n test_obj = GRTesting::BuyflowTest.new(title: testrun['test name'], browser: testrun['Driver'], configuration: campaign_data, offer_code: offer_code, id: testrun['id'])\n \n # Store the author of the test run \n # @todo - use the given Ran_By\n # I don't even think this code is needed anymore, but I don't want to remove it for risk of breaking something. Will investigate if time, but for now its not hurting anything.\n test_obj.report.author = \"Automation\"\n \n # The environment the test run is being run in\n test_obj.report.environment = testrun['Env']\n \n # The url that the test run is being run against\n test_obj.report.url = URLFactory.generate_url(brand: campaign_data['Brand'], server: testrun['Env'], campaign: campaign_data['grcid'], test: (campaign_data['testenabled'] == 1)) if(testrun['url'].empty?)\n \n # Print out the url to be tested from URL factory\n test_obj.report.uci_report.expected_uci = campaign_data['UCI']\n Rails.logger.info \"Url from URLFactory: #{test_obj.report.url}\"\n \n # override of url (for realm 2 fix) from campaign configuration\n if(test_obj.report.environment == \"prod\")\n test_obj.report.url = campaign_data[\"produrl\"] if(!campaign_data[\"produrl\"].empty?)\n Rails.logger.info \"OVERRIDE - Url from Campaign Configuration: #{test_obj.report.url}\"\n else\n test_obj.report.url = campaign_data[\"qaurl\"] if(!campaign_data[\"qaurl\"].empty?)\n Rails.logger.info \"OVERRIDE - Url from Campaign Configuration: #{test_obj.report.url}\"\n end\n \n # Override url if testrun has a different url\n test_obj.report.url = testrun['url'] if !testrun['url'].strip.empty?\n if(!test_obj.report.url.include?(\"http\"))\n test_obj.report.url = \"http://#{test_obj.report.url}\"\n end\n #ssankara - adding to append mmcore.gm=2 for maxymiser test urls on Realm 2 (7 lines) \n if(campaign_data[\"testenabled\"] == 1 && !test_obj.report.url.include?(\"mmcore\"))\n if(test_obj.report.url.include?(\"?\"))\n test_obj.report.url = \"#{test_obj.report.url}&mmcore.gm=2\"\n else\n test_obj.report.url = \"#{test_obj.report.url}/?mmcore.gm=2\"\n end\n end\n Rails.logger.info \"OVERRIDE Url from Test Run configuration: #{test_obj.report.url}\"\n\n test_obj.report.suite_id = testrun['test_suites_id']\n test_obj.report.buyflow_report.expected_offer_code = offer_code\n suite['Status'] = 'Running'\n suite.save! # \n \n # runs the test in Grotto\n test_obj.run() \n\n # Records test report to database\n test_obj.report.upload \n\n # updates suite record in database\n update_suite(suite) \n\n end", "def report_base_path\n @report_base_path ||= \"knapsack\"\n end", "def generate_ranking_report2\n @batch = @subject.batch\n @students ||= @batch.students\n @exam_groups ||= @batch.result_published\n end", "def build_report\n end", "def planning_report_download\n profile = []\n profile.push(\"CPU #{@sb[:planning][:rpt].extras[:vm_profile][:cpu]}\") if @sb[:planning][:rpt].extras[:vm_profile][:cpu]\n profile.push(\"RAM #{@sb[:planning][:rpt].extras[:vm_profile][:memory]}\") if @sb[:planning][:rpt].extras[:vm_profile][:memory]\n profile.push(\"Disk #{@sb[:planning][:rpt].extras[:vm_profile][:storage]}\") if @sb[:planning][:rpt].extras[:vm_profile][:storage]\n @sb[:planning][:rpt].title = _(\"Counts of VMs (%{profile})\") % {:profile => profile.join(\", \")}\n filename = \"VM Counts per #{ui_lookup(:model => @sb[:planning][:options][:target_typ])}\"\n disable_client_cache\n case params[:typ]\n when \"txt\"\n send_data(@sb[:planning][:rpt].to_text,\n :filename => \"#{filename}.txt\")\n when \"csv\"\n send_data(@sb[:planning][:rpt].to_csv,\n :filename => \"#{filename}.csv\")\n when \"pdf\"\n render_pdf(@sb[:planning][:rpt])\n end\n end", "def set_budget\n self.budget = self.package.price + self.affiliate_fee\n self.freelancer_fee = self.package.freelancer_fee\n end", "def create_config_cups kit, number_of_compartments, cup_layouts\n cup_count = 0\n cup_layouts.each_with_index do |cup_layout,index|\n cup_layout = cup_layout.sort { |a,b| a[1] <=> b[1] }\n cup = Array.new\n cup_layout.each { |cl| cup << cl.at(1) }\n cup.uniq!\n record_to_sort = Array.new\n cup.each { |record|\n record_to_sort << cup_layout.select { |data| data[1] == record }\n }\n cup_layout = Array.new\n record_to_sort.each { |rec|\n record = rec.sort! { |a,b| a[0] <=> b[0] }\n record.each { |new_rec| cup_layout << new_rec }\n }\n number_of_compartments = cup_layout.count\n index = index + 1\n\n for i in 0..number_of_compartments-1\n cup_id = kit.cups.create(:commit_status => false,:cup_dimension => cup_layout[i].join(','),:cup_number => cup_count + i+1, :status => 1)\n cup_id.update_attribute(\"cup_dimension\",cup_id.cup_dimension+\",#{index}\"+\",#{cup_id.id}\")\n end\n cup_count = cup_count + (i + 1)\n end\n cup_count =0\n end", "def build_packages(xml, weight)\n @loop_times = (weight / 100).to_i + 1\n @weight_breakdown = (weight.to_f / @loop_times.to_f).round(2)\n\n @loop_times.times do |i|\n xml.Package do\n xml.PackagingType do\n xml.Code '02'\n xml.Description 'Package' + i.to_s\n end\n xml.Description 'Rate Shopping'\n xml.PackageWeight do\n xml.Weight @weight_breakdown\n xml.UnitOfMeasurement do\n xml.Code \"LBS\"\n end\n# <PackageServiceOptions>\n# <InsuredValue>\n# <CurrencyCode>USD</CurrencyCode>\n# <MonetaryValue>$insured_value</MonetaryValue>\n# </InsuredValue>\n# </PackageServiceOptions>\n end\n end\n end\n end", "def index\n @appfigures = self.appfigures\n @chartboost = self.chartboost\n #@money_spent = 0\n \n \n # @chartboost.sort_by {|day| day['Date']}.each do |key|\n # selected_date = key['Date'].to_s\n # money_spent = key['Money Spent'].scan(/[.0-9]/).join().to_f\n # money_earned = key['Money Earned'].scan(/[.0-9]/).join().to_f\n \n # profit = @appfigures[selected_date]['revenue'].to_f + money_earned - money_spent\n # profit = profit.to_s\n \n # p key['Date'] + ' Revenue: $' + @appfigures[selected_date]['revenue'] + ' Spent: '+ key['Money Spent'] + ' CB Rev: '+ key['Money Earned'] + ' Profit: $' + profit\n #end\n \n @appfigures.sort.each do |date, value|\n puts value['date'] + value['revenue']\n puts @chartboost[2]['Money Spent']\n end\n\n end", "def init_config\n\t \t@use_caching = Bibmix::get_config('request_caching', true)\n\t \t# CCSB shows relevance numbers next to search results, only try to integrate results\n \t\t# with a higher relevance than stated below.\n \t\t@request_relevance_threshold = Bibmix::get_config('ccsb_request_relevance_threshold', 50)\n\t \tend", "def market_offers_max; CONFIG['market.offers.max']; end", "def after_build_report\n end", "def NBC_936_2010_RuleSet( ruleType, elements, locale_HDD, cityName )\n\n\n # System data...\n primHeatFuelName = getPrimaryHeatSys( elements )\n secSysType = getSecondaryHeatSys( elements )\n primDHWFuelName = getPrimaryDHWSys( elements )\n\n # Basement, slab, or both in model file?\n # Decide which to use for compliance based on count!\n # ADW May 17 2018: Basements are modified through Opt-H2KFoundation, slabs and crawlspaces through Opt-H2KFoundationSlabCrawl\n # Determine if a crawlspace is present, and if it is, if the crawlspace is heated\n numOfCrawl = 0\n isCrawlHeated = false\n if elements[\"HouseFile/House/Components/Crawlspace\"] != nil\n numOfCrawl += 1\n if elements[\"HouseFile/House/Temperatures/Crawlspace\"].attributes[\"heated\"] =~ /true/\n isCrawlHeated = true\n end\n end\n\n # Choices that do NOT depend on ruleType!\n\n $ruleSetChoices[\"Opt-ACH\"] = \"ACH_NBC\"\n $ruleSetChoices[\"Opt-Baseloads\"] = \"NBC-Baseloads\"\n $ruleSetChoices[\"Opt-ResultHouseCode\"] = \"General\"\n $ruleSetChoices[\"Opt-Temperatures\"] = \"NBC_Temps\"\n if ($PermafrostHash[cityName] == \"continuous\")\n $ruleSetChoices[\"Opt-Specifications\"] = \"NBC_Specs_Perma\"\n else\n $ruleSetChoices[\"Opt-Specifications\"] = \"NBC_Specs_Normal\"\n end\n\n # Heating Equipment performance requirements (Table 9.36.3.10) - No dependency on ruleType!\n if (primHeatFuelName =~ /gas/) != nil # value is \"Natural gas\"\n $ruleSetChoices[\"Opt-HVACSystem\"] = \"NBC-gas-furnace\"\n elsif (primHeatFuelName =~ /Oil/) != nil # value is Oil\n $ruleSetChoices[\"Opt-HVACSystem\"] = \"NBC-oil-heat\"\n elsif (primHeatFuelName =~ /Elect/) != nil # value is \"Electricity\n if secSysType =~ /AirHeatPump/ # TODO: Should we also include WSHP & GSHP in this check?\n $ruleSetChoices[\"Opt-HVACSystem\"] = \"NBC-CCASHP\"\n else\n $ruleSetChoices[\"Opt-HVACSystem\"] = \"NBC-elec-heat\"\n end\n end\n\n # DHW Equipment performance requirements (Table 9.36.4.2)\n if (primDHWFuelName =~ /gas/) != nil\n $ruleSetChoices[\"Opt-DHWSystem\"] = \"NBC-HotWater_gas\"\n elsif (primDHWFuelName =~ /Elect/) != nil\n $ruleSetChoices[\"Opt-DHWSystem\"] = \"NBC-HotWater_elec\"\n elsif (primDHWFuelName =~ /Oil/) != nil\n $ruleSetChoices[\"Opt-DHWSystem\"] = \"NBC-HotWater_oil\"\n end\n\n # Thermal zones and HDD by rule type\n #-------------------------------------------------------------------------\n if ruleType =~ /NBC9_36_noHRV/\n\n # Implement reference ventilation system (HRV with 0% recovery efficiency)\n $ruleSetChoices[\"Opt-HRVonly\"] = \"NBC_noHRV\"\n\n # Zone 4 ( HDD < 3000) without an HRV\n if locale_HDD < 3000\n # Effective thermal resistance of above-ground opaque assemblies (Table 9.36.2.6 A&B)\n $ruleSetChoices[\"Opt-GenericWall_1Layer_definitions\"] = \"NBC_Wall_zone4\"\n $ruleSetChoices[\"Opt-AtticCeilings\"] = \"NBC_Ceiling_zone4\"\n $ruleSetChoices[\"Opt-CathCeilings\"] = \"NBC_FlatCeiling_zone4\"\n $ruleSetChoices[\"Opt-FlatCeilings\"] = \"NBC_FlatCeiling_zone4\"\n\n $ruleSetChoices[\"Opt-ExposedFloor\"] = \"NBC_exposed_zone4\"\n\n # Effective thermal resistance of fenestration (Table 9.36.2.7.(1))\n $ruleSetChoices[\"Opt-CasementWindows\"] = \"NBC-zone4-window\"\n $ruleSetChoices[\"Opt-Doors\"] = \"NBC-zone4-door\"\n $ruleSetChoices[\"Opt-DoorWindows\"] = \"NBC-zone4-Doorwindow\"\n\n # Effective thermal resistance of assemblies below-grade or in contact with the ground (Table 9.36.2.8.A&B)\n $ruleSetChoices[\"Opt-H2KFoundation\"] = \"NBC_BCIN_zone4\"\n if isCrawlHeated\n $ruleSetChoices[\"Opt-H2KFoundationSlabCrawl\"] = \"NBC_SCB_zone4\"\n else # There is a crawlspace, but it isn't heated. Treat floor above crawlspace as exposed floor\n $ruleSetChoices[\"Opt-H2KFoundationSlabCrawl\"] = \"NBC_SOnly_zone4\" # If there are any slabs, insulate them\n $ruleSetChoices[\"Opt-FloorAboveCrawl\"] = \"NBC_crawlceiling_zone4\"\n end\n\n # Zone 5 ( 3000 < HDD < 3999) without an HRV\n elsif locale_HDD >= 3000 && locale_HDD < 3999\n # Effective thermal resistance of above-ground opaque assemblies (Table 9.36.2.6 A&B)\n $ruleSetChoices[\"Opt-GenericWall_1Layer_definitions\"] = \"NBC_Wall_zone5_noHRV\"\n $ruleSetChoices[\"Opt-FloorHeader\"] = \"NBC_Wall_zone5_noHRV\"\n $ruleSetChoices[\"Opt-AtticCeilings\"] = \"NBC_Ceiling_zone5_noHRV\"\n $ruleSetChoices[\"Opt-CathCeilings\"] = \"NBC_FlatCeiling_zone5\"\n $ruleSetChoices[\"Opt-FlatCeilings\"] = \"NBC_FlatCeiling_zone5\"\n\n $ruleSetChoices[\"Opt-ExposedFloor\"] = \"NBC_exposed_zone5\"\n\n # Effective thermal resistance of fenestration (Table 9.36.2.7.(1))\n $ruleSetChoices[\"Opt-CasementWindows\"] = \"NBC-zone5-window\"\n $ruleSetChoices[\"Opt-Doors\"] = \"NBC-zone5-door\"\n $ruleSetChoices[\"Opt-DoorWindows\"] = \"NBC-zone5-Doorwindow\"\n\n # Effective thermal resistance of assemblies below-grade or in contact with the ground (Table 9.36.2.8.A&B)\n $ruleSetChoices[\"Opt-H2KFoundation\"] = \"NBC_BCIN_zone5_noHRV\"\n if isCrawlHeated\n $ruleSetChoices[\"Opt-H2KFoundationSlabCrawl\"] = \"NBC_SCB_zone5_noHRV\"\n else # There is a crawlspace, but it isn't heated. Treat floor above crawlspace as exposed floor\n $ruleSetChoices[\"Opt-H2KFoundationSlabCrawl\"] = \"NBC_SOnly_zone5\" # If there are any slabs, insulate them\n $ruleSetChoices[\"Opt-FloorAboveCrawl\"] = \"NBC_crawlceiling_zone5\"\n end\n\n # Zone 6 ( 4000 < HDD < 4999) without an HRV\n elsif locale_HDD >= 4000 && locale_HDD < 4999\n # Effective thermal resistance of above-ground opaque assemblies (Table 9.36.2.6 A&B)\n $ruleSetChoices[\"Opt-GenericWall_1Layer_definitions\"] = \"NBC_Wall_zone6_noHRV\"\n $ruleSetChoices[\"Opt-FloorHeader\"] = \"NBC_Wall_zone6_noHRV\"\n $ruleSetChoices[\"Opt-AtticCeilings\"] = \"NBC_Ceiling_zone6\"\n $ruleSetChoices[\"Opt-CathCeilings\"] = \"NBC_FlatCeiling_zone6\"\n $ruleSetChoices[\"Opt-FlatCeilings\"] = \"NBC_FlatCeiling_zone6\"\n\n $ruleSetChoices[\"Opt-ExposedFloor\"] = \"NBC_exposed_zone6\"\n\n # Effective thermal resistance of fenestration (Table 9.36.2.7.(1))\n $ruleSetChoices[\"Opt-CasementWindows\"] = \"NBC-zone6-window\"\n $ruleSetChoices[\"Opt-Doors\"] = \"NBC-zone6-door\"\n $ruleSetChoices[\"Opt-DoorWindows\"] = \"NBC-zone6-Doorwindow\"\n\n # Effective thermal resistance of assemblies below-grade or in contact with the ground (Table 9.36.2.8.A&B)\n $ruleSetChoices[\"Opt-H2KFoundation\"] = \"NBC_BCIN_zone6_noHRV\"\n if isCrawlHeated\n $ruleSetChoices[\"Opt-H2KFoundationSlabCrawl\"] = \"NBC_SCB_zone6_noHRV\"\n else # There is a crawlspace, but it isn't heated. Treat floor above crawlspace as exposed floor\n $ruleSetChoices[\"Opt-H2KFoundationSlabCrawl\"] = \"NBC_SOnly_zone6\" # If there are any slabs, insulate them\n $ruleSetChoices[\"Opt-FloorAboveCrawl\"] = \"NBC_crawlceiling_zone6\"\n end\n\n # Zone 7A ( 5000 < HDD < 5999) without an HRV\n elsif locale_HDD >= 5000 && locale_HDD < 5999\n # Effective thermal resistance of above-ground opaque assemblies (Table 9.36.2.6 A&B)\n $ruleSetChoices[\"Opt-GenericWall_1Layer_definitions\"] = \"NBC_Wall_zone7A_noHRV\"\n $ruleSetChoices[\"Opt-FloorHeader\"] = \"NBC_Wall_zone7A_noHRV\"\n $ruleSetChoices[\"Opt-AtticCeilings\"] = \"NBC_Ceiling_zone7A_noHRV\"\n $ruleSetChoices[\"Opt-CathCeilings\"] = \"NBC_FlatCeiling_zone7A\"\n $ruleSetChoices[\"Opt-FlatCeilings\"] = \"NBC_FlatCeiling_zone7A\"\n\n $ruleSetChoices[\"Opt-ExposedFloor\"] = \"NBC_exposed_zone7A\"\n\n # Effective thermal resistance of fenestration (Table 9.36.2.7.(1))\n $ruleSetChoices[\"Opt-CasementWindows\"] = \"NBC-zone7A-window\"\n $ruleSetChoices[\"Opt-Doors\"] = \"NBC-zone7A-door\"\n $ruleSetChoices[\"Opt-DoorWindows\"] = \"NBC-zone7A-Doorwindow\"\n # Effective thermal resistance of assemblies below-grade or in contact with the ground (Table 9.36.2.8.A&B)\n $ruleSetChoices[\"Opt-H2KFoundation\"] = \"NBC_BCIN_zone7A_noHRV\"\n if isCrawlHeated\n $ruleSetChoices[\"Opt-H2KFoundationSlabCrawl\"] = \"NBC_SCB_zone7A_noHRV\"\n else # There is a crawlspace, but it isn't heated. Treat floor above crawlspace as exposed floor\n $ruleSetChoices[\"Opt-H2KFoundationSlabCrawl\"] = \"NBC_SOnly_zone7A_noHRV\" # If there are any slabs, insulate them\n $ruleSetChoices[\"Opt-FloorAboveCrawl\"] = \"NBC_crawlceiling_zone7A\"\n end\n\n # Zone 7B ( 6000 < HDD < 6999) without an HRV\n elsif locale_HDD >= 6000 && locale_HDD < 6999\n # Effective thermal resistance of above-ground opaque assemblies (Table 9.36.2.6 A&B)\n $ruleSetChoices[\"Opt-GenericWall_1Layer_definitions\"] = \"NBC_Wall_zone7B_noHRV\"\n $ruleSetChoices[\"Opt-FloorHeader\"] = \"NBC_Wall_zone7B_noHRV\"\n $ruleSetChoices[\"Opt-AtticCeilings\"] = \"NBC_Ceiling_zone7B\"\n $ruleSetChoices[\"Opt-CathCeilings\"] = \"NBC_FlatCeiling_zone7B\"\n $ruleSetChoices[\"Opt-FlatCeilings\"] = \"NBC_FlatCeiling_zone7B\"\n\n $ruleSetChoices[\"Opt-ExposedFloor\"] = \"NBC_exposed_zone7B\"\n\n # Effective thermal resistance of fenestration (Table 9.36.2.7.(1))\n $ruleSetChoices[\"Opt-CasementWindows\"] = \"NBC-zone7B-window\"\n $ruleSetChoices[\"Opt-Doors\"] = \"NBC-zone7B-door\"\n $ruleSetChoices[\"Opt-DoorWindows\"] = \"NBC-zone7B-Doorwindow\"\n\n # Effective thermal resistance of assemblies below-grade or in contact with the ground (Table 9.36.2.8.A&B)\n $ruleSetChoices[\"Opt-H2KFoundation\"] = \"NBC_BCIN_zone7B_noHRV\"\n if isCrawlHeated\n $ruleSetChoices[\"Opt-H2KFoundationSlabCrawl\"] = \"NBC_SCB_zone7B_noHRV\"\n else # There is a crawlspace, but it isn't heated. Treat floor above crawlspace as exposed floor\n $ruleSetChoices[\"Opt-H2KFoundationSlabCrawl\"] = \"NBC_SOnly_zone7B_noHRV\" # If there are any slabs, insulate them\n $ruleSetChoices[\"Opt-FloorAboveCrawl\"] = \"NBC_crawlceiling_zone7B\"\n end\n\n # Zone 8 (HDD <= 7000) without an HRV\n elsif locale_HDD >= 7000\n # Effective thermal resistance of above-ground opaque assemblies (Table 9.36.2.6 A&B)\n $ruleSetChoices[\"Opt-GenericWall_1Layer_definitions\"] = \"NBC_Wall_zone8_noHRV\"\n $ruleSetChoices[\"Opt-FloorHeader\"] = \"NBC_Wall_zone8_noHRV\"\n $ruleSetChoices[\"Opt-AtticCeilings\"] = \"NBC_Ceiling_zone8\"\n $ruleSetChoices[\"Opt-CathCeilings\"] = \"NBC_FlatCeiling_zone8\"\n $ruleSetChoices[\"Opt-FlatCeilings\"] = \"NBC_FlatCeiling_zone8\"\n\n $ruleSetChoices[\"Opt-ExposedFloor\"] = \"NBC_exposed_zone8\"\n\n # Effective thermal resistance of fenestration (Table 9.36.2.7.(1))\n $ruleSetChoices[\"Opt-CasementWindows\"] = \"NBC-zone8-window\"\n $ruleSetChoices[\"Opt-Doors\"] = \"NBC-zone8-door\"\n $ruleSetChoices[\"Opt-DoorWindows\"] = \"NBC-zone8-Doorwindow\"\n\n # Effective thermal resistance of assemblies below-grade or in contact with the ground (Table 9.36.2.8.A&B)\n $ruleSetChoices[\"Opt-H2KFoundation\"] = \"NBC_BCIN_zone8_noHRV\"\n if isCrawlHeated\n $ruleSetChoices[\"Opt-H2KFoundationSlabCrawl\"] = \"NBC_SCB_zone8_noHRV\"\n else # There is a crawlspace, but it isn't heated. Treat floor above crawlspace as exposed floor\n $ruleSetChoices[\"Opt-H2KFoundationSlabCrawl\"] = \"NBC_SOnly_zone8_noHRV\" # If there are any slabs, insulate them\n $ruleSetChoices[\"Opt-FloorAboveCrawl\"] = \"NBC_crawlceiling_zone8\"\n end\n\n end\n\n #-------------------------------------------------------------------------\n elsif ruleType =~ /NBC9_36_HRV/\n\n # Performance of Heat/Energy-Recovery Ventilator (Section 9.36.3.9.3)\n \t\t$ruleSetChoices[\"Opt-HRVonly\"] = \"NBC_HRV\"\n\n # Zone 4 ( HDD < 3000) without an HRV\n if locale_HDD < 3000\n # Effective thermal resistance of above-ground opaque assemblies (Table 9.36.2.6 A&B)\n $ruleSetChoices[\"Opt-GenericWall_1Layer_definitions\"] = \"NBC_Wall_zone4\"\n $ruleSetChoices[\"Opt-FloorHeader\"] = \"NBC_Wall_zone4\"\n $ruleSetChoices[\"Opt-AtticCeilings\"] = \"NBC_Ceiling_zone4\"\n $ruleSetChoices[\"Opt-CathCeilings\"] = \"NBC_FlatCeiling_zone4\"\n $ruleSetChoices[\"Opt-FlatCeilings\"] = \"NBC_FlatCeiling_zone4\"\n\n $ruleSetChoices[\"Opt-ExposedFloor\"] = \"NBC_exposed_zone4\"\n\n # Effective thermal resistance of fenestration (Table 9.36.2.7.(1))\n $ruleSetChoices[\"Opt-CasementWindows\"] = \"NBC-zone4-window\"\n $ruleSetChoices[\"Opt-Doors\"] = \"NBC-zone4-door\"\n $ruleSetChoices[\"Opt-DoorWindows\"] = \"NBC-zone4-Doorwindow\"\n\n # Effective thermal resistance of assemblies below-grade or in contact with the ground (Table 9.36.2.8.A&B)\n $ruleSetChoices[\"Opt-H2KFoundation\"] = \"NBC_BCIN_zone4\"\n if isCrawlHeated\n $ruleSetChoices[\"Opt-H2KFoundationSlabCrawl\"] = \"NBC_SCB_zone4\"\n else # There is a crawlspace, but it isn't heated. Treat floor above crawlspace as exposed floor\n $ruleSetChoices[\"Opt-H2KFoundationSlabCrawl\"] = \"NBC_SOnly_zone4\" # If there are any slabs, insulate them\n $ruleSetChoices[\"Opt-FloorAboveCrawl\"] = \"NBC_crawlceiling_zone4\"\n end\n\n # Zone 5 ( 3000 < HDD < 3999) with an HRV\n elsif locale_HDD >= 3000 && locale_HDD < 3999\n # Effective thermal resistance of above-ground opaque assemblies (Table 9.36.2.6 A&B)\n $ruleSetChoices[\"Opt-GenericWall_1Layer_definitions\"] = \"NBC_Wall_zone5_HRV\"\n $ruleSetChoices[\"Opt-FloorHeader\"] = \"NBC_Wall_zone5_HRV\"\n $ruleSetChoices[\"Opt-AtticCeilings\"] = \"NBC_Ceiling_zone5_HRV\"\n $ruleSetChoices[\"Opt-CathCeilings\"] = \"NBC_FlatCeiling_zone5\"\n $ruleSetChoices[\"Opt-FlatCeilings\"] = \"NBC_FlatCeiling_zone5\"\n\n $ruleSetChoices[\"Opt-ExposedFloor\"] = \"NBC_exposed_zone5\"\n\n # Effective thermal resistance of fenestration (Table 9.36.2.7.(1))\n $ruleSetChoices[\"Opt-CasementWindows\"] = \"NBC-zone5-window\"\n $ruleSetChoices[\"Opt-Doors\"] = \"NBC-zone5-door\"\n $ruleSetChoices[\"Opt-DoorWindows\"] = \"NBC-zone5-Doorwindow\"\n\n # Effective thermal resistance of assemblies below-grade or in contact with the ground (Table 9.36.2.8.A&B)\n $ruleSetChoices[\"Opt-H2KFoundation\"] = \"NBC_BCIN_zone5_HRV\"\n if isCrawlHeated\n $ruleSetChoices[\"Opt-H2KFoundationSlabCrawl\"] = \"NBC_SCB_zone5_HRV\"\n else # There is a crawlspace, but it isn't heated. Treat floor above crawlspace as exposed floor\n $ruleSetChoices[\"Opt-H2KFoundationSlabCrawl\"] = \"NBC_SOnly_zone5\" # If there are any slabs, insulate them\n $ruleSetChoices[\"Opt-FloorAboveCrawl\"] = \"NBC_crawlceiling_zone5\"\n end\n\n # Zone 6 ( 4000 < HDD < 4999) with an HRV\n elsif locale_HDD >= 4000 && locale_HDD < 4999\n # Effective thermal resistance of above-ground opaque assemblies (Table 9.36.2.6 A&B)\n $ruleSetChoices[\"Opt-GenericWall_1Layer_definitions\"] = \"NBC_Wall_zone6_HRV\"\n $ruleSetChoices[\"Opt-FloorHeader\"] = \"NBC_Wall_zone6_HRV\"\n $ruleSetChoices[\"Opt-AtticCeilings\"] = \"NBC_Ceiling_zone6\"\n $ruleSetChoices[\"Opt-CathCeilings\"] = \"NBC_FlatCeiling_zone6\"\n $ruleSetChoices[\"Opt-FlatCeilings\"] = \"NBC_FlatCeiling_zone6\"\n\n $ruleSetChoices[\"Opt-ExposedFloor\"] = \"NBC_exposed_zone6\"\n\n # Effective thermal resistance of fenestration (Table 9.36.2.7.(1))\n $ruleSetChoices[\"Opt-CasementWindows\"] = \"NBC-zone6-window\"\n $ruleSetChoices[\"Opt-Doors\"] = \"NBC-zone6-door\"\n $ruleSetChoices[\"Opt-DoorWindows\"] = \"NBC-zone6-Doorwindow\"\n\n # Effective thermal resistance of assemblies below-grade or in contact with the ground (Table 9.36.2.8.A&B)\n $ruleSetChoices[\"Opt-H2KFoundation\"] = \"NBC_BCIN_zone6_HRV\"\n if isCrawlHeated\n $ruleSetChoices[\"Opt-H2KFoundationSlabCrawl\"] = \"NBC_SCB_zone6_HRV\"\n else # There is a crawlspace, but it isn't heated. Treat floor above crawlspace as exposed floor\n $ruleSetChoices[\"Opt-H2KFoundationSlabCrawl\"] = \"NBC_SOnly_zone6\" # If there are any slabs, insulate them\n $ruleSetChoices[\"Opt-FloorAboveCrawl\"] = \"NBC_crawlceiling_zone6\"\n end\n\n # Zone 7A ( 5000 < HDD < 5999) with an HRV\n elsif locale_HDD >= 5000 && locale_HDD < 5999\n # Effective thermal resistance of above-ground opaque assemblies (Table 9.36.2.6 A&B)\n $ruleSetChoices[\"Opt-GenericWall_1Layer_definitions\"] = \"NBC_Wall_zone7A_HRV\"\n $ruleSetChoices[\"Opt-FloorHeader\"] = \"NBC_Wall_zone7A_HRV\"\n $ruleSetChoices[\"Opt-AtticCeilings\"] = \"NBC_Ceiling_zone7A_HRV\"\n $ruleSetChoices[\"Opt-CathCeilings\"] = \"NBC_FlatCeiling_zone7A\"\n $ruleSetChoices[\"Opt-FlatCeilings\"] = \"NBC_FlatCeiling_zone7A\"\n\n $ruleSetChoices[\"Opt-ExposedFloor\"] = \"NBC_exposed_zone7A\"\n\n # Effective thermal resistance of fenestration (Table 9.36.2.7.(1))\n $ruleSetChoices[\"Opt-CasementWindows\"] = \"NBC-zone7A-window\"\n $ruleSetChoices[\"Opt-Doors\"] = \"NBC-zone7A-door\"\n $ruleSetChoices[\"Opt-DoorWindows\"] = \"NBC-zone7A-Doorwindow\"\n\n # Effective thermal resistance of assemblies below-grade or in contact with the ground (Table 9.36.2.8.A&B)\n $ruleSetChoices[\"Opt-H2KFoundation\"] = \"NBC_BCIN_zone7A_HRV\"\n if isCrawlHeated\n $ruleSetChoices[\"Opt-H2KFoundationSlabCrawl\"] = \"NBC_SCB_zone7A_HRV\"\n else # There is a crawlspace, but it isn't heated. Treat floor above crawlspace as exposed floor\n $ruleSetChoices[\"Opt-H2KFoundationSlabCrawl\"] = \"NBC_SOnly_zone7A_HRV\" # If there are any slabs, insulate them\n $ruleSetChoices[\"Opt-FloorAboveCrawl\"] = \"NBC_crawlceiling_zone7A\"\n end\n\n # Zone 7B ( 6000 < HDD < 6999) with an HRV\n elsif locale_HDD >= 6000 && locale_HDD < 6999\n # Effective thermal resistance of above-ground opaque assemblies (Table 9.36.2.6 A&B)\n $ruleSetChoices[\"Opt-GenericWall_1Layer_definitions\"] = \"NBC_Wall_zone7B_HRV\"\n $ruleSetChoices[\"Opt-FloorHeader\"] = \"NBC_Wall_zone7B_HRV\"\n $ruleSetChoices[\"Opt-AtticCeilings\"] = \"NBC_Ceiling_zone7B\"\n $ruleSetChoices[\"Opt-CathCeilings\"] = \"NBC_FlatCeiling_zone7B\"\n $ruleSetChoices[\"Opt-FlatCeilings\"] = \"NBC_FlatCeiling_zone7B\"\n\n $ruleSetChoices[\"Opt-ExposedFloor\"] = \"NBC_exposed_zone7B\"\n\n # Effective thermal resistance of fenestration (Table 9.36.2.7.(1))\n $ruleSetChoices[\"Opt-CasementWindows\"] = \"NBC-zone7B-window\"\n $ruleSetChoices[\"Opt-Doors\"] = \"NBC-zone7B-door\"\n $ruleSetChoices[\"Opt-DoorWindows\"] = \"NBC-zone7B-Doorwindow\"\n\n # Effective thermal resistance of assemblies below-grade or in contact with the ground (Table 9.36.2.8.A&B)\n $ruleSetChoices[\"Opt-H2KFoundation\"] = \"NBC_BCIN_zone7B_HRV\"\n if isCrawlHeated\n $ruleSetChoices[\"Opt-H2KFoundationSlabCrawl\"] = \"NBC_SCB_zone7B_HRV\"\n else # There is a crawlspace, but it isn't heated. Treat floor above crawlspace as exposed floor\n $ruleSetChoices[\"Opt-H2KFoundationSlabCrawl\"] = \"NBC_SOnly_zone7B_HRV\" # If there are any slabs, insulate them\n $ruleSetChoices[\"Opt-FloorAboveCrawl\"] = \"NBC_crawlceiling_zone7B\"\n end\n\n # Zone 8 (HDD <= 7000) with an HRV\n elsif locale_HDD >= 7000\n # Effective thermal resistance of above-ground opaque assemblies (Table 9.36.2.6 A&B)\n $ruleSetChoices[\"Opt-GenericWall_1Layer_definitions\"] = \"NBC_Wall_zone8_HRV\"\n $ruleSetChoices[\"Opt-FloorHeader\"] = \"NBC_Wall_zone8_HRV\"\n $ruleSetChoices[\"Opt-AtticCeilings\"] = \"NBC_Ceiling_zone8\"\n $ruleSetChoices[\"Opt-CathCeilings\"] = \"NBC_FlatCeiling_zone8\"\n $ruleSetChoices[\"Opt-FlatCeilings\"] = \"NBC_FlatCeiling_zone8\"\n\n $ruleSetChoices[\"Opt-ExposedFloor\"] = \"NBC_exposed_zone8\"\n\n # Effective thermal resistance of fenestration (Table 9.36.2.7.(1))\n $ruleSetChoices[\"Opt-CasementWindows\"] = \"NBC-zone8-window\"\n $ruleSetChoices[\"Opt-Doors\"] = \"NBC-zone8-door\"\n $ruleSetChoices[\"Opt-DoorWindows\"] = \"NBC-zone8-Doorwindow\"\n\n # Effective thermal resistance of assemblies below-grade or in contact with the ground (Table 9.36.2.8.A&B)\n $ruleSetChoices[\"Opt-H2KFoundation\"] = \"NBC_BCIN_zone8_HRV\"\n if isCrawlHeated\n $ruleSetChoices[\"Opt-H2KFoundationSlabCrawl\"] = \"NBC_SCB_zone8_HRV\"\n else # There is a crawlspace, but it isn't heated. Treat floor above crawlspace as exposed floor\n $ruleSetChoices[\"Opt-H2KFoundationSlabCrawl\"] = \"NBC_SOnly_zone8_HRV\" # If there are any slabs, insulate them\n $ruleSetChoices[\"Opt-FloorAboveCrawl\"] = \"NBC_crawlceiling_zone8\"\n end\n\n end\n end # Check on NBC rule set type\nend", "def populate_elm_stuff\n save\n @populator.populate calculate_solution\n puts 'Packages configured successfully!'\n end", "def init_cost\n if @level + 1 <= @max_level\n cost = Config[:buildings][@type][:cost][@level + 1]\n @cost_time = cost[:time]\n @cost_res = cost[:res]\n @ttb_string = seconds_to_hm(@cost_time)\n end\n end", "def allocate_total\n\t\torders = Order.not_allocated.picking('total')\n\t\treturn false if orders.size == 0\n\t\tpickings = self.allocate(orders)\n\t\t# total_picking_list\n\t\ttotal_pickings = {}\n\t\tpickings.each do |p|\n\t\t\tif total_pickings[p.values_at(0,2,3,4,6)] \t\t\t\n\t\t\t\ttotal_pickings[p.values_at(0,2,3,4,6)][3] += p[4]\n\t\t\telse\n\t\t\t\ttotal_pickings[p.values_at(0,2,3,4,6)] = p.values_at(0,2,3,4,6) \t\t\t\n\t\t\tend\n\t\tend\n\t\tself.report_type = 'total'\n\t\tself.show_picking_list(total_pickings.values.sort{|a,b| a.values_at(0,1,2,3) <=> b.values_at(0,1,2,3)})\n\n\t\t# feeding_list\n\t\tfeedings = {}\n\t\tpickings.each do |p|\n\t\t\tif feedings[p.values_at(0,1,2,4,5)] \t\t\t\n\t\t\t\tfeedings[p.values_at(0,1,2,4,5)][3] += p[4]\n\t\t\telse\n\t\t\t\tfeedings[p.values_at(0,1,2,4,5)] = p.values_at(0,1,2,4,5) \t\t\t\n\t\t\tend\n\t\tend\n\t\t#work No set\n\t\tlast_work_no = '';last_customer_code = ''; last_store_code = ''\n\t\tfeedings.values.sort{|a,b| a.values_at(0,1) <=> b.values_at(0,1)}.each do |pi|\n\t\t\tunless (pi[0] == last_customer_code and pi[1] == last_store_code)\n\t\t\t\tlast_work_no = NumberMaster.new_picking_work_no\t\n\t\t\t\tlast_customer_code = pi[0]\n\t\t\t\tlast_store_code = pi[1]\n\t\t\tend\n\t\t\tpi.push last_work_no\n\t\tend\n\t\tself.report_type = 'feeding'\n\t\tself.show_picking_list(feedings.values.sort{|a,b| a.values_at(0,1) <=> b.values_at(0,1)})\n\tend", "def create_xpert_test_order(params)\n params['month'] = 0 if params['month'].nil? or params['month'] == ''\n check_key 'patient_etb_id', params\n check_key 'sample_collected_date', params\n check_key 'laboratory_region', params\n check_key 'laboratory_name', params\n check_key 'result', params\n\n check_valid 'result', params, ['0', '1', '2', '3', '4']\n\n resp = get(uri(\"cases/casedata.seam?id=#{params['patient_etb_id']}\"))\n resp = get(uri(\"cases/edtexamgenexpert.seam?id=#{params['patient_etb_id']}\"))\n\n keys = {}\n keys['sample_collected_date'] = resp.parser.css('input.rich-calendar-input').first.attributes['name'].text\n keys['_current_sample_collected_date'] = resp.parser.css('input.rich-calendar-input').first.next_element.next_element.attributes['name'].text\n params['_current_sample_collected_date'] = resp.parser.css('input.rich-calendar-input').first.next_element.next_element.attributes['value'].text\n keys['laboratory_serial_number'] = resp.parser.css('input[maxlength=\"50\"]')[0].attributes['name'].text\n keys['laboratory_region'] = resp.parser.css(\"select\")[0].attributes['name'].text\n keys['laboratory_name'] = resp.parser.css(\"select\")[1].attributes['name'].text\n keys['month'] = resp.parser.css(\"select\")[2].attributes['name'].text\n keys['date_of_release'] = resp.parser.css('input.rich-calendar-input')[1].attributes['name'].text\n keys['_current_date_of_release'] = resp.parser.css('input.rich-calendar-input')[1].next_element.next_element.attributes['name'].text\n params['_current_date_of_release'] = resp.parser.css('input.rich-calendar-input')[1].next_element.next_element.attributes['value'].text\n keys['result'] = resp.parser.css('select[onchange=\"examResultChanged(this)\"]')[0].attributes['name'].text\n keys['comment'] = resp.parser.css('textarea')[0].attributes['name'].value\n keys['_formexam'] = resp.parser.css('form[action=\"/etbmanager/cases/edtexamgenexpert.seam\"][class=\"form1\"]')[0].attributes['name'].text\n params['_formexam'] = keys['_formexam']\n params['_viewstate'] = resp.parser.css('input[id=\"javax.faces.ViewState\"]').first.attributes['value'].text\n params['_ajax_simple'] = resp.parser.css('span[class=\"readonly-value\"] > select')[0].attributes['name'].text\n keys['_last'] = resp.parser.css('span[class=\"readonly-value\"]').first.inner_html[/(?<=similarityGroupingId...)[^']+/]\n keys['_formexam2'] = resp.parser.css('a[class=\"button\"][href=\"#\"]').first.attributes['name'].text\n params['_formexam2'] = keys['_formexam2']\n\n post_data_region = {\n 'AJAXREQUEST' => '_viewRoot',\n keys['sample_collected_date'] => params['sample_collected_date'],\n keys['_current_sample_collected_date'] => params['_current_sample_collected_date'],\n keys['laboratory_serial_number'] => params['laboratory_serial_number'],\n keys['laboratory_name'] => 'org.jboss.seam.ui.NoSelectionConverter.noSelectionValue',\n keys['month'] => params['month'],\n keys['date_of_release'] => params['date_of_release'],\n keys['_current_date_of_release'] => params['_current_date_of_release'],\n keys['result'] => params['result'],\n keys['comment'] => params['comment'],\n params['_formexam'] => params['_formexam'],\n 'autoScroll' => '',\n 'javax.faces.ViewState' => params['_viewstate'],\n keys['laboratory_region'] => '950887',\n 'ajaxSingle' => params['_ajax_simple'],\n keys['_last'] => keys['_last']\n }\n\n resp = post(uri('cases/edtexamgenexpert.seam'), post_data_region)\n params['laboratory_name'] = resp.search(\"select > option\").select{|e| e.text == params['laboratory_name']}.first\n raise RuntimeError, \"invalid Lab Name\" unless params['laboratory_name']\n params['laboratory_name'] = params['laboratory_name'].attributes['value'].text\n\n post_data = {\n 'AJAXREQUEST' => '_viewRoot',\n keys['sample_collected_date'] => params['sample_collected_date'],\n keys['_current_sample_collected_date'] => params['_current_sample_collected_date'],\n keys['laboratory_serial_number'] => params['laboratory_serial_number'],\n keys['laboratory_region'] => '950887',\n keys['laboratory_name'] => params['laboratory_name'],\n keys['month'] => params['month'],\n keys['date_of_release'] => params['date_of_release'],\n keys['_current_date_of_release'] => params['_current_date_of_release'],\n keys['result'] => params['result'],\n keys['comment'] => params['comment'],\n params['_formexam'] => params['_formexam'],\n 'autoScroll' => '',\n 'javax.faces.ViewState' => params['_viewstate'],\n keys['_formexam2'] => params['_formexam2']\n }\n \n @agent.redirect_ok = false\n resp = post(uri('cases/edtexamgenexpert.seam'), post_data)\n @agent.redirect_ok = true\n\n if resp.class == Mechanize::XmlFile and resp.header and resp.header['location'].include?(\"/etbmanager/cases/casedata.seam?id=#{params['patient_etb_id']}\")\n return { success: true, error: '', patient_etb_id: params['patient_etb_id'] }\n else\n raise RuntimeError, \"Something went wrong\"\n end\n rescue StandardError => ex\n return { success: false, error: ex.message, patient_etb_id: params['patient_etb_id'] }\n end", "def configure_training_request\n available_ledgers :training_request\n set_training_request\n end", "def admin_aircraft_report\n return unless has_permission :can_do_billing\n @page_title = \"Billing Report\"\n @earliest = FlightRecord.find(:first, :order => \"flight_date\")\n if @earliest.nil? or params[:date].nil? then return end\n\n @start_date = Time.local(params[:date][:year].to_i, params[:date][:month].to_i)\n @end_date = @start_date.months_since params[:date][:range].to_i \n @page_title = \"Billing Report for \" + @start_date.strftime(\"%b %Y\") + \" to \" + @end_date.strftime(\"%b %Y\")\n\n @solo = FlightRecord.sum('hobbs_end-hobbs_start',:group=>:aircraft,\n :conditions=>['aircraft_id is not NULL and instructor_id is NULL and flight_date>=? and flight_date<?',@start_date,@end_date])\n @dual = FlightRecord.sum('hobbs_end-hobbs_start',:group=>:aircraft,\n :conditions=>['aircraft_id is not NULL and instructor_id is not NULL and flight_date>=? and flight_date<?',@start_date,@end_date])\n @charges = FlightRecord.sum('charge_amount',:group=>:aircraft,\n :conditions=>['aircraft_id is not NULL and flight_date>=? and flight_date<?',@start_date,@end_date])\n @aircrafts = Aircraft.find(:all,:conditions=>['deleted=false'],:order=>'identifier')\n \n @solo_total = @solo.inject(0){|s,e| s = s + e[1].to_f}\n @dual_total = @dual.inject(0){|s,e| s = s + e[1].to_f}\n @time_total = @solo_total + @dual_total\n @charges_total = @charges.inject(0){|s,e| s = s + e[1].to_f} \nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Download knapsack report from gcs bucket
def download_report logger.debug("Downloading latest knapsack report for '#{report_name}' to '#{report_path}'") file = client.get_object(BUCKET, report_file) File.write(report_path, file[:body]) rescue StandardError => e ENV["KNAPSACK_REPORT_PATH"] = FALLBACK_REPORT logger.warn("Failed to fetch latest knapsack report: #{e}") logger.warn("Falling back to '#{FALLBACK_REPORT}'") end
[ "def get_usage_export_bucket project:\n projects_client = ::Google::Cloud::Compute::V1::Projects::Rest::Client.new\n project_data = projects_client.get project: project\n export_location = project_data.usage_export_location\n\n if !export_location.nil? && export_location.report_name_prefix.empty?\n puts \"Report name prefix not set, replacing with default value of `usage_gce`.\"\n export_location.report_name_prefix = \"usage_gce\"\n end\n export_location\nend", "def download(ci_project_name)\n bucket_items = gcs_storage.list_objects(BUCKET, prefix: ci_project_name).items\n\n files_list = bucket_items&.each_with_object([]) do |obj, arr|\n arr << obj.name\n end\n\n return puts \"\\nNothing to download!\" if files_list.blank?\n\n FileUtils.mkdir_p('tmp/')\n\n files_list.each do |file_name|\n local_path = \"tmp/#{file_name.split('/').last}\"\n Runtime::Logger.info(\"Downloading #{file_name} to #{local_path}\")\n file = gcs_storage.get_object(BUCKET, file_name)\n File.write(local_path, file[:body])\n\n Runtime::Logger.info(\"Deleting #{file_name} from bucket\")\n gcs_storage.delete_object(BUCKET, file_name)\n end\n\n puts \"\\nDone\"\n end", "def report\n buckets.map {|bucket|\n \"#{bucket.length} packages between #{bucket.min} and #{bucket.max} days, totaling #{Artifactory::Cleaner::Util::filesize bucket.filesize}\"\n }.join(\"\\n\")\n end", "def upload_report(glob)\n reports = Pathname.glob(glob).each_with_object(Hash.new { |hsh, key| hsh[key] = [] }) do |report, hash|\n next unless report.extname == \".json\"\n\n hash[report.parent.basename.to_s].push(report)\n end\n return logger.error(\"Glob '#{glob}' did not contain any valid report files!\") if reports.empty?\n\n reports.each do |name, jsons|\n file = \"#{name}.json\"\n\n report = jsons\n .map { |json| JSON.parse(File.read(json)) }\n .reduce({}, :merge)\n .sort_by { |k, v| v } # sort report by execution time\n .to_h\n next logger.warn(\"Knapsack generated empty report for '#{name}', skipping upload!\") if report.empty?\n\n logger.info(\"Uploading latest knapsack report '#{file}'\")\n client.put_object(BUCKET, file, JSON.pretty_generate(report))\n rescue StandardError => e\n logger.error(\"Failed to upload knapsack report for '#{name}'. Error: #{e}\")\n end\n end", "def download\n cloud_api.download(self)\n end", "def download_chunk(key, range); end", "def upload_latest_copy\n upload_to_gcs(report_files, prefix)\n end", "def get_workspace_storage_cost(workspace_namespace, workspace_name)\n path = self.api_root + \"/api/workspaces/#{uri_encode(workspace_namespace)}/#{uri_encode(workspace_name)}/storageCostEstimate\"\n process_firecloud_request(:get, path)\n end", "def download_data(url) \n solar_pv_yield = {}\n uri = URI(url)\n response = Net::HTTP.get(uri)\n data = JSON.parse(response)\n total_yield = 0.0\n data_count = 0\n data.each do |key, value|\n value.each do |components|\n id, datetimestr, generation, capacity, _stations = components\n unless generation.nil?\n time = DateTime.parse(datetimestr)\n halfhour_yield = generation / capacity\n total_yield += halfhour_yield\n solar_pv_yield[time] = halfhour_yield\n # puts \"Download: #{time} #{halfhour_yield}\"\n data_count += 1\n end\n end\n end\n puts \"total yield #{total_yield} items #{data_count}\"\n solar_pv_yield\nend", "def download_data(url)\n solar_pv_yield = {}\n uri = URI(url)\n response = Net::HTTP.get(uri)\n data = JSON.parse(response)\n total_yield = 0.0\n data_count = 0\n data.each_value do |value|\n value.each do |components|\n _id, datetimestr, generation, capacity, _stations = components\n unless generation.nil?\n # rubocop:disable Style/DateTime\n # Time is too slow on Windows, order of magnitude slower than DateTime\n time = DateTime.parse(datetimestr)\n # rubocop:disable Style/DateTime\n halfhour_yield = generation / capacity\n total_yield += halfhour_yield\n solar_pv_yield[time] = halfhour_yield\n # puts \"Download: #{time} #{halfhour_yield}\"\n data_count += 1\n end\n end\n end\n puts \"total yield #{total_yield} items #{data_count}\"\n solar_pv_yield\nend", "def gridfs_download(repetitions = Benchmarking::TEST_REPETITIONS)\n client.database.drop\n create_collection\n fs = client.with(write_concern: { w: 1 }).database.fs(write_concern: { w: 1})\n\n file_id = fs.upload_from_stream('gridfstest', File.open(GRIDFS_FILE))\n io = StringIO.new\n\n results = repetitions.times.collect do\n io.rewind\n Benchmark.realtime do\n fs.download_to_stream(file_id, io)\n end\n end\n Benchmarking.median(results)\n end", "def set_usage_export_bucket project:, bucket_name:, report_name_prefix: \"\"\n export_location = { bucket_name: bucket_name, report_name_prefix: report_name_prefix }\n if report_name_prefix.empty?\n # Sending an empty value for report_name_prefix results in the\n # next usage report being generated with the default prefix value\n # \"usage_gce\". (ref: https://cloud.google.com/compute/docs/reference/rest/v1/projects/setUsageExportBucket)\n puts \"Setting report_name_prefix to empty value causes the report \" \\\n \"to have the default prefix of `usage_gce`.\"\n end\n projects_client = ::Google::Cloud::Compute::V1::Projects::Rest::Client.new\n operation = projects_client.set_usage_export_bucket project: project,\n usage_export_location_resource: export_location\n wait_until_done operation: operation\nend", "def quickstart project_id:, gcs_source_bucket:, gcs_sink_bucket:\n # Your Google Cloud Project ID\n # project_id = \"your-project_id\"\n\n # The name of the source GCS bucket to transfer objects from\n # gcs_source_bucket = \"your-source-gcs-source-bucket\"\n\n # The name of the GCS bucket to transfer objects to\n # gcs_sink_bucket = \"your-sink-gcs-bucket\"\n\n require \"google/cloud/storage_transfer\"\n\n transfer_job = {\n project_id: project_id,\n transfer_spec: {\n gcs_data_source: {\n bucket_name: gcs_source_bucket\n },\n gcs_data_sink: {\n bucket_name: gcs_sink_bucket\n }\n },\n status: :ENABLED\n }\n\n client = Google::Cloud::StorageTransfer.storage_transfer_service\n\n transfer_job_response = client.create_transfer_job transfer_job: transfer_job\n\n run_request = {\n project_id: project_id,\n job_name: transfer_job_response.name\n }\n client.run_transfer_job run_request\n\n puts \"Created and ran transfer job between #{gcs_source_bucket} and #{gcs_sink_bucket} with name #{transfer_job_response.name}\"\nend", "def gs_url\n \"gs://#{self.study.bucket_id}/#{self.bucket_location}\"\n end", "def download_job(uuid, out_fn, username, password)\n puts \"Downloading data from job #{uuid} to #{out_fn}\"\n fail \"Output file exists!\" if File.exist?(out_fn)\n\n job = get_job(uuid, username, password)\n puts \"Job info:\"\n puts summarise_job(job, 2)\n puts \"\"\n\n # Download stuff.\n puts \"Retrieving index...\"\n index = get_json(job['results']['dataURL'], username, password, '')\n\n num_files = index['urlCount']\n puts \"Retrieving #{num_files} files...\"\n \n i = 0\n File.open(out_fn, 'w') do |out|\n index['urlList'].each do |url|\n i += 1\n print \" #{i} / #{num_files} (#{((i.to_f / num_files.to_f) * 100.0).round(2)}%) \\r\"\n\n begin\n # RAW HTTP get request\n res = Net::HTTP.get(URI(url))\n zlibr = Zlib::GzipReader.new(StringIO.new(res.to_s))\n out.puts zlibr.read\n rescue StandardError => e\n print \"\\n*** ERR on file #{i}, URL: #{url}\\n\"\n end\n \n end # /url iteration\n end # /file handle\n\n print \"Done\\n\"\nend", "def storage_estimate\n workspaces = @fire_cloud_client.workspaces(params[:project_name])\n @workspaces = {}\n @total_cost = 0.0\n # parallelize retrieving workspace storage estimates\n Parallel.map(workspaces, in_threads: 100) do |workspace|\n begin\n client = FireCloudClient.new(user: current_user, project: params[:project_name])\n workspace_name = workspace.dig('workspace', 'name')\n cost_estimate = client.get_workspace_storage_cost(params[:project_name], workspace_name)\n actual_cost = cost_estimate['estimate'].gsub(/\\$/, '').to_f\n @workspaces[workspace_name] = actual_cost\n @total_cost += actual_cost\n rescue => e\n ErrorTracker.report_exception(e, current_user, params)\n logger.error \"Error in computing storage costs for #{params[:project_name]}: #{e.message}\"\n end\n end\n end", "def set_usage_export_bucket request_pb, options = nil\n raise ::ArgumentError, \"request must be provided\" if request_pb.nil?\n\n uri, body, query_string_params = transcode_set_usage_export_bucket_request request_pb\n response = @client_stub.make_post_request(\n uri: uri,\n body: body,\n params: query_string_params,\n options: options\n )\n result = ::Google::Cloud::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true\n\n yield result, response if block_given?\n result\n end", "def gamma_dist()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::Gamma_Dist::GammaDistRequestBuilder.new(@path_parameters, @request_adapter)\n end", "def download_cell_counts \n file = Dir.glob(\"#{Rails.root}/public/Predict/counts/*.csv\")[0].to_s\n logger.debug file\n send_file(file)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rename and move new regenerated report to a separate folder used to indicate report name
def move_regenerated_report return unless ENV["KNAPSACK_GENERATE_REPORT"] == "true" tmp_path = "tmp/knapsack/#{report_name}" FileUtils.mkdir_p(tmp_path) # Use path from knapsack config in case of fallback to master_report.json knapsack_report_path = Knapsack.report.report_path logger.debug("Moving regenerated #{knapsack_report_path} to save as artifact") FileUtils.cp(knapsack_report_path, "#{tmp_path}/#{ENV['CI_NODE_INDEX']}.json") end
[ "def export_rename(custodian)\n @@dialog.logMessage('Renaming files')\n dir = report_path(custodian)\n FileUtils.mkdir_p(dir)\n Dir.glob(export_path('*')).each do |p|\n if File.file?(p)\n rename_file(p, File.join(dir, File.basename(p))) unless p.end_with?('.pst')\n elsif @naming == 'item_name'\n rename_psts(p, custodian)\n end\n end\n end", "def move_reports(custodian)\n report_dir = File.join(@reports_dir, custodian)\n @@dialog.setSubStatusAndLogIt(\"Moving reports to #{report_dir}\")\n FileUtils.mkdir_p(report_dir)\n Dir.glob(File.join(@export_dir, '*.*')).each do |f|\n @@dialog.logMessage(\"Moving: #{f}\")\n File.rename(f, File.join(report_dir, File.basename(f)))\n end\n export_progress\n end", "def generatedReportFolder\n currentData, currentTime = DateTime.now.strftime(\"%Y_%m_%d %H_%M\").split(' ')\n path = \"#{$ROOT}/../output\"\n creatFolder(path)\n path += \"/#{currentData}\"\n creatFolder(path)\n path += \"/#{currentTime}\"\n creatFolder(path)\n path\n end", "def rename_file\n new_file_name = \"#{user_id}_#{user.first_name}_#{user.last_name}\"\n resume.instance_write :file_name, new_file_name + '.pdf'\n end", "def move_app_thinning_size_report\n if File.exist?(PackageCommandGenerator.app_thinning_size_report_path)\n FileUtils.mv(PackageCommandGenerator.app_thinning_size_report_path, File.expand_path(Gym.config[:output_directory]), force: true)\n app_thinning_size_report_path = File.join(File.expand_path(Gym.config[:output_directory]), File.basename(PackageCommandGenerator.app_thinning_size_report_path))\n\n UI.success(\"Successfully exported the App Thinning Size Report.txt file:\")\n UI.message(app_thinning_size_report_path)\n app_thinning_size_report_path\n end\n end", "def execute()\r\n File.rename(@OldFileName, @NewFileName)\r\n end", "def rename; end", "def rename_file\n\n end", "def create_report\n dir = Dir.pwd\n file_name = \"#{@name}.log\"\n reports_dir = dir + \"/spec/reports\"\n if File.directory? reports_dir\n @spec_report_file = File.open(reports_dir + \"/\" + file_name, 'w')\n @spec_report_file.puts \"WatirmarkLog: \" + @name\n else\n #spec/Reports directory does not exits\n @spec_report_file = nil\n end\n end", "def rename(old, new)\n old_dir, old_basename = split_if_nested(old) || [self, old]\n new_dir, new_basename = split_if_nested(new) || [self, new]\n\n if old_dir.hrx? && new_dir.hrx?\n unless old_file = old_dir.archive[old_basename]\n raise \"#@path/old doesn't exist\"\n end\n\n new_dir.archive.add(\n HRX::File.new(new_basename, old_file.content, comment: old_file.comment),\n after: new_dir == old_dir ? old_file.path : nil)\n new_dir._write!\n\n old_dir.delete(old_basename)\n else\n new_dir.write(new_basename, old_dir.read(old_basename))\n old_dir.delete(old_basename)\n end\n end", "def rename_temp_folder\n FileUtils.mv [ rails_plugins_path, temp_plugin_name ].to_path,\n [ rails_plugins_path, plugin.name ].to_path\n end", "def save_csv_report(file_name = 'default_feature_report')\n # reassign the initialize local variable @file_name to the file name input.\n @file_name = file_name\n\n # define the results_dir_path\n results_dir_path = File.join(@directory_name, 'feature_reports')\n # create feature reports directory\n Dir.mkdir(results_dir_path) unless Dir.exist?(File.join(@directory_name, 'feature_reports'))\n\n ## copy CSV report to the new feature_reports folder\n # get all folder names in the feature diectory\n directory_folders = Dir.glob \"#{@directory_name}/*/\"\n # copy the CSV report to the new feature_reports folder\n directory_folders.each do |f|\n if f.include? '_default_feature_reports'\n FileUtils.cp(File.join(f, 'default_feature_reports.csv'), File.join(results_dir_path, @file_name + '.csv'))\n end\n end\n end", "def rename_psts(dir, custodian)\n # Handle multiple PSTs\n Dir.glob(File.join(dir, 'Export*.pst')).each do |pst|\n rename_file(pst, export_path(File.basename(pst).sub('Export', custodian)))\n end\n # Remove directory if now empty\n FileUtils.remove_dir(dir) if Dir.glob(File.join(dir, '*')).empty?\n end", "def report_path(name)\n return File.join(@export_dir, @reports_dir) if name.nil?\n\n File.join(@export_dir, @reports_dir, name)\n end", "def create_new_report!\n File.write(report_filename, report_title + report_body)\n end", "def rename(file, newname)\n raise \"Sorry... 'AimsCalc rename' isn't implemented yet.\"\nend", "def fix_name!()\r\n\t\tnew_basename = (\"0\" + episode_number)[-2,2] + \" - \" + name\r\n\t\t# sanitize the name \r\n\t\tnew_basename.sub!(\":\", \" -\")\r\n\t\t[\"?\",\"\\\\\",\":\",\"\\\"\",\"|\",\">\", \"<\", \"*\", \"/\"].each {|l| new_basename.sub!(l,\"\")}\r\n\t\t\r\n\t\t\r\n\t\tnew_filename = @filename.dirname + (new_basename + @filename.extname)\r\n\t\tnew_episode_xml_path = @episode_xml_path.dirname + (new_basename + \".xml\")\r\n\t\t\r\n\t\traise \"can not rename #{@filename} detected a duplicate\" if new_filename.file? \r\n\t\t\r\n\t\tFile.rename(@filename, new_filename)\r\n\t\tFile.rename(@episode_xml_path, new_episode_xml_path)\r\n\t\t\r\n\t\t@filename = new_filename\r\n\t\t@episode_xml_path = new_episode_xml_path\r\n\t\t\r\n\tend", "def file_name_xunit_report\n Pathname.new 'report.xml'\n end", "def rename!\n puts \"\"\n puts \"Renaming from #{@from} to #{@to}\"\n\n rename_files\n rename_contents\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merge and upload knapsack report to gcs bucket Fetches all files defined in glob and uses parent folder as report name
def upload_report(glob) reports = Pathname.glob(glob).each_with_object(Hash.new { |hsh, key| hsh[key] = [] }) do |report, hash| next unless report.extname == ".json" hash[report.parent.basename.to_s].push(report) end return logger.error("Glob '#{glob}' did not contain any valid report files!") if reports.empty? reports.each do |name, jsons| file = "#{name}.json" report = jsons .map { |json| JSON.parse(File.read(json)) } .reduce({}, :merge) .sort_by { |k, v| v } # sort report by execution time .to_h next logger.warn("Knapsack generated empty report for '#{name}', skipping upload!") if report.empty? logger.info("Uploading latest knapsack report '#{file}'") client.put_object(BUCKET, file, JSON.pretty_generate(report)) rescue StandardError => e logger.error("Failed to upload knapsack report for '#{name}'. Error: #{e}") end end
[ "def upload_latest_copy\n upload_to_gcs(report_files, prefix)\n end", "def place_files_in_buckets\n @files.each do |file|\n place_file_in_buckets(file)\n end\n end", "def process_workspace_bucket_files(files)\n # first mark any files that we already know are study files that haven't changed (can tell by generation tag)\n files_to_remove = []\n files.each do |file|\n # first, check if file is in a submission directory, and if so mark it for removal from list of files to sync\n if @submission_ids.include?(file.name.split('/').first) || file.name.end_with?('/')\n files_to_remove << file.generation\n else\n directory_name = DirectoryListing.get_folder_name(file.name)\n found_file = {'name' => file.name, 'size' => file.size, 'generation' => file.generation}\n # don't add directories to files_by_dir\n unless file.name.end_with?('/')\n # add to list of discovered files\n @files_by_dir[directory_name] ||= []\n @files_by_dir[directory_name] << found_file\n end\n found_study_file = @study_files.detect {|f| f.generation.to_i == file.generation }\n if found_study_file\n @synced_study_files << found_study_file\n files_to_remove << file.generation\n end\n end\n end\n\n # remove files from list to process\n files.delete_if {|f| files_to_remove.include?(f.generation)}\n\n # next update map of existing files to determine what can be grouped together in a directory listing\n @file_extension_map = DirectoryListing.create_extension_map(files, @file_extension_map)\n\n files.each do |file|\n # check first if file type is in file map in a group larger than 10 (or 20 for text files)\n file_extension = DirectoryListing.file_extension(file.name)\n directory_name = DirectoryListing.get_folder_name(file.name)\n if @file_extension_map.has_key?(directory_name) && !@file_extension_map[directory_name][file_extension].nil? &&\n @file_extension_map[directory_name][file_extension] >= DirectoryListing::MIN_SIZE\n process_directory_listing_file(file, file_extension)\n else\n # we are now dealing with singleton files or fastqs, so process accordingly (making sure to ignore directories)\n if DirectoryListing::PRIMARY_DATA_TYPES.any? {|ext| file_extension.include?(ext)} && !file.name.end_with?('/')\n # process fastq file into appropriate directory listing\n process_directory_listing_file(file, 'fastq')\n else\n # make sure file is not actually a folder by checking its size\n if file.size > 0\n # create a new entry\n unsynced_file = StudyFile.new(study_id: @study.id, name: file.name, upload_file_name: file.name, upload_content_type: file.content_type, upload_file_size: file.size, generation: file.generation, remote_location: file.name)\n @unsynced_files << unsynced_file\n end\n end\n end\n end\n end", "def process_workspace_bucket_files(files)\n # first mark any files that we already know are study files that haven't changed (can tell by generation tag)\n files_to_remove = []\n files.each do |file|\n # first, check if file is in a submission directory, and if so mark it for removal from list of files to sync\n if @submission_ids.include?(file.name.split('/').first) || file.name.end_with?('/')\n files_to_remove << file.generation\n else\n directory_name = DirectoryListing.get_folder_name(file.name)\n found_file = {'name' => file.name, 'size' => file.size, 'generation' => file.generation}\n # don't add directories to files_by_dir\n unless file.name.end_with?('/')\n # add to list of discovered files\n @files_by_dir[directory_name] ||= []\n @files_by_dir[directory_name] << found_file\n end\n found_study_file = @study_files.detect {|f| f.generation.to_i == file.generation }\n if found_study_file\n @synced_study_files << found_study_file\n files_to_remove << file.generation\n end\n end\n end\n\n # remove files from list to process\n files.delete_if {|f| files_to_remove.include?(f.generation)}\n\n # next update map of existing files to determine what can be grouped together in a directory listing\n @file_extension_map = DirectoryListing.create_extension_map(files, @file_extension_map)\n\n files.each do |file|\n # check first if file type is in file map in a group larger than 10 (or 20 for text files)\n file_extension = DirectoryListing.file_extension(file.name)\n directory_name = DirectoryListing.get_folder_name(file.name)\n max_size = file_extension == 'txt' ? 20 : 10\n if @file_extension_map.has_key?(directory_name) && !@file_extension_map[directory_name][file_extension].nil? && @file_extension_map[directory_name][file_extension] >= max_size\n process_directory_listing_file(file, file_extension)\n else\n # we are now dealing with singleton files or fastqs, so process accordingly (making sure to ignore directories)\n if DirectoryListing::PRIMARY_DATA_TYPES.any? {|ext| file_extension.include?(ext)} && !file.name.end_with?('/')\n # process fastq file into appropriate directory listing\n process_directory_listing_file(file, 'fastq')\n else\n # make sure file is not actually a folder by checking its size\n if file.size > 0\n # create a new entry\n unsynced_file = StudyFile.new(study_id: @study.id, name: file.name, upload_file_name: file.name, upload_content_type: file.content_type, upload_file_size: file.size, generation: file.generation, remote_location: file.name)\n @unsynced_files << unsynced_file\n end\n end\n end\n end\n end", "def fitFiles(target)\n buckets()\n runningSize = 0\n fileSet = FileSet.new(target, @log, @DEBUG, @LOG_DEBUG)\n \n # Go thru each bucket...\n @sortedBuckets.each do |bkt|\n Utils.printMux(@log, \"Processing bucket '#{bkt}'\")\n\n # ... And each file in the bucket\n @data[bkt].each do |file| \n Utils.printMux(@log, \"\\tProcessing file '#{file}'\")\n\n # The regular call to size won't work with larger (> 2 GB) files in some versions of Ruby, so call the custom version added above.\n fsize = File.size_big(file)\n\n Utils.printMux(@log, \"\\t\\t fsize: #{fsize}\\n\", @DEBUG, @LOG_DEBUG, Utils::DEBUG_LOW, Utils::LOG_LOW)\n Utils.printMux(@log, \"\\t\\trunningSize: #{runningSize}\\n\", @DEBUG, @LOG_DEBUG, Utils::DEBUG_LOW, Utils::LOG_LOW)\n Utils.printMux(@log, \"\\t\\t target: #{target}\\n\", @DEBUG, @LOG_DEBUG, Utils::DEBUG_LOW, Utils::LOG_LOW)\n\n\t\t\t # Sanity check the file size\n if (fsize < 0)\n Utils.printMux(@log, \"\\t\\t*** WARNING: fsize < 0 - skipping!\\n\", @DEBUG, @LOG_DEBUG, Utils::DEBUG_LOW, Utils::LOG_LOW)\n next\n end\n\n # Make sure this file won't push us over the limit\n if (fsize + runningSize) < target\n # take the first file in this bucket \n Utils.printMux(@log, \"\\t\\tAdding '#{file}' and removing from bucket\")\n fileSet.add(file, fsize)\n runningSize += fsize\n \n # Remove the file from the original list\n @data[bkt].delete(file)\n \n # See if we should remove the bucket, too\n if @data[bkt].size() == 0\n @data.delete(bkt)\n Utils.printMux(@log, \"Removed bucket '#{bkt}'\\n\")\n end\n else\n # Go to the next bucket and look at smaller files\n Utils.printMux(@log, \"\\t\\tDropping down to next bucket\\n\")\n break\n end\n\n # Give the CPU a bit of a break in between files\n sleep @sleepInterval\n end # iterate files\n\n # Give the CPU a bit of a break in between buckets\n sleep @sleepInterval\n end # iterate buckets\n \n # Save off the running size in the object\n @totalSize = runningSize\n \n # Save off the file set\n @fileSets << fileSet\n\n Utils.printMux(@log, \"totalSize: #{totalSize}\\n\", @DEBUG, @LOG_DEBUG, Utils::DEBUG_LOW, Utils::LOG_LOW)\n Utils.printMux(@log, \"fileSets:\\n\" + @fileSets.pretty_inspect(), @DEBUG, @LOG_DEBUG, Utils::DEBUG_LOW, Utils::LOG_LOW)\n\n return fileSet\n end", "def upload_latest_copy\n upload_to_s3(report_files, prefix)\n end", "def insert_report_files\n Dir[\"#{DROPBOX.home}#{entry_files_folder}/*\"].each_with_index do |f, i|\n bname = File.basename(f)\n se = SortedEntry.where(:branch_id=>self.id, \n :dropbox_file=>bname, :forum_session_id=>nil).last\n if !se \n e = Entry.create :branch_id=>self.id, :dropbox_file=>bname,\n :forum_type=>'report', :dropbox_dir=>entry_files_folder,\n :is_private=>false\n SortedEntry.create :branch_id=>self.id, :entry_id=>e.id,\n :dropbox_file=>bname, :rank=>i+1\n else\n se.update_attribute :rank, i+1\n end\n end\n end", "def consolidate_files\n\n p \"Consolidating files: #{get_span_name(@config.data_span)}\"\n\n #Looking before leaping.\n #What data span are the files currently in?\n #What data span are we generating?\n #What if there are two types? --> Supported, commonly use case where consolidation is not complete.\n #What if there are three? --> Notify user and quit.\n\n #Tour data_dir and look at file names to determine what to do.\n #Do any files end in gz? Ignore gz files?\n\n set_span_target_details(@config.data_span)\n\n file_count = 0\n extensions = []\n have_target_filename = false\n target_span_name = get_span_name(@config.data_span)\n\n files = Array.new\n files = FileList.new(\"#{@config.data_dir}/*#{@config.job_uuid}*.*\").exclude(\"*#{target_span_name}*\")\n\n files.each do |file|\n if file.include? target_span_name then\n File.delete(file)\n end\n end\n\n files.each do |file|\n\n #p file.to_s\n\n file_count = file_count + 1\n\n ext = file.split('.')[-1]\n #p \"Has extension: #{ext}\"\n if !extensions.include?(ext) then\n extensions << ext\n end\n\n set_source_times(file)\n\n if !have_target_filename then\n set_target_filename(file)\n have_target_filename = true\n end\n end\n\n set_target_times #Based on source times, set target times\n\n if @span_target_minutes > 0 then\n p \"Source files contain activities starting at #{@set_source_start} and ending at #{@set_source_end}...\"\n p \"Will build Target files starting at #{@set_target_start} and ending at #{@set_target_end}...\"\n else\n p \"Will build files of a set size (default = #{SET_FILE_SIZE} MB)...\"\n end\n\n\n case extensions.length\n when 0\n p 'No files'\n return\n when 1\n p \"Files: #{file_count} -- Single extension found: #{extensions[0]}\"\n #If CSV or JSON we are set to consolidate.\n\n when 2\n # (*.json and *.csv and config.convert_data)?\n # Probably stopped in middle of conversion process.\n else\n p \"Have no idea what to do, bye, bye.\"\n end\n\n current_target_time = Time.new\n current_target_time = @set_target_start\n current_target_filename = @filename_target_template.gsub('<TARGET_FILE_DATE>', get_date_string(current_target_time))\n\n p \"First target filename: #{current_target_filename}\"\n\n #Now tour files to examine their names and read contents...\n #Compare Source filenames and extract date, then decide whether to write to current Target file,\n #OR create next Target file.\n\n #Going in, we know: set_source_start, set_source_end, set_target_start, set_target_end\n #Also, current boundaries: file_source_start/end, file_target_start/end\n #Also, source and target spans: span_source_minutes, span_target_minutes\n\n files_consolidated = 0\n #Create Target file.\n file_target = File.new(\"#{@config.data_dir}/#{current_target_filename}\", 'w')\n need_header = true\n\n files.each do |filename|\n\n p \"Processing #{filename}\"\n #Look at file name\n\n files_consolidated = files_consolidated + 1\n\n if files_consolidated % 10 == 0 then\n @status.files_consolidated = files_consolidated\n @status.save_status\n\n @status.get_status\n if @status.consolidate == false then\n @logger.message 'Disabled, stopping consolidation and exiting.'\n exit\n end\n end\n\n file_source = File.open(filename)\n\n file_time = get_file_time(filename)\n\n file_size = File.size(file_target).to_f/ 2 ** 20\n\n if (@span_target_minutes == 0 and file_size < SET_FILE_SIZE) or (@span_target_minutes != 0 and (file_time < (current_target_time + (@span_target_minutes * 60)) or @span_target_minutes == ALL_MINUTES)) then #Still in current target file's domain.\n #Write Source contents to Target file.\n p 'Write Source contents to Target file'\n\n else #Then we have a new Target file\n\n file_target.close\n\n #OK, we may have skipped one or more Target spans, so check and generate new Target filename.\n\n #Increment new Target time and generate new Target filename.\n current_target_time = get_target_time(file_time)\n\n if @span_target_minutes != 0 then\n current_target_filename = String.new(@filename_target_template.gsub('<TARGET_FILE_DATE>', get_date_string(current_target_time)))\n else\n current_target_filename = String.new(@filename_target_template.gsub('<TARGET_FILE_DATE>', get_date_string(current_target_time)))\n end\n #p \"Creating new Target file: #{current_target_filename}\"\n\n file_target = File.new(\"#{@config.data_dir}/#{current_target_filename}\", 'w')\n need_header = true\n end\n\n #TODO: we need to manage the source file headers here.\n if need_header then\n file_target.puts file_source.read\n need_header = false\n else\n file_target.puts File.readlines(file_source)[1..-2]\n end\n\n file_source.close\n File.delete(file_source)\n end\n\n if @span_target_minutes == ALL_MINUTES then\n file_target.close\n end\n end", "def globalReport(psdFiles, base)\n psdFiles.each do |psdFile|\n name = File.basename(psdFile, \".psd\")\n PSD.open(psdFile) do |psd|\n content = psd.tree.to_hash\n jsonContent = JSON.pretty_generate(content)\n file = File.join(base, \"#{name}.json\")\n File.open(file, \"w\") { |f| f.write(jsonContent) }\n puts \"[create] #{file}\"\n end\n end\nend", "def folder_asset_ingest(args = { })\n parameters = api_method_parameters(__method__)\n _args = process_parameters(parameters, args.dup)\n\n folder_to_ingest = _args.delete(:folder_to_ingest) { }\n\n raise ArgumentError, ':folder_to_ingest is a required argument.' unless folder_to_ingest\n\n folder_to_ingest = File.join(folder_to_ingest, '*') if File.directory?(folder_to_ingest)\n\n file_paths = Dir.glob(folder_to_ingest)\n\n file_paths.map { |file_path| asset_ingest_any( _args.merge( :file_to_ingest => file_path ) ) }\n end", "def get_usage_export_bucket project:\n projects_client = ::Google::Cloud::Compute::V1::Projects::Rest::Client.new\n project_data = projects_client.get project: project\n export_location = project_data.usage_export_location\n\n if !export_location.nil? && export_location.report_name_prefix.empty?\n puts \"Report name prefix not set, replacing with default value of `usage_gce`.\"\n export_location.report_name_prefix = \"usage_gce\"\n end\n export_location\nend", "def git_upload_pack\n enqueue_fetch_statistics_update\n\n render_ok\n end", "def gridfs_upload\n n = 50\n client.database.drop\n fs = client.database.fs\n\n files = [*0...n].collect do |i|\n name = \"#{GRIDFS_MULTI_BASE}#{i}.txt\"\n {\n file: File.open(name, 'r'),\n name: File.basename(name)\n }\n end\n\n s = StringIO.new('a')\n fs.upload_from_stream('create-indices.test', s)\n\n Benchmark.realtime do\n n.times do |i|\n fs.upload_from_stream(files[i][:name], files[i][:file])\n end\n end\n end", "def merge_parallel_json(json_folder)\r\n reports = Dir.glob(\"#{json_folder}/report_parallel*.json\")\r\n reports_rerun = Dir.glob(\"#{json_folder}/report_rerun*.json\")\r\n\r\n reports.each do |json|\r\n nameBegin = json.rindex '/'\r\n nameBegin = 0 if nameBegin < 0\r\n nameEnd = json.rindex '.'\r\n name = json[nameBegin+1..nameEnd-1]\r\n reports_rerun.each do |rerun_json|\r\n merge(rerun_json, json, \"#{name}_merged.json\")\r\n File.rename(\"#{name}_merged.json\", \"#{name}.json\")\r\n end\r\n end\r\n\r\n reports_rerun.each do |json|\r\n File.delete json\r\n end\r\n\r\nend", "def gridfs_upload(repetitions)\n client.database.drop\n create_collection\n fs = client.with(write_concern: { w: 1 }).database.fs(write_concern: { w: 1})\n\n s = StringIO.new('a')\n fs.upload_from_stream('create-indices.test', s)\n\n file = File.open(GRIDFS_FILE)\n\n results = repetitions.times.collect do\n file.rewind\n Benchmark.realtime do\n fs.upload_from_stream('GRIDFS_LARGE', file)\n end\n end\n Benchmarking.median(results)\n end", "def gridfs_download\n n_files = 50\n n_threads = BSON::Environment.jruby? ? 4 : 2\n threads = []\n client.database.drop\n fs = client.database.fs\n\n file_info = [*0...n_files].collect do |i|\n name = \"#{GRIDFS_MULTI_BASE}#{i}.txt\"\n {\n _id: fs.upload_from_stream(name, File.open(name)),\n output_name: \"#{GRIDFS_MULTI_OUTPUT_BASE}#{i}.txt\"\n }\n end.freeze\n\n reps = n_files/n_threads.freeze\n Benchmark.realtime do\n n_threads.times do |i|\n threads << Thread.new do\n reps.times do |j|\n index = i * reps + j\n fs.download_to_stream(file_info[index][:_id], File.open(file_info[index][:output_name], \"w\"))\n end\n end\n end\n threads.collect(&:value)\n end\n end", "def move_regenerated_report\n return unless ENV[\"KNAPSACK_GENERATE_REPORT\"] == \"true\"\n\n tmp_path = \"tmp/knapsack/#{report_name}\"\n FileUtils.mkdir_p(tmp_path)\n\n # Use path from knapsack config in case of fallback to master_report.json\n knapsack_report_path = Knapsack.report.report_path\n logger.debug(\"Moving regenerated #{knapsack_report_path} to save as artifact\")\n FileUtils.cp(knapsack_report_path, \"#{tmp_path}/#{ENV['CI_NODE_INDEX']}.json\")\n end", "def concat_files (folder_name, all_files, sample_list)\n #puts all_files\n if all_files.nil?\n sample_list_file = File.open(sample_list)\n list = []\n sample_list_file.each do |line|\n list.push(\"#{folder_name}/\"+line.strip)\n end\n #puts list\n `cat #{list.join(\" \")} > all_bc_reads.fq`\n\n else\n `cat #{folder_name}/#{all_files} > all_bc_reads.fq` \n end\n\n abort(\"!!!!The file with all the reads required for clustering does not exist!!!!\") if !File.exists?(\"all_bc_reads.fq\")\nend", "def merge_sort(input_dir: '', input_filter: '*', output_dir: '', add_suffix: '', reference: {}, group_by_samples: false, config: {}, container: {container: false}, wf_log: false)\n ram = config[:ram]\n task_name = \"GATK_MergeSortSam\"\n group_spliter = '_' # Split file names on this character\n group_on_index = 0 # Sample are on the first par of the splited file name\n tmp_dir = output_dir + '/tmp'\n FileUtils.mkdir_p(output_dir)\n FileUtils.mkdir_p(tmp_dir)\n Logger.info message: 'GATK merge and sort', logfile: wf_log\n file_list = get_file_names path: input_dir, filter: \"*#{input_filter}*.bam\", full_path: true\n # Get a list of samples\n groups_list = ['*']\n if group_by_samples\n Logger.info message: \" Regroup file by Samples, sample name on index #{group_on_index} after spliting file names with #{group_spliter}\", logfile: wf_log\n groups_list = []\n file_list.each do |file|\n filename = file.split('/')[-1] # Get the file name only\n groupname = filename.split(group_spliter)[group_on_index]\n groups_list.push groupname if not groups_list.include? groupname\n end\n Logger.info message: \" Group by samples: #{groups_list.size} samples found\", logfile: wf_log\n end\n error_list.push 'Cannot find sample tags to group files' if groups_list.size == 0\n # For each sample merge all files\n groups_list.each do |sample_tag|\n inputs_list = []\n if sample_tag == '*'\n inputs_list = file_list\n else\n file_list.each do |file|\n inputs_list.push file if file.include? sample_tag\n end\n end\n Logger.info message: \" Sample: #{sample_tag} : #{inputs_list.size} files found\", logfile: wf_log\n bin_cmd = []\n bin_cmd << 'java'\n bin_cmd << \"-Xmx#{ram}G\"\n bin_cmd << \"-Djava.io.tempdir=#{tmp_dir}\"\n bin_cmd << \"-jar #{GATK_JAR}\"\n binary = bin_cmd.join(' ').to_s\n inputs = []\n for file in inputs_list\n inputs << \"--INPUT #{file}\"\n end\n base_name = sample_tag\n base_name = 'mapped_sequences' if sample_tag == '*'\n output_file = base_name + add_suffix + '.bam'\n skip_test = File.exist?(\"#{output_dir}/#{output_file}\")\n step = Runner.new task_name: \"#{task_name}_#{base_name}\", wf_log: wf_log, task_log_dir: output_dir\n step.in_container(engine: container[:type], imgURL: \"#{container[:repo]}#{GATK_IMG}\", additional_options: container[:optional_args], mountList: container[:mountList]) if container[:container]\n step.cmd_line << binary\n step.cmd_line << 'MergeSamFiles'\n step.cmd_line << inputs.join(' ').to_s\n step.cmd_line << \"--OUTPUT=#{output_dir}/#{output_file}\"\n step.cmd_line << \"--TMP_DIR #{tmp_dir}\"\n step.cmd_line << '--USE_THREADING=true'\n step.cmd_line << '--CREATE_INDEX=true'\n step.cmd_line << '--MAX_RECORDS_IN_RAM=1000000'\n step.cmd_line << '--SORT_ORDER=coordinate'\n step.cmd_line << '--VALIDATION_STRINGENCY=LENIENT'\n step.run skip: skip_test, debug: false\n end\n FileUtils.rm_rf(tmp_dir)\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Base path of knapsack report
def report_base_path @report_base_path ||= "knapsack" end
[ "def app_thinning_size_report_path\n Gym.cache[:app_thinning_size_report] ||= File.join(temporary_output_path, \"App Thinning Size Report.txt\")\n end", "def relative_path\n calculation_directory\n end", "def file_path_xunit_report\n Noop::Config.dir_path_reports + file_name_xunit_report\n end", "def folder_base; File.join(output_path, underscored_description.to_s); end", "def files_dir\n File.absolute_path(File.join(@root_dir, 'lib/urbanopt/reporting/default_reports/'))\n end", "def base_path\n @path\n end", "def base_path\n @doc.fetch(\"basePath\", nil).try(:downcase)\n end", "def base_path\n @base_path || '.'\n end", "def get_base\n case @source\n when \"dropbox\"\n base = \"#{@user.dirs[:dropbox]}/Braincase/Memories\"\n when \"local\"\n base = \"#{@user.dirs[:backups]}/daily_backup\"\n else\n raise RestoreError, \"Could not determine base directory: invalid source #{@source}\"\n end\n base\n end", "def generatedReportFolder\n currentData, currentTime = DateTime.now.strftime(\"%Y_%m_%d %H_%M\").split(' ')\n path = \"#{$ROOT}/../output\"\n creatFolder(path)\n path += \"/#{currentData}\"\n creatFolder(path)\n path += \"/#{currentTime}\"\n creatFolder(path)\n path\n end", "def base_path_to(resource = '')\n result = resource\n level.times { result = \"../#{result}\" }\n result\n end", "def relative_pallet_path_for(element) \n sub_path = @sub_path.to_s\n sub_path = sub_path[1..-1] + '/' unless sub_path.blank?\n return sub_path << element\n end", "def data_bags_path\n\t# These can occur on suite-level, provisioner-level, verifier or at the default location\n kitchen_provisioner_config[:data_bags_path] || kitchen_verifier_config[:data_bags_path] || File.join('test', 'data_bags')\n end", "def template_base_path\n @template_base_path ||= Inkblot.vendor_path('templates')\n end", "def data_path(dataset_key)\n @directory.join(\"#{dataset_key}.pack\")\n end", "def base_folder\n\t\t\ttemp_folder_path = \"/tmp/MIAConverter\"\n\t\t\tDir.mkdir(temp_folder_path) unless Dir.exists?(temp_folder_path)\n\t\t\ttemp_folder_path\n\t\tend", "def reports_path; end", "def base_template_path\n File.join(Rails.root, 'config', 'default_data', 'master-template.xlsx')\n end", "def get_base_path\n return @payload.get_path(\"base_path\"){\"\"}\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Report name Infer report name from ci job name Remove characters incompatible with gcs bucket naming from job names like ee:instanceparallel
def report_name @report_name ||= ENV["CI_JOB_NAME"].split(" ").first.tr(":", "-") end
[ "def job_name\n @job_name ||= QA::Runtime::Env.ci_job_name&.gsub(%r{ \\d{1,2}/\\d{1,2}}, '')\n end", "def name_with_job\n return name + \"(\" + job.name + \")\"\n end", "def job_name_from_package_name(package_name)\n \"#{job_prefix}#{package_name.gsub('/', '-')}\"\n end", "def trim_job_name(job_name)\n job_name = job_name.gsub('grid-', '');\n job_name = job_name.gsub('store-', '');\n job_name = job_name.gsub('sphere-', '');\n job_name = job_name.gsub('-public-deb', '');\n job_name = job_name.gsub('-private-deb', '');\n job_name = job_name.gsub('solr', 's');\n job_name = job_name.gsub('automation', 'am');\n job_name = job_name.gsub('webtests-production', 'wp');\n job_name = job_name.gsub('webtests-staging', 'ws');\n job_name = job_name.gsub('checkout', 'co');\n job_name = job_name.gsub('saucelabs', 'slabs');\n return job_name\nend", "def job_name_entry\n if job\n job.to_s\n else\n job_name_override\n end\n end", "def job_name\n return settings[:job_name] if settings[:job_name]\n relevant_filename = args.compact.uniq.map { |path| File.basename(path, '.rb') }.join('-')\n \"#{relevant_filename}---#{input_paths}---#{output_path}\".gsub(%r{[^\\w/\\.\\-\\+]+}, '')\n end", "def get_job_name(course, assessment, submission)\n \"#{course.name}_#{assessment.name}_#{submission.version}_#{submission.course_user_datum.email}\"\n end", "def buildJobName()\n processID = $$\n @jobName = @jobPrefix + \"_\" + processID.to_s + \"_\" + rand(5000).to_s\n end", "def job_name\n \"#{action_name}_#{model_name}_job\"\n end", "def job_name_illegal_chars\n ENV[\"OOD_JOB_NAME_ILLEGAL_CHARS\"].to_s\n end", "def synthesize_job_name\n klass_name = name.scan(/[^:]+/).last\n klass_name = klass_name[/(.+)Job/, 1] || klass_name\n klass_name.scan(/[A-Z][a-z]+/).map(&:downcase).join('_').to_sym\n end", "def job_name\n md5 = Digest::MD5.new\n md5 << name\n md5 << uri\n md5 << job_config_path.read\n md5 << builder.callback_url.to_s\n \"#{name}-#{md5.hexdigest[0,12]}\"\n end", "def set_job_name\n (Time.now.to_f * 1000).to_i.to_s\n end", "def sanitize_job_name(job_name)\n # escape ^ and omit -\n chars = job_name_illegal_chars.to_s.gsub(\"^\", \"\\\\^\").gsub(\"-\", \"\")\n job_name.tr(chars, \"-\")\n end", "def gen_company_report_name(hash)\n name = fix_company_name(hash)[\"company_name\"] + \" Report\"\n hash[\"name\"] = name\n return hash\n end", "def job_spec_name\n self.job_spec.name\n end", "def set_log_base_name\n @job_log_base_name = \"#{Rails.env}-#{self.job_spec.name}-#{Time.now.strftime('%Y%m%d-%H%M%S%z')}-#{SecureRandom.hex(2)}.log\"\n end", "def report_name\n return @report_name\n end", "def report_to_filename( report )\n filename = \"#{URI(report.options['url']).host}:#{report.start_datetime}\"\n filename.gsub( ':', '.' ).gsub( ' ', '_' ).gsub( '-', '_' ).gsub( '__', '_' )\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
clean the tree, for example, eliminates sequence that have only one child (use the child directly).
def clean_tree(branch) branch.children = branch.children.inject(Children.new(branch)) do |r, c| cc = if c.name == 'sequence' and c.children.size == 1 c.children.first else c end r << clean_tree(cc) end branch end
[ "def clean_tree (branch)\n\n branch.children = branch.children.inject(Children.new(branch)) do |r, c|\n cc = if c.name == 'sequence' and c.children.size == 1\n c.children.first\n else\n c\n end\n r << clean_tree(cc)\n end\n\n branch\n end", "def delete_tree\n @root = nil # In ruby it will be taken care by garbage collector\n end", "def clean_children\n\n return unless @children\n\n @children.each do |child_fei|\n #next unless child.is_a?(FlowExpressionId)\n get_expression_pool.remove(child_fei)\n end\n end", "def clean_tree rn\n return if(rn.elements.nil?)\n rn.elements.delete_if{|n| n.class.name == \"Treetop::Runtime::SyntaxNode\" }\n rn.elements.each {|n| clean_tree(n) }\n end", "def clean_tree(root_node)\n return if(root_node.elements.nil?)\n root_node.elements.delete_if{|node| not node.is_ast? }\n root_node.elements.each{|e| e.clean_tree(e)}\n end", "def remove\r\n return unless parent? # No need to remove if parentless\r\n\r\n parent_obj = zobj self.parent\r\n sibling_obj = zobj self.sibling\r\n\r\n clear_parent\r\n clear_sibling\r\n\r\n if parent_obj.child == self.id # Am I my parent's child?\r\n parent_obj.child = sibling_obj.id\r\n else\r\n child_obj = zobj parent_obj.child\r\n while self.id != child_obj.sibling # Next Child!\r\n raise \"malformed object tree\" if child_obj.sibling == 0\r\n child_obj = zobj child_obj.sibling\r\n end\r\n child_obj.sibling = sibling_obj.id\r\n end\r\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_parenthetical! # TODO breaks dependencies\n @tree.breadth_each do |l|\n if l.parenthetical?\n #p 'removed'\n l.parent.remove!(l)\n end\n end\n end", "def prune!\n self.children.each {|c| c.prune!}\n\n self.children =\n self.children.reject do |c|\n c.tag != :text && c.children.empty?\n end\n end", "def remove!\n # Rebuild this tree without the root node. \n tree = _rebuild(nil, true)\n\n # Replace ourself with the new tree\n @value = tree.value\n @left = tree.left\n @right = tree.right\n end", "def nullify_children\n children.each do |c|\n c.parent = c.parent_id = nil\n c.save\n end\n end", "def prune!\n return if root?\n if normal?\n parent.children_hash.delete(name)\n else\n parent.children_hash.default = nil\n end\n old_parent = parent\n @parent = nil\n old_parent.prune! if old_parent.useless?\n end", "def trim_tree\n\t\t@corridor_seeds.each { |seed| check_branch(corridor_map[seed]) }\n\tend", "def remove_children\n @children.clear\n end", "def remove_child(le)\n\t\t\t@children.delete le\n\t\t\tle.parent = nil\n\t\tend", "def eliminate!\n # puts \"eliminating #{self}\"\n return unless parent\n parent.add_self_time(self)\n parent.add_wait_time(self)\n children.each do |kid|\n if call = parent.find_call(kid)\n call.merge_call_tree(kid)\n else\n parent.children << kid\n # $stderr.puts \"setting parent of #{kid}\\nto #{parent}\"\n kid.parent = parent\n end\n end\n parent.children.delete(self)\n end", "def prune\n # First: prune all children.\n self.each { |_, n| n.prune }\n # Then delete all nil leaf children.\n @succ.clone.each do |key, n|\n delete key if n.val == nil && n.leaf?\n end\n end", "def test_remove_from_parent_bang\n setup_test_tree\n\n assert(@root.has_children?, \"Should have children\")\n assert(!@root.is_leaf?, \"Root is not a leaf here\")\n\n child1 = @root[0]\n assert_not_nil(child1, \"Child 1 should exist\")\n assert_same(@root, child1.root, \"Child 1's root should be ROOT\")\n assert(@root.include?(child1), \"root should have child1\")\n child1.remove_from_parent!\n assert_same(child1, child1.root, \"Child 1's root should be self\")\n assert(!@root.include?(child1), \"root should not have child1\")\n\n child1.remove_from_parent!\n assert_same(child1, child1.root, \"Child 1's root should still be self\")\n end", "def destroy_self_and_children!\n children.each do |node|\n node.destroy\n end\n destroy\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Configuration blocks allow for lists of remote hosts, those are split into seperate configuration blocks here
def split_multi_remotehost_config_blocks(config_block) split_config = [] config_block['remoteHost'].each do |single_remote_host| # Clone the block containing the multiple remote hosts config_block_for_single_remote_host = config_block.clone # And replace them with a single remote host config_block_for_single_remote_host['remoteHost'] = single_remote_host split_config.push(config_block_for_single_remote_host) end # Return split config blocks that each have a single remote host split_config end
[ "def get_host_options(key, &block)\n opts = {}\n sky_instances.each{|sky_instance|\n merging = configuration_data.keep_merge configuration_data[\"roles\"][sky_instance.role.to_s]\n if block\n value = block.call(merging[key])\n end\n opts[\"hostvar_#{sky_instance.hostname}\"] = value\n }\n return opts\n end", "def host_list\n if ARGV.size >= 1\n hosts = ARGV\n else \n LOAD_PATHS.each do |path|\n hosts = read_config File.expand_path(File.join(path, \"load_config.yaml\"))\n if hosts\n # puts \"Using hosts listed in load_config.yaml from #{path}\"\n return hosts\n end\n end\n\n # If no host config was found, just use localhost.\n if hosts.nil?\n puts \"Warning: Unable to find host information.\"\n hosts = {:localhost => 0}\n end\n end\nend", "def node_list\n nodes = []\n nodes += config['hosts'] if config['hosts']\n nodes += config['passives'] if config['passives']\n nodes += [\"#{@host}:#{@port}\"] if @client.mongos?\n nodes\n end", "def ssh_config\n ENTRIES.inject([]) { |out, keyvalue|\n host, keywords = keyvalue\n out << [\n 'Host ' + host,\n keywords.inject([]) do |subout, subkeyvalue|\n key, value = subkeyvalue\n subout << \"#{INDENT}#{key.to_s}#{SEPARATOR}#{value.to_s}\"\n end\n ]\n }.join(\"\\n\")\nend", "def ssh_config(ssh_exec: 'ssh', known_hosts_file: nil, nodes: @nodes_handler.known_nodes)\n config_content = <<~EO_SSH_CONFIG\n ############\n # GATEWAYS #\n ############\n\n #{@ssh_gateways_conf.nil? || !@config.known_gateways.include?(@ssh_gateways_conf) ? '' : @config.ssh_for_gateway(@ssh_gateways_conf, ssh_exec: ssh_exec, user: @ssh_user)}\n\n #############\n # ENDPOINTS #\n #############\n\n EO_SSH_CONFIG\n\n # Add each node\n # Query for the metadata of all nodes at once\n @nodes_handler.prefetch_metadata_of nodes, %i[private_ips hostname host_ip description]\n nodes.sort.each do |node|\n # Generate the conf for the node\n connection, connection_user, gateway, gateway_user = connection_info_for(node, no_exception: true)\n if connection.nil?\n config_content << \"# #{node} - Not connectable using SSH - #{@nodes_handler.get_description_of(node) || ''}\\n\"\n else\n config_content << \"# #{node} - #{connection} - #{@nodes_handler.get_description_of(node) || ''}\\n\"\n config_content << \"Host #{ssh_aliases_for(node).join(' ')}\\n\"\n config_content << \" Hostname #{connection}\\n\"\n config_content << \" User \\\"#{connection_user}\\\"\\n\" if connection_user != @ssh_user\n config_content << \" ProxyCommand #{ssh_exec} -q -W %h:%p #{gateway_user}@#{gateway}\\n\" unless gateway.nil?\n if @passwords.key?(node)\n config_content << \" PreferredAuthentications password\\n\"\n config_content << \" PubkeyAuthentication no\\n\"\n end\n end\n config_content << \"\\n\"\n end\n # Add global definitions at the end of the SSH config, as they might be overriden by previous ones, and first match wins.\n config_content << <<~EO_SSH_CONFIG\n ###########\n # GLOBALS #\n ###########\n\n Host *\n User #{@ssh_user}\n # Default control socket path to be used when multiplexing SSH connections\n ControlPath #{control_master_file('%h', '%p', '%r')}\n #{open_ssh_major_version >= 7 ? 'PubkeyAcceptedKeyTypes +ssh-dss' : ''}\n #{known_hosts_file.nil? ? '' : \"UserKnownHostsFile #{known_hosts_file}\"}\n #{@ssh_strict_host_key_checking ? '' : 'StrictHostKeyChecking no'}\n\n EO_SSH_CONFIG\n config_content\n end", "def configure\n nodes.each do |k,v|\n rs_storage = RSpec.configuration.rs_storage[:nodes][k]\n\n # Fixup profile to avoid noise\n if v.facts['osfamily'] == 'Debian'\n shell(:n => k, :c => \"sed -i 's/^mesg n/# mesg n/' /root/.profile\")\n end\n\n # Setup ntp\n if v.facts['osfamily'] == 'Debian' then\n shell(:n => k, :c => 'apt-get install -y ntpdate')\n elsif v.facts['osfamily'] == 'RedHat' then\n if v.facts['lsbmajdistrelease'] == '5' then\n shell(:n => k, :c => 'yum install -y ntp')\n else\n shell(:n => k, :c => 'yum install -y ntpdate')\n end\n end\n shell(:n => k, :c => 'ntpdate -u pool.ntp.org')\n\n # Grab IP address for host, if we don't already have one\n rs_storage[:ipaddress] ||= shell(:n => k, :c => \"ip a|awk '/g/{print$2}' | cut -d/ -f1 | head -1\").stdout.chomp\n\n # Configure local hostname and hosts file\n shell(:n => k, :c => \"hostname #{k}\")\n\n if v.facts['osfamily'] == 'Debian' then\n shell(:n => k, :c => \"echo '#{k}' > /etc/hostname\")\n end\n\n hosts = <<-EOS\n#{rs_storage[:ipaddress]} #{k}\n127.0.0.1 #{k} localhost\n::1 #{k} localhost\n EOS\n shell(:n => k, :c => \"echo '#{hosts}' > /etc/hosts\")\n\n # Display setup for diagnostics\n shell(:n => k, :c => 'cat /etc/hosts')\n shell(:n => k, :c => 'hostname')\n shell(:n => k, :c => 'hostname -f')\n end\n nil\n end", "def configure_hosts!(hosts)\n @hosts_queue = Queue.new\n Array(hosts).each do |host|\n @hosts_queue.push(host)\n end\n end", "def get_host_options(cfg_name, &block)\n opts = {}\n rubber_instances.each do |ic|\n env = rubber_cfg.environment.bind(ic.role_names, ic.name)\n cfg_value = env[cfg_name]\n\n if cfg_value\n if cfg_value.is_a?(Hash)\n cfg_value = cfg_value[ic.os_version]\n end\n\n if block\n cfg_value = block.call(cfg_value)\n end\n\n opts[\"hostvar_#{ic.full_name}\"] = cfg_value if cfg_value && cfg_value.strip.size > 0\n end\n end\n return opts\n end", "def hosts\n @model.config['hosts'].map { |row|\n row.merge(@model.cpus[row['name']]).merge({\n openssl: @model.versions[row['name']],\n })\n }\n end", "def configure_remote_hostname\n system_name = @hostname.split(/^(\\w*)\\.*./)[1]\n @remote.name = system_name if @remote.name != system_name\n @remote.fqdn = @hostname if @remote.fqdn != @hostname\n end", "def parse_hosts\n entries = config.scan(\n /^logging(?:\\svrf\\s([^\\s]+))?\\shost\\s([^\\s]+)\\s(\\d+)\n \\sprotocol\\s([^\\s]+)/x\n )\n hosts = []\n entries.each do |vrf, address, port, proto|\n hosts << { address: address,\n vrf: vrf.nil? ? 'default' : vrf,\n port: port,\n protocol: proto }\n end\n { hosts: hosts }\n end", "def configure\n connect!\n get_configurable_node_hostnames\n upload_chef_assets\n super\n end", "def build_hosts_list(env_vms)\n\n int_id = 10\n\n first = true\n env_vms.each do |vm, vmconfig|\n vmconfig[\"networks\"].each do |name, netcfg|\n if netcfg[\"type\"] == \"private\" then\n if netcfg['ip'].nil? then\n netcfg['ip'] = \"192.168.50.\" + int_id.to_s\n #add the default IP to the environment definnition\n env_vms[vm][\"networks\"][name][\"ip\"] = \"192.168.50.\" + int_id.to_s\n int_id += 1\n end\n if first then\n $base_vars = \"vms_hosts={\"\n $base_vars << \"\\\"#{netcfg['ip']}\\\":\\\"#{vm}\\\"\"\n first = false\n elsif\n $base_vars << \",\\\"#{netcfg['ip']}\\\":\\\"#{vm}\\\"\"\n end\n end\n end if vmconfig[\"networks\"]\n end\n $base_vars << \"}\" if $base_vars\nend", "def ssh_configs\n configs = []\n configs << project_git_config if project_git_config.host\n configs << database_git_config if database_git_config.host\n configs.concat @standalone_ssh_configs\n configs.compact\n end", "def configure *xs, &blk\n Nyara::Config.configure *xs, &blk\nend", "def host_config\n { 'Binds' => @binds,\n 'Privileged' => @privileged,\n 'NetworkMode' => @networkmode.to_s }\n end", "def getSlaveConfigs(nodename)\n return getResourceList(nodename, '^\\/etc\\/bind\\/conf\\.d\\/.*\\.conf$')\nend", "def configure(&block)\n @configure_blocks ||= []\n @configure_blocks << block\n end", "def ssh_config\n identities = [self.users.map(&:identity), self.node.identity].flatten.compact.uniq\n\n output = <<-EOF\n#{ZTK::Template.do_not_edit_notice(:message => %(TestLab \"#{self.id}\" SSH Configuration))}\nHost #{self.id}\n HostName #{self.ip}\n Port 22\n UserKnownHostsFile /dev/null\n StrictHostKeyChecking no\n PasswordAuthentication no\n ForwardAgent no\n IdentitiesOnly yes\nEOF\n\n identities.each do |identity|\n output += \" IdentityFile #{identity}\\n\"\n end\n\n output\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an image tag for a Google Maps image with the GPS polyline of the activity.
def polyline_image(polyline, size = 150, color = "blue") image_tag(polyline_map_url(polyline, size, color), alt: "Activity map") end
[ "def map_image location, width=500, height=275, zoom=15\n image_tag(\"http://maps.googleapis.com/maps/api/staticmap?center=#{location.latitude},#{location.longitude}&zoom=#{zoom}&size=#{width}x#{height}&markers=color:blue%7Clabel:1%7C#{location.latitude},#{location.longitude}&sensor=false\", :class => \"map_image\")\n end", "def get_google_map_image_link(latitude, longitude)\n return \"http://maps.google.com/maps/api/staticmap?size=450x300&sensor=false&zoom=16&markers=#{latitude}%2C#{longitude}\"\n end", "def gmaps4rails_marker_picture\n {\n \"picture\" => \"/images/marker.png\",\n \"width\" => 24,\n \"height\" => 24,\n \"marker_anchor\" => [24,24]\n }\n end", "def simple_map_image\n \"image_path(#{simple_map_url})\"\n end", "def img_tag(width, height, options = {})\n map_type = value['type']\n\n if value['latitude'].present? and value['longitude'].present?\n if map_type == MAP_TYPE_GOOGLE\n zoom_if_any = value['zoom'].present? ? \"&zoom=#{value['zoom']}\" : nil\n marker_size_if_any = options[:marker_size] ? \"|size:#{options[:marker_size]}\" : nil\n\n url = %Q(\n http://maps.googleapis.com/maps/api/staticmap?\n language=ru&\n size=#{width}x#{height}&\n maptype=roadmap&\n markers=color:red#{marker_size_if_any}|\n #{value['latitude']},#{value['longitude']}&\n sensor=false\n #{zoom_if_any}\n ).gsub(/\\s+/, '')\n\n else # yandex\n zoom_if_any = value['zoom'].present? ? \"&z=#{value['zoom']}\" : nil\n marker_size = options[:marker_size] == :large ? 'l' : 'm'\n\n url = %Q(\n http://static-maps.yandex.ru/1.x/?\n l=map&\n size=#{width},#{height}&\n pt=#{value['longitude']},#{value['latitude']},pm2bl#{marker_size}&\n #{zoom_if_any}\n ).gsub(/\\s+/, '')\n end\n %Q(<img src=\"#{url}\" width=\"#{width}\" height=\"#{height}\" />).html_safe\n else\n ''\n end\n end", "def map_image_tag(post_locations, picture_locations, width, height, place = false, country = false)\n \n # Initialise strings\n markers = 'markers='\n center = ''\n post_location_ids = ''\n picture_location_ids = ''\n \n if post_locations\n \n # Add marker declarations to the markers string for each post location\n # Post markers are red, unless the place flag is set\n post_locations.each do |l|\n if l\n if place\n markers += \"#{l.latitude},#{l.longitude},smallyellow|\"\n else\n markers += \"#{l.latitude},#{l.longitude},midred|\"\n end\n \n # Set the center every time, so it ends up being centered on the\n # last marker\n center = \"center=#{l.latitude},#{l.longitude}\"\n \n # Collect the ids of each locations for use when constructing\n # the link to view a bigger map\n post_location_ids << \"#{l.id},\"\n end\n end\n end\n \n # Add marker declarations to the markers string for each picture location\n # Picture markers are white\n if picture_locations\n picture_locations.each do |l|\n if l\n markers += \"#{l.latitude},#{l.longitude},midwhite|\"\n \n # Set the center every time, so it ends up being centered on the\n # last marker\n center = \"center=#{l.latitude},#{l.longitude}\"\n \n # Collect the ids of each locations for use when constructing\n # the link to view a bigger map\n picture_location_ids << \"#{l.id},\"\n end\n end\n end\n \n # Trim the last comma off the comma-delimited strings\n markers = markers[0..-2]\n post_location_ids = post_location_ids[0..-2]\n picture_location_ids = picture_location_ids[0..-2]\n \n # Start map string with declarations for markers, size and api key\n url = \"http://maps.google.com/staticmap?#{markers}&size=#{width}x#{height}&key=#{$GOOGLE_MAPS_API_KEY}\"\n \n # If the country flag is set, do not add a link to the map image\n # If there is only one marker on the map, set a zoom level of 10\n # If there is more than one marker, let the map set its own zoom level\n if (post_locations.length + picture_locations.length == 1 and country)\n url += \"&#{center}&zoom=1\"\n return \"<img src=\\\"#{url}\\\" width=\\\"#{width}\\\" height=\\\"#{height}\\\" alt=\\\"Map of tagged locations!\\\" class=\\\"map\\\"/>\"\n elsif (post_locations.length + picture_locations.length == 1)\n url += \"&#{center}&zoom=10\"\n return \"<a class=\\\"map-link\\\" href=\\\"/map/#{post_location_ids}/#{picture_location_ids}\\\" rel=\\\"shadowbox;player=iframe\\\"><img src=\\\"#{url}\\\" width=\\\"#{width}\\\" height=\\\"#{height}\\\" alt=\\\"Map of tagged locations!\\\" class=\\\"map\\\"/></a>\"\n elsif (post_locations.length + picture_locations.length > 1)\n return \"<a class=\\\"map-link\\\" href=\\\"/map/#{post_location_ids}/#{picture_location_ids}\\\" rel=\\\"shadowbox;player=iframe\\\"><img src=\\\"#{url}\\\" width=\\\"#{width}\\\" height=\\\"#{height}\\\" alt=\\\"Map of tagged locations!\\\" class=\\\"map\\\"/></a>\"\n else\n return ''\n end\n end", "def store_finder_map_image\n $tracer.trace(format_method(__method__))\n return ToolTag.new(@tag.find.div.className(create_ats_regex_string(\"ats-storefindermapimg\")), format_method(__method__))\n end", "def activity_map_url\n url = \"http://maps.google.com/maps/api/staticmap?\"\n parts = []\n\n stops =\n activity.map do |act|\n CGI::escape(act.location.address.to_s)\n end.uniq.reverse\n\n path_parts = []\n path_parts << \"path=color:0x0000ff\"\n path_parts << \"weight:5\"\n stops.each { |addy| path_parts << addy }\n parts << path_parts.join('|')\n\n origin = stops.shift\n last = stops.pop\n\n parts << \"markers=color:red|size:mid|#{origin}\" if origin\n parts << \"markers=color:green|#{last}\"\n\n parts << 'size=512x512'\n parts << 'maptype=roadmap'\n parts << 'sensor=false'\n url += parts.join('&')\n url\n end", "def activity_map_url\n url = \"http://maps.google.com/maps/api/staticmap?\"\n parts = []\n\n stops =\n activity.select do |act|\n act.location.address.city\n end.map do |act|\n CGI::escape(act.location.address.to_s)\n end.uniq.reverse\n\n path_parts = []\n path_parts << \"path=color:0x0000ff\"\n path_parts << \"weight:5\"\n stops.each { |addy| path_parts << addy }\n parts << path_parts.join('|')\n\n origin = stops.shift\n last = stops.pop\n\n parts << \"markers=color:red|size:mid|#{origin}\" if origin\n parts << \"markers=color:green|#{last}\"\n\n parts << 'size=512x512'\n parts << 'maptype=roadmap'\n parts << 'sensor=false'\n url += parts.join('&')\n url\n end", "def get_img_url_by_point(width,height)\n self.set_defaults\n return 'No latitude or longitude set for location' unless self.latitude && self.longitude\n # Build request URL\n params = \"#{self.map_type}/#{self.latitude},#{self.longitude}/#{self.zoom_level}\"\n params += \"?mapSize=#{width},#{height}&pushpin=#{self.latitude},#{self.longitude}\"\n params += \"&mapLayer=TrafficFlow\" if self.show_traffic == TRUE \n request_url = $img_base_url+params+\"&key=#{self.api_key}\"\n return request_url\n end", "def marker_img_path_for_grade grade\n image_path(\"#{marker_img_for_grade(grade)}\")\n end", "def get_img_by_point(width,height)\n self.set_defaults\n return 'No latitude or longitude set for location' unless self.latitude && self.longitude\n # Build request URL\n params = \"#{self.map_type}/#{self.latitude},#{self.longitude}/#{self.zoom_level}\"\n params += \"?mapSize=#{width},#{height}&pushpin=#{self.latitude},#{self.longitude}\"\n params += \"&mapLayer=TrafficFlow\" if self.show_traffic == TRUE \n request_url = $img_base_url+params+\"&key=#{self.api_key}\"\n # REST request !\n begin\n tmp = Tempfile.new('map_image.jpeg')\n tmp.write Net::HTTP.get_response(URI.parse(request_url)).body \n return tmp.flush\n rescue\n return FALSE\n end\n end", "def gmaps_endpoints\n coordinates = self.coordinates.sort_by &:time_stamp\n endpoints = [coordinates.first, coordinates.last]\n\n \n count = 0\n hash = Gmaps4rails.build_markers(endpoints) do |coord, marker|\n time = Time.at(coord.time_stamp/1000)\n marker.lat coord.latitude\n marker.lng coord.longitude\n if count == 0\n marker.infowindow \"Start of Trip (#{time.strftime('%r')})\"\n marker.picture({\n :url => \"/assets/car_map.png\",\n :width => 32,\n :height => 35\n })\n else\n marker.infowindow \"End of Trip (#{time.strftime('%r')})\"\n marker.picture({\n :url => \"/assets/stop.png\",\n :width => 32,\n :height => 35\n })\n end\n\n marker.title time.strftime('%r')\n count += 1\n end\n\n hash.to_json\n end", "def map_marker\n=begin\n kita_icon = GIcon.new(:image => \"/images/red-dot.png\",\n :shadow => \"/images/shadow.png\",\n :shadow_size => GSize.new(49,32),\n :icon_anchor => GPoint.new(16,32))\n=end\n GMarker.new([self.lat, self.lng], :title => \"#{self.name}\", :info_window => \"\n <p> <b>#{self.name}</b><br />#{self.street}<br />#{self.country_code}-#{self.zip} #{self.city} </p>\n <p><a href='/kitas/#{self.id}'>Mehr Details...</a></p>\n \")\n end", "def imageURL(x, y, z, layer=@layer)\n \"http://mt1.google.com/vt/lyrs=#{layer}&hl=ru&x=#{x}&s=&y=#{y}&z=#{z.to_s}&apistyle=s.t%3A3%7Cs.e%3Al%7Cp.v%3Aoff\"\n end", "def store_map_locator\n $tracer.trace(__method__)\n return ToolTag.new(a.className(create_ats_regex_string(\"MapPushpinBase\")).find.img, __method__)\n end", "def latitude_for(image_meta)\n image_meta&.gps&.latitude\n end", "def to_g_polyline_api2(polyline_options = {}, options = {})\n klass = if options[:short_class]\n 'GPolyline'\n else\n 'google.maps.Polyline'\n end\n\n poly_opts = if polyline_options[:polyline_options]\n Geos::Helper.camelize_keys(polyline_options[:polyline_options])\n end\n\n args = [\n (polyline_options[:color] ? \"'#{Geos::Helper.escape_javascript(polyline_options[:color])}'\" : 'null'),\n (polyline_options[:weight] || 'null'),\n (polyline_options[:opacity] || 'null'),\n (poly_opts ? poly_opts.to_json : 'null')\n ].join(', ')\n\n \"new #{klass}([#{self.to_g_lat_lng(options).join(', ')}], #{args})\"\n end", "def extract_geolocation\n img_lat = get_exif('GPSLatitude')[0][1].split(', ') rescue nil\n img_lng = get_exif('GPSLongitude')[0][1].split(', ') rescue nil\n lat_ref = get_exif('GPSLatitudeRef')[0][1] rescue nil\n lng_ref = get_exif('GPSLongitudeRef')[0][1] rescue nil\n return unless img_lat && img_lng && lat_ref && lng_ref \n latitude = to_frac(img_lat[0]) + (to_frac(img_lat[1])/60) + (to_frac(img_lat[2])/3600)\n longitude = to_frac(img_lng[0]) + (to_frac(img_lng[1])/60) + (to_frac(img_lng[2])/3600) \n latitude = latitude * -1 if lat_ref == 'S' # (N is +, S is -)\n longitude = longitude * -1 if lng_ref == 'W' # (W is -, E is +) \n self.latitude = latitude\n self.longitude = longitude\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Detect the player in a specific direction
def detect_player(nb_pas, direction) return false if $game_switches[Yuki::Sw::Env_Detection] c = $game_map.events[@event_id] dx = $game_player.x - c.x dy = $game_player.y - c.y case direction when :right, 6 return (dy == 0 && dx >= 0 && dx <= nb_pas) when :down, 2 return (dx == 0 && dy >= 0 && dy <= nb_pas) when :left, 4 return (dy == 0 && dx <= 0 && dx >= -nb_pas) else return (dx == 0 && dy <= 0 && dy >= -nb_pas) end end
[ "def turn_toward_player\n # get pixel movement rate\n pix = BlizzABS.pixel\n # calculates differences in x and y\n dx, dy = @x - ($game_player.x+pix/2)/pix, @y - ($game_player.y+pix*3/4)/pix\n # determines where to turn according to the x and y differences\n if dx < 0 && dx.abs >= dy.abs # player is right\n turn_right\n elsif dx > 0 && dx.abs >= dy.abs # player is left\n turn_left\n elsif dy < 0 # player is down\n turn_down\n elsif dy > 0 # player is up\n turn_up\n end\n end", "def decideDirection()\n if @@invaderDirection == :right\n if !insideScreen(@speed)\n @@invaderDirection = :left\n end\n\n elsif @@invaderDirection == :left\n if !insideScreen(@speed)\n @@invaderDirection = :right\n end \n end\n end", "def turn_away_from_player\n # get pixel movement rate\n pix = BlizzABS.pixel\n # calculates differences in x and y\n dx, dy = @x - ($game_player.x+pix/2)/pix, @y - ($game_player.y+pix*3/4)/pix\n # determines where to turn according to the x and y differences\n if dx < 0 && dx.abs >= dy.abs # player is right\n turn_left\n elsif dx > 0 && dx.abs >= dy.abs # player is left\n turn_right\n elsif dy < 0 # player is down\n turn_up\n elsif dy > 0 # player is up\n turn_down\n end\n end", "def attacking_direction\n mouse_x, mouse_y = @game_state.camera[0] + $window.mouse_x, @game_state.camera[1] + $window.mouse_y\n \n distance_from_x = (mouse_x - mid_point_x).abs\n distance_from_y = (mouse_y - mid_point_y).abs\n \n if distance_from_x > distance_from_y\n if mouse_x > mid_point_x\n :right\n else mouse_x < mid_point_x\n :left\n end\n else\n if mouse_y > mid_point_y\n :down\n else mouse_y < mid_point_y\n :up\n end\n end\n end", "def turn_toward_player(is_player = true)\n # is it the player\n if is_player\n # calculates differences in x and y\n dx, dy = @x - $game_player.x, @y - $game_player.y\n # or only his remembered position\n else\n # calculates differences in x and y\n dx = @AI_data.find_x > 0 ? @x - @AI_data.find_x : 0\n dy = @AI_data.find_y > 0 ? @y - @AI_data.find_y : 0\n end\n # determines where to turn according to the x and y differences\n if dx < 0 && dx.abs >= dy.abs # player is right\n turn_right\n elsif dx > 0 && dx.abs >= dy.abs # player is left\n turn_left\n elsif dy < 0 # player is down\n turn_down\n elsif dy > 0 # player is up\n turn_up\n end\n end", "def pbEventCanReachPlayer?(event, player, distance)\r\n return false if !pbEventFacesPlayer?(event, player, distance)\r\n delta_x = (event.direction == 6) ? 1 : (event.direction == 4) ? -1 : 0\r\n delta_y = (event.direction == 2) ? 1 : (event.direction == 8) ? -1 : 0\r\n case event.direction\r\n when 2 # Down\r\n real_distance = player.y - event.y - 1\r\n when 4 # Left\r\n real_distance = event.x - player.x - 1\r\n when 6 # Right\r\n real_distance = player.x - event.x - event.width\r\n when 8 # Up\r\n real_distance = event.y - event.height - player.y\r\n end\r\n if real_distance > 0\r\n real_distance.times do |i|\r\n return false if !event.can_move_from_coordinate?(event.x + i * delta_x, event.y + i * delta_y, event.direction)\r\n end\r\n end\r\n return true\r\nend", "def face_battler_direction\n relative_x = @battler.actual_x - @battler.target_x\n relative_y = @battler.actual_y - @battler.target_y \n if relative_y.abs > relative_x.abs and Battle_Style > 1\n @battler.direction = @battler.returning? ? (relative_y < 0 ? 8 : 2) : (relative_y < 0 ? 2 : 8) \n elsif relative_x.abs >= relative_y.abs\n @battler.direction = @battler.returning? ? (relative_x < 0 ? 4 : 6) : (relative_x < 0 ? 6 : 4)\n end\n end", "def move_toward_player\n # get pixel movement rate\n pix = BlizzABS.pixel\n # calculates differences in x and y\n dx, dy = @x - ($game_player.x+pix/2)/pix, @y - ($game_player.y+pix*3/4)/pix\n # determines where to move according to the x and y differences\n if dx > 0 && dy > 0 # player is up left\n move_left if !move_upper_left && !move_up\n elsif dx > 0 && dy < 0 # player is down left\n move_left if !move_lower_left && !move_down\n elsif dx < 0 && dy > 0 # player is up right\n move_right if !move_upper_right && !move_up\n elsif dx < 0 && dy < 0 # player is down right\n move_right if !move_lower_right && !move_down\n elsif dx < 0 && dy == 0 # player is right\n move_right\n elsif dx > 0 && dy == 0 # player is left\n move_left\n elsif dx == 0 && dy < 0 # player is down\n move_down\n elsif dx == 0 && dy > 0 # player is up\n move_up\n end\n end", "def find_room_in_direction direction\n\t\tfind_room_in_dungeon(@player.location).connections[direction]\n\tend", "def currenDirection\n @track.points[-2].bearingTo(point:@track.points[-1])\n end", "def find_room_in_direction(direction)\n\t\tfind_room_in_dungeon(@player.location).connections[direction]\n\tend", "def direction_after_turn(left_or_right)\n modifier = 1\n modifier = -1 if left_or_right == :left\n\n DIRECTIONS[(DIRECTIONS.index(@facing) + modifier) % 4]\n end", "def pointing_north?\n self.direction == 'n'\n end", "def letter_direction\n just_walk_forward = sign_in_direction(direction)\n return direction unless finished?(just_walk_forward)\n crossroads_direction\n end", "def turn_toward_target\n # get pixel movement rate\n pix = BlizzABS.pixel\n # calculate the differences\n dx, dy = @real_x*pix/128-@x, @real_y*pix/128-@y\n # check the differences\n if dx < 0 && dx.abs >= dy.abs # target is right\n turn_right\n elsif dx > 0 && dx.abs >= dy.abs # target is left\n turn_left\n elsif dy < 0 # target is down\n turn_down\n elsif dy > 0 # target is up\n turn_up\n end\n end", "def travel dir\r\n $client.send action: ?m,\r\n pos: @pos+dir.to_vector2,\r\n speed: @speed\r\n end", "def move(dir)\n return case dir\n when 1 then player.move_lower_left\n when 2 then player.move_down\n when 3 then player.move_lower_right\n when 4 then player.move_left\n when 6 then player.move_right\n when 7 then player.move_upper_left\n when 8 then player.move_up\n when 9 then player.move_upper_right\n end\n end", "def move(dir)\n return case (player.restriction == 3 ? 10 - dir : dir)\n when 1 then player.move_lower_left\n when 2 then player.move_down\n when 3 then player.move_lower_right\n when 4 then player.move_left\n when 6 then player.move_right\n when 7 then player.move_upper_left\n when 8 then player.move_up\n when 9 then player.move_upper_right\n end\n end", "def track_direction\n @track_direction ||=\n begin\n edge_a, edge_b = normalized_edges\n\n if (edge_a - edge_b).abs == 3\n :straight\n elsif edge_a > edge_b\n :right\n elsif edge_a < edge_b\n :left\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Detect the player in a rectangle around the event
def detect_player_rect(nx, ny) return false if $game_switches[Yuki::Sw::Env_Detection] c = $game_map.events[@event_id] dx = ($game_player.x - c.x).abs dy = ($game_player.y - c.y).abs return (dx <= nx && dy <= ny) end
[ "def pbEventFacesPlayer?(event, player, distance)\r\n return false if !event || !player || distance <= 0\r\n x_min = x_max = y_min = y_max = -1\r\n case event.direction\r\n when 2 # Down\r\n x_min = event.x\r\n x_max = event.x + event.width - 1\r\n y_min = event.y + 1\r\n y_max = event.y + distance\r\n when 4 # Left\r\n x_min = event.x - distance\r\n x_max = event.x - 1\r\n y_min = event.y - event.height + 1\r\n y_max = event.y\r\n when 6 # Right\r\n x_min = event.x + event.width\r\n x_max = event.x + event.width - 1 + distance\r\n y_min = event.y - event.height + 1\r\n y_max = event.y\r\n when 8 # Up\r\n x_min = event.x\r\n x_max = event.x + event.width - 1\r\n y_min = event.y - event.height + 1 - distance\r\n y_max = event.y - event.height\r\n else\r\n return false\r\n end\r\n return player.x >= x_min && player.x <= x_max &&\r\n player.y >= y_min && player.y <= y_max\r\nend", "def release_from_event? event\n (event.win_x-@radius)**2 + (event.win_y-@radius)**2 < @radius**2 &&\n (event.win_x-@radius)**2 + (event.win_y-@radius)**2 > (@radius*0.75)**2\n end", "def insideScreen(delta)\n if $playerMove == :right\n (@x + @image.width + delta) < $windowW\n \n elsif $playerMove == :left\n (@x - delta) > 0\n end\n end", "def check_collide_with_own_size?(x,y)\n $game_map.events_xy_nt(x, y).any? do |event|\n event != self\n end\n end", "def check_diving_trigger_here\n if !@__bridge &&\n !$game_temp.message_window_showing &&\n $game_player.surfing? &&\n $game_map.system_tag_here?($game_player.x, $game_player.y, ::GameData::SystemTags::TUnderWater)\n $game_temp.common_event_id = Game_CommonEvent::DIVE\n end\n end", "def inside_game_area?(object) \r\n object.x >= @game_area.x && object.x <= @game_area.width &&\r\n object.y >= @game_area.x && object.y <= @game_area.height\r\n end", "def touch?(player=@player)\n if (player.getCollisionMask.intersects_with?(getCollisionMask)) and player.status == :alive\n player.touched\n true\n else\n false\n end\n end", "def check_event_trigger_at(x, y)\n # get pixel movement rate\n pix = $BlizzABS.pixel\n # if player touched this event and not jumping and not over_trigger\n if !jumping? && !over_trigger? && $BlizzABS.util.rect_intersection(\n Rect.new(@x * pix, @y * pix, pix, pix), Rect.new(x, y, pix, pix))\n # start\n start\n # started\n return true\n end\n # not started\n return false\n end", "def check_event_trigger_at(x, y)\n # get pixel movement rate\n pix = $BlizzABS.pixel\n # if player touched this event and not jumping and not over_trigger\n if !jumping? && !over_trigger? && $BlizzABS.util.rect_intersection(\n Rect.new(@x, @y, pix, pix), Rect.new(x, y, pix, pix))\n # start\n start\n # started\n return true\n end\n # not started\n return false\n end", "def check_event_trigger_touch(x, y)\n BlizzABS.player.check_event_trigger_touch(x, y) if BlizzABS.player.player == self\n end", "def pbEventCanReachPlayer?(event, player, distance)\r\n return false if !pbEventFacesPlayer?(event, player, distance)\r\n delta_x = (event.direction == 6) ? 1 : (event.direction == 4) ? -1 : 0\r\n delta_y = (event.direction == 2) ? 1 : (event.direction == 8) ? -1 : 0\r\n case event.direction\r\n when 2 # Down\r\n real_distance = player.y - event.y - 1\r\n when 4 # Left\r\n real_distance = event.x - player.x - 1\r\n when 6 # Right\r\n real_distance = player.x - event.x - event.width\r\n when 8 # Up\r\n real_distance = event.y - event.height - player.y\r\n end\r\n if real_distance > 0\r\n real_distance.times do |i|\r\n return false if !event.can_move_from_coordinate?(event.x + i * delta_x, event.y + i * delta_y, event.direction)\r\n end\r\n end\r\n return true\r\nend", "def inside?(rect)\n position.inside?(rect)\n end", "def check_event_trigger_touch(x, y)\n $BlizzABS.player.check_event_trigger_touch(x, y) if self == $game_player\n end", "def target_from_event event\n cp = captive_positions(self.trap.captives.length, 0, 0, @radius)\n r_squared = @radius**2/9\n self.trap.captives.each_with_index do |c,i|\n if (cp[i].x - event.win_x)**2 + (cp[i].y - event.win_y)**2 < r_squared\n return c\n end\n end\n nil\n end", "def inside(player)\n acttions.each { |action| action.inside(player) }\n end", "def inside?(mouse_x, mouse_y)\n pos_x = @x * @width\n pos_y = @y * @height\n mouse_x >= pos_x && mouse_x <= pos_x + @width && \\\n mouse_y >= pos_y && mouse_y <= pos_y + @height\n end", "def should_turn()\n\t\tx = snake_head.rect.x\n\t\ty = snake_head.rect.y\n\t\tlambda {|rect| if x == rect.x and y == rect.y then true else false end}\t\t\n\tend", "def checkVictory\n if @player.x > @exitDoor.x - @exitDoor.width / 2 and @player.x < @exitDoor.x + @exitDoor.width / 2 and @player.y >\n @exitDoor.y - @exitDoor.height / 2 and @player.y < @exitDoor.y + @exitDoor.height / 2\n winGame\n end\n end", "def event_check(x, y, d, self_event = nil)\n # get pixel movement rate and set bit\n pix, bit = $BlizzABS.pixel, (1 << (d / 2 - 1)) & 0x0F\n # iterate trough all events except self\n (self.events_only - [self_event]).each {|event|\n # if there's an event that's not through and has a graphic\n if event.character_name != \"\" && event.x == x / pix && \n event.y == y / pix && !event.through &&\n (!self_event.is_a?(Map_Battler) || event.tile_id >= 384)\n # if obstacle bit is set\n if @passages[event.tile_id] & bit != 0\n # get x and y of next tile\n case d\n when 2 then nx, ny = x / pix, (y + 1) / pix\n when 4 then nx, ny = (x - 1) / pix, y / pix\n when 6 then nx, ny = (x + 1) / pix, y / pix\n when 8 then nx, ny = x / pix, (y - 1) / pix\n else\n nx = ny = nil\n end\n # impassable if not on the same tile anymore\n return false if x / pix != nx || y / pix != ny\n # if obstacle bit is set in all directions\n elsif @passages[event.tile_id] & 0x0F == 0x0F\n # impassable in the given direction\n return false\n # if priority is 0\n elsif @priorities[event.tile_id] == 0\n # passable in the given direction\n return true\n # if event is not a tile and not through\n elsif !event.through\n # impassable in any direction\n return false\n end\n end}\n # passable\n return true\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete the current event forever
def delete_this_event_forever $env.set_event_delete_state(@event_id) $game_map.events[@event_id]&.erase end
[ "def delete_event ev\n @@game.events.delete ev\n @@game.current_state.events.delete ev\n end", "def gcdelete_event\n cal_event = Event.find_by(gamecall_tag: self.id)\n cal_event.destroy if cal_event\n end", "def delete\n MoxiworksPlatform::Event.delete(self.to_hash)\n end", "def free\n bro_event_free(@ev)\n end", "def garbage_event(event)\n log(:garbage_event, droby_id, event)\n remove_free_event(event)\n end", "def on_delete_event\n\t\tif @event\n\t\t\t@room.events.delete(@event)\n\t\t\t\n\t\t\tannounce(:event_remove_succ, @event.id)\n\t\tend\n\t\t\n\t\t@event = nil\n\t\t\n\t\tcancel\n\tend", "def clear_event(event)\n @events.delete(event)\n end", "def purge\n i = 0\n debug \"Purge events on GCal... \"\n g_cal.events_all.each do |e|\n next if e.status == 'cancelled'\n debug \"Delete: #{e}\"\n e.delete\n i += 1\n end\n debug \"Done. #{i} event(s) deleted.\"\n i\n end", "def purge\n i = 0\n debug 'Purge events on GCal... '\n g_cal.events_all.each do |e|\n next if e.status == 'cancelled'\n debug \"Delete: #{e}\"\n e.delete\n i += 1\n end\n debug \"Done. #{i} event(s) deleted.\"\n i\n end", "def remove_event(event); end", "def clear!\n event_store.clear\n end", "def delete\n @calendar.delete_event(self)\n @id = nil\n end", "def future_single_events_cleanup\n self.single_events.rule_based_in_future.each do |single_event|\n single_event.delete unless schedule.occurs_at? single_event.occurrence\n end\n end", "def future_single_events_cleanup\n self.single_events.rule_based_in_future.each do |single_event|\n single_event.delete unless schedule.occurs_at?(single_event.occurrence)\n end\n end", "def clear_events\n @events.clear\n end", "def clear_gevent\r\n @num_of_suspend = 0\r\n @proc_queue.clear\r\n end", "def quit_on_delete!\n on_delete do\n quit\n end\n end", "def clear_eventable_id\n self.eventable_id = nil\n end", "def entryEvicted(event)\n @engine.destroy_client(event.key)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wait for the end of the movement of this particular character
def wait_character_move_completion(event_id = @event_id) @move_route_waiting = true @move_route_waiting_id = event_id end
[ "def wait_for_player\n wait_character_move_completion 0\n end", "def movement_end_anim\n if @update_base_position\n @battler.base_x = @battler.actual_x\n @battler.base_y = @battler.actual_y\n @update_base_position = false\n end\n @battler.initial_x = @battler.actual_x\n @battler.initial_y = @battler.actual_y\n movement_anim(@battler.returning? ? 'Return_End' : 'Advance_End')\n @battler.mirage = false\n @move_pose = false\n @move_set = false\n @can_move = false\n end", "def wait_until_cursor_at(row, column)\n x_send_no_rsp \"MoveCursor(#{row-1},#{column-1})\"\n end", "def action_movement_end\n pos = action_postions\n target = @target_battlers[0]\n return if pos.nil? or target.nil?\n dir = @direction\n @target_x = @actual_x + (dir == 2 ? pos[3] : dir == 4 ? - pos[2] : dir == 6 ? pos[2] : pos[3])\n @target_y = @actual_y + (dir == 2 ? pos[2] : dir == 4 ? pos[3] : dir == 6 ? pos[3] : - pos[2])\n @move_speed = pos[4]\n end", "def move_to_end\n @cursor = @text.length # put cursor outside of text\n end", "def cursor_move_to_end\n @cursor_position = @text.scan(/./m).size\n self.reset_cursor_blinking\n end", "def move_away_from_char(char)\n move_away_from_xy(char.x, char.y)\n end", "def pose_delay_end(battler)\n return battler.pose_wait <= 0\n end", "def trigger_character; end", "def wait_internal\n Graphics.update\n Input.update\n if Input.triggerex?(0x43) && Input.triggerex?(0x11) # CTRL + C\n raise ConsoleInterrupt\n end\n end", "def get_move\n while true\n board.display_board(cursor.position)\n puts\n chr = cursor.update_position\n break if chr == \"\\r\" || chr == \"\\d\" || chr == 'q'\n end\n\n raise \"User quit game\" if chr == 'q'\n chr\n end", "def wait()\n go_to_termination(false)\n end", "def idle\n\n t = GLUT.Get(GLUT::ELAPSED_TIME)\n\n if t - @lastMove > 10\n @lastMove = t \n GLUT.PostRedisplay()\n move\n end\n\n end", "def end?\n @cursor == @text.length\n end", "def wait_until_cursor_at(row, column)\n platform.wait_until_cursor_at(row, column)\n end", "def input_wait(timeout)\r\n time_left = timeout * 60\r\n \r\n start = Time.new.to_f\r\n while time_left > 0 do\r\n return :rock if Input.press?(:VK_A)\r\n return :scissors if Input.press?(:VK_S)\r\n return :paper if Input.press?(:VK_D) \r\n time_left -= 1\r\n wait(1)\r\n end\r\n \r\n return nil\r\nend", "def get_good_move\n loop do\n\t\t @player_move = self.get_player_move\n break if @current_state[@player_move].nil?\n puts \"That position is taken. Try another.\"\n end\n @player_move\n end", "def end?\n @cursor == @text.length\n end", "def stucked?\n # Get the data\n route = @character.path\n route_index = @character.move_route_index\n x = @character.x\n y = @character.y\n z = @character.z\n b = @character.__bridge\n\n # Iterate commands to the last one, which is Lentgh - 2 (considering the empty command at end)\n route[route_index..[route.length - 2, route_index + OBSTACLE_DETECTION_RANGE - 1].min]&.each do |command|\n return true unless @cursor.sim_move?(x, y, z, command.code, b)\n\n x = @cursor.x\n y = @cursor.y\n z = @cursor.z\n b = @cursor.__bridge\n end\n return false\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
URL slug creation logic The steps are roughly as follows 1. If the record hasn't passed its validations, exit immediately 2. If the source_column is empty, exit immediately (no error is thrown this should be checked with your own validation) 3. If the slug is already set we have nothing to do, otherwise a. Strip out punctuation b. Replace unusable characters with dashes c. Clean up any doubled up dashes d. Check if the slug is unique and, if not, append a number until it is e. Save the URL slug
def create_slug return if self.errors.size > 0 return if self[source_column].blank? if self[slug_column].to_s.empty? proposed_slug = self[source_column].to_slug suffix = "" existing = true acts_as_slugable_class.transaction do while existing != nil # look for records with the same url slug and increment a counter until we find a unique slug existing = acts_as_slugable_class. where(slug_column => proposed_slug + suffix). where(slug_scope_condition).first if existing suffix = suffix.empty? ? "-0" : suffix.succ end end end # end of transaction self[slug_column] = proposed_slug + suffix end end
[ "def create_slug\r\n return if self.errors.length > 0\r\n \r\n if self[source_column].nil? or self[source_column].empty?\r\n return\r\n end\r\n\r\n if self[slug_column].to_s.empty? \r\n #remove accents\r\n proposed_slug = self[source_column].parameterize.to_s\r\n \r\n suffix = nil\r\n existing = true\r\n \r\n acts_as_slugable_class.transaction do\r\n while existing != nil\r\n # look for records with the same url slug and increment a counter until we find a unique slug\r\n existing = acts_as_slugable_class.find(:first, :conditions => [\"#{slug_column} = ? and #{slug_scope_condition}\", proposed_slug + (suffix.nil? ? '' : \"-#{suffix}\")])\r\n if existing\r\n suffix ||= 1\r\n suffix += 1\r\n end\r\n end\r\n end # end of transaction\r\n self[slug_column] = proposed_slug + (suffix.nil? ? '' : \"-#{suffix}\")\r\n end\r\n end", "def create_slug\r\n # Use the attribute\r\n source_col = self.send(source_column.to_sym)\r\n \r\n return if self.errors.length > 0 || source_col.blank?\r\n \r\n proposed_slug = Multiup::Acts::Sluggable.escape(source_col)\r\n \r\n suffix = \"\"\r\n existing = true\r\n acts_as_sluggable_class.transaction do\r\n while existing != nil\r\n # look for records with the same url slug and increment a counter until we find a unique slug\r\n existing = acts_as_sluggable_class.find(:first, :conditions => [\"id != ? AND #{slug_column} = ? AND #{slug_scope_condition}\", self.id, proposed_slug + suffix])\r\n if existing\r\n if suffix.empty?\r\n suffix = \"-0\"\r\n else\r\n suffix.succ!\r\n end\r\n end\r\n end\r\n end # end of transaction \r\n self[slug_column] = proposed_slug + suffix\r\n end", "def slug_management\n if self.slug.blank?\n if self.class.slug_source_field_name.blank?\n self.get_slug_source\n end\n self.slug= self.send(self.class.slug_source_field_name)\n end #slug.blank\n self.fix_duplicated_slug\n end", "def prepare_slug\n if new_record? && slug.blank?\n @reassemble_slug_after_create = true\n super(\"#{name.to_s.strip}-#{SecureRandom.uuid}\")\n else\n super(\"#{name.to_s.strip}-#{id}\")\n end\n end", "def before_save\n if !new? && (title = fields[title_field_name])\n set_slug_from_title(title)\n end\n fix_generated_slug_conflicts if changed_columns.include?(:slug)\n super\n end", "def build_slug(record, subject_column)\n if subject_column.is_a?(Proc)\n slug = subject_column.call(record)\n else\n slug = record[subject_column]\n end\n slug.try(:parameterize) || '-'\n end", "def generate_slug\n slug_value = self.class.slug_value_for(send(self.slug_source))\n if slug_value.present?\n scope = self.class.other_than(self).slug_scope_relation(self).where(:shop_id => self.shop_id)\n slug_value = Slugged.next_value(scope, slug_value)\n write_attribute self.cached_slug_column, slug_value\n elsif self.default_uuid_slug\n write_attribute self.cached_slug_column, Slugged.generate_uuid_slug\n else\n write_attribute self.cached_slug_column, nil\n end\n end", "def create_slug\n return if self.title.blank?\n tail, int = \"\", 1\n initial = convert_to_slug(self.title)\n while Post.find_by_slug(initial + tail) do \n int += 1\n tail = \"-#{int}\"\n end\n self.slug = initial + tail\n end", "def slug_needs_update?\n slug.blank? || (word_slug? and send(\"#{source_column}_changed?\") and base_slug != slug.gsub(/\\-[0-9]+$/,''))\n end", "def _update_slug\n if self.class._friendly_use_key == :database\n current_slug = self.to_param\n unless _slug_exists?(current_slug)\n self.slug = current_slug\n else\n self.slug = [current_slug.to_s, SecureRandom.hex(6)].join(\"-\")\n end\n end\n end", "def create_slug\n if subject.present? && slug.blank?\n self.slug = subject.parameterize\n self.slug = truncate(slug, omission: '', length: Rails.configuration.discussion_slug_length, separator: ' ')\n end\n # Ensure uniqueness of slug; this could probably be less ugly!\n while Post.where(\"slug=? and id<>coalesce(?,-1)\", slug, id).any?\n self.slug += ('-' + rand(0..100).to_s)\n end\n end", "def _create_slug\n fresh_slug = self.class._friendly_attribute_list.map do |attribute|\n _lookup_key(self.class.send(\"_friendly_#{attribute.to_s}_key\")).to_s\n end.\n join(\"-\").\n gsub(/<\\/?[^>]*>|[^\\.\\w\\s-]/, '').\n strip.downcase.gsub(/\\s{1,}|\\./, '-').\n gsub(/-{2,}/, \"-\")\n\n fresh_slug[-1] == \"-\" ? fresh_slug[0...-1] : fresh_slug\n end", "def slug_column; end", "def before_save\n unless new?\n if (title = self.fields[title_field])\n set_slug_from_title(title)\n end\n end\n fix_generated_slug_conflicts\n super\n end", "def make_slug\n self.permalink = (self.permalink.downcase.gsub(/[^a-zA-Z 0-9]/, \"\")).gsub(/\\s/,'-') if self.permalink\n end", "def create_slug\n if !self.name.nil? && !self.date.nil?\n slug = self.name.parameterize\n # look for other slugs with the same name\n s = Event.where(slug: self.slug)\n if !s.nil?\n slug = slug + \"-\" + self.date.strftime(\"%Y\") + \"-\" + self.date.strftime(\"%m\") + \"-\" + self.date.strftime(\"%d\")\n end\n end\n self.slug = slug\n end", "def generate_slug\n if self.slug.blank? || self.slug.nil?\n unless self.name.blank?\n if Clinic.where(slug: name.parameterize).count != 0\n n = 1\n while Clinic.where(slug: \"#{name.parameterize}-#{n}\").count != 0\n n+= 1\n end\n self.slug = \"#{name.parameterize}-#{n}\"\n else\n self.slug = name.parameterize\n end\n else\n self.slug = 'no-name-entered'.parameterize\n end\n end\n end", "def slug_column=(_arg0); end", "def generate_slug\n if self.slug.blank? || self.slug.nil?\n unless self.name.blank?\n if Department.in_clinic(self).where(slug: name.parameterize).count != 0\n n = 1\n while Department.where(slug: \"#{name.parameterize}-#{n}\").count != 0\n n+= 1\n end\n self.slug = \"#{name.parameterize}-#{n}\"\n else\n self.slug = name.parameterize\n end\n else\n self.slug = 'no-name-entered'.parameterize\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is the constructor for the Paper class. All dimension parameters to this method are in twips. ==== Parameters name:: The name for the paper object. width:: The width of the paper in portrait mode. height:: The height of the paper in portrait mode.
def initialize(name, width, height) @name = name @width = width @height = height end
[ "def initialize (name, height = 10)\n @name = name\n @height = height\n end", "def initialize(width = 0, height = 0)\n @width = width\n @height = height\n end", "def initialize\n @paper = Paper::A4\n @left_margin = DEFAULT_LEFT_MARGIN\n @right_margin = DEFAULT_RIGHT_MARGIN\n @top_margin = DEFAULT_TOP_MARGIN\n @bottom_margin = DEFAULT_BOTTOM_MARGIN\n @gutter = nil\n @orientation = PORTRAIT\n end", "def initialize (h, w)\n\t\t@height = h\n\t\t@width = w\n\t\t@rovers = []\n\tend", "def initialize(name, height, species)\n @name = name\n @height = height\n @species = species\n end", "def initialize(paper=:A4, options={})\n \n @options=DEFAULT_OPTIONS.merge(options)\n @paper=paper \n end", "def initialize(height: nil, width: nil, figsize_unit: :cm)\n super(0, 0)\n @title = ''\n @nrows = 1\n @ncols = 1\n @width = (width || DEFAULT_CANVAS_DIM).to_f\n @height = (height || DEFAULT_CANVAS_DIM).to_f\n @top_spacing = 5\n @bottom_spacing = 5\n @left_spacing = 5\n @right_spacing = 5\n @subplots = nil\n @figsize_unit = figsize_unit\n set_rubyplot_artist_coords!\n setup_default_theme\n add_subplots! @nrows, @ncols\n end", "def paper_width; 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 set_paper(paper_size = 0)\n @paper_size = paper_size\n end", "def initialize(width, height)\n @width, @height = width, height\n @chars = Array.new(height) { Array.new(width, \" \") }\n end", "def make_painting(title, width, height)\n # **QUIZ** What is self in this line?\n Painting.new(title, width, height, self)\n end", "def setSize(width, height)\n setWidth(width)\n setHeight(height)\n end", "def size=(width, height)\n end", "def initialize(x, y, w, h)\n @win = newwin(h, w, y, x)\n @width = w\n @height = h\n end", "def initialize(name)\n fail(ArgumentError, 'Outputter expects a name') if name.nil?\n @name = name\n end", "def initialize(name)\n super()\n\n @name = name\n build_document\n build_root\n end", "def initialize(name, age = 0, weight = rand(60..100), height = rand(150..200), eye_color = nil, hair_color = nil)\n\t\t@name = name\n\t\t@age = age\n\t\t@weight = weight\n\t\t@height = height\n\tend", "def initialize(x, y, w, h)\n @x = x; @y = y; @w = w; @h = h\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
assert("RustRegexpcasefold?", '15.2.15.7.6') do assert_false RustRegexp.new("(https?://[^/]+)[azAZ09./]+", RustRegexp::MULTILINE).casefold? assert_true RustRegexp.new("(https?://[^/]+)[azAZ09./]+", RustRegexp::IGNORECASE | RustRegexp::EXTENDED).casefold? assert_true RustRegexp.new("(https?://[^/]+)[azAZ09./]+", RustRegexp::MULTILINE | RustRegexp::IGNORECASE).casefold? assert_false RustRegexp.new("(https?://[^/]+)[azAZ09./]+").casefold? assert_true RustRegexp.new("(https?://[^/]+)[azAZ09./]+", true).casefold? end
def test_match reg = RustRegexp.new("(https?://[^/]+)[-a-zA-Z0-9./]+") assert_false reg.match("http://masamitsu-murase.12345/hoge.html").nil? assert_nil reg.match("http:///masamitsu-murase.12345/hoge.html") end
[ "def prefer_for_regular_expression_match; end", "def casefold?\n end", "def casefold?() end", "def test_match_nocase\r\n\t\t#content with exact match\r\n\t\tcontent = \"first line.\\nthis string contains a case insensitive match on: MyMatch123\"\r\n\t\tsnort_rule_content = SnortRuleContent.new\r\n\t\tsnort_rule_content.unescaped_string = \"mymatch123\"\r\n\t\tsnort_rule_content.nocase = true\r\n\t\tmatch = snort_rule_content.match(content,0)\r\n\t\tassert_equal(62, match,\"no case insensitive match on content.\")\r\n\tend", "def regex_verify_case_statement\n /(?:.*;)?\\s*case\\s*(?:#+.*\\s*)*(?:\\s:*\\w+(?:\\(:?.*\\))?\\s|'(?:[^']?(?:\\\\')?)*'|\"(?:[^\"]?(?:\\\\\")?)*\")\\s*(?:#+.*\\s*)*\\s*when\\s*(?:#+.*\\s*)*(?:\\s:*\\w+(?:\\(:?.*\\))?\\s|'(?:[^']?(?:\\\\')?)*'|\"(?:[^\"]?(?:\\\\\")?)*\")/\nend", "def case_sensitive?\n !@regexp.casefold?\n end", "def case_insensitive_match; end", "def test_exclusion_match\r\n\t\tcontent = \"first line.\\nthis string contains a case sensitive match on: MyMatch123\"\r\n\t\tsnort_rule_content = SnortRuleContent.new\r\n\t\tsnort_rule_content.not_modifier = true\r\n\t\tsnort_rule_content.unescaped_string = \"MyMatch123\"\r\n\t\tsnort_rule_content.nocase = false\r\n\t\tassert(!snort_rule_content.match(content,0),\"incorrect case sensitive exclusion match on content.\")\r\n\tend", "def test_exclusion_match_nocase\r\n\t\tcontent = \"first line.\\nthis string does not contain a case sensitive match on: MyMatch123\"\r\n\t\tsnort_rule_content = SnortRuleContent.new\r\n\t\tsnort_rule_content.not_modifier = true\r\n\t\tsnort_rule_content.unescaped_string = \"mymatch123\"\r\n\t\tsnort_rule_content.nocase = false\r\n\t\tmatch = snort_rule_content.match(content,0)\r\n\t\tassert_equal(0, match,\"case sensitive exclusion match on content didnt fire.\")\t\r\n\tend", "def test_match_case_sensitive_depth_no_match\r\n\t\t#content with exact match\r\n\t\tcontent = \"123MyMatch and some more\"\r\n\t\tsnort_rule_content = SnortRuleContent.new\r\n\t\tsnort_rule_content.unescaped_string = \"MyMatch\"\r\n\t\tsnort_rule_content.depth = 9\r\n\t\tsnort_rule_content.nocase = false\r\n\t\tassert(!snort_rule_content.match(content,0),\"incorrect match on content with depth.\")\r\n\tend", "def regex_verify_case_when\n /case\\s*(?:\\s:*\\w+(?:\\(:?.*\\))?\\s|'(?:[^']?(?:\\\\')?)*'|\"(?:[^\"]?(?:\\\\\")?)*\")\\s*when/\nend", "def test_exclusion_match_nocase_no_match\r\n\t\tcontent = \"first line.\\nthis string does not contain a case insensitive match on: MyMatch123\"\r\n\t\tsnort_rule_content = SnortRuleContent.new\r\n\t\tsnort_rule_content.not_modifier = true\r\n\t\tsnort_rule_content.unescaped_string = \"some other string\"\r\n\t\tsnort_rule_content.nocase = true\r\n\t\tmatch = snort_rule_content.match(content,0)\r\n\t\tassert_equal(0, match,\"nocase exclusion match on content didnt fire.\")\t\r\n\tend", "def test_match_case_sensitive_depth\r\n\t\t#content with exact match\r\n\t\tcontent = \"123MyMatch and some more\"\r\n\t\tsnort_rule_content = SnortRuleContent.new\r\n\t\tsnort_rule_content.unescaped_string = \"MyMatch\"\r\n\t\tsnort_rule_content.depth = 10\r\n\t\tsnort_rule_content.nocase = false\r\n\t\tmatch = snort_rule_content.match(content,0)\r\n\t\tassert_equal(3, match,\"no match on content with depth.\")\r\n\tend", "def test_exclusion_match_nocase\r\n\t\tcontent = \"first line.\\nthis string contains a case insensitive match on: MyMatch123\"\r\n\t\tsnort_rule_content = SnortRuleContent.new\r\n\t\tsnort_rule_content.not_modifier = true\r\n\t\tsnort_rule_content.unescaped_string = \"mymatch123\"\r\n\t\tsnort_rule_content.nocase = true\r\n\t\tassert(!snort_rule_content.match(content,0),\"incorrect nocase exclusion match on content.\")\r\n\tend", "def spec\n string_match_operator\n string_element_reference_regexp\n string_byteslice\n string_scan\n string_unary_minus\n string_reverse\n string_tr\n\n true\nend", "def test_case_2\n terms = @gh.all_words.with_word_length(6).begins_with('e', 'a').does_not_contain('y', 'i')\n assert(terms.all? { |term| term.size == 6 && term.match(/\\A[ea][^iy]{5}\\z/) })\n end", "def test_extended_patterns_no_flags\n [\n [ \".*\", \"abcd\\nefg\", \"abcd\" ],\n [ \"^a.\", \"abcd\\naefg\", \"ab\" ],\n [ \"^a.\", \"bacd\\naefg\", \"ae\" ],\n [ \".$\", \"bacd\\naefg\", \"d\" ]\n ].each do |reg, str, result|\n m = RustRegexp.new(reg).match(str)\n puts m.inspect\n unless m.nil?\n assert_equal result, m[0]\n end\n end\n end", "def test_match_case_sensitive_within\r\n\t\t#content with exact match\r\n\t\tcontent = \"123MyMatch123MyMatch\"\r\n\t\tsnort_rule_content = SnortRuleContent.new\r\n\t\tsnort_rule_content.unescaped_string = \"MyMatch\"\r\n\t\tsnort_rule_content.within = 10\r\n\t\tsnort_rule_content.nocase = false\r\n\t\tmatch = snort_rule_content.match(content,10)\r\n\t\tassert_equal(13, match,\"no match on content with within.\") #13 pos of second MyMatch\r\n\tend", "def test_match_case_sensitive_offset_no_match\r\n\t\t#content with exact match\r\n\t\tcontent = \"123MyMatch and some more\"\r\n\t\tsnort_rule_content = SnortRuleContent.new\r\n\t\tsnort_rule_content.unescaped_string = \"MyMatch\"\r\n\t\tsnort_rule_content.offset = 4\r\n\t\tsnort_rule_content.nocase = false\r\n\t\tassert(!snort_rule_content.match(content,0),\"incorrect match on content with offset.\")\r\n\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
if RustRegexp.const_defined? :ASCII_RANGE assert('RustRegexpoptions (no options)') do assert_equal RustRegexp::ASCII_RANGE | RustRegexp::POSIX_BRACKET_ALL_RANGE | RustRegexp::WORD_BOUND_ALL_RANGE, OnigRegexp.new(".").options end assert('RustRegexpoptions (multiline)') do assert_equal RustRegexp::MULTILINE | RustRegexp::ASCII_RANGE | RustRegexp::POSIX_BRACKET_ALL_RANGE | OnigRegexp::WORD_BOUND_ALL_RANGE, OnigRegexp.new(".", OnigRegexp::MULTILINE).options end end
def test_extended_patterns_no_flags [ [ ".*", "abcd\nefg", "abcd" ], [ "^a.", "abcd\naefg", "ab" ], [ "^a.", "bacd\naefg", "ae" ], [ ".$", "bacd\naefg", "d" ] ].each do |reg, str, result| m = RustRegexp.new(reg).match(str) puts m.inspect unless m.nil? assert_equal result, m[0] end end end
[ "def prefer_for_regular_expression_match; end", "def valid_regex; end", "def test_regexp\n# (find-node \"(emacs-ja)Regexps\")\n \n conv = lambda{|from,to| assert_equal(to, el4r_conv_regexp(from)) }\n conv[ //, '' ]\n conv[ /a/, 'a' ]\n conv[ /a./, 'a.' ]\n conv[ /a*/, 'a*' ]\n conv[ /a+/, 'a+' ]\n conv[ /a?/, 'a?' ]\n conv[ /[ab]/, '[ab]' ]\n conv[ /[^ab]/, '[^ab]' ]\n conv[ /^ab/, '^ab' ]\n conv[ /ab$/, 'ab$' ]\n conv[ /a|b/, 'a\\|b' ]\n conv[ /(ab)/, '\\(ab\\)' ]\n conv[ /\\As/, '\\`s' ]\n conv[ /s\\Z/, %q[s\\'] ]\n # \\=\n conv[ /\\bball\\B/, '\\bball\\B']\n # \\<\n # \\>\n conv[ /\\w/, '[0-9A-Za-z_]']\n conv[ /\\W/, '[^0-9A-Za-z_]']\n # \\sC\n # \\SC\n # \\D (number)\n end", "def macro_regex(opts={})\n opts = { unicode: true, tokens: true, emoticons: true }.merge(opts)\n unicode_regex if opts[:unicode]\n token_regex if opts[:tokens]\n emoticon_regex if opts[:emoticons]\n pattern = []\n\n if opts[:emoticons] && opts[:unicode]\n pattern << \"(?:#{ @emoticon_pattern })\"\n pattern << @unicode_pattern\n else\n pattern << @emoticon_pattern if opts[:emoticons]\n pattern << @unicode_pattern if opts[:unicode]\n end\n\n pattern = pattern.any? ? \"(#{ pattern.join('|') })\" : \"\"\n\n if opts[:tokens]\n if pattern.empty?\n pattern = @token_pattern\n else\n pattern = \"(?:#{ @token_pattern })|#{ pattern }\"\n end\n end\n\n Regexp.new(pattern)\n end", "def extract_regexp_options args\n\t\t\treturn 0 if args.nil?\n\t\t\traise ArgumentError unless args.kind_of? String\n\t\t\toptions_map = {\n\t\t\t\t'i' => Regexp::IGNORECASE,\n\t\t\t\t'm' => Regexp::MULTILINE,\n\t\t\t\t'x' => Regexp::EXTENDED,\n\t\t\t}\n\t\t\toptions = 0\n\t\t\targs.each { |char|\n\t\t\t\toptions |= options_map[char] || 0\n\t\t\t}\n\t\t\treturn options\n\t\tend", "def allow_matcher; end", "def invalid_regexp_chars\n @invalid_regexp_chars ||= TwitterCldr::Utils::RangeSet.new(\n [2..7, 55296..57343]\n )\n end", "def regexp\n /\\A#{(options[:with].to_s.each_char.collect { |char| character_map[char] || \"\\\\#{char}\" }).join}\\z/\n end", "def each_match_range(range, regex); end", "def option_regex\n options.option_regex || OPTION_REGEX\n end", "def ==(other)\n other.is_a?(RegexpRange) && other.state == state\n end", "def check_for_range_expression(expr)\r\n skip_white_space\r\n if [RDoc::RubyToken::TkDOT2,RDoc::RubyToken::TkDOT3].include?(@tk.class)\r\n range_expr = RangeExpression.new(expr.line_no,expr.char_no,'')\r\n range_expr.low = expr\r\n get_tk\r\n range_expr.high = parse_expression\r\n return range_expr\r\n else\r\n return expr\r\n end\r\n end", "def valid_ruby_range?\n !(empty? || exclude_begin? || (STARTLESS_RANGE_NOT_SUPPORTED && !self.begin) || (ENDLESS_RANGE_NOT_SUPPORTED && !self.end))\n end", "def character_range?( rule_spec )\n return false unless string_pattern?(rule_spec)\n return Grammar.node_has_type?(rule_spec.expression.string_pattern, \"character_set\")\n end", "def is_range?\n self =~ /\\A(([\\d]+)|(['\"][\\w]{1}['\"]))\\.\\.\\.?(([\\d]+)|(['\"][\\w]{1}['\"]))\\z/i\n end", "def spec\n string_match_operator\n string_element_reference_regexp\n string_byteslice\n string_scan\n string_unary_minus\n string_reverse\n string_tr\n\n true\nend", "def match_range(range, match); end", "def lex_en_regexp_modifiers; end", "def regexp_source; end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /requests/1 DELETE /requests/1.json
def destroy @request.destroy respond_to do |format| format.html { redirect_to requests_url } format.json { head :no_content } end end
[ "def delete\n RestClient.delete \"#{@uri}/api/requests/request/#{@data['requestId']||@data['id']}\"\n puts ' Deleted request: '.red + \"#{@data['requestId']||@data['id']}\".light_blue\n end", "def destroy\n @request = Request.find(params[:id])\n @request.destroy\n\n respond_to do |format|\n format.html { redirect_to requests_url }\n format.json { head :ok }\n end\n end", "def delete_request\n client.create_request('DELETE', url_path)\n end", "def destroy\n @req = Req.find(params[:id])\n @req.destroy\n\n respond_to do |format|\n format.html { redirect_to reqs_url }\n format.json { head :no_content }\n end\n end", "def delete(path, params={}); make_request(:delete, host, port, path, params); end", "def delete endpoint\n do_request :delete, endpoint\n end", "def destroy\n @request.destroy\n respond_to do |format|\n format.html { redirect_to admin_requests_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @recuest = Recuest.find(params[:id])\n @recuest.destroy\n\n respond_to do |format|\n format.html { redirect_to requests_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @request = Request.find(params[:id])\n @request.destroy\n\n respond_to do |format|\n format.html { redirect_to(requests_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @http_request.destroy\n respond_to do |format|\n format.html { redirect_to http_requests_url }\n format.json { head :no_content }\n end\n end", "def delete_requests\n self.requests.each {|request| request.destroy}\n end", "def destroy\n @sub_request = SubRequest.find(params[:id])\n @sub_request.destroy\n\n respond_to do |format|\n format.html { redirect_to sub_requests_url }\n format.json { head :ok }\n end\n end", "def destroy\n @req.destroy\n respond_to do |format|\n flash[:notice] = \"Req was successfully destroyed.\"\n format.html { redirect_to reqs_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @request_status = RequestStatus.find(params[:id])\n @request_status.destroy\n\n respond_to do |format|\n format.html { redirect_to request_statuses_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @user_request = UserRequest.find(params[:id])\n @user_request.destroy\n\n respond_to do |format|\n format.html { redirect_to user_requests_url }\n format.json { head :no_content }\n end\n end", "def delete_request(item, request)\n option_hash = {accept: :json, cookies: @maint_cookie}\n begin\n res = @api[\"items/#{item[\"id\"]}/requests/#{request[\"id\"]}\"].delete option_hash\n rescue => e\n @logger&.error \"delete_request => exception #{e.class.name} : #{e.message}\"\n if (ej = JSON.parse(e.response)) && (eje = ej[\"errors\"])\n eje.each do |k, v|\n @logger&.error \"#{k}: #{v.first}\"\n end\n end\n return nil\n end\n res\n end", "def destroy\n @request_info.destroy\n respond_to do |format|\n format.html { redirect_to request_infos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @sa_request.destroy\n respond_to do |format|\n format.html { redirect_to sa_requests_url, notice: 'Sa request was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @oc_request.destroy\n respond_to do |format|\n format.html { redirect_to oc_requests_url, notice: 'Oc request was successfully destroyed.' }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return current user instance, used for authorization. This method can be redefined in ApplicationController if you want to use application's auth system. ex: class ApplicationController < ActionController::Base def current_puffer_user current_user end end In this case returner user model instance should respond to has_role? method, or you should properly redefine +has_puffer_access?+ See +has_puffer_access?+ source and docs.
def current_puffer_user @current_puffer_user ||= begin super rescue NoMethodError ::Admin::SessionsController.model.to_adapter.get(session[:puffer_user_id]) end end
[ "def current_user\n model = Bolt::Config.user_model_class\n @current_user ||= (logged_in? ? model.find(session[:user_id]) : model.new)\n end", "def current_user\n return @current_user\n end", "def current_user\n return @current_user if @current_user\n\n token = request.headers['X-Auth-Token'].presence || params[:token].presence\n return nil if token.blank?\n @current_user ||= User.find_by_api_token(token)\n end", "def current_user\n if browserid_email.nil?\n nil\n elsif @current_user\n @current_user\n else\n config = browserid_config\n user_model = config.user_model.constantize\n find_method = \"find_by_#{config.email_field}\".intern\n\n @current_user = user_model.send find_method, browserid_email\n end\n end", "def current_alchemy_user\n raise NoCurrentUserFoundError if !defined?(current_user)\n current_user\n end", "def current_user\n begin\n unless @current_user.is_a?(User)\n @current_user = if session[:sage_user]\n user = user_for_cas_user(session[:sage_user], session[:cas_extra_attributes])\n if user\n api_token.set_current_user(user) if api_token?\n # set session[:sage_user] to sage_username of the found user. This allows\n # login with email. Could also be done at the rubycas_client level, but\n # dual login is somewhat sage-specific\n session[:sage_user] = user.sage_username\n end\n\n user.nil? ? :false : user\n elsif self.web_service_user\n self.web_service_user\n elsif session[:web_service_user]\n User.find_by_sage_username(session[:web_service_user])\n else\n :false\n end\n end\n rescue Exception => e\n RAILS_DEFAULT_LOGGER.warn \"exception getting current user:\\n#{e.inspect}\"\n RAILS_DEFAULT_LOGGER.debug e.backtrace.join(\"\\n\")\n @current_user = :false\n end\n return @current_user\n end", "def user\r\n return for_context(nil, false) { |c| c.user }\r\n end", "def current_alchemy_user\n current_user_method = Alchemy.current_user_method\n raise NoCurrentUserFoundError if !respond_to?(current_user_method, true)\n\n send current_user_method\n end", "def current_user\n @current_user ||= CurrentUser.includes(:roles).find_by(email: id_token[:email])\n end", "def current_user\n begin\n @current_user ||= Outpost.user_class\n .where(can_login: true).find(session[:user_id])\n rescue ActiveRecord::RecordNotFound\n session[:user_id] = nil\n @current_user = nil\n end\n end", "def current_user\n if logged_in?\n return User.get(session['user'])\n end\n AnonymousUser.new\n end", "def user_for_rate_limiter\n return nil unless respond_to?(:current_user)\n\n current_user\n end", "def get_user\n if @options[:user]\n @options[:user]\n elsif @options[:get_user_method]\n send( @options[:get_user_method] )\n elsif self.respond_to? :current_user\n current_user\n elsif not @options[:allow_guests]\n raise( CannotObtainUserObject, \"Couldn't find #current_user or @user, and nothing appropriate found in hash\" )\n end\n end", "def current_user\n @current_user ||= ::User.send(\"find_by_#{self.identifier_attribute}!\", session[identifier_name])\n rescue ActiveRecord::RecordNotFound\n nil\n end", "def current_user\n authentication.account\n end", "def user\n @user ||= Interface::User.new(self)\n end", "def get_current_user\n User.find_by_id(session[:user_id])\n end", "def current_user_model\n @current_user_model ||= (login_from_session || login_from_basic_auth || login_from_cookie || :false)\n end", "def get_current_user\n user = nil\n token = nil\n if params[:id]\n user = User.find_by_id(params[:id])\n elsif params[:email]\n user = User.find_by_email(params[:email])\n elsif params[:auth_token]\n token = UserAuthorizationToken.find_by_token(params[:auth_token])\n if token\n user = token.user\n end\n else\n token = UserAuthorizationToken.find_by_token(session[:session_token])\n if token\n user = token.user\n end\n end\n user\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Execute record creation based in quantity input
def execute_customer_record_create(qty) puts "Starting to create Customer records... Please give the API time to respond...\n" qty.times do |t| body = FakeCustomer.new.generate # puts JSON.pretty_generate(JSON.parse(body.to_json)) FakeRestActions.new(endpoint: "Customers", body: body, access_token: @access_token).post_request end end
[ "def add_units(qty)\n qty.to_i.times do\n #create item\n item = supply_items.new\n item.status = SupplyItem::STATUS_AVAILABLE\n item.save\n end\n end", "def create(name, price, description, quantity)\n @products.exec(\"INSERT INTO acme_shop (name, price, description, quantity) VALUES ('#{name}','#{price}','#{description}','#{quantity}');\")\n print \"You created #{name} (#{id}), #{description}, that costs $#{price}\"\nend", "def create\n load_object\n variant = Variant.find(params[:purchase_line_item][:variant_id])\n\n before :create\n\n @purchase_order.add_variant(variant, params[:purchase_line_item][:qty].to_i)\n\n if @purchase_order.save\n after :create\n set_flash :create\n response_for :create\n else\n after :create_fails\n set_flash :create_fails\n response_for :create_fails\n end\n\n end", "def create\n load_object\n variant = Variant.find(params[:line_item][:variant_id])\n\n before :create\n\n @order.add_variant(variant, params[:line_item][:quantity].to_i)\n\n if @order.save\n after :create\n set_flash :create\n response_for :create\n else\n after :create_fails\n set_flash :create_fails\n response_for :create_fails\n end\n\n end", "def test_create_item_with_quantity\n me = Trader.named(\"Me\", :credits => 100)\n you = Trader.named(\"You\", :credits => 100)\n (my_item = me.propose_item_with_quantity(\"One\", 7, 1, :fixed, nil, nil)).activate\n (your_item = you.propose_item_with_quantity(\"Four\", 11, 4, :fixed, nil, nil)).activate\n\n assert_equal(me.items, [my_item])\n assert(my_item.quantity == 1)\n assert_equal(you.items, [your_item])\n assert(your_item.quantity == 4)\n end", "def new_quantity args={}\n SY::Quantity.new args.merge( composition: self )\n end", "def create_fake_order()\n \n \n if product.inventory_ordered.nil?\n product.inventory_ordered = InventoryOrdered.new(:quant_dvd => 0)\n product.inventory_ordered.save\n end\n \n product.inventory_ordered.quant_dvd = 1\n orderdate = Date.today - 7\n product.save\n vol = VendorOrderLog.find(:all, :conditions => \"product_id = #{product.product_id} AND orderDate = '#{orderdate}' AND quant > 0\")[0]\n if (vol.nil?) \n vol = VendorOrderLog.new(:product_id => product.product_id, :orderDate => orderdate, :purchaser_id=> Purchaser.find_by_name_first(\"smartflix\").andand.id) \n end\n # quant is positive, bc the number on order has increased\n vol.quant += 1\n vol.save\n \n \n end", "def assign_stock_entry( item , quantity ) \n # Find the empty stock entry. assign himself\n # if it is not enough, split into multiple stock_entry_usage \n requested_quantity = quantity \n supplied_quantity = 0 \n is_first = true \n while supplied_quantity != requested_quantity\n unfulfilled_quantity = requested_quantity - supplied_quantity \n stock_entry = StockEntry.first_available_stock( item )\n # what if 1 stock entry quantity is not enough?\n # get it from the next stock entry. However, it means that we need to use \n # NEW StockEntryUsage.. recursive call? \n\n # stock_entry.nil? raise error # later.. \n if stock_entry.nil?\n raise ActiveRecord::Rollback, \"Can't be executed. No Item in the stock\" \n end\n\n available_quantity = stock_entry.available_quantity \n\n served_quantity = 0 \n if unfulfilled_quantity <= available_quantity \n served_quantity = unfulfilled_quantity \n else\n served_quantity = available_quantity \n end\n\n stock_entry.update_usage(served_quantity) \n if is_first\n self.stock_entry_id = stock_entry.id \n self.quantity = served_quantity\n self.save\n is_first = false \n else\n StockEntryUsage.create(\n :stock_entry_id => stock_entry.id , \n :quantity => served_quantity, \n :source_document_entry_id => self.source_document_entry_id,\n :source_document_id => self.source_document_id, \n :source_document_entry => self.source_document_entry,\n :source_document => self.source_document,\n :case => self.case \n )\n end\n \n supplied_quantity += served_quantity \n end \n end", "def generate(quantity, options={})\n defaults = {\n :type => :promotion,\n :batch => get_new_batch_code,\n :expires_at => Time.now.utc + 3.months\n }\n options = defaults.merge(options).symbolize_keys\n\n result = []\n quantity.times do \n voucher = new(options)\n if voucher.valid?\n voucher.save\n result << voucher\n end\n end\n result\n end", "def adding_item(db, item, quantity, store)\r\n\r\n db.execute(\"INSERT INTO groceries (item, quantity, store) VALUES (?, ?, ?)\", [item, quantity, store])\r\n\r\nend", "def create\n if !@order\n @order = Order.create(user_id: current_user, state: \"pending\")\n end\n if @order.order_items.find_by(inventory_id: params[:inventory_id]).present?\n set_order_item\n check_order_limit\n @order_item.save\n else\n if params[:qty].nil?\n @order_item = OrderItem.create!(inventory_id: params[:inventory_id], order_id: @order.id, qty: 1)\n else\n @order_item = OrderItem.create!(inventory_id: params[:inventory_id], order_id: @order.id, qty: params[:qty])\n end\n flash[:notice] = \"This item has been saved to your cart\"\n end\n @order.save\n redirect_to request.referrer\n end", "def qubic_create(data)\n pp \"RUN Qlite::qubic_create\"\n body = {command: 'qubic_create', \"execution start\": data[:execution_start], \"runtime limit\": data[:runtime_limit], \"hash period duration\": data[:hash_period_duration], \"result period duration\": data[:result_period_duration], code: data[:code]}\n return send_request(body)\n rescue => e\n puts \"failed #{e}\"\n end", "def create\n qd_params = params[:quality_dimension_field]\n selected_default = qd_params[:selected_default]\n field_notes = qd_params[:field_notes]\n extraction_form_id = qd_params[:extraction_form_id]\n unless selected_default == 'custom'\n QualityDimensionField.generate_legacy_quality_dimensions(extraction_form_id, selected_default)\n else\n title = qd_params[:custom]\n unless title.blank?\n QualityDimensionField.transaction do \n nextnum = QualityDimensionField.where(:extraction_form_id=>extraction_form_id).maximum(:question_number)\n if nextnum.nil?\n QualityDimensionField.assign_initial_qnums(extraction_form_id)\n nextnum = QualityDimensionField.where(:extraction_form_id=>extraction_form_id).maximum(:question_number)\n end\n # In cases where no quality dimension field exists yet, we need to start the counter\n if nextnum.nil?\n nextnum = 0\n end\n nextnum += 1\n QualityDimensionField.create(:title=>title, :field_notes => field_notes, :question_number => nextnum,:extraction_form_id=>extraction_form_id)\n end\n end \n end\n @quality_dimension_fields = QualityDimensionField.where(:extraction_form_id=> extraction_form_id).order(\"question_number ASC\")\n @quality_dimension_field = QualityDimensionField.new\n @extraction_form = ExtractionForm.find(extraction_form_id)\n @project = Project.find(@extraction_form.project_id)\n end", "def create_item_pack_product_code\n puts \"IN RETAIL CREATE IPC\"\n cosmetic_code = \"\"\n if self.label_code == \"U\" \n if self.carton_setup.treatment_code == \"U\"\n cosmetic_code = \"UL\"\n else\n cosmetic_code = \"WX\"\n end\n else\n if self.carton_setup.treatment_code == \"U\"\n cosmetic_code = \"LB\"\n else\n cosmetic_code = \"LW\"\n end\n \n end\n \n \n class_code = self.carton_setup.product_class_code\n puts \"prod sched: \" + self.production_schedule_code\n commodity = RmtSetup.find_by_production_schedule_name(self.production_schedule_code).commodity_code\n grade_code = self.carton_setup.grade_code\n \n std_count = StandardSizeCount.find_by_standard_size_count_value_and_commodity_code_and_basic_pack_code(self.carton_setup.standard_size_count_value,commodity,self.basic_pack_code)\n \n if !std_count\n err = \"An IPC could not be found or created, because no standard_size_count record exists for the following field values: <br>\"\n err += \"standard_size_count_value: \" + self.carton_setup.standard_size_count_value.to_s + \"<br>\"\n err += \"commodity: \" + commodity + \"<br>\"\n err += \"basic_pack_code: \" + self.basic_pack_code\n raise err\n \n end\n actual_count = std_count.actual_count\n \n variety = self.carton_setup.marketing_variety_code\n \n item_pack = ItemPackProduct.find_by_product_class_code_and_commodity_code_and_grade_code_and_actual_count_and_marketing_variety_code_and_cosmetic_code_name_and_size_ref_and_basic_pack_code(class_code,commodity,grade_code,actual_count,variety,cosmetic_code,self.size_ref,self.basic_pack_code)\n \n if ! item_pack\n \n item_pack = ItemPackProduct.new\n item_pack.product_class_code = class_code\n item_pack.commodity_code = commodity\n item_pack.commodity_group_code = std_count.commodity.commodity_group_code\n item_pack.cosmetic_code_name = cosmetic_code\n item_pack.grade_code = grade_code\n item_pack.basic_pack_code = self.basic_pack_code\n \n item_pack.treatment_code = self.carton_setup.treatment_code\n item_pack.treatment = Treatment.find_by_treatment_code_and_treatment_type_code(item_pack.treatment_code,\"PACKHOUSE\")\n item_pack.grade = Grade.find_by_grade_code(grade_code)\n item_pack.standard_size_count = std_count\n item_pack.standard_size_count_value = std_count.standard_size_count_value\n item_pack.marketing_variety_code = variety\n item_pack.actual_count = actual_count\n item_pack.size_ref = self.size_ref\n puts item_pack.size_ref\n item_pack.create\n \n \n end\n \n \n if ! self.new_record?\n old_ri = RetailItemSetup.find(self.id)\n old_ipc = old_ri.item_pack_product_code \n old_mark = old_ri.mark_code\n end\n \n self.item_pack_product = item_pack\n \n \n self.item_pack_product_code = item_pack.item_pack_product_code\n \n if ! self.new_record? && self.carton_setup.fg_setup\n \n if old_ipc != self.item_pack_product_code||old_mark != self.mark_code\n @update_fg = true\n end\n end\n \n end", "def update_creation_stock_mutation\n self.creation_stock_mutation.update_quantity( self.quantity ) \n self.creation_stock_entry_mutation.update_quantity( self.quantity )\n self.update_ready_quantity \n end", "def create\n\t\tputs \"Running allocation_process.create\"\n\t\t# update_allocation_factors\n\t\tcreate_allocation_transaction_reversals\n\t\tadd_allocation_transactions\n\t\tverify_journal_set\n\tend", "def add_quantity(quantity, variant, sub_location, row_hash)\n # if only one sub location listed\n if sub_location.split(\",\").length > 1\n @errors << { :part_number => row_hash[:name], :condition => row_hash[:condition], :message => \"Cannot add initial quantity for part with multiple sub locations (#{sub_location})\" }\n # otherwise if there is a sub_location stock item\n elsif stock_item = variant.sub_location(sub_location)\n #if !(stock_item = @new_product_condition.where(\"sub_location=?\", sub_location)).empty\n stock_item.adjust_count_on_hand(quantity)\n else\n @errors << { :part_number => row_hash[:name], :condition => row_hash[:condition], :message => \"Cannot find stock item for \" + sub_location }\n end\n\n end", "def create\n @sales_order = SalesOrder.find_by_id params[:sales_order_id]\n @item = Item.find_by_id params[:item_id]\n @quantity = params[:sales_entry][:quantity].to_i\n @selling_price_per_piece = BigDecimal( params[:sales_entry][:selling_price_per_piece] )\n \n @has_past_item = @sales_order.has_sales_entry_for_item?(@item) \n \n \n @sales_entry = @sales_order.add_sales_entry_item( @item, \n @quantity, \n @selling_price_per_piece )\n \n @has_no_errors = @sales_entry.errors.messages.length == 0 \n end", "def create_product\n puts \"Enter a name for the product:\"\n name = gets.chomp\n puts \"Enter a category for the product:\"\n category = gets.chomp\n puts \"Enter a price for the product:\"\n price = gets.chomp.to_i\n puts \"In Season? (true/false)\"\n in_season = gets.chomp\n\n\n new_product = Product.create(name: name, category: category, price: price, in_season: in_season)\n i = 0\n while i < Store.all.length do\n StoreProduct.create(store_id: (i+1), product_id: new_product.id)\n i += 1\n end\n\n puts \"Product Created:\"\n puts \"#{new_product.name} - #{new_product.category} - #{new_product.price} - #{new_product.in_season}\"\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /bookings GET /bookings.json
def index @bookings = Booking.all respond_to do |format| format.html format.json { render :json => @bookings } end end
[ "def index\n @bookings = Booking.all\n\n render json: @bookings\n end", "def index\n @bookings = Booking.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @bookings }\n end\n end", "def index\n render json: { bookings: @site.bookings.order(datetime: :asc) }, status: 200\n end", "def list\n @bookings = Booking.all.find(:hotel_id == params[:bookings_for_hotel])\n @bookings = Booking.all.find(:conditions => [\"hotel_id = ? \", params[:bookings_for_hotel]])\n @bookings = Booking.find_by_hotel_id_and_bookings_for_hotel(hotel_id, params[:bookings_for_hotel])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @booking }\n end\n end", "def index\n @service_bookings = ServiceBooking.all\n\n render json: @service_bookings\n end", "def index\n @biddings = Bidding.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @biddings }\n end\n end", "def all_booking_of_client\n\t\t@bookings = Booking.where(client_id: params[:client_id])\n\t\trender json: @bookings, status: 200\n\tend", "def tool_bookings\n @bookings = Booking.where(tool_id: params[:id])\n render json: @bookings, :root => false\n end", "def index\n @billings = Billing.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @billings }\n end\n end", "def index\n @listings = Listing.all\n render json: @listings\n end", "def index\n @listings = Listing.by_user(current_user).all\n\n render json: @listings\n end", "def get_brandings\n request :get,\n '/v3/brandings.json'\n end", "def get_brandings\n request :get, \"/v3/brandings.json\"\n end", "def index\n @listings = Listing.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @listings }\n end\n end", "def index\n @bookings = @hairdresser.bookings\n end", "def all_bookings\n if allow?(:bookings, :edit)\n Booking.includes(:user, :court).ordered.load\n else\n bookings.includes(:court).ordered.load\n end\n end", "def index\n @bookingshowings = Bookingshowing.all\n end", "def booking(booking, options = {})\n get(\"bookings/#{booking}\", options).pop\n end", "def index\n @biblebooks = Biblebook.all\n\n respond_to do |format|\n format.html\n format.json{ render json: @biblebooks, root: false}\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /student_app_cat_regnos GET /student_app_cat_regnos.json
def index @student_app_cat_regnos = StudentAppCatRegno.all end
[ "def index\n @student_app_cat_217127274s = StudentAppCat217127274.all\n end", "def create\n @student_app_cat_regno = StudentAppCatRegno.new(student_app_cat_regno_params)\n\n respond_to do |format|\n if @student_app_cat_regno.save\n format.html { redirect_to @student_app_cat_regno, notice: 'Student app cat regno was successfully created.' }\n format.json { render :show, status: :created, location: @student_app_cat_regno }\n else\n format.html { render :new }\n format.json { render json: @student_app_cat_regno.errors, status: :unprocessable_entity }\n end\n end\n end", "def get_student_attribute_subcategories_of_project\n respond_to do |format|\n format.json {\n @subcategories = Array.new\n param = params[:payload]\n @requirements = ProjectRequirement.where(:project_id => param[:project])\n\n if @requirements\n for req in @requirements\n @subcategory = RequirementSubcategory.find_by_id(req.requirement_subcategory_id)\n if @subcategory.student_attribute\n @subcategories.push(@subcategory)\n end\n end\n render :json => @subcategories\n else\n render :nothing => true, :status => 200, :content_type => 'text/html'\n end\n }\n end\n end", "def index\n # @student_categories = StudentCategory.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @student_categories }\n end\n end", "def get_appcon_categories \n get(\"/appcon.json/categories\")\nend", "def get_all_apps_with_categories \n get(\"/appcon.json/\")\nend", "def course_genders\n authorize :report, :view?\n render json: Application.report_course_genders(params[:id], params[:year].to_i)\n end", "def college_categories\n authorize :report, :view?\n render json: Category.joins(courses: {course_selections: :application})\n .where('courses.college_id': params[:id])\n .where('applications.created_at' => Application.current_year(params[:year].to_i))\n .group('categories.name')\n .order('count_id DESC')\n .limit(10)\n .count('id')\n end", "def index\n @student_genders = StudentGender.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @student_genders }\n end\n end", "def index\n @incidentcategories = Incidentcategory.all\n json_response(@incidentcategories)\n end", "def index\n @student_types = StudentType.all\n\n render json: @student_types\n end", "def show\n @noc_boat_registration = NocBoatRegistration.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json {render json: @noc_boat_registration}\n end\n end", "def get_appcon_categories \n get(\"/appcon.json/categories\")\n end", "def index\n @refagencycategories = Refagencycategory.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @refagencycategories }\n end\n end", "def index\n @registration_requests = RegistrationRequest.all\n\n render json: @registration_requests\n end", "def index\n @nursing_diagnoses = NursingDiagnosis.all\n render json: @nursing_diagnoses\n end", "def new\n # @student_category = StudentCategory.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @student_category }\n end\n end", "def college_genders\n authorize :report, :view?\n render json: Application.report_gender(params[:id], params[:year].to_i)\n end", "def index\n @diagnosis_categories = DiagnosisCategory.all\n render json: @diagnosis_categories\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /student_app_cat_regnos POST /student_app_cat_regnos.json
def create @student_app_cat_regno = StudentAppCatRegno.new(student_app_cat_regno_params) respond_to do |format| if @student_app_cat_regno.save format.html { redirect_to @student_app_cat_regno, notice: 'Student app cat regno was successfully created.' } format.json { render :show, status: :created, location: @student_app_cat_regno } else format.html { render :new } format.json { render json: @student_app_cat_regno.errors, status: :unprocessable_entity } end end end
[ "def index\n @student_app_cat_regnos = StudentAppCatRegno.all\n end", "def create\n @student_app_cat_217127274 = StudentAppCat217127274.new(student_app_cat_217127274_params)\n\n respond_to do |format|\n if @student_app_cat_217127274.save\n format.html { redirect_to @student_app_cat_217127274, notice: 'Student app cat 217127274 was successfully created.' }\n format.json { render :show, status: :created, location: @student_app_cat_217127274 }\n else\n format.html { render :new }\n format.json { render json: @student_app_cat_217127274.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @incidentcategory = Incidentcategory.new(incidentcategory_params)\n\n if @incidentcategory.save\n json_response(@incidentcategory)\n else\n render json: @incidentcategory.errors, status: :unprocessable_entity\n end\n end", "def create\n @catregory = Catregory.new(catregory_params)\n\n respond_to do |format|\n if @catregory.save\n format.html { redirect_to @catregory, notice: 'Catregory was successfully created.' }\n format.json { render :show, status: :created, location: @catregory }\n else\n format.html { render :new }\n format.json { render json: @catregory.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @congress_memory_has_student = CongressMemoryHasStudent.new(congress_memory_has_student_params)\n\n respond_to do |format|\n if @congress_memory_has_student.save\n format.html { redirect_to @congress_memory_has_student, notice: 'Congress memory has student was successfully created.' }\n format.json { render :show, status: :created, location: @congress_memory_has_student }\n else\n format.html { render :new }\n format.json { render json: @congress_memory_has_student.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n # @student_category = StudentCategory.new(params[:student_category])\n\n respond_to do |format|\n if @student_category.save\n format.html { redirect_to @student_category, notice: 'Student category was successfully created.' }\n format.json { render json: @student_category, status: :created, location: @student_category }\n else\n format.html { render action: \"new\" }\n format.json { render json: @student_category.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @perf_review_catg = PerfReviewCatg.new(perf_review_catg_params)\n\n respond_to do |format|\n if @perf_review_catg.save\n format.html { redirect_to perf_review_catgs_url, notice: 'Perf review catg was successfully created.' }\n format.json { render :show, status: :created, location: @perf_review_catg }\n else\n format.html { render :new }\n format.json { render json: @perf_review_catg.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @students_reserved = StudentsReserved.new(students_reserved_params2)\n @reservation = Reservation.find(@students_reserved.reservation_id)\n @carrels = StudyCarrel.find_by_id(@reservation.study_carrel_id)\n respond_to do |format|\n if @students_reserved.save\n format.html { redirect_to home_path, notice: 'Students reserved was successfully created.' }\n format.json { render :show, status: :created, location: @students_reserved }\n else\n format.html { render :new }\n format.json { render json: @students_reserved.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n # @regdetail = Regdetail.new(regdetail_params)\n #\n # respond_to do |format|\n # if @regdetail.save\n # format.html { redirect_to @regdetail, notice: 'Regdetail was successfully created.' }\n # format.json { render :show, status: :created, location: @regdetail }\n # else\n # format.html { render :new }\n # format.json { render json: @regdetail.errors, status: :unprocessable_entity }\n # end\n # end\n end", "def create\n @student_registration = StudentRegistration.new(student_registration_params)\n\n respond_to do |format|\n if @student_registration.save\n format.html { redirect_to @student_registration, notice: 'Student registration was successfully created.' }\n format.json { render :show, status: :created, location: @student_registration }\n else\n format.html { render :new }\n format.json { render json: @student_registration.errors, status: :unprocessable_entity }\n end\n end\n end", "def get_student_attribute_subcategories_of_project\n respond_to do |format|\n format.json {\n @subcategories = Array.new\n param = params[:payload]\n @requirements = ProjectRequirement.where(:project_id => param[:project])\n\n if @requirements\n for req in @requirements\n @subcategory = RequirementSubcategory.find_by_id(req.requirement_subcategory_id)\n if @subcategory.student_attribute\n @subcategories.push(@subcategory)\n end\n end\n render :json => @subcategories\n else\n render :nothing => true, :status => 200, :content_type => 'text/html'\n end\n }\n end\n end", "def destroy\n @student_app_cat_regno.destroy\n respond_to do |format|\n format.html { redirect_to student_app_cat_regnos_url, notice: 'Student app cat regno was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def create\n @catgrade = Catgrade.new(catgrade_params)\n\n respond_to do |format|\n if @catgrade.save\n format.html { redirect_to @catgrade, notice: 'Catgrade was successfully created.' }\n format.json { render action: 'show', status: :created, location: @catgrade }\n else\n format.html { render action: 'new' }\n format.json { render json: @catgrade.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\n #@student_allergy = StudentAllergy.new(params[:student_allergy])\n\n #respond_to do |format|\n # if @student_allergy.save\n # format.html { redirect_to @student_allergy, notice: 'Student allergy was successfully created.' }\n # format.json { render json: @student_allergy, status: :created, location: @student_allergy }\n # else\n # format.html { render action: \"new\" }\n # format.json { render json: @student_allergy.errors, status: :unprocessable_entity }\n # end\n # end\n end", "def create\n @rest_cat = RestCat.new(rest_cat_params)\n\n respond_to do |format|\n if @rest_cat.save\n format.html { redirect_to @rest_cat, notice: 'Rest cat was successfully created.' }\n format.json { render :show, status: :created, location: @rest_cat }\n else\n format.html { render :new }\n format.json { render json: @rest_cat.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @nfi_pregnancy_category = NfiPregnancyCategory.new(nfi_pregnancy_category_params)\n\n respond_to do |format|\n if @nfi_pregnancy_category.save\n format.html { redirect_to @nfi_pregnancy_category, notice: 'Nfi pregnancy category was successfully created.' }\n format.json { render :show, status: :created, location: @nfi_pregnancy_category }\n else\n format.html { render :new }\n format.json { render json: @nfi_pregnancy_category.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @indcat = Indcat.new(indcat_params)\n\n respond_to do |format|\n if @indcat.save\n format.html { redirect_to @indcat, notice: 'Indcat was successfully created.' }\n format.json { render :show, status: :created, location: @indcat }\n else\n format.html { render :new }\n format.json { render json: @indcat.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @reg_course = RegCourse.new(params[:reg_course])\n\n respond_to do |format|\n if @reg_course.save\n format.html { redirect_to @reg_course, notice: 'Reg course was successfully created.' }\n format.json { render json: @reg_course, status: :created, location: @reg_course }\n else\n format.html { render action: \"new\" }\n format.json { render json: @reg_course.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @clase_cat = ClaseCat.new(clase_cat_params)\n\n respond_to do |format|\n if @clase_cat.save\n format.html { redirect_to @clase_cat, notice: 'Clase cat was successfully created.' }\n format.json { render :show, status: :created, location: @clase_cat }\n else\n format.html { render :new }\n format.json { render json: @clase_cat.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /student_app_cat_regnos/1 PATCH/PUT /student_app_cat_regnos/1.json
def update respond_to do |format| if @student_app_cat_regno.update(student_app_cat_regno_params) format.html { redirect_to @student_app_cat_regno, notice: 'Student app cat regno was successfully updated.' } format.json { render :show, status: :ok, location: @student_app_cat_regno } else format.html { render :edit } format.json { render json: @student_app_cat_regno.errors, status: :unprocessable_entity } end end end
[ "def update\n respond_to do |format|\n if @student_app_cat_217127274.update(student_app_cat_217127274_params)\n format.html { redirect_to @student_app_cat_217127274, notice: 'Student app cat 217127274 was successfully updated.' }\n format.json { render :show, status: :ok, location: @student_app_cat_217127274 }\n else\n format.html { render :edit }\n format.json { render json: @student_app_cat_217127274.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @noc_boat_registration = NocBoatRegistration.find(params[:id])\n\n respond_to do |format|\n if @noc_boat_registration.update_attributes(noc_params)\n format.html {redirect_to @noc_boat_registration, notice: 'Noc boat registration was successfully updated.'}\n format.json {head :no_content}\n else\n format.html {render action: \"edit\"}\n format.json {render json: @noc_boat_registration.errors, status: :unprocessable_entity}\n end\n end\n end", "def update\n @cat.update(cat_params)\n render json: @cat\n end", "def update\n respond_to do |format|\n if @rest_cat.update(rest_cat_params)\n format.html { redirect_to @rest_cat, notice: 'Rest cat was successfully updated.' }\n format.json { render :show, status: :ok, location: @rest_cat }\n else\n format.html { render :edit }\n format.json { render json: @rest_cat.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @congress_memory_has_student.update(congress_memory_has_student_params)\n format.html { redirect_to @congress_memory_has_student, notice: 'Congress memory has student was successfully updated.' }\n format.json { render :show, status: :ok, location: @congress_memory_has_student }\n else\n format.html { render :edit }\n format.json { render json: @congress_memory_has_student.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @studentcourse = Studentcourse.find(params[:id])\n if @studentcourse.update_attributes(studentcourse_params)\n render json: @studentcourse\n else\n render 'edit'\n end\n end", "def update\n # @student_category = StudentCategory.find(params[:id])\n\n respond_to do |format|\n if @student_category.update_attributes(params[:student_category])\n format.html { redirect_to @student_category, notice: 'Student category was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @student_category.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @cat_criterio_eval_residencia.update(cat_criterio_eval_residencia_params)\n format.html { redirect_to cat_criterio_eval_residencias_path, notice: 'Cat criterio eval residencia was successfully updated.' }\n format.json { render :show, status: :ok, location: @cat_criterio_eval_residencia }\n else\n format.html { render :edit }\n format.json { render json: @cat_criterio_eval_residencia.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @student_major = StudentMajor.find(params[:id])\n\n respond_to do |format|\n if @student_major.update_attributes(student_major_params)\n format.html { redirect_to @student_major, notice: 'Student major was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @student_major.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n if @student.update(student_params)\n render json: @student\n else\n render json: @student.errors, status: :unprocessable_entity\n end\n end", "def update\n @complaint = Complaint.find(params[:id])\n\n if @complaint.update_attributes(params[:complaint])\n head :no_content\n else\n render json: @complaint.errors, status: :unprocessable_entity\n end\n end", "def update\n cat = Cat.find(params[:id])\n if cat.update(cat_params)\n render json: cat, status: 200\n else\n render json: cat, status: 422\n end\n end", "def update\n respond_to do |format|\n if @catgrade.update(catgrade_params)\n format.html { redirect_to @catgrade, notice: 'Catgrade was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @catgrade.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @socio_carteira_prof.update(socio_carteira_prof_params)\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: @socio_carteira_prof.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @cat = Cat.find(params[:id])\n if @cat.update(cat_params)\n redirect_to cat_url(@cat)\n else\n render json: @cat.errors.full_messages, status: 422 # unprocesable entity\n end\n end", "def update\n respond_to do |format|\n if @cat02.update(cat02_params)\n format.html { redirect_to @cat02, notice: 'Cat02 was successfully updated.' }\n format.json { render :show, status: :ok, location: @cat02 }\n else\n format.html { render :edit }\n format.json { render json: @cat02.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @co_reg_value = CoRegValue.find(params[:id])\n\n respond_to do |format|\n if @co_reg_value.update_attributes(params[:co_reg_value])\n format.html { redirect_to @co_reg_value, notice: 'Co reg value was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @co_reg_value.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n # @student_parent_occupation = StudentParentOccupation.find(params[:id])\n\n respond_to do |format|\n if @student_parent_occupation.update_attributes(params[:student_parent_occupation])\n format.html { redirect_to @student_parent_occupation, notice: 'Student parent occupation was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @student_parent_occupation.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @cat_libri.update(cat_libri_params)\n format.html { redirect_to @cat_libri, notice: 'La categoria è stata modificata con successo.' }\n format.json { render :show, status: :ok, location: @cat_libri }\n else\n format.html { render :edit }\n format.json { render json: @cat_libri.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /student_app_cat_regnos/1 DELETE /student_app_cat_regnos/1.json
def destroy @student_app_cat_regno.destroy respond_to do |format| format.html { redirect_to student_app_cat_regnos_url, notice: 'Student app cat regno was successfully destroyed.' } format.json { head :no_content } end end
[ "def destroy\n @student_app_cat_217127274.destroy\n respond_to do |format|\n format.html { redirect_to student_app_cat_217127274s_url, notice: 'Student app cat 217127274 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @congress_memory_has_student.destroy\n respond_to do |format|\n format.html { redirect_to congress_memory_has_students_url, notice: 'Congress memory has student was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @studentrec = Studentrec.find(params[:id])\n @studentrec.destroy\n\n respond_to do |format|\n format.html { redirect_to studentrecs_url }\n format.json { head :no_content }\n end\n end", "def destroy\n #@incidentcategory.destroy\n render json: {}, status: 200\n end", "def destroy\n @efficacy_master.destroy\n respond_to do |format|\n format.html { redirect_to efficacy_masters_url, notice: DELETE_NOTICE }\n format.json { head :no_content }\n end\n end", "def destroy\n # @student_category = StudentCategory.find(params[:id])\n @student_category.destroy\n\n respond_to do |format|\n format.html { redirect_to student_categories_url }\n format.json { head :ok }\n end\n end", "def datadelete\n\n current_email = current_user.email\n athena_name = current_email[/[^@]+/]\n\n @neo = Neography::Rest.new(ENV['NEO4J_URL'] || \"http://localhost:7474\")\n\n category_name = params[:category]\n\n ret = {:response => \"All good\"}\n\n if category_name == \"living group\" or category_name == \"work\"\n ret = {:response => \"Can't delete living gorup or work categories!\"}\n else\n if params[:name]\n connection_name = params[:name]\n puts \"DELETING CONNECTION TO #{connection_name} IN CATEGORY #{category_name}\"\n @neo.execute_query(\"START n=node(*) MATCH (n)-[r:`#{category_name}`]->(x) WHERE (n.athena ='#{athena_name}' and x.athena='#{connection_name}') DELETE r;\")\n else\n puts \"DELETING CATEGORY #{category_name}\"\n @neo.execute_query(\"START n=node(*) MATCH (n)-[r:`#{category_name}`]->() WHERE n.athena ='#{athena_name}' DELETE r;\")\n end\n end\n \n render :json => ret.to_json\n end", "def destroy\n @student.delete\n respond_to do |format|\n format.html { redirect_to students_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @json.destroy\n\n head :no_content\n end", "def destroy\n @student_entity.destroy\n render json: {msg: 'deleted successfully'}, status: 200\n end", "def destroy\n @student_major = StudentMajor.find(params[:id])\n @student_major.destroy\n\n respond_to do |format|\n format.html { redirect_to student_majors_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @regulation_master.destroy\n respond_to do |format|\n format.html { redirect_to regulation_masters_url, notice: DELETE_NOTICE }\n format.json { head :no_content }\n end\n end", "def destroy\n \t@studentcourse = Studentcourse.find(params[:id])\n @studentcourse.destroy\n render json: {success: \"ok\"}\n end", "def destroy\n @admin_student_major.destroy\n respond_to do |format|\n format.html { redirect_to admin_student_majors_url, notice: 'Student major was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n AccDatum.find(params[:id]).destroy\n respond_to do |format|\n format.html { redirect_to acc_data_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @graduate_student_info = GraduateStudentInfo.find(params[:id])\n @graduate_student_info.destroy\n\n respond_to do |format|\n format.html { redirect_to graduate_student_infos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @refagencycategory = Refagencycategory.find(params[:id])\n @refagencycategory.destroy\n\n respond_to do |format|\n format.html { redirect_to refagencycategories_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @daily_regiman = DailyRegimen.find(params[:id])\n @daily_regiman.destroy\n\n respond_to do |format|\n format.html { redirect_to daily_regimen_index_url }\n format.json { head :no_content }\n end\n end", "def destroy\n # @student_parent_occupation = StudentParentOccupation.find(params[:id])\n @student_parent_occupation.destroy\n\n respond_to do |format|\n format.html { redirect_to student_parent_occupations_url }\n format.json { head :ok }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /promulher_forms GET /promulher_forms.json
def index @promulher_forms = PromulherForm.all end
[ "def retrieve_forms()\n start.uri('/api/form')\n .get()\n .go()\n end", "def index #retirar\n @pergunta_forms = PerguntaForm.all\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @pergunta_forms }\n end\n end", "def index\n\t\t@forms = @client.forms.all\n\n\t\trespond_to do |format|\n \t\tformat.html # index.html.erb\n \t\tformat.json { render json: @forms }\n \tend\n\tend", "def forms\n get(:forms)['Forms'].map do |details|\n Form.new(details['Url'], party: self, details: details)\n end\n end", "def index\n @forms = Form.all\n\n render json: @forms\n end", "def retrieve_form_fields()\n start.uri('/api/form/field')\n .get()\n .go()\n end", "def form\n @form ||= Form.new(get(\"form/#{all['form_id']}\")).use_api(@api)\n end", "def show\n @pergunta_form = PerguntaForm.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @pergunta_form }\n end\n end", "def show\n @pec_form = PecForm.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @pec_form }\n end\n end", "def forms\n @forms ||= fetch_references(parsed_json).fetch('forms', []).map { |form_json| UmmForm.new(form_section_json: fetch_references(form_json), json_form: self, schema: schema, options: options, field_value: object) }\n end", "def index\n @filled_forms = FilledForm.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @filled_forms }\n end\n end", "def get_forms\r\n Form.where(\"opportunity_id = ?\", opportunity_id).all\r\n end", "def form\n @form_hash ||= JSON.parse(form_json)\n end", "def form(id)\n make_json_api_request :get, \"v2/#{account_id}/forms/#{id}\"\n end", "def new\n @formulario = Formulario.new\n\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @formulario }\n end\n end", "def index\n @competitions_pit_forms = CompetitionsPitForm.all\n end", "def index\n @appraisal_forms = AppraisalForm.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @appraisal_forms }\n end\n end", "def index\n @pit_forms = PitForm.all\n end", "def new\n @plataform = Plataform.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @plataform }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /promulher_forms POST /promulher_forms.json
def create @promulher_form = PromulherForm.new(promulher_form_params) respond_to do |format| if @promulher_form.save format.html { redirect_to @promulher_form, notice: 'Promulher form was successfully created.' } format.json { render :show, status: :created, location: @promulher_form } else format.html { render :new } format.json { render json: @promulher_form.errors, status: :unprocessable_entity } end end end
[ "def create_form(form_id, request)\n start.uri('/api/form')\n .url_segment(form_id)\n .body_handler(FusionAuth::JSONBodyHandler.new(request))\n .post()\n .go()\n end", "def create\n @poole_app_form = current_user.poole_app_forms.build(poole_app_form_params)\n\n respond_to do |format|\n if @poole_app_form.save\n format.html { redirect_to @poole_app_form, notice: 'Poole app form was successfully created.' }\n format.json { render :show, status: :created, location: @poole_app_form }\n else\n format.html { render :new }\n format.json { render json: @poole_app_form.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\n\n\n @power_form = PowerForm.new(power_form_params)\n\n\n respond_to do |format|\n if @power_form.save\n format.html { redirect_to @power_form, notice: 'Power form was successfully created.' }\n format.json { render :show, status: :created, location: @power_form }\n\n else\n format.html { render :new }\n format.json { render json: @power_form.errors, status: :unprocessable_entity }\n\n end\n end\n\n end", "def create\n @pform = Pform.new(pform_params)\n\n respond_to do |format|\n if @pform.save\n format.html { redirect_to @pform, notice: 'Pform was successfully created.' }\n format.json { render :show, status: :created, location: @pform }\n else\n format.html { render :new }\n format.json { render json: @pform.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @pergunta_form = PerguntaForm.new(params[:pergunta_form])\n\n respond_to do |format|\n if @pergunta_form.save\n format.html { redirect_to @pergunta_form, notice: 'Pergunta form was successfully created.' }\n format.json { render json: @pergunta_form, status: :created, location: @pergunta_form }\n else\n format.html { render action: \"new\" }\n format.json { render json: @pergunta_form.errors, status: :unprocessable_entity }\n end\n end\n end", "def form\n @form_hash ||= JSON.parse(form_json)\n end", "def create\n @form_parq = current_user.build_form_parq(form_parq_params)\n\n respond_to do |format|\n if @form_parq.save\n format.html { redirect_to @form_parq, notice: 'Formulário de PAR-Q preenchido com sucesso.' }\n format.json { render action: 'show', status: :created, location: @form_parq }\n else\n format.html { render action: 'new' }\n format.json { render json: @form_parq.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @plataform = Plataform.new(params[:plataform])\n\n respond_to do |format|\n if @plataform.save\n format.html { redirect_to @plataform, notice: 'Plataform was successfully created.' }\n format.json { render json: @plataform, status: :created, location: @plataform }\n else\n format.html { render action: \"new\" }\n format.json { render json: @plataform.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @plataform = Plataform.new(plataform_params)\n\n respond_to do |format|\n if @plataform.save\n format.html { redirect_to @plataform, notice: 'Plataform was successfully created.' }\n format.json { render :show, status: :created, location: @plataform }\n else\n format.html { render :new }\n format.json { render json: @plataform.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @formulario = Formulario.new(params[:formulario])\n\n respond_to do |format|\n if @formulario.save\n format.html { redirect_to formularios_path }\n format.json { render json: @formulario, status: :created, location: @formulario }\n else\n format.html { render action: \"new\" }\n format.json { render json: @formulario.errors, status: :unprocessable_entity }\n end\n end\n end", "def form_blueprint_json\n fields_markup.to_json\n end", "def create\n @form_instance = FormInstance.new\n @form_instance.form = Form.find(params[:form_id])\n# @form_instance.respondent = Respondent.find(1)\n \n params[:field].each do |id,value|\n Response.create(:form_field_id => id, :form_instance => @form_instance, :value => value) unless value.blank?\n end\n\n respond_to do |format|\n if @form_instance.save\n if (@form_instance.form.next_form.nil?)\n format.html { redirect_to @form_instance, :notice => 'Form instance was successfully created.' }\n format.json { render :json => @form_instance, :status => :created, :location => @form_instance }\n else\n format.html { redirect_to new_form_form_instance_path(@form_instance.form.next_form), :notice => 'Form instance was successfully created.' }\n end\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @form_instance.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @multistep_form = MultistepForm.new(multistep_form_params)\n\n respond_to do |format|\n if @multistep_form.save\n format.html { redirect_to @multistep_form, notice: 'Multistep form was successfully created.' }\n format.json { render :show, status: :created, location: @multistep_form }\n else\n format.html { render :new }\n format.json { render json: @multistep_form.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @user = current_user\n @appform = @user.appforms.create(params[:appform])\n\n respond_to do |format|\n if @appform.save\n format.html { redirect_to root_url, notice: 'Your application was successfully created.' }\n format.json { render json: @appform, status: :created, location: @appform }\n else\n format.html { render action: \"new\" }\n format.json { render json: @appform.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @filled_form = @filled_forms.new(params[:filled_form], as: :admin)\n @filled_form.save\n respond_with :admin, @form, @filled_form\n end", "def publish_form\n form_data = params.require(:form).permit(:id)\n\n render json: Form.publish_form(form_data[:id], current_user[\"id\"])\n end", "def create\n @formulario = Formulario.new(params[:formulario])\n\n respond_to do |format|\n if @formulario.save\n format.html { redirect_to @formulario, notice: 'Formulario was successfully created.' }\n format.json { render json: @formulario, status: :created, location: @formulario }\n else\n format.html { render action: \"new\" }\n format.json { render json: @formulario.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @plataform = Plataform.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @plataform }\n end\n end", "def create\n @survey_form = SurveyForm.new(survey_form_params)\n @survey_form = current_user.survey_forms.create(survey_form_params)\n \n respond_to do |format|\n if @survey_form.save\n format.html { redirect_to survey_forms_path, notice: 'Survey form was successfully created.' }\n format.json { render :show, status: :created, location: @survey_form }\n else\n format.html { render :new }\n format.json { render json: @survey_form.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /promulher_forms/1 PATCH/PUT /promulher_forms/1.json
def update respond_to do |format| if @promulher_form.update(promulher_form_params) format.html { redirect_to @promulher_form, notice: 'Promulher form was successfully updated.' } format.json { render :show, status: :ok, location: @promulher_form } else format.html { render :edit } format.json { render json: @promulher_form.errors, status: :unprocessable_entity } end end end
[ "def update_form(form_id, request)\n start.uri('/api/form')\n .url_segment(form_id)\n .body_handler(FusionAuth::JSONBodyHandler.new(request))\n .put()\n .go()\n end", "def update\n @formulario = Formulario.find(params[:id])\n\n respond_to do |format|\n if @formulario.update_attributes(params[:formulario])\n format.html { redirect_to formularios_path }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @formulario.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @pec_form = PecForm.find(params[:id])\n\n respond_to do |format|\n if @pec_form.update_attributes(params[:pec_form])\n format.html { redirect_to @pec_form, notice: I18n.t('pec_form.notice.update') }\n format.json { head :ok }\n else\n\t\t\t\tgon.edit_pec_form = true\n\t\t\t\tgon.registration_time = @pec_form.registration_time.strftime('%m/%d/%Y %H:%M') if @pec_form.registration_time\n format.html { render action: \"edit\" }\n format.json { render json: @pec_form.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @pergunta_form = PerguntaForm.find(params[:id])\n\n respond_to do |format|\n if @pergunta_form.update_attributes(params[:pergunta_form])\n format.html { redirect_to @pergunta_form, notice: 'Pergunta form was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @pergunta_form.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @poole_app_form.update(poole_app_form_params)\n format.html { redirect_to @poole_app_form, notice: 'Poole app form was successfully updated.' }\n format.json { render :show, status: :ok, location: @poole_app_form }\n else\n format.html { render :edit }\n format.json { render json: @poole_app_form.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @form1 = Form1.find(params[:id])\n @form1.user_id = current_user.id\n respond_to do |format|\n if @form1.update_attributes(params[:form1])\n format.html { redirect_to @form1, notice: 'Form1 was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @form1.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @plataform = Plataform.find(params[:id])\n\n respond_to do |format|\n if @plataform.update_attributes(params[:plataform])\n format.html { redirect_to @plataform, notice: 'Plataform was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @plataform.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @form1.update(form1_params)\n format.html { redirect_to @form1, notice: 'Form was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @form1.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @formulario = Formulario.find(params[:id])\n\n respond_to do |format|\n if @formulario.update_attributes(params[:formulario])\n format.html { redirect_to @formulario, notice: 'Formulario was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @formulario.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @pform.update(pform_params)\n format.html { redirect_to @pform, notice: 'Pform was successfully updated.' }\n format.json { render :show, status: :ok, location: @pform }\n else\n format.html { render :edit }\n format.json { render json: @pform.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @form = Form.find(params[:id])\n\n respond_to do |format|\n if @form.update_attributes(params[:form])\n format.html { redirect_to @form, notice: 'Form was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @form.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @form_parq.update(form_parq_params)\n format.html { redirect_to @form_parq, notice: 'Form parq was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @form_parq.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @appform = Appform.find(params[:id])\n\n respond_to do |format|\n if @appform.update_attributes(params[:appform])\n format.html { redirect_to root_url, notice: 'Your application was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @appform.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @proforma.update(proforma_params)\n format.html { redirect_to @proforma, notice: 'Proforma generada correctamente.' }\n format.json { render :show, status: :ok, location: @proforma }\n else\n format.html { render :edit }\n format.json { render json: @proforma.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @pelicula = Pelicula.find(params[:id])\n @pelicula.update(update_params)\n render json: @pelicula, status: :ok\n end", "def update\n @form_of_payment = FormOfPayment.find(params[:id])\n\n respond_to do |format|\n if @form_of_payment.update_attributes(params[:form_of_payment])\n format.html { redirect_to @form_of_payment, :notice => 'Form of payment was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @form_of_payment.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @premio = Premio.find(params[:id])\n\n respond_to do |format|\n if @premio.update_attributes(params[:premio])\n format.html { redirect_to @premio, :notice => 'Premio was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @premio.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @filled_form = @filled_forms.find(params[:id])\n\n @filled_form.update_attributes(params[:filled_form], as: :admin)\n respond_with :admin, @form, @filled_form\n end", "def update\n respond_to do |format|\n if @formaenvio.update(formaenvio_params)\n format.html { redirect_to @formaenvio, notice: 'Forma de envio alterado com sucesso.' }\n format.json { render :show, status: :ok, location: @formaenvio }\n else\n format.html { render :edit }\n format.json { render json: @formaenvio.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /promulher_forms/1 DELETE /promulher_forms/1.json
def destroy @promulher_form.destroy respond_to do |format| format.html { redirect_to promulher_forms_url, notice: 'Promulher form was successfully destroyed.' } format.json { head :no_content } end end
[ "def destroy\n @form1.destroy\n respond_to do |format|\n format.html { redirect_to form1s_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @pergunta_form = PerguntaForm.find(params[:id])\n @pergunta_form.destroy\n\n respond_to do |format|\n format.html { redirect_to pergunta_forms_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @form1 = Form1.find(params[:id])\n @form1.destroy\n\n respond_to do |format|\n format.html { redirect_to form1s_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @formulario = Formulario.find(params[:id])\n @formulario.destroy\n\n respond_to do |format|\n format.html { redirect_to formularios_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @formulario = Formulario.find(params[:id])\n @formulario.destroy\n\n respond_to do |format|\n format.html { redirect_to formularios_url }\n format.json { head :ok }\n end\n end", "def destroy\n @formulatio.destroy\n respond_to do |format|\n format.html { redirect_to formulatios_url, notice: 'Formulatio was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete_form(id)\n @client.raw('delete', \"/content/forms/#{id}\")\n end", "def destroy\n @form607.destroy\n respond_to do |format|\n format.html { redirect_to form607s_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @pec_form = PecForm.find(params[:id])\n @pec_form.destroy\n\n respond_to do |format|\n format.html { redirect_to pec_forms_url }\n format.json { head :ok }\n end\n end", "def delete_form(form_id)\n start.uri('/api/form')\n .url_segment(form_id)\n .delete()\n .go()\n end", "def destroy\n @form = Form.find(params[:id])\n @form.destroy\n\n respond_to do |format|\n format.html { redirect_to forms_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @poole_app_form.destroy\n respond_to do |format|\n format.html { redirect_to poole_app_forms_url, notice: 'Poole app form was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @appform = Appform.find(params[:id])\n @appform.destroy\n\n respond_to do |format|\n format.html { redirect_to appforms_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @eolform = Eolform.find(params[:id])\n @eolform.destroy\n\n respond_to do |format|\n format.html { redirect_to eolforms_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @soi_form = SoiForm.find(params[:id])\n @soi_form.destroy\n\n respond_to do |format|\n format.html { redirect_to personal_detail_path }\n format.json { head :no_content }\n end\n end", "def destroy\n @filled_form = FilledForm.find(params[:id])\n @filled_form.destroy\n\n respond_to do |format|\n format.html { redirect_to form_templates_path }\n format.json { head :ok }\n end\n end", "def destroy\n @multistep_form.destroy\n respond_to do |format|\n format.html { redirect_to multistep_forms_url, notice: 'Multistep form was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @covenant_form.destroy\n respond_to do |format|\n format.html { redirect_to covenant_forms_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @sectioneight_form = SectioneightForm.find(params[:id])\n @sectioneight_form.destroy\n\n respond_to do |format|\n format.html { redirect_to sectioneight_forms_url }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /minuts/1 DELETE /minuts/1.json
def destroy @minut.destroy respond_to do |format| format.html { redirect_to minuts_url, notice: 'Minut was successfully destroyed.' } format.json { head :no_content } end end
[ "def destroy\n @ministerio = Ministerio.find(params[:id])\n @ministerio.destroy\n\n respond_to do |format|\n format.html { redirect_to ministerios_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @mast.destroy\n respond_to do |format|\n format.html { redirect_to masts_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @json.destroy\n\n head :no_content\n end", "def destroy\n @minutum.destroy\n respond_to do |format|\n format.html { redirect_to minuta_url, notice: 'Minutum was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @minicurso = Minicurso.find(params[:id])\n @minicurso.destroy\n\n respond_to do |format|\n format.html { redirect_to minicursos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @minister = Minister.find(params[:id])\n @minister.destroy\n\n respond_to do |format|\n format.html { redirect_to ministers_url }\n format.json { head :no_content }\n end\n end", "def destroy\r\n @sivic_ministerio.destroy\r\n respond_to do |format|\r\n format.html { redirect_to sivic_ministerios_url }\r\n format.json { head :no_content }\r\n end\r\n end", "def destroy\n @ministerios = Ministerios.find(params[:id])\n @ministerios.destroy\n\n respond_to do |format|\n format.html { redirect_to(ministerios_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @mini = Mini.find(params[:id])\n @mini.destroy\n\n respond_to do |format|\n format.html { redirect_to minis_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @ministries = Ministries.find(params[:id])\n @ministries.destroy\n\n respond_to do |format|\n format.html { redirect_to(ministries_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @m1.destroy\n respond_to do |format|\n format.html { redirect_to m1s_url, notice: 'M1 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @single_action.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @smallmobunit = Smallmobunit.find(params[:id])\n @smallmobunit.destroy\n\n respond_to do |format|\n format.html { redirect_to smallmobunits_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @smallmob = Smallmob.find(params[:id])\n @smallmob.destroy\n\n respond_to do |format|\n format.html { redirect_to smallmobs_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @ministerio = Ministerio.find(params[:id])\n @ministerio.destroy\n\n respond_to do |format|\n format.html { redirect_to(ministerios_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @stimul.destroy\n respond_to do |format|\n format.html { redirect_to stimuls_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @ministerio = Ministerio.find(params[:id])\n @ministerio.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_ministerios_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @uset = Uset.find(params[:id])\n @uset.destroy\n\n respond_to do |format|\n format.html { redirect_to usets_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @mint = Mint.find(params[:id])\n @mint.destroy\n\n respond_to do |format|\n format.html { redirect_to mints_url }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make sure password and confirm_password are the same on update
def validate_on_update unless plain_password.blank? unless plain_password == password_confirmation errors.add_to_base("Passwords don't match") end # Validate password criteria unless plain_password.length >= 6 errors.add_to_base("Password must be at least 6 characters long.") end end end
[ "def validate_on_update\n unless plain_password.blank?\n unless plain_password == password_confirmation\n errors.add_to_base(\"Passwords don't match\")\n end\n # Validate password criteria\n unless plain_password.length >= 6\n errors.add_to_base(\"Password must be at least 6 characters long.\")\n end\n end\n end", "def update_password(old_password, new_password, new_password_confirmation)\n if self.authenticated?(old_password)\n if new_password.blank?\n false\n elsif new_password == new_password_confirmation\n self.password = new_password\n self.password_confirmation = new_password_confirmation\n self.save\n else\n false\n end\n else\n false\n end\n end", "def should_validate_password?\n #updating_password || new_record?\n updating_password\n end", "def forced_password_change\n if force_password_change_was == true\n if password_hash_was == BCrypt::Engine.hash_secret(@password,password_salt)\n errors.add(:password, \"cannot be the same\")\n return false\n end\n end\n end", "def password_match_password_confirmation\n if password != password_confirmation\n errors.add(:password_confirmation, I18n.t(\".activerecord.errors.models.user.attributes.password_confirmation\"))\n end\n end", "def password_match\n if password != confirm_password\n errors.add(:password, \"doesn't match\")\n end\n end", "def check_password_changed\n self.temp_password = nil if ( changed.include?('encrypted_password') && !(changed.include?('temp_password')))\n end", "def check_password_updated\n if self.new_record? then\n @password_update = false\n else\n if password.empty? then\n user = User.find(self.id)\n self.password = user.password\n @password_update = false\n else\n @password_update = true\n end\n end\n true\n end", "def correct_password_confirmation_match\n return if password == password_confirmation\n\n errors.add(:password_confirmation, :invalid,\n message: I18n.t('new_password_form.errors.password_not_equal'))\n end", "def update_password(pass)\n self.password_confirmation = pass\n self.password = pass\n end", "def should_update_password?\n # TODO: Have an accessor for marking this as being updated, i.e.:\n # updating_password || new_record?\n new_record?\n end", "def password_match?\n self.password == self.password_confirmation\n end", "def validate_match_password\n if password_confirmation && password != password_confirmation\n errors.add(:password, :confirmation)\n end\n end", "def updating_password?\n new_record? or updating_password\n end", "def password_with_confirmation (password, confirmation)\n return unless @password_match = (!password.blank?)\n return unless @password_match = (password == confirmation)\n self.password = password\n end", "def test_behaviour_when_new_and_confirmation_is_modified\r\n user = @user_class.new\r\n user.password_confirmation = @valid_data[:password_confirmation]\r\n\r\n assert_nil user.password\r\n assert_equal @valid_data[:password_confirmation], user.password_confirmation\r\n assert_nil user.password_salt\r\n assert_equal nil, user.password_hash_type\r\n assert_equal true, user.password_new?\r\n assert_equal false, user.password_equals?(@valid_data[:password])\r\n end", "def updating_password?\n (!persisted? && requires_password?) || (!password.nil?)\n end", "def correct_password_confirmation\n return if password == password_confirmation\n\n error_message = I18n.t('password.errors.password_equality')\n errors.add(:password, :invalid, message: error_message)\n errors.add(:password_confirmation, :invalid, message: error_message)\n end", "def need_change_password?\n password_change_requested? || password_too_old?\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
We are going to connect this user object with a facebook id. But only ever one account.
def link_fb_connect(fb_user_id) unless fb_user_id.nil? #check for existing account existing_fb_user = ::User.find_by_fb_user_id(fb_user_id) #merge the existing account unless existing_fb_user.nil? merge_with(existing_fb_user) end #link the new one self.fb_user_id = fb_user_id save(false) end end
[ "def link_fb_connect(fb_user_id)\n unless fb_user_id.nil?\n # check for existing account\n existing_fb_user = User.find_by_fb_user_id(fb_user_id)\n # unlink the existing account\n unless existing_fb_user.nil?\n existing_fb_user.fb_user_id = nil\n existing_fb_user.save!\n end\n # link the new one\n self.fb_user_id = fb_user_id\n save!\n end\n end", "def link_fb_connect(fb_user_id)\n unless fb_user_id.nil?\n #check for existing account\n existing_fb_user = User.find_by_fb_user_id(fb_user_id)\n #unlink the existing account\n unless existing_fb_user.nil?\n existing_fb_user.fb_user_id = nil\n existing_fb_user.save(false)\n end\n #link the new one\n self.fb_user_id = fb_user_id\n save(false)\n end\n end", "def fb_user_id\n self.user.fb_user_id\n end", "def update_facebook_id\n return unless self.facebook_access_token_changed?\n return if self.facebook_access_token.blank?\n \n facebook_user = self.facebook_client.me\n self.facebook_id = facebook_user[\"id\"] if facebook_user\n \n rescue Exception => e\n Rails.logger.error \"User#update_facebook_id: #{e.message}\"\n end", "def existing_facebook_user\n User.find_by_facebook_uid(auth_hash.uid)\n end", "def user_connected!\n \n profile = nil\n\n graph = Koala::Facebook::API.new(access_token)\n\n if fb_profile = graph.get_object(\"me\")\n profile = Model::Facebook::Profile.first(:facebook_user_id => fb_profile['id']) ||\n Users::Profile.first(:email => fb_profile['email'])\n unless profile \n adapted_data = adapt_fb_profile_data(fb_profile)\n profile = Model::Facebook::Profile.create({\n :username => \"#{fb_profile['id']}01\", \n \t :facebook_user_id => fb_profile['id'],\n :email => fb_profile['email'], \n \t :full_name => fb_profile['name'],\n \t :sex => adapted_data[:gender],\n :preferred_language => fb_profile['locale'][0..1],\n :date_of_birth => Date.strptime(fb_profile['birthday'],'%m/%d/%Y'),\n :country_of_origin => adapted_data[:country_of_origin],\n :usergroups => [Users::Group.get('user'), Users::Group.get('facebook')]\n \t })\n end\n end\n\n return profile\n\n end", "def facebook_uid\n credential = self.facebook_credential\n credential && credential.facebook_uid\n end", "def facebook_connect(auth)\n self.provider = auth[:provider]\n self.uid = auth[:uid]\n save\n end", "def associate_user\n \tfbUserIdString = params[:idString]\t\n \tuser = User.new(fbUserId:fbUserIdString)\n \tif user.valid?\t\n\t\t\t user = User.create(fbUserId:fbUserIdString)\n\t\t\t success = true\n\t\t end\n\t\t start_session(fbUserIdString)\n end", "def facebook_user_create\n Rails.logger.debug \"Creating CacheParty::FacebookUser for DryAuth::User from #{ __FILE__ }\\n\"\n self.user.create_facebook_user(facebook_id: self.uid)\n end", "def authenticate_with_facebook_connect(attributes = {})\n if attributes[:uid].present?\n self.find_for_facebook_connect(attributes[:uid])\n end\n end", "def get_facebook_user(facebook_id)\n @graph = Koala::Facebook::API.new(fb_access_token) if !fb_access_token.blank?\n @graph ? @graph.get_object(\"me\") : nil\n end", "def transfer_to_facebook_account(facebook_user_id)\n\n # current account (old) -> facebook account (new)\n # current is destroyed\n # current account must be standard account\n\n old_user = self\n new_user = User.find(facebook_user_id)\n\n # the current user (old_user) should be a standard account (log in with email/password)\n raise \"Current user (the one which will be destroyed) is not a standard account!\" if !old_user.standard_account?\n\n # the new user should be a facebook-authenticated account\n raise \"New user (the one to be merged to and retained) is not a facebook account!\" if !new_user.facebook_account?\n\n transfer_account :old => old_user, :new => new_user\n\n end", "def fbconnect\n if @u\n # for current login users, connect FB accounts\n @u.link_fb_connect(facebook_session.user.id) unless @u.fb_id == facebook_session.user.id\n redirect_back_or_default(home_path) and return\n else\n # otherwise register with FB\n user = User.find_by_fb_user(facebook_session.user)\n if user.nil?\n user = User.create_from_fb_connect(facebook_session.user)\n AuthMailer.deliver_registration(:subject=>\"new #{SITE_NAME} registration\", :body => \"username = '#{user.login}', email = 'none'\", :recipients=>REGISTRATION_RECIPIENTS)\n end\n @u = user\n self.user = user\n\n if user.nil?\n flash.now[:error] = \"Uh-oh, facebook login didn't work. Try it again.\"\n redirect_to '/'\n else\n flash[:notice] = \"Hello #{@u.f}\"\n redirect_back_or_default(home_path)\n end\n end\n end", "def find_friend_by_facebook_id(fb_id)\n if fb_id == external_id\n return user\n else\n friend_index = get_friends.index{|i| i['id'].to_i == fb_id.to_i}\n if friend_index\n FacebookAccount.find_or_create(get_friends[friend_index]).user\n else\n return nil\n end\n end\n end", "def login_from_facebook\n fb_cookie = get_facebook_cookie\n return unless fb_cookie and fb_cookie[\"uid\"]\n\n #uid : 507527287\n #sig : ddf9dffcd85fcc41dbe4257b5eee922b\n #base_domain : gear.com\n #secret : fSoxbS_tGGF0oP2c9_SUbw__\n #access_token : 225955489319|2.KBSGTAnBP5tSEIxJBXcWfA__.3600.1278799200-507527287|d5zULU1zLZFguUUcsqVU0-C-tOM.\n #session_key : 2.KBSGTAnBP5tSEIxJBXcWfA__.3600.1278799200-507527287\n #expires : 1278799200\n\n user = User.find_by_fb_user_id(fb_cookie[\"uid\"])\n\n # cant find the user in the db but they have a fb session..\n return unless user\n \n # Add fb user to the user object and set the current user\n self.current_user = user \n end", "def connect_to_facebook(auth)\n self.provider = auth[\"provider\"]\n self.uid = auth[\"uid\"]\n self.token = auth[\"credentials\"][\"token\"]\n self.save\n end", "def link_fb_to_user\n\t\trender :json=>{:success=>false, :msg=>'User not logged in.'} and return if @user.nil?\n\n\t\taccess_token = params[:access_token]\n\t\t\n\t\t#url = 'https://graph.facebook.com/me?access_token='+access_token\n\t\tbegin\n\t\t\tfb_user = FbGraph::User.fetch('me', :access_token=>access_token)\n\t\t\tfb_id = fb_user.identifier\n\t\t\temail = fb_user.email.strip.downcase\n\t\t\t\n\t\t\t#Check if user exists by email\n\t\t\tuser = User.find_by_email(email)\n\t\t\trender :json=>{:success=>false, :msg=>'An account already exists under your Facebook email.'} and return if (!user.nil? && user.id!=@user.id)\n\t\t\t\n\t\t\t#Check if user exists by Facebook ID\n\t\t\tuser = User.find_by_fb_id(fb_id)\n\t\t\trender :json=>{:success=>false, :msg=>'An account already exists under this Facebook account.'} and return if (!user.nil? && user.id!=@user.id)\n\t\t\t\n\t\t\t@user.fb_id = fb_id\n\t\t\t@user.fb_access_token = access_token\n\t\t\t\n\t\t\t@user.save\n\t\t\tsession['user'] = @user\n\t\t\t\n\t\t\trender :json=>{:success=>true, :msg=>'success'} and return\n\t\t\t\n\t\trescue\n\t\t\trender :json=>{:success=>false, :msg=>'There was an error. Refresh the page and try again.'} and return\n\t\tend\n\tend", "def register_user_to_fb\n if self.facebook_user?\n users = {:email => email, :account_id => id}\n Facebooker::User.register([users])\n self.email_hash = Facebooker::User.hash_email(email)\n save(false)\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
find the user in the database, first by the facebook user id and if that fails through the email hash
def find_by_fb_user(fb_user) u = ::User.find(:first, :conditions => {_(:fb_user_id, :user) => fb_user.uid}) || ::User.find(:first, :conditions => {_(:facebook_hash, :user) => fb_user.email_hashes}) # make sure we have a person if u && !u.person u.create_person_from_fb(fb_user) end u.update_attribute(:fb_user_id, fb_user.uid) if u && !u.fb_user_id u rescue ::Facebooker::Session::SessionExpired nil end
[ "def existing_facebook_user\n User.find_by_facebook_uid(auth_hash.uid)\n end", "def find_user_by_bot_id\n @user = User.find_by(:fb_bot_id => params[:fb_bot_id])\n link_facebook unless @user && @user.id\n end", "def find_friend_by_facebook_id(fb_id)\n if fb_id == external_id\n return user\n else\n friend_index = get_friends.index{|i| i['id'].to_i == fb_id.to_i}\n if friend_index\n FacebookAccount.find_or_create(get_friends[friend_index]).user\n else\n return nil\n end\n end\n end", "def find_by_email(email)\n if email.strip.length > 0\n result = Ripple::client.search('users', \"email:#{email.downcase}\")\n if result['response']['numFound'] == 1\n return User.find(result['response']['docs'][0]['id']) # is this the best way?\n end\n end\n nil # Returned if no conditions met (explicit to avoid IDE griping)\n end", "def existing_user_by_email\n return if user_with_email.blank?\n\n if get_an_identity_id.blank?\n return response_with_user(user_with_email) if user_with_email.get_an_identity_id.blank?\n\n return email_lookup_failed_as_matching_get_an_identity_id_not_sent_response\n end\n\n update_get_an_identity_id_on_user_with_email\n end", "def find_using_oauth_email(oauth_data, oauth_user_id)\r\n user = nil\r\n oauth_email = oauth_data.info.email\r\n if oauth_email.present?\r\n user = self.find_by(email: oauth_email)\r\n if user.present? && user.oauth_user_id.blank?\r\n user.oauth_user_id = oauth_user_id\r\n else\r\n user = nil # don't update if has an oauth user id (will error on duplicate email validation)\r\n end\r\n end\r\n user\r\n end", "def get_user(email)\n #faço a chamada para buscar o id do usuario com find que vai trazer uma lista de usuarios\n #mas com essa condição que passo do email coloco o firt que vai trazer a esperada\n user = @users.find({ email: email }).first\n\n #capturo somente o _id do usuario e faço o return do metodo\n return user[:_id]\n end", "def find_user_for_facebook_id(facebook_id = nil, disable_token=nil)\n if facebook_id.nil? then facebook_id = @@peter_id end\n puts \"find user for facebook_id: #{facebook_id}\"\n headers_hash = Hash.new\n headers_hash['Accept'] = 'application/json'\n\n # By default, use a token and require these specific fields\n params_hash = Hash.new\n if disable_token.nil?\n params_hash['access_token'] = @access_token\n params_hash['fields'] = 'third_party_id,first_name,last_name,name,gender,locale,verified'\n else\n\n end\n\n response = Typhoeus::Request.get(\"#{@@fb_host}/#{facebook_id}\", :params => params_hash, :headers => headers_hash, :disable_ssl_peer_verification => true)\n\n parsed_response = self.check_facebook_response_for_errors(response)\n if parsed_response.nil?\n return nil\n end\n\n # Parse user\n facebook_user = self.serialize_user(parsed_response)\n\n return facebook_user\n end", "def find_user_by(login)\n user = User.find_by_username login\n user ||= User.find_by_email login\n head :not_found unless user\n user\n end", "def find_local_by_email\n # Look for a local user by their email address\n email_encoded = self.email_addr\n begin\n email_check = email_encoded.dup\n email_check.force_encoding(\"UTF-8\").encode(\"cp1252\")\n rescue ##ToDO MAKE ME BETTER PLEASE####\n email_encoded = URI.encode(email_encoded)\n end\n\n local_user = User.where{email == my{email_encoded}}.first\n if local_user.nil?\n local_user = User.where{boinc_id == my{self.id}}.first\n end\n\n local_user\n end", "def user_from_id_hash\n User.find_by_id_hash params[:id_hash]\n end", "def find_user_by_email(email: user&.email)\n users = client.list_users(\"active\", {\n filter: email,\n order: \"ascending\",\n page: 1\n })\n\n users.first\n end", "def efind(email)\n User.find_by_email email\n end", "def find_by_email(email:)\n users.where(email: email).first\n end", "def find_user\n if session[:otp_user_id]\n User.find(session[:otp_user_id])\n elsif user_params[:email]\n User.find_for_authentication(email: user_params[:email]).tap do |user|\n session[:otp_user_id] = user&.id\n end\n end\n end", "def extract_user_id(params)\n User.find_by_id(params[:user_id]) || User.find_by_email(params[:email]) || nil\n end", "def find_email\n val = @email\n return if val.nil? \n val = LdapQuery::Scanner.search(val).as_user_attributes[:email] \n if val.nil?\n errors.add :base, 'Email address not found'\n return false\n end\n @email = val\n xdelegate = User.find_by_email(val.to_s)\n if xdelegate.nil?\n errors.add :base, 'Email does not have an account on this website'\n return false\n else\n self.delegate_user_id = xdelegate.id\n end\n\n end", "def find_for_facebook_oauth(auth, current_user = nil)\n if current_user && current_user.accounts.facebook.where(uid: auth['uid']).exists?\n current_user\n else\n includes(:accounts)\n .where(accounts: {type: Accounts::Facebook, uid: auth['uid']})\n .first\n end\n end", "def find_user(aUser_input)\n found_user = nil\n self.users.each do |user|\n if (aUser_input == user.id) || (aUser_input == user.name)\n return user\n end\n end\n return found_user\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
delete the default shipment and create split shipments out of it
def split_shipment! self.shipments.destroy_all units = self.inventory_units.includes(:variant=>:product) units.group_by{|u| u.variant.product.brand_id}.each do |brand_id,units| s = Spree::Shipment.create!({ :order => self, :shipping_method => shipping_method, :address => self.ship_address, :inventory_units => units}, :without_protection => true) end end
[ "def create_drop_ship_orders\n self.drop_ship_orders.destroy_all\n self.line_items.group_by{ |li| li.product.supplier_id }.each do |supplier_id, supplier_items|\n if supplier_id.present?\n supplier = Spree::Supplier.find(supplier_id)\n dso = supplier.orders.create({:order_id => self.id})\n supplier_items.each do |line_item|\n dso.drop_ship_line_items.create({line_item_id: line_item.id})\n end\n end\n end\n end", "def create_default_shipment!\n Order.call_with_thread_options({}) do\n create_shipment!\n end\n end", "def create_shipment!\n line_items.each do |item|\n if (shipment_by_store = Spree::Shipment.by_order(self.id).by_store(item.store_id).first).blank?\n self.shipments << Spree::Shipment.create(:order => self,\n :shipping_method_id => Spree::Config[:default_shipping_method_id],\n :address => self.ship_address,\n :store => item.store,\n :state => 'pending') \n end\n end\n end", "def create_shipment!\n shipping_method(true)\n\n if shipment.present?\n shipment.update_attributes!(:shipping_method => shipping_method)\n else\n self.shipments << Shipment.create!({ :order => self,\n :shipping_method => shipping_method,\n :address => self.ship_address}, :without_protection => true)\n end\n \n end", "def finalize_with_drop_ship!\n finalize_without_drop_ship!\n shipments.each do |shipment|\n if SpreeDropShip::Config[:send_supplier_email] && shipment.supplier.present?\n Spree::Core::MailMethod.new.deliver!(Spree::DropShipOrderMailer.supplier_order(shipment.id))\n end\n end\n end", "def create_shipment!\n shipping_method(true)\n if shipment.present?\n shipment.update_attributes(:shipping_method => shipping_method)\n else\n self.shipments << Shipment.create(:order => self,\n :shipping_method => shipping_method,\n :address => self.ship_address)\n end\n\n end", "def destroy\n @ms_shippment = MsShippment.find(params[:id])\n @ms_shippment.destroy\n\n respond_to do |format|\n format.html { redirect_to(ms_shippments_url) }\n format.xml { head :ok }\n end\n end", "def create_shipment(user_id, save_to_db = true)\n\n raise \"There are no items in this order\" if total_items == 0\n\n seq = 1\n max_seq = shipments.maximum(:sequence)\n seq = max_seq + 1 unless max_seq.nil?\n\n shipment = Shipment.new(order_id: id,\n sequence: seq,\n recipient_company: shipping_company,\n recipient_name: shipping_name,\n recipient_street1: shipping_street1,\n recipient_street2: shipping_street2,\n recipient_city: shipping_city,\n recipient_state: shipping_state,\n recipient_zip: shipping_zip,\n recipient_country: shipping_country,\n status: 'pending')\n\n loc_id = Cache.setting(domain_id, :shipping, \"Ship From Location ID\")\n loc = Location.find(loc_id) if loc_id\n\n unless loc.nil?\n shipment.assign_attributes(ship_from_company: loc.name,\n ship_from_street1: loc.street1,\n ship_from_street2: loc.street2,\n ship_from_city: loc.city,\n ship_from_state: loc.state,\n ship_from_zip: loc.zip,\n ship_from_country: loc.country,\n ship_from_email: loc.email,\n ship_from_phone: loc.phone)\n end\n\n # set invoice amount\n # shipment.invoice_amount = shipment.order.total if seq == 1\n\n # build the shipment items \n items.each do |item|\n\n # regular order item, not a daily deal\n if item.product_id\n shipment.items.build(order_item_id: item.id,\n quantity: item.quantity_accepted - item.quantity_shipped)\n\n elsif item.daily_deal_id\n\n if item.custom_text.blank?\n item.daily_deal.items.each do |di|\n shipment.items.build(order_item_id: item.id,\n quantity: item.quantity * di.quantity)\n end\n else\n # user may have selected a specific item from drowndown\n p = Product.find_by(item_number: item.custom_text.split(\":\").first)\n shipment.items.build(order_item_id: item.id, quantity: item.quantity)\n end\n\n end\n\n end\n\n if save_to_db && shipment.save!\n OrderHistory.create(order_id: id, user_id: user_id, event_type: :shipment_created,\n system_name: 'Rhombus', identifier: shipment.id, comment: \"shipment created: #{shipment}\")\n end\n\n shipment\n end", "def auto_book_shipment(company_id: nil, customer_id: nil, shipment_id: nil)\n nil\n end", "def shipment\n @shipment ||= Shipment.new(:order => order, :address => ship_address)\n end", "def remove_from_shipping_list\n\t\tOrderItem.where(id: params[:oi_id]).first.shipped\n\t\t@orders = Order.all.not_shipped.chronological.to_a\n\t\t# redirect_to home_path\n\tend", "def create_shipment\n begin\n shipment = Shipment.new()\n @shipment_id = shipment.create(prepare_shipments_data)\n rescue\n puts \"Oops! Something went wrong while importing Shipments\"\n end\n end", "def destroy\n @ship_placement.destroy\n respond_to do |format|\n format.html { redirect_to ship_placements_url, notice: 'Ship placement was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @payable = Payable.find(params[:payable_id])\n @payable_shipment = @payable.payable_shipments.find(params[:id])\n @payable_shipment.destroy\n\n respond_to do |format|\n format.html { redirect_to payable_payable_shipments_url(payable) }\n format.json { head :ok }\n end\n end", "def destroy\n @ship_group.destroy\n respond_to do |format|\n format.html { redirect_to ship_groups_url, notice: 'Ship group was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @po_shipment = PoShipment.find(params[:id])\n @po_shipment.destroy\n\n respond_to do |format|\n format.html { redirect_to po_shipments_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @shipment_type = ShipmentType.find(params[:id])\n @shipment_type.kill\n\n respond_to do |format|\n format.html { redirect_to(shipment_types_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @ship_request.destroy\n\n head :no_content\n end", "def create\n \n @max_ships=50 \n @ship_group = ShipGroup.new(ship_group_params)\n @ship_name =Unit.find(@ship_group.unit_id).name\n respond_to do |format|\n if @ship_group.save\n format.html { redirect_to @ship_group, notice: 'Ship group was successfully created.' }\n format.json { render :show, status: :created, location: @ship_group }\n else\n format.html { render :new }\n format.json { render json: @ship_group.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method combines First name, Middle name & Last name and returns Full Name of Contact
def full_name return Contact.generate_full_name self.first_name, self.middel_name, self.last_name end
[ "def get_full_name (contact)\n \"#{contact[\"name\"]} #{contact[\"last_name\"]}\"\n end", "def full_name\n [first_name, surname].join(' ')\n end", "def full_name_and_company_name\n \"#{self.fname.downcase.titleize} #{self.lname.downcase.titleize} of #{self.company_name}\"\n end", "def full_name_last_first\n return self.first_name unless (self.last_name.length > 0)\n return (self.last_name + \", \" + self.first_name)\n end", "def full_name\n return \"#{first_name} #{last_name}\"\n end", "def full_name(options = {})\n opts = options.reverse_merge(:middle_name => false, :last_first => false)\n f_name = if opts[:middle_name] && self.middle_name?\n \"#{first_name} #{middle_name}\"\n else\n first_name\n end\n \n if opts[:last_first]\n \"#{last_name}, #{f_name}\"\n else\n \"#{f_name} #{last_name}\"\n end\n end", "def full_name(first, last)\n\tfirst + \" \" + last\nend", "def full_name\n full_name = \"#{first} #{middle} #{last}\"\n if maiden != last\n full_name += \" nee #{maiden}\"\n end\n return full_name\n end", "def full_name\n first_name.present? && last_name.present? ? \"#{first_name} #{last_name}\" : uid\n end", "def fullname(opt = {})\n options = { :middlename => true, :skip_update => false, :override_with_local => true, :ignore_nickname => false }.merge(opt)\n if person_resource? && !options[:skip_update]\n update_resource_cache! rescue nil\n return display_name unless options[:override_with_local]\n end\n return display_name if firstname.blank? && lastname.blank?\n parts = []\n parts << (options[:ignore_nickname] ? read_attribute(:firstname) : firstname)\n parts << \"(#{nickname})\" if !Customer.display_nicknames_by_default? && !options[:ignore_nickname] && !nickname.blank?\n parts << (middlename.length == 1 ? \"#{middlename.to_s}.\" : middlename.to_s) if options[:middlename] && !middlename.blank?\n parts << lastname\n parts.join(\" \")\n end", "def complete_name\n\t\t\"#{first_name} #{last_name}\"\n\tend", "def parse_contact_name(value)\n return nil,nil if value.nil?\n #first name is whats before the space, last name is everything else\n name = value.split(\" \")\n fname= name[0]\n name.delete_at(0)\n lname = name.join(\" \")\n return fname,lname\n end", "def merge_first_and_last_name_into_name\n self.name = [first_name, last_name].compact.join(' ').strip\n end", "def full_name\n return @full_name unless @full_name.nil?\n\n full_name = []\n full_name << personGivenName if respond_to?(:personGivenName)\n full_name << personFamilyName if respond_to?(:personFamilyName)\n\n @full_name = full_name.join(' ')\n end", "def full_name(patient)\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 last_name_first(options={})\n return (last_name || '') + (first_name || '') if last_name.blank? || first_name.blank?\n options[:short] = false if options[:paren_short] # paren_short overrides the short option\n if options[:short] && !short_name.blank? # use the short form of first name if it's defined\n first = short_name\n else\n first = first_name # || '*Missing First Name*'\n end\n if options[:initial] && !middle_name.blank? # use middle initial rather than whole middle name?\n middle = middle_initial\n else\n middle = middle_name || ''\n end\n if (options[:paren_short]) && !short_name.blank? && short_name != first\n first = first + \" (#{short_name})\"\n end\n s = (last_name) + ', ' + first \n s << (' ' + middle) unless options[:middle] == false || middle.empty?\n return s || ''\n end", "def full_name(order = 1)\n if order == 1\n return \"#{@first_name} #{@middle_names[0]} #{@last_name}\"\n elsif order == 2\n return \"#{@last_name}, #{@first_name}\"\n else\n raise StandardError.new(\"Unknown order argument for Person#get_full_name method\")\n end\n end", "def mother_full_name\n\t\t[mother_first_name, mother_middle_name, mother_last_name].delete_if(&:blank?).join(' ')\n\tend", "def full_name\n\t\tself.employee_fname.capitalize + \" \" + self.employee_lname.capitalize\n\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method returns the top connector status of Contact
def is_top_connector? TopConnector.exists? :contact_id => self.id end
[ "def status\n @connections.status\n end", "def status\n @client.raw('get', '/status', nil, nil, @contact_v1_url)\n end", "def status\n self.activities.status_updates.by_newest.first\n end", "def connector_type\n cable.connector_types[self.end - 1]\n end", "def getConnectorStart()\n\t\tif @roomConnectors.length() > 0\n\t\t\treturn @roomConnectors[0][0], @roomConnectors[0][1]\n\t\telse\n\t\t\treturn false\n\t\tend\n\tend", "def connection_status\n @conn.getprop(SybConstant::CS_CON_STATUS)\n end", "def cursor_state\n self.getprop( CS_CUR_STATUS)\n end", "def open_contacts?\n self.contacts.select(&:open?).size > 0\n end", "def connected\n\t\treturn @connected\n\tend", "def onboarding_status\n return @onboarding_status\n end", "def external_status\n @external_status\n end", "def get_preferred_contactinfo\n rci = get_preferred_role_contactinfo\n result = nil\n result = rci.contactinfo if !rci.blank?\n result\n end", "def contact_state\n details? ? details[\"Contact\"][\"state\"] : ''\n end", "def status\n @messaging['account_linking']['status']\n end", "def active_clients \n Contact.count(:all, :conditions => [\"assigned_to_employee_user_id=? AND contact_stage_id=? AND status_type=?\",get_employee_user_id,current_company.contact_stages.array_hash_value('lvalue','Client','id'),current_company.prospect_status_types.find_by_lvalue(\"Active\").id])\n end", "def active?\n resp = @coopr_client.get(\"v2/clusters/#{id}/status\")\n @last_status = JSON.parse(resp.to_str)\n @last_status['status'] == 'active'\n end", "def connected\n return @connected\n end", "def status\n Skype.send_ :command => \"get call #{@call_id} status\"\n end", "def get_node_status(position)\n @board[position-1].status\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method validates a Contact for Manual Update
def validated_for_update?(c) valid = true if first_name.blank? && last_name.blank? c.errors.add_to_base("Must enter contact name") valid = false end ex_email = Contact.find(:first, :include => [:emails], :conditions => ["emails.email_text = ? AND contacts.user_id = ? AND contacts.id != ? AND merged_to_form_contact_id = 0", email, user_id, c.id]) if ex_email c.errors.add_to_base("Contact already in network") valid = false end valid end
[ "def validate_updated_contact_form_fields\n errors.add(:contact_form_fields, :invalid_contact_form_field) unless contact_form_fields.all? { |s| s.valid? || s.new_record? }\n end", "def validate_update(comment)\n true\n end", "def validate_contact\n errors.add(:mail, \"You must fill in at least one contact field\") if phone.blank? && mail.blank? && website.blank?\n end", "def validate_on_update # :doc:\n end", "def update\n @organization_contact = @organization.contacts.find(params[:id])\n @organization_contact.person.require_validations = true\n \n respond_to do |format|\n if @organization_contact.update_attributes(params[:organization_contact])\n flash[:notice] = 'Contact was successfully updated.'\n format.html { redirect_to(community_partner_service_learning_organization_contact_url(@quarter, @organization_contact)) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @organization_contact.errors, :status => :unprocessable_entity }\n end\n end\n end", "def validate_contact_info \n case contact_method\n when 'email'\n errors.add(:email, \"Invalid email address\") unless EmailVeracity::Address.new(email).valid?\n when 'phone'\n if phone_numbers.empty?\n errors.add(:phone_number, \"Please enter a phone number\")\n else \n phone_numbers.each do |pn|\n errors.add_to_base(pn.errors.full_messages) if pn && !pn.valid?\n end\n end\n when 'mail'\n if address.nil?\n errors.add(:address, \"Please fill in mailing address\")\n else\n errors.add_to_base(address.errors.full_messages) unless address.valid?\n end\n end\n end", "def ensure_contact_details\n if email.blank? and phone.blank?\n message = '- please ensure you have either an email or phone contact details'\n errors.add :email, message\n errors.add :phone, message\n end\n end", "def validate_that_at_least_one_set_of_contact_info_is_present\n return if veteran_contact_info.present? || claimant_contact_info.present?\n\n errors.add :form_data, I18n.t('appeals_api.errors.contact_info_presence')\n end", "def validate_on_update\n unless self.changed?\n self.errors.add_to_base('No changes')\n end\n if direct_changed?\n if count_changed?\n self.errors.add_to_base('Do not manually change the count value')\n end\n if !self.direct?\n if self.count == 1\n self.errors.add_to_base('Cannot make a direct link with count 1 indirect')\n end\n end\n end\n end", "def valid?(params = {})\n if super(params)\n if self.disp && self.contact.blank?\n self.errors.add(:contact, \"can't be blank and displayed\")\n return false\n else\n return true\n end\n else\n return false\n end\n end", "def patch_valid?\n validate(false).empty?\n end", "def modify_contact\n contact = retrieve_contact_by_email\n if contact\n attr_code = attr_menu\n if attr_code\n print \"You have chosen to change the contact's #{@@attr_ops[attr_code]}. Is that correct? \"\n confirm = gets.chomp.downcase\n if confirm == 'yes'\n print \"Please provide the new value for #{@@attr_ops[attr_code]}: \"\n new_value = gets.chomp\n contact = @rolodex.modify(contact, attr_code, new_value)\n if contact\n puts \"Contact successfully updated:\\n#{contact}\\n\"\n end\n elsif confirm == 'no'\n print \"Update canceled. \"\n else\n puts \"Error: only 'yes' and 'no' are valid responses.\"\n end\n end\n end \n return contact\n end", "def contact_attempted!\n if status == :initialized then update_attribute(:status,:contact_attempted); end\n end", "def save\n validate!\n unless errors.any?\n begin\n self.cc = @ccapi.get_contact_by_email(email_address) unless email_address.to_s.empty?\n if !cc\n self.cc = @ccapi.add_contact(self)\n else\n self.cc = @ccapi.update_contact(self)\n end\n ccontact_to_contact\n rescue Exception => e\n errors.add(:email_address, e.to_s)\n return false\n end\n end\n end", "def verify_contact_address\n unless contact_address =~ /\\A([^@\\s]+)@((?:[-a-z0-9]+\\.)+[a-z]{2,})\\z/i\n errors.add(:contact_address, \"is not an email address\")\n end\n end", "def check_contact_info\n @user = current_user\n if @user.invalid?\n return redirect_to edit_user_path(current_user)\n end\n end", "def update_with_contact(params, company_id)\n begin\n self.transaction do\n if params[:contact] && params[:contact].has_key?(:id) && params[:contact][:id].present? \n contact = Contact.find(params[:contact][:id])\n unless contact.accounts.length > 0\n self.contacts << Contact.find(params[:contact][:id])\n end\n params[:account].merge!(:primary_contact_id => params[:contact][:id]) unless self.primary_contact_id \n end\n \n #:TODO Temp fix for shipping and billing addres, cod not working with address module\n # err = validate_zip_code_format(params)\n if self.update_attributes(params[:account]) #&& err.empty?\n true\n else \n false\n end\n end\n rescue\n false\n end\n end", "def padma_contact_setted_correctly\n return if self.padma_contact.nil?\n unless padma_contact.is_a?(PadmaContact)\n raise 'This is not a contact!'\n end\n if padma_contact.id != self.contact_id\n if self.contact_id.nil?\n # if they differ because contact_id is nil we set it here\n self.contact_id = self.padma_contact.id\n else\n raise 'This is the wrong contact!'\n end\n end\n end", "def must_have_contact_phone\n errors[:contact_phone] << \"is required\" if self.persisted? && self.vendors.count > 0 && self.contact_phone.blank?\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method Returns Collection of Contacts that are suspected as duplicates in the Merge but not Merged. THis scenario does not occur now.
def duplicates Contact.find(:all, :conditions => ["id != ? AND merge_id = ?", id, merge_id]) end
[ "def unconnected_contacts\n unconnected = []\n Contact.all.each do |contact|\n unconnected << contact if contacts.exclude? contact\n end\n return unconnected\nend", "def merge(contacts_with_dupes)\n group_by_email(contacts_with_dupes).flat_map do |_, contacts|\n contacts.sort_by! { |c| c[:date_added] }\n\n contacts.first.tap do |merged|\n contacts[1..-1].each do |newer|\n merged.keys.each do |key|\n merged[key] = newer[key] unless newer[key].to_s.empty?\n end\n end\n end\n end\n end", "def similarity_of_contacts\n return if self.finished?\n if !Contact.where(:_id => self.first_contact_id).exists? || !Contact.where(:_id => self.second_contact_id).exists?\n self.errors[:existence_of_contacts] << I18n.t('errors.merge.existence_of_contacts')\n else\n if !first_contact.similar.include?(second_contact)\n self.errors[:similarity_of_contacts] << I18n.t('errors.merge.similarity_of_contacts')\n end\n end\n end", "def duplicates\n relations_to.select {|r| r.relation_type == IssueRelation::TYPE_DUPLICATES}.collect {|r| r.issue_from}\n end", "def duplicates\n relations_to.select { |r| r.relation_type == IssueRelation::TYPE_DUPLICATES }.collect { |r| r.issue_from }\n end", "def missed_contacts\n @contacts.where(contact_type: 'PBX', answered: nil, after_call_ended: nil, direction: 'I').where.not(call_ended: nil, service_id: 120)\n end", "def similar(options = {})\n ActiveSupport::Notifications.instrument(\"get_similar_contacts\") do\n if options[:only_in_account_name]\n contacts = Account.where(name: options[:only_in_account_name]).first.contacts\n else\n contacts = Contact.all\n end\n \n @unfiltered = true\n \n unless options[:ignore_name]\n if self.last_name.blank?\n unless self.first_name.blank?\n self.first_name.split.each do |first_name|\n @unfiltered = false\n contacts = contacts.any_of(:normalized_first_name => {'$regex' => \".*#{first_name.parameterize}.*\"})\n end\n end\n else\n self.last_name.split.each do |last_name|\n self.first_name.split.each do |first_name|\n @unfiltered = false\n contacts = contacts.any_of(:normalized_last_name => {'$regex' => \".*#{last_name.parameterize}.*\"},\n :normalized_first_name => {'$regex' => \".*#{first_name.parameterize}.*\"})\n end\n end\n end\n end\n\n self.emails.map(&:value).each do |email|\n @unfiltered = false\n contacts = contacts.any_of(contact_attributes: { '$elemMatch' => {\n '_type' => 'Email',\n 'value' => email,\n }})\n end\n\n self.mobiles.map(&:value).each do |mobile|\n @unfiltered = false\n contacts = contacts.any_of(contact_attributes: {'$elemMatch' => {\n '_type' => 'Telephone',\n 'category' => /mobile/i,\n 'value' => mobile\n }})\n end\n \n self.telephones.select{|t| t.category.blank? }.map(&:value).each do |telephone|\n @unfiltered = false\n contacts = contacts.any_of(contact_attributes: {'$elemMatch' => {\n '_type' => 'Telephone',\n 'value' => telephone\n }})\n end\n\n self.identifications.each do |identification|\n @unfiltered = false\n contacts = contacts.any_of(contact_attributes: {'$elemMatch' => {\n _type: 'Identification',\n category: identification.category,\n value: identification.get_normalized_value\n }})\n end\n \n if @unfiltered\n return []\n end\n\n if self.id.present?\n contacts = contacts.excludes(:id => self.id)\n end\n\n contacts = contacts.to_a\n\n contacts.delete_if do |c|\n not_similar = false\n c.identifications.each do |id|\n if self.identifications.where(:category => id.category).select{ |id_v|\n id_v.get_normalized_value != id.get_normalized_value\n }.length > 0\n not_similar = true\n end\n end\n not_similar\n end\n end\n end", "def duplicates\r\n clone.duplicates!\r\n end", "def contacts\n collect\n end", "def contacts\n collection = CapsuleCRM::ContactCollection.new(self,CapsuleCRM::Contact, [])\n collection.concat emails\n collection.concat phone_numbers\n collection.concat websites\n collection.concat addresses\n collection\n end", "def related_contacts\n return @related_contacts\n end", "def common_contacts_with(other_dog, options = {})\n # I tried to do this in SQL for efficiency, but failed miserably.\n # Horrifyingly, MySQL lacks support for the INTERSECT keyword.\n common_contacts = []\n dogs.each do |dog|\n common_contacts << (dog.contacts & other_dog.contacts)\n end\n return common_contacts.flatten.uniq.paginate(options)\n end", "def shared_contacts\n User.find_by_sql(<<-SQL)\n SELECT\n contacts.*\n FROM\n contacts\n JOIN\n contact_shares\n ON\n contacts.id = contact_shares.contact_id\n WHERE\n contacts.user_id = #{self.id}\n SQL\n end", "def remote_subscribed_to_contacts\n @user.subscribed_to_contacts.reject do |c|\n @config.local_jid?(c.jid)\n end\n end", "def contacts\n contact_ids = @redis.smembers(\"contacts_for:#{entity.id}:#{check}\")\n\n if @logger\n @logger.debug(\"#{contact_ids.length} contact(s) for #{entity.id}:#{check}: \" +\n contact_ids.inspect)\n end\n\n entity.contacts + contact_ids.collect {|c_id|\n Flapjack::Data::Contact.find_by_id(c_id, :redis => @redis, :logger => @logger)\n }.compact\n end", "def answered_contacts\n @contacts.where(contact_type: 'PBX').where.not(answered: nil, service_id: 120)\n end", "def get_account_contacts\n acontacts = self.contact.accounts[0].present? ? (self.contact.accounts[0].contacts - [self.contact]) : []\n clientcontacts = self.matter_peoples.client_contacts\n acontacts - clientcontacts.collect(&:contact)\n end", "def creator_contact_ids\n self.creator ? self.creator.added_contact_ids + [self.creator_id] : []\n end", "def possible_duplicates\n @duplicates = {}\n if last_name.present?\n last_name_duplicates = Person.where(last_name: last_name).where.not(id: id)\n last_name_duplicates.each do |duplicate|\n duplicate_hash = {}\n duplicate_hash['person'] = duplicate\n duplicate_hash['match_count'] = 1\n duplicate_hash['last_name_match'] = true\n duplicate_hash['matches_on'] = ['Last Name']\n @duplicates[duplicate.id] = duplicate_hash\n end\n end\n if email_address.present?\n email_address_duplicates = Person.where(email_address: email_address).where.not(id: id)\n email_address_duplicates.each do |duplicate|\n if @duplicates.key? duplicate.id\n @duplicates[duplicate.id]['match_count'] += 1\n @duplicates[duplicate.id]['matches_on'].push('Email Address')\n else\n @duplicates[duplicate.id] = {}\n @duplicates[duplicate.id]['person'] = duplicate\n @duplicates[duplicate.id]['match_count'] = 1\n @duplicates[duplicate.id]['matches_on'] = ['Email Address']\n end\n @duplicates[duplicate.id]['email_address_match'] = true\n end\n end\n if phone_number.present?\n phone_number_duplicates = Person.where(phone_number: phone_number).where.not(id: id)\n phone_number_duplicates.each do |duplicate|\n if @duplicates.key? duplicate.id\n @duplicates[duplicate.id]['match_count'] += 1\n @duplicates[duplicate.id]['matches_on'].push('Phone Number')\n else\n @duplicates[duplicate.id] = {}\n @duplicates[duplicate.id]['person'] = duplicate\n @duplicates[duplicate.id]['match_count'] = 1\n @duplicates[duplicate.id]['matches_on'] = ['Phone Number']\n end\n @duplicates[duplicate.id]['phone_number_match'] = true\n end\n end\n if address_1.present?\n address_1_duplicates = Person.where(address_1: address_1).where.not(id: id)\n address_1_duplicates.each do |duplicate|\n if @duplicates.key? duplicate.id\n @duplicates[duplicate.id]['match_count'] += 1\n @duplicates[duplicate.id]['matches_on'].push('Address_1')\n else\n @duplicates[duplicate.id] = {}\n @duplicates[duplicate.id]['person'] = duplicate\n @duplicates[duplicate.id]['match_count'] = 1\n @duplicates[duplicate.id]['matches_on'] = ['Address_1']\n end\n @duplicates[duplicate.id]['address_1_match'] = true\n end\n end\n @duplicates\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method To Unmerge Contact
def un_merge Contact.transaction do self.parents.each do |contact| contact.update_attribute('merged_to_form_contact_id', 0) if contact.contact_type == Constants::CONTACT_TYPE::PROSPECT ContactProspect.update_all("prospect_old_id = NULL, prospect_id = #{contact.id}", "prospect_old_id = #{contact.id}") else ContactProspect.update_all("contact_old_id = NULL, contact_id = #{contact.id}", "contact_old_id = #{contact.id}") end end self.emails.clear self.sources.clear self.contact_metas.clear self.destroy_shares self.destroy end end
[ "def remove_tag_from_contact\n\t\t\t\t# unlike the remove method in account, this only removes the tag from one contact\n\t\t\t\t\n\t\t\tend", "def unlink_contact(_contact)\n _rc = false\n if self.contacts.detect { |c| c._id ==_contact._id }\n _facility = self.facilities.any_in(consumer_ids: [_contact._id]).first\n if _facility\n _facility.delete_or_remove_consumer(_contact)\n self.save!\n @contacts = nil\n _rc = true\n end\n end\n if self.reverse_contacts.detect { |c| c._id ==_contact._id }\n _facility = _contact.facilities.any_in(consumer_ids: [self._id]).first\n if _facility\n _facility.delete_or_remove_consumer(self)\n _contact.save!\n @reverse_contacts = nil\n _contact\n _rc = true\n end\n end\n _rc\n end", "def clear_contacts!\n Activity.remove_all_contacts_from_lists( self.uid )\n end", "def delete\n @@contacts.delete(self) #I'm honestly just making an educated guess with this one. Or just a regular guess.\n end", "def unlink(contact)\n contact.accounts.delete(self)\n contact.lists = contact.lists.reject{|l|l.account == self}\n if contact.owner == self\n contact.owner = nil\n contact.cached_owner = nil\n end\n contact.save\n end", "def clear_facility_contacts\n Contact.collection.update({\"facility_ids\" => id}, {\"$pull\" => { \"facility_ids\" => id }}, :multi => true)\n end", "def destroy\n @linked_in_contact.destroy\n end", "def remove\n contacts_that_use_this_field = \n Contact.all.select {\n |contact| contact.contact_fields.include? self.name.downcase.to_sym\n }\n \n contacts_that_use_this_field.each do |contact|\n contact.remove_custom_field(self.name.downcase.to_sym)\n contact.save!\n end\n\n self.destroy\n end", "def deactivate_contact(current_user)\n self.updated_by_user_id=current_user.id\n msg, confirm=self.checkassociation\n self.save(false) \n if self.account_contacts.present?\n self.account_contacts.each do |acc_cont|\n acc_cont.update_attribute(:updated_by_user_id,current_user.id)\n acc_cont.destroy\n end\n end\n\n if confirm.present?\n self.opportunities.each do |opp|\n opp.update_attributes(:stage => CompanyLookup.find_by_company_id_and_lvalue(self.company_id, \"Closed/Lost\").id, :reason => 'Contact Deactivated')\n Opportunity.destroy(opp.id)\n end\n end\n if self.members.present?\n self.members.each do |mem|\n mem.destroy!\n end\n end\n\n if self.matter_peoples.present?\n self.matter_peoples.each do |mp|\n mp.destroy\n end\n end\n \n Contact.destroy(self.id)\n end", "def delete\n MoxiworksPlatform::Contact.delete(self.to_hash)\n end", "def remove_contacts(*ruby_values)\n ruby_values.each {|val| self.contact_property.delete(RiCal::PropertyValue::Text.convert(self, val))}\n end", "def uncheck_remove_contact(contact)\n self.div(:id=>\"addpeople_selected_contacts_container\").link(:text=>contact).parent.checkbox.clear\n end", "def destroy\n @referral_contact.destroy\n end", "def uncheck_remove_contact(contact)\n @browser.div(:id=>\"addpeople_selected_contacts_container\").link(:text=>contact).parent.checkbox.clear\n end", "def delete\n\t\t#@@contacts -= [delete_id.to_i]\n\t\t@@contacts.delete(self)\n\tend", "def remove_contact(contact)\n case contact\n when User\n UserContact.destroy self.user_contacts.where(user_id: contact.id)\n when Email\n EmailContact.destroy self.email_contacts.where(email: contact.email)\n end\n end", "def contact_merge(contact_id, duplicate_contact_id)\n response = xmlrpc('ContactService.merge', contact_id, duplicate_contact_id)\n end", "def remove_contacts\n pars = contact_group_params\n contact_ids = []\n pars[:contact_ids].each do |cid|\n contact_ids << BSON::ObjectId.from_string(cid)\n end\n\n removed = Contact.where(uid: current_user.id).in(:_id => contact_ids).pull(contact_group_ids: @contact_group[:_id])\n\n respond_to do |format|\n format.html { redirect_to @contact_group,\n notice: \"#{removed.documents.first[:nModified]}\n #{(t :contacts_successfully_removed).gsub('%group_label%', @contact_group[:label])}.\" }\n format.json { render :show, status: :ok, location: @contact_group }\n end\n end", "def unsubscribe!(contact)\n # try to find the contact in the case watcher list\n subscriber = Case_Watcher_List.find(:first, :conditions => [\"case_watcher_id__c = ? AND contact_id__c = ?\",id,contact.id])\n # if the contact is in the subscriber list, delete the SF record and the local copy\n if subscriber\n subscriber.class.establish_connection :salesforce\n subscriber.destroy \n subscriber.clone.destroy if subscriber.clone\n elsif local_watcher = SfcaseWatcherList.find(:first, :conditions => [\"case_watcher_id__c = ? AND contact_id__c = ?\",id,contact.id])\n # couldn't find the SF record...delete the local one\n local_watcher.destroy\n end\n # if the subscriber list is empty, delete the case watcher as well\n if case_watcher_lists.empty?\n Case_Watcher_List.destroy(id)\n clone.destroy if clone\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
def set_company(company_name) if self.valid? unless company_name.nil? company_name = company_name.strip unless company_name.blank? company = Company.find_or_create_by_name company_name self.company_id = company.id self.company_name = company.name end end end end
def update_company company_name if self.valid? unless company_name.nil? company_name = company_name.strip if company_name.blank? self.company_id = 0 self.company_name = '' else company = Company.find_or_create_by_name company_name unless company.id == self.company_id self.company_id = company.id self.company_name = company.name end end end end end
[ "def company_name=(value)\n if value.present?\n if existing_company = Company.find_by_name(value)\n self.company = existing_company\n else\n self.build_company(:name => value)\n end\n else\n self.company = nil\n end\n end", "def setCompanyName(companyName)\r\n\t\t\t\t\t@companyName = companyName\r\n\t\t\t\tend", "def company_name=(value)\n @company_name = value\n end", "def check_co_name(company)\n company.update(name: 'Some Company AB') if company.name.blank?\n end", "def company=(new_company)\n new_company = nil if new_company.blank?\n super new_company\n end", "def company=(v)\n Axlsx.validate_string v\n @company = v\n end", "def set_Company(value)\n set_input(\"Company\", value)\n end", "def yomi_company_name=(value)\n @yomi_company_name = value\n end", "def assign_company_and_set_passenger\n self.type= 'Passenger'\n if self.email\n domain = self.email.split('@')[1]\n company = Company.find_or_initialize_by(domain: domain)\n if company.new_record?\n logger.debug 'creating company with '+domain\n company.name= domain\n company.address= 'unknown'\n end\n self.company = company\n self.default_office = company.offices.first if self.default_office.nil?\n else\n false\n end\n end", "def current_company=(company_obj)\n self.current_company_id = company_obj.id\n self.save\n end", "def default_company_name\n self.name = random_name if name.blank?\n end", "def create_company\n @company = Company.new(company_name: params[:company_name], key: generate_key)\n user = registered_user\n user.company = @company\n user.role = 'company'\n @company.users << user\n\n if @company.save && user.save\n UserNotifier.send_signup_email(user).deliver\n authenticate!\n else\n resource_not_saved\n @company.destroy\n user.destroy\n render 'new_company'\n end\n end", "def find_company_id(name)\n @company = Company.find_or_create_by(name: name)\n @company.id\n end", "def create\n @company = Company.new\n @company.name = params[:new_company][:name]\n @company.slug = @company.name.parameterize\n @company.state = COMPANY_STATE[:unchecked]\n @user = User.new\n if @company.save\n @user = @company.users.build\n @user.email = params[:new_company][:email]\n @user.name = t(:root)\n @user.state = STATE[:unchecked]\n @user.role = ROOT\n @user.password_digest = 0\n @user.locale = I18n.locale\n if @user.save\n UserMailer.verification_email(@user).deliver\n flash[:success] = t(:company_account_created)\n redirect_to company_signin_path @company.id\n else\n @company.destroy\n render 'new'\n end\n else\n render 'new'\n end\n end", "def yomi_company=(value)\n @yomi_company = value\n end", "def company_name\n @company_name\n end", "def create\n @company_name = CompanyName.new(company_name_params)\n\n respond_to do |format|\n if @company_name.save\n format.html { redirect_to @company_name, notice: 'Company name was successfully created.' }\n format.json { render :show, status: :created, location: @company_name }\n else\n format.html { render :new }\n format.json { render json: @company_name.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_up_company\n @company = Company.friendly.find(params[:company_id] || params[:id])\n result = JointUserCompany.find_by(user_id: @user.id, company_id: @company.id)\n if result.nil?\n self.dashboard_function()\n end\n end", "def create\n @company_contact = CompanyContact.new(params[:company_contact]) \n @company = Company.new(session[:company])\n @company.save\n @company_contact.company_id = @company.id\n @company_contact.save\n redirect_to @company\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save titles for contact
def save_contact_titles(positions) title_str= '' positions.each_with_index do |position, index| if position.is_current == 'true' company = Company.find_or_create_by_name(position.company.name) title = self.titles.build(:position => position.title, :company_id => company.id) title_str += ', ' unless index == 0 title_str += "#{title.position} at #{company.name}" end end self.update_attribute(:title, title_str) end
[ "def _before_save_title_checks\n populate_title_if_needed(:contents, TITLE_LENGTH)\n end", "def sync_titles\n # Title was submitted\n if self.title.blank?\n self.title = get_title_from_chartup(chartup) || 'Untitled'\n else\n set_chartup_title(self.title)\n end\n end", "def name_article\n puts \"What title would you like to give this article\"\n title = gets.chomp\n self.users_title = title\n self.save\n end", "def update_title(new_title)\n \t@title = new_title\n end", "def save\n c = Hash.new\n if @contacts.length > 0\n @contacts.keys.uniq.each do |l|\n c[l.to_s.to_sym] = Hash.new\n end\n end\n File.open(@rs_config.contacts_filename, \"wb\") do |file|\n file.puts '#--- ! RubySoulNG contacts file'\n file.puts c.to_yaml\n end\n end", "def SetTitle(title)\n #Title of document\n @title = title\n end", "def rename_title(edited_title)\n \t@title = edited_title\n end", "def save_title\n @todolist_file.puts\n save_bar('*', @title.length)\n @todolist_file.puts @title\n save_bar('*', @title.length)\n @todolist_file.puts\n end", "def save_changes\n\t \t\tset_title_value()\n\t \t\treturn super if @fields.empty? # if no fieldlets, save the normal way\n\t \t return false if !self.valid?\n\t \t\tself.db.transaction do\n\t \t\t\tif(@new)\n\t \t\t\t\tself.save\n\t \t\t\telse\t\n\t \t\t\t\tsuper #call for the inherited save action - saves the entity\n\t \t\t\tend\n\t \t\t\t\n\t \t\t\t@fields.save\n\t \t\tend\n\t \t\treturn true\n\t \tend", "def add_title\n @bib.title.to_bibtex @item\n end", "def updateTitle(id, title)\n item = Todo.find(id)\n item.title = title\n item.save\nend", "def insert_title(title, domain)\n sth = @connection.prepare(\"INSERT INTO tbl_title(title, domain, count) VALUES(?, ?, 1)\")\n sth.execute(title, domain)\n sth.finish\n end", "def store_title_text_stream # :nodoc:\n formula = @title_formula\n ai_type = _formula_type(2, 1, formula)\n\n store_text(*@config[:title_text])\n\n store_begin\n store_pos(*@config[:title_text_pos])\n store_fontx(7)\n store_ai(0, ai_type, formula)\n\n unless @title_name.nil?\n store_seriestext(@title_name, @title_encoding)\n end\n\n store_objectlink(1)\n store_end\n end", "def title_name(title_name)\n @title = title_name\n end", "def edit_book_title(selected_book, model)\n print \"New title: >>\"\n title = gets.chomp\n saved = selected_book.update_attributes(title: title)\n record_save_result(saved, selected_book, model)\nend", "def set_title(title)\n @title = title\n end", "def SetTitle(title)\n\t\t#Title of document\n\t\t@title = title\n\tend", "def specific_title(titles = nil)\n @titles = titles\n end", "def title(title) ; @question_title = title ; end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /transferences GET /transferences.json
def index @transferences = Transference.all end
[ "def index\n @payment_transferences = Payment::Transference.all\n end", "def index\n @transaccions = Transaccion.all\n end", "def index\n @transits = current_user.transits\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @transits }\n end\n end", "def index\n @transaktions = Transaktion.all\n end", "def create\n @transference = Transference.new(transference_params)\n\n respond_to do |format|\n if @transference.save\n format.html { redirect_to @transference, notice: 'Transference was successfully created.' }\n format.json { render :show, status: :created, location: @transference }\n else\n format.html { render :new }\n format.json { render json: @transference.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @committee = Committee.find(params[:committee_id])\n @instalments = @committee.instalments.reverse\n respond_to do |format|\n \tformat.json { render :json => @instalments.to_json }\n end\n end", "def index\n @tranvia = Tranvium.all\n render :json => @tranvia\n end", "def index\n @transacts = Transact.all\n end", "def index\n @transfers = Transfer.all\n render json: @transfers\n end", "def index\n @tangents = Tangent.all\n end", "def requests\n @veteran = Veteran.find(params[:id])\n requesters = @veteran.followers - @veteran.follows\n render json: requesters\n end", "def index\n @task_transitions = TaskTransition.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @task_transitions }\n end\n end", "def transactions\n @transactions = Transaction.where(\"user_id = ? AND mission_story_id = ?\", session[:user_id], params[:id])\n\n respond_to do |format|\n format.html\n format.json {render json: @transactions}\n end\n end", "def approver_transactions\n\ttransactions = Transaction.find_by approver_id: params[:id]\n\trender json: transactions, status: 200\n end", "def transitions\n require_parameters :issue\n issue_key = params[:issue]\n transitions = Internal.issues.listTransitions(issue_key)\n render :json => jsonp(\n {\n :transitions => transitions.map { |t| t.key() }\n }\n )\n end", "def index\n @transformation_ratio_transfromers = TransformationRatioTransfromer.all\n end", "def index\n @translinks = Translink.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @translinks }\n end\n end", "def index\n @kitty_trans = KittyTran.all\n end", "def index\n @transitarios = Transitario.all\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /transferences POST /transferences.json
def create @transference = Transference.new(transference_params) respond_to do |format| if @transference.save format.html { redirect_to @transference, notice: 'Transference was successfully created.' } format.json { render :show, status: :created, location: @transference } else format.html { render :new } format.json { render json: @transference.errors, status: :unprocessable_entity } end end end
[ "def index\n @transferences = Transference.all\n end", "def create\n @transation = Transation.new(transation_params)\n @stores = Store.all\n @representatives = Representative.all\n\n\n respond_to do |format|\n if @transation.save\n format.html { redirect_to action: \"index\", notice: \"Transation was successfully created.\" }\n format.json { render :show, status: :created, location: @transation }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @transation.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n \n @transcation = current_user.transcations.create(:amount => params[:transcation][:amount], :title => params[:transcation][:title])\n\n respond_to do |format|\n if @transcation.save\n format.html { redirect_to @transcation, notice: 'Transcation was successfully created.' }\n format.json { render json: @transcation, status: :created, location: @transcation }\n else\n format.html { render action: \"new\" }\n format.json { render json: @transcation.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @payment_transferences = Payment::Transference.all\n end", "def create\n @traduction = Traduction.new(traduction_params)\n @data = JSON.parse(open(URI.escape(\"http://translate.google.com/translate_a/t?client=p&q=\"+@traduction.fr+\"&hl=en&sl=fr&tl=en&ie=UTF-8&oe=UTF-8&multires=0\")).read)\n @tmp = @data['sentences'][0]['trans']\n @traduction.en = @tmp\n respond_to do |format|\n if @traduction.save\n format.html { redirect_to @traduction, notice: 'Traduction was successfully created.' }\n format.json { render action: 'show', status: :created, location: @traduction }\n else\n format.html { render action: 'home' }\n format.json { render json: @traduction.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @tranjection = Tranjection.new(tranjection_params)\n\n #@tranjection.\n\n respond_to do |format|\n if @tranjection.save\n format.html { redirect_to @tranjection, notice: \"Tranjection was successfully created.\" }\n format.json { render :show, status: :created, location: @tranjection }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @tranjection.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @transference.update(transference_params)\n format.html { redirect_to @transference, notice: 'Transference was successfully updated.' }\n format.json { render :show, status: :ok, location: @transference }\n else\n format.html { render :edit }\n format.json { render json: @transference.errors, status: :unprocessable_entity }\n end\n end\n end", "def destroy\n @transference.destroy\n respond_to do |format|\n format.html { redirect_to transferences_url, notice: 'Transference was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def create\n @tangent = Tangent.new(tangent_params)\n\n respond_to do |format|\n if @tangent.save\n format.html { redirect_to @tangent, notice: 'Tangent was successfully created.' }\n format.json { render action: 'show', status: :created, location: @tangent }\n else\n format.html { render action: 'new' }\n format.json { render json: @tangent.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @ticket_transcation = TicketTranscation.new(ticket_transcation_params)\n\n respond_to do |format|\n if @ticket_transcation.save\n format.html { redirect_to @ticket_transcation, notice: 'Ticket transcation was successfully created.' }\n format.json { render :show, status: :created, location: @ticket_transcation }\n else\n format.html { render :new }\n format.json { render json: @ticket_transcation.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @transcendence = Transcendence.new(transcendence_params)\n\n respond_to do |format|\n if @transcendence.save\n format.html { redirect_to @transcendence, notice: 'Transcendence was successfully created.' }\n format.json { render action: 'show', status: :created, location: @transcendence }\n else\n format.html { render action: 'new' }\n format.json { render json: @transcendence.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @translantion = Translantion.new(params[:translantion])\n\n respond_to do |format|\n if @translantion.save\n format.html { redirect_to @translantion, notice: 'Translantion was successfully created.' }\n format.json { render json: @translantion, status: :created, location: @translantion }\n else\n format.html { render action: \"new\" }\n format.json { render json: @translantion.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @transaccion = Transaccion.new(transaccion_params)\n\n respond_to do |format|\n if @transaccion.save\n format.html { redirect_to @transaccion, notice: 'Transaccion was successfully created.' }\n format.json { render :show, status: :created, location: @transaccion }\n else\n format.html { render :new }\n format.json { render json: @transaccion.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @transformation = Transformation.new(transformation_params)\n\n respond_to do |format|\n if @transformation.save\n format.html { redirect_to @transformation, notice: 'Transformation was successfully created.' }\n format.json { render :show, status: :created, location: @transformation }\n else\n format.html { render :new }\n format.json { render json: @transformation.errors, status: :unprocessable_entity }\n end\n end\n end", "def submit_transaction\n trans_id = \"IN\" + request.params[\"ref1\"] + request.params[\"ref2\"] + request.params[\"ref3\"] + request.params[\"ref4\"] + request.params[\"ref5\"] + request.params[\"ref6\"]\n url_send = \"http://stagingapi.instarem.com/v1/api/v1/GetPaymentDetails?RefNumber=\"+trans_id\n auth_token = check_login\n response = instarem_api(url_send , nil , auth_token)\n trans_response = JSON.parse(response.read_body)\n puts trans_response\n @trans = trans_response[\"responseData\"]\n end", "def create\n @transfer = Transfer.new(transfer_params)\n\n if @transfer.save\n render json: @transfer, status: :created, location: @transfer\n else\n render json: @transfer.errors, status: :unprocessable_entity\n end\n end", "def create\n #@transaction = Tranxaction.new(params[:tranxaction])\n @transaction = Tranxaction.new(params.require(:tranxaction).permit(:transaction_date, :description, { transaction_entries_attributes: [:debit_amount, :tranxaction_id, :account_id]}))\n\n respond_to do |format|\n if @transaction.save\n format.html { redirect_to @transaction, :notice => 'Transaction was successfully created.' }\n format.json { render :json => @transaction, :status => :created, :location => @transaction }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @transaction.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @tu_tran = TuTran.new(tu_tran_params)\n\n respond_to do |format|\n if @tu_tran.save\n format.html { redirect_to @tu_tran, notice: 'Tu tran was successfully created.' }\n format.json { render :show, status: :created, location: @tu_tran }\n else\n format.html { render :new }\n format.json { render json: @tu_tran.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @slate = Slate.new(slate_params)\n @slate.delegates << Delegate.where(id: params[:delegates])\n\n respond_to do |format|\n if @slate.save\n format.html { redirect_to @slate, notice: 'Slate was successfully created.' }\n format.json { render :show, status: :created, location: @slate }\n else\n format.html { render :new }\n format.json { render json: @slate.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /transferences/1 PATCH/PUT /transferences/1.json
def update respond_to do |format| if @transference.update(transference_params) format.html { redirect_to @transference, notice: 'Transference was successfully updated.' } format.json { render :show, status: :ok, location: @transference } else format.html { render :edit } format.json { render json: @transference.errors, status: :unprocessable_entity } end end end
[ "def update\n\n respond_to do |format|\n if @transact.update(transact_params)\n format.html { redirect_to @transact, notice: 'Transact was successfully updated.' }\n format.json { render :show, status: :ok, location: @transact }\n else\n format.html { render :edit }\n format.json { render json: @transact.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @payment_transference.update(payment_transference_params)\n format.html { redirect_to @payment_transference, notice: 'Transference was successfully updated.' }\n format.json { render :show, status: :ok, location: @payment_transference }\n else\n format.html { render :edit }\n format.json { render json: @payment_transference.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @trasnference.update(trasnference_params)\n format.html { redirect_to @trasnference, notice: 'Trasnference was successfully updated.' }\n format.json { render :show, status: :ok, location: @trasnference }\n else\n format.html { render :edit }\n format.json { render json: @trasnference.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @future_transaction.update(future_transaction_params)\n make_calcs(@future_transaction,future_transaction_params)\n respond_to do |format|\n if @future_transaction.update(future_transaction_params)\n format.html { redirect_to @future_transaction, notice: 'Future transaction was successfully updated.' }\n format.json { render :show, status: :ok, location: @future_transaction }\n else\n format.html { render :edit }\n format.json { render json: @future_transaction.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @transect.update(transect_params)\n format.html { redirect_to @transect, notice: 'Transect was successfully updated.' }\n format.json { render :show, status: :ok, location: @transect }\n else\n format.html { render :edit }\n format.json { render json: @transect.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @transect.update(transect_params)\n # format.html { redirect_to @transect, notice: 'Transect was successfully updated.' }\n format.html { redirect_to transects_path, notice: 'Transect was successfully updated.' }\n format.json { render :show, status: :ok, location: @transect }\n else\n format.html { render :edit }\n format.json { render json: @transect.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @transcendence.update(transcendence_params)\n format.html { redirect_to @transcendence, notice: 'Transcendence was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @transcendence.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @kitty_tran.update(kitty_tran_params)\n format.html { redirect_to @kitty_tran, notice: 'Kitty tran was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @kitty_tran.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @tx.update(tx_params)\n format.html { redirect_to @tx, notice: 'Tx was successfully updated.' }\n format.json { render :show, status: :ok, location: @tx }\n else\n format.html { render :edit }\n format.json { render json: @tx.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @translantion = Translantion.find(params[:id])\n\n respond_to do |format|\n if @translantion.update_attributes(params[:translantion])\n format.html { redirect_to @translantion, notice: 'Translantion was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @translantion.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @transfert.update(transfert_params)\n format.html { redirect_to @transfert, notice: 'Transfert was successfully updated.' }\n format.json { render :show, status: :ok, location: @transfert }\n else\n format.html { render :edit }\n format.json { render json: @transfert.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_tenant_circle(args = {}) \n put(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend", "def update\n respond_to do |format|\n format.any(:trips_json, :json) do\n if @trip.update(trip_params)\n head :no_content\n else\n render json: @trip.errors, status: :unprocessable_entity\n end\n end\n end\n end", "def update\n respond_to do |format|\n if @tangent.update(tangent_params)\n format.html { redirect_to @tangent, notice: 'Tangent was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @tangent.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @transformer = Transformer.find(params[:id])\n\n respond_to do |format|\n if @transformer.update_attributes(params[:transformer])\n format.html { redirect_to @transformer, notice: 'Transformer was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @transformer.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @transaktion.update(transaktion_params)\n format.html { redirect_to @transaktion, notice: 'Transaktion was successfully updated.' }\n format.json { render :show, status: :ok, location: @transaktion }\n else\n format.html { render :edit }\n format.json { render json: @transaktion.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @transcation = Transcation.find(params[:id])\n\n respond_to do |format|\n if @transcation.update_attributes(params[:transcation])\n format.html { redirect_to @transcation, notice: 'Transcation was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @transcation.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @cta.update(cta_params)\n format.html { redirect_to @cta, notice: 'cta was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @cta.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @transaction = Tranxaction.find(params[:id])\n\n respond_to do |format|\n if @transaction.update_attributes(params.require(:tranxaction).permit(:transaction_date, :description, { transaction_entries_attributes: [:debit_amount, :tranxaction_id, :account_id, :id, :_destroy]}))\n format.html { redirect_to @transaction, :notice => 'Transaction was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @transaction.errors, :status => :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /transferences/1 DELETE /transferences/1.json
def destroy @transference.destroy respond_to do |format| format.html { redirect_to transferences_url, notice: 'Transference was successfully destroyed.' } format.json { head :no_content } end end
[ "def destroy\n @transit = Transit.find(params[:id])\n @transit.destroy\n\n respond_to do |format|\n format.html { redirect_to transits_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @translantion = Translantion.find(params[:id])\n @translantion.destroy\n\n respond_to do |format|\n format.html { redirect_to translantions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @transact.destroy\n respond_to do |format|\n format.html { redirect_to transacts_url, notice: 'Transact was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @transaccion = Transaccion.find(params[:id])\n @transaccion.destroy\n\n respond_to do |format|\n format.html { redirect_to transacciones_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @transcation = Transcation.find(params[:id])\n @transcation.destroy\n\n respond_to do |format|\n format.html { redirect_to transcations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @transaccion.destroy\n respond_to do |format|\n format.html { redirect_to transacciones_url, notice: 'La transacción se eliminó correctamente.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @transaction = Tranxaction.find(params[:id])\n @transaction.destroy\n\n respond_to do |format|\n format.html { redirect_to tranxactions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @tipo_transaccion.destroy\n respond_to do |format|\n format.html { redirect_to tipo_transaccions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @transaccion.destroy\n respond_to do |format|\n format.html { redirect_to transaccions_url, notice: 'Transaccion was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @transation.destroy\n respond_to do |format|\n format.html { redirect_to transations_url, notice: \"Transation was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @trasnference.destroy\n respond_to do |format|\n format.html { redirect_to trasnferences_url, notice: 'Trasnference was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @translink = Translink.find(params[:id])\n @translink.destroy\n\n respond_to do |format|\n format.html { redirect_to translinks_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @txn = Txn.find(params[:id])\n @txn.destroy\n\n respond_to do |format|\n format.html { redirect_to txns_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @transfert.destroy\n respond_to do |format|\n format.html { redirect_to transferts_url, notice: 'Transfert was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @transito = Transito.find(params[:id])\n @transito.destroy\n\n respond_to do |format|\n format.html { redirect_to(transitos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @tx.destroy\n respond_to do |format|\n format.html { redirect_to txes_url, notice: 'Tx was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @transcendence.destroy\n respond_to do |format|\n format.html { redirect_to transcendences_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @trans_dot = TransDot.find(params[:id])\n @trans_dot.destroy\n\n respond_to do |format|\n format.html { redirect_to(trans_dots_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @transfer = Transfer.find(params[:id]) \n @transfer.destroy\n\n respond_to do |format|\n format.html { redirect_to transfers_url }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Amazon's description: > Call the CloseOrderReference operation to indicate that a previously > confirmed order reference has been fulfilled (fully or partially) and that > you do not expect to create any new authorizations on this order > reference. You can still capture funds against open authorizations on the > order reference. > After you call this operation, the order reference is moved into the > Closed state.
def close_order_reference client.close_order_reference(@amazon_order_reference_id) end
[ "def close_order_reference(options = {})\n requires!(options, :amazon_order_reference_id)\n commit('CloseOrderReference', options)\n end", "def cancel_order_reference(options = {})\n requires!(options, :amazon_order_reference_id)\n commit('CancelOrderReference', options)\n end", "def confirm_order_reference(options = {})\n requires!(options, :amazon_order_reference_id)\n commit('ConfirmOrderReference', options)\n end", "def close_billing_agreement(options = {})\n requires!(options, :amazon_billing_agreement_id)\n commit('CloseBillingAgreement', options)\n end", "def cancel(original_reference:, reference:, merchantAccount: @merchant_account)\n postJSON(\"/Payment/v12/cancel\",\n reference: reference,\n merchantAccount: merchant_account,\n originalReference: original_reference\n )\n end", "def cancel_or_refund(original_reference:, reference:, merchantAccount: @merchant_account)\n postJSON(\"/Payment/v12/cancelOrRefund\",\n reference: reference,\n merchantAccount: merchant_account,\n originalReference: original_reference\n )\n end", "def refund(original_reference:, amount:, reference:, merchantAccount: @merchant_account, currency: @currency)\n postJSON(\"/Payment/v12/refund\",\n reference: reference,\n merchantAccount: merchant_account,\n modificationAmount: { value: amount, currency: currency },\n originalReference: original_reference\n )\n end", "def get_order_reference_details(options = {})\n requires!(options, :amazon_order_reference_id)\n commit('GetOrderReferenceDetails', options)\n end", "def set_order_reference_details(options = {})\n requires!(options, :amazon_order_reference_id, :order_reference_attributes)\n requires!(options[:order_reference_attributes], :order_total)\n requires!(options[:order_reference_attributes][:order_total], :amount, :currency_code)\n commit('SetOrderReferenceDetails', options)\n end", "def close_issue(options = {})\n github_client.close_issue(context.repo, context.issue_id, options)\n end", "def close_authorization(options = {})\n requires!(options, :amazon_authorization_id)\n commit('CloseAuthorization', options)\n end", "def refund_order\n\t\t@order = Order.find(params[:order_id])\n\n\t\tif @order.refunded\n\t\t\trender :json => { :error => \"Order has already been refunded\" }\n\t\telse \n\t\t\tcharge = Stripe::Charge.retrieve(order.charge_id)\n\t\t\trefund = charge.refunds.create\n\t\t\trender :json => { :refunded => true, :refund_id => refund.id, :message => \"Order refunded successfully\" }\n\t\tend\n\n\tend", "def set_order_reference_details(\n amazon_order_reference_id,\n amount,\n currency_code: @currency_code,\n platform_id: nil,\n seller_note: nil,\n seller_order_id: nil,\n request_payment_authorization: nil,\n store_name: nil,\n order_item_categories: nil,\n custom_information: nil,\n supplementary_data: nil,\n merchant_id: @merchant_id,\n mws_auth_token: nil\n )\n\n parameters = {\n 'Action' => 'SetOrderReferenceDetails',\n 'SellerId' => merchant_id,\n 'AmazonOrderReferenceId' => amazon_order_reference_id,\n 'OrderReferenceAttributes.OrderTotal.Amount' => amount,\n 'OrderReferenceAttributes.OrderTotal.CurrencyCode' => currency_code\n }\n\n optional = {\n 'OrderReferenceAttributes.PlatformId' => platform_id,\n 'OrderReferenceAttributes.RequestPaymentAuthorization' => request_payment_authorization,\n 'OrderReferenceAttributes.SellerNote' => seller_note,\n 'OrderReferenceAttributes.SellerOrderAttributes.SellerOrderId' => seller_order_id,\n 'OrderReferenceAttributes.SellerOrderAttributes.StoreName' => store_name,\n 'OrderReferenceAttributes.SellerOrderAttributes.CustomInformation' => custom_information,\n 'OrderReferenceAttributes.SellerOrderAttributes.SupplementaryData' => supplementary_data,\n 'MWSAuthToken' => mws_auth_token\n }\n\n if order_item_categories\n optional.merge!(\n get_categories_list(\n 'OrderReferenceAttributes',\n order_item_categories\n )\n )\n end\n\n operation(parameters, optional)\n end", "def cancel_order(options)\n request :account, :delete, 'order', options\n end", "def refund_transaction(options = {})\n requires! options, :reference_number, :amount\n\n request = build_request(__method__, options)\n commit(__method__, request)\n end", "def cancel_order(symbol:, order_id: nil, orig_client_order_id: nil, new_client_order_id: nil, recv_window: nil)\n params = {\n symbol: symbol\n }\n params[:orderId] = order_id if order_id\n params[:origClientOrderId] = orig_client_order_id if orig_client_order_id\n params[:newClientOrderId] = new_client_order_id if new_client_order_id\n params[:recvWindow] = recv_window if recv_window\n\n SignedRequest.perform({\n request_method: :delete,\n path: '/api/v3/order',\n params: params,\n })\n end", "def refund(money, tx_reference, options = {})\n post = {}\n add_money(post, money, options)\n action = STANDARD_ACTIONS[:refund][:end_point].gsub(/{{charge_id}}/, tx_reference)\n post = filter_gateway_fields(post, options, STANDARD_ACTIONS[:refund][:allowed_fields])\n commit(action, post)\n end", "def cancel_unshipped_order(invoice)\n transaction do\n self.update_attributes(active: false)\n invoice.cancel_authorized_payment\n end\n end", "def get_order_reference_details(\n amazon_order_reference_id,\n address_consent_token: nil,\n access_token: nil,\n merchant_id: @merchant_id,\n mws_auth_token: nil\n )\n\n parameters = {\n 'Action' => 'GetOrderReferenceDetails',\n 'SellerId' => merchant_id,\n 'AmazonOrderReferenceId' => amazon_order_reference_id\n }\n\n optional = {\n # Preseving address_consent_token for backwards compatibility\n # AccessToken returns all data in AddressConsentToken plus new data\n 'AccessToken' => access_token || address_consent_token,\n 'MWSAuthToken' => mws_auth_token\n }\n\n operation(parameters, optional)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform a key lookup in the registered data tables
def table_lookup(key, arg, table = nil) lookup_key = key[1..-1].to_sym lookup_table = table || @tables[lookup_key] if lookup_table.kind_of? Hash lookup_table[arg.to_sym] elsif lookup_table.kind_of? Array if lookup_table.member? arg or lookup_table.member? arg.to_sym arg else raise "Invalid argument" end elsif lookup_table.kind_of? Proc table_lookup(key, arg, lookup_table.call) else raise "Unknown lookup table type" end #table[1][arg.to_sym] unless table.nil? end
[ "def lookup_keys\n @lookup_keys ||= %i[id name login email number] & attribute_names.map(&:to_sym)\n end", "def load_specified(table, key)\n self.table = table\n self.key = key\n load\n end", "def already_loaded_records_by_key; end", "def data_key(name, data) ; name end", "def call(*lookup)\n\t\treturn KeyDialler.new(self, *lookup).call\n\tend", "def internal_lookup(name)\n name = name.to_s\n # TODO: Check if name is a valid name\n if Gem::Version.new(::Hiera.version) > Gem::Version.new('2.0.0')\n @values_table.fetch(name) do\n Connect.debug(\"looked up '#{name}' but found nothing\")\n throw :no_such_key\n end\n else\n @values_table.fetch(name) { Entry::Value.new(nil) }\n end\n end", "def db_keys; end", "def in_table?(key)\n (@subroutine.key?(key) || @class.key?(key))\n end", "def find(key)\n @data[key]\n end", "def fetch(key)\n key = find_key_case(key)\n val = nil\n val = super if(@imported_by[key] != 'self')\n if (val.nil? and @_module and @_module.framework)\n val = @_module.framework.datastore[key]\n end\n val = super if val.nil?\n val\n end", "def resolve(key); end", "def search(key)\n backend.find(key)\n end", "def define_static_cache_key_finder#:nodoc:\n return unless acts_as_static_record_options[:find_by_attribute_support]\n #define the key column if it is not a hash column\n if ((key_column = acts_as_static_record_options[:key]) &&\n (!column_methods_hash.include?(key_column.to_sym)))\n class_eval %{\n def self.find_by_#{key_column}(arg)\n self.static_record_cache[:key][arg.to_s]\n end\n }, __FILE__, __LINE__\n end\n end", "def collect_key(*arg)\n \n table= arg[0][:table]\n cle = arg[0][:key]||'id'\n t= _create_class(table)\n request= \"Tempo_\" + table\n array_cle= eval \"#{request}.find_by_sql \\\"SELECT #{cle} FROM #{table} \\\"\"\n puts array_cle.count\n array_cle\n end", "def primary_key_lookup(pk)\n return super unless use_prepared_statements_for_pk_lookup?\n # SEQUEL5: Remove\n prepared_lookup.call(primary_key_hash(pk))\n end", "def lookup!(key)\n dependencies[key]\n end", "def prepared_lookup_dataset(ds)\n cached_prepared_statement(:lookup_sql, ds.sql){prepare_statement(ds.where(prepared_statement_key_array(primary_key).map{|k, v| [SQL::QualifiedIdentifier.new(ds.model.table_name, k), v]}), :first)}\n end", "def getUserMetaByKey(key)\n return database[:accounts][:key => key]\nend", "def load_chemist_by_key(key)\n @tables.each do |table|\n chemist_data = table.find { |row| row[:key] == key }\n chemist = make_chemist(key, chemist_data[:type], chemist_data) if chemist_data\n return fetch_from_cache(chemist) if chemist\n end\n raise ArgumentError, \"Chemist for type \\\"#{key}\\\" not found!\"\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete tags from a learnerId Delete the specified tags from the learner. Deleting tags that do not exist will still result in a success.
def delete_learner_tags(learner_id, tags, opts = {}) delete_learner_tags_with_http_info(learner_id, tags, opts) nil end
[ "def delete_learner_tags_with_http_info(learner_id, tags, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: LearnerApi.delete_learner_tags ...'\n end\n # verify the required parameter 'learner_id' is set\n if learner_id.nil?\n fail ArgumentError, \"Missing the required parameter 'learner_id' when calling LearnerApi.delete_learner_tags\"\n end\n # verify the required parameter 'tags' is set\n if tags.nil?\n fail ArgumentError, \"Missing the required parameter 'tags' when calling LearnerApi.delete_learner_tags\"\n end\n # resource path\n local_var_path = '/learner/{learnerId}/tags'.sub('{' + 'learnerId' + '}', learner_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'])\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(tags)\n auth_names = ['APP_NORMAL', 'OAUTH']\n data, status_code, headers = @api_client.call_api(:DELETE, 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: LearnerApi#delete_learner_tags\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def bookmarks_tags_delete(id, *tags)\n request(:bookmarks_tags_delete, :id => id, :tags => tags)\n end", "def delete_tags\n @tags.delete_tags(@filename) unless @tags.nil?\n end", "def batch_delete_tag(batch_client, tags)\n perform_delete_tag(batch_client, tags)\n end", "def perform_delete_tags(batch_client, tags)\n self.class.make_request(client, batch_client, :delete_tag, scope_parameters.merge(\n self.class.primary_key_name => primary_key,\n tags: tags\n ))\n end", "def del_unused\n if params[:tags_ids].nil?\n flash[:notice] = l('tags.no_tags_selected')\n redirect_to :action => \"index\"\n else\n @tags = Tag.find_all_by_id params[:tags_ids]\n @tags = @tags.to_a.map(&:name)\n Tag.destroy params[:tags_ids]\n flash[:notice] = \"#{l('tags.deleted_tags')}: #{@tags.join(\", \")}\"\n redirect_to :action => \"index\"\n end\n end", "def tag_delete(id, tag)\n wf_source_id?(id)\n wf_string?(tag)\n api.delete([id, 'tag', tag].uri_concat)\n end", "def delete(*tags_or_ids)\n execute_only(:delete, *tags_or_ids)\n end", "def tag_delete(id, tag)\n wf_event_id?(id)\n wf_string?(tag)\n api.delete([id, 'tag', tag].uri_concat)\n end", "def delete_tags(tags)\n params = {}\n tags.each_with_index do |tag, i|\n tag.each do |key, value|\n params[\"Tags.member.#{i+1}.#{key}\"] = value unless value.nil?\n end\n end\n request({\n 'Action' => 'DeleteTags',\n :parser => Fog::Parsers::AWS::AutoScaling::Basic.new\n }.merge!(params))\n end", "def delete_tag(project_id, tag_id)\n delete \"projects/#{project_id}/tags/#{tag_id}\"\n end", "def destroy_tag(tag_id)\n tag_id = DomainEnumerated.is_an_integer(tag_id)\n raise \"Unknown tag tag_id=#{tag_id}\" unless tag_id and tag_ids.include?(tag_id)\n descriptor[:tag_ids].delete(tag_id)\n update_attribute(:descriptor, descriptor)\n begin\n dtag = Dtag.find(tag_id)\n rescue\n \n else\n dtag.destroy\n end\n\n end", "def delete_course_tags_with_http_info(course_id, tags, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: CourseApi.delete_course_tags ...'\n end\n # verify the required parameter 'course_id' is set\n if course_id.nil?\n fail ArgumentError, \"Missing the required parameter 'course_id' when calling CourseApi.delete_course_tags\"\n end\n # verify the required parameter 'tags' is set\n if tags.nil?\n fail ArgumentError, \"Missing the required parameter 'tags' when calling CourseApi.delete_course_tags\"\n end\n # resource path\n local_var_path = '/courses/{courseId}/tags'.sub('{' + 'courseId' + '}', course_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'])\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(tags)\n auth_names = ['APP_NORMAL', 'OAUTH']\n data, status_code, headers = @api_client.call_api(:DELETE, 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: CourseApi#delete_course_tags\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def delete(*keys)\n return if keys.empty?\n keys = keys.map { |k, v| { :key => k.to_s } }\n client.remove_tags api_args.merge(:tags => keys)\n end", "def delete_tags(name); end", "def remove_tags(alert_ids, tag_names)\n query = generate_query_params(alertIds: alert_ids, tagNames: tag_names)\n http_delete('/tags' + query)\n end", "def delete_tag(model, text)\n model_tag = model.model_tags.find_by(name: text, user_ids: self.id)\n if model_tag\n model_tag.user_ids.delete(self.id)\n model_tag.inc(:taggings_count, -1)\n\n model_tag.save\n model.reload\n end\n model.model_tags.destroy_all(taggings_count: 0)\n\n tag = Tag.find_by(name: text)\n if tag.taggings.destroy_all(tagger: self, taggable: model)\n tag.inc(:taggings_count, -1)\n end\n\n Tag.destroy_all(taggings_count: 0)\n end", "def delete_from(taggable, tags)\n delete_all ['taggable_id = ? and taggable_type = ? and tag_id in (?)', \n taggable.id, taggable.class.base_class.name, tags.collect { |t| t.is_a?(Tag) ? t.id : t }] if tags.any?\n end", "def delete_all_tags\n for tag in tags\n tag.reload\n tag.unlink\n end\n tags.clear\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete tags from a learnerId Delete the specified tags from the learner. Deleting tags that do not exist will still result in a success.
def delete_learner_tags_with_http_info(learner_id, tags, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: LearnerApi.delete_learner_tags ...' end # verify the required parameter 'learner_id' is set if learner_id.nil? fail ArgumentError, "Missing the required parameter 'learner_id' when calling LearnerApi.delete_learner_tags" end # verify the required parameter 'tags' is set if tags.nil? fail ArgumentError, "Missing the required parameter 'tags' when calling LearnerApi.delete_learner_tags" end # resource path local_var_path = '/learner/{learnerId}/tags'.sub('{' + 'learnerId' + '}', learner_id.to_s) # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/json']) # form parameters form_params = {} # http body (model) post_body = @api_client.object_to_http_body(tags) auth_names = ['APP_NORMAL', 'OAUTH'] data, status_code, headers = @api_client.call_api(:DELETE, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) if @api_client.config.debugging @api_client.config.logger.debug "API called: LearnerApi#delete_learner_tags\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end
[ "def bookmarks_tags_delete(id, *tags)\n request(:bookmarks_tags_delete, :id => id, :tags => tags)\n end", "def delete_learner_tags(learner_id, tags, opts = {})\n delete_learner_tags_with_http_info(learner_id, tags, opts)\n nil\n end", "def delete_tags\n @tags.delete_tags(@filename) unless @tags.nil?\n end", "def batch_delete_tag(batch_client, tags)\n perform_delete_tag(batch_client, tags)\n end", "def perform_delete_tags(batch_client, tags)\n self.class.make_request(client, batch_client, :delete_tag, scope_parameters.merge(\n self.class.primary_key_name => primary_key,\n tags: tags\n ))\n end", "def del_unused\n if params[:tags_ids].nil?\n flash[:notice] = l('tags.no_tags_selected')\n redirect_to :action => \"index\"\n else\n @tags = Tag.find_all_by_id params[:tags_ids]\n @tags = @tags.to_a.map(&:name)\n Tag.destroy params[:tags_ids]\n flash[:notice] = \"#{l('tags.deleted_tags')}: #{@tags.join(\", \")}\"\n redirect_to :action => \"index\"\n end\n end", "def tag_delete(id, tag)\n wf_source_id?(id)\n wf_string?(tag)\n api.delete([id, 'tag', tag].uri_concat)\n end", "def delete(*tags_or_ids)\n execute_only(:delete, *tags_or_ids)\n end", "def tag_delete(id, tag)\n wf_event_id?(id)\n wf_string?(tag)\n api.delete([id, 'tag', tag].uri_concat)\n end", "def delete_tags(tags)\n params = {}\n tags.each_with_index do |tag, i|\n tag.each do |key, value|\n params[\"Tags.member.#{i+1}.#{key}\"] = value unless value.nil?\n end\n end\n request({\n 'Action' => 'DeleteTags',\n :parser => Fog::Parsers::AWS::AutoScaling::Basic.new\n }.merge!(params))\n end", "def delete_tag(project_id, tag_id)\n delete \"projects/#{project_id}/tags/#{tag_id}\"\n end", "def destroy_tag(tag_id)\n tag_id = DomainEnumerated.is_an_integer(tag_id)\n raise \"Unknown tag tag_id=#{tag_id}\" unless tag_id and tag_ids.include?(tag_id)\n descriptor[:tag_ids].delete(tag_id)\n update_attribute(:descriptor, descriptor)\n begin\n dtag = Dtag.find(tag_id)\n rescue\n \n else\n dtag.destroy\n end\n\n end", "def delete_course_tags_with_http_info(course_id, tags, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: CourseApi.delete_course_tags ...'\n end\n # verify the required parameter 'course_id' is set\n if course_id.nil?\n fail ArgumentError, \"Missing the required parameter 'course_id' when calling CourseApi.delete_course_tags\"\n end\n # verify the required parameter 'tags' is set\n if tags.nil?\n fail ArgumentError, \"Missing the required parameter 'tags' when calling CourseApi.delete_course_tags\"\n end\n # resource path\n local_var_path = '/courses/{courseId}/tags'.sub('{' + 'courseId' + '}', course_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'])\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(tags)\n auth_names = ['APP_NORMAL', 'OAUTH']\n data, status_code, headers = @api_client.call_api(:DELETE, 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: CourseApi#delete_course_tags\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def delete(*keys)\n return if keys.empty?\n keys = keys.map { |k, v| { :key => k.to_s } }\n client.remove_tags api_args.merge(:tags => keys)\n end", "def delete_tags(name); end", "def remove_tags(alert_ids, tag_names)\n query = generate_query_params(alertIds: alert_ids, tagNames: tag_names)\n http_delete('/tags' + query)\n end", "def delete_tag(model, text)\n model_tag = model.model_tags.find_by(name: text, user_ids: self.id)\n if model_tag\n model_tag.user_ids.delete(self.id)\n model_tag.inc(:taggings_count, -1)\n\n model_tag.save\n model.reload\n end\n model.model_tags.destroy_all(taggings_count: 0)\n\n tag = Tag.find_by(name: text)\n if tag.taggings.destroy_all(tagger: self, taggable: model)\n tag.inc(:taggings_count, -1)\n end\n\n Tag.destroy_all(taggings_count: 0)\n end", "def delete_from(taggable, tags)\n delete_all ['taggable_id = ? and taggable_type = ? and tag_id in (?)', \n taggable.id, taggable.class.base_class.name, tags.collect { |t| t.is_a?(Tag) ? t.id : t }] if tags.any?\n end", "def delete_all_tags\n for tag in tags\n tag.reload\n tag.unlink\n end\n tags.clear\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get tags for a learnerId Returns the tags for the learner.
def get_learner_tags(learner_id, opts = {}) data, _status_code, _headers = get_learner_tags_with_http_info(learner_id, opts) data end
[ "def get_learner_tags_with_http_info(learner_id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: LearnerApi.get_learner_tags ...'\n end\n # verify the required parameter 'learner_id' is set\n if learner_id.nil?\n fail ArgumentError, \"Missing the required parameter 'learner_id' when calling LearnerApi.get_learner_tags\"\n end\n # resource path\n local_var_path = '/learner/{learnerId}/tags'.sub('{' + 'learnerId' + '}', learner_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'])\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 = ['APP_NORMAL', 'OAUTH']\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 => 'TagListSchema')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: LearnerApi#get_learner_tags\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def tags(id)\n wf_source_id?(id)\n api.get([id, 'tag'].uri_concat)\n end", "def tags(id)\n wf_event_id?(id)\n api.get([id, 'tag'].uri_concat)\n end", "def gettags(tag_or_id)\n execute(:gettags, tag_or_id).to_a\n end", "def get_course_tags(course_id, opts = {})\n data, _status_code, _headers = get_course_tags_with_http_info(course_id, opts)\n data\n end", "def tags\n get.tagGuids\n end", "def list(user_id)\n @_client.get(\"/users/#{user_id}/tags\")\n end", "def machine_tags(review_id, tag_prompt_deployment_id=nil)\n tags = AnswerTag.where(answer_id: review_id).where.not(confidence_level: nil)\n tags = tags.where(tag_prompt_deployment_id: tag_prompt_deployment_id) if tag_prompt_deployment_id\n tags\n end", "def skill_tags\n return @skill_tags\n end", "def list_service_offering_tags(id, opts = {})\n data, _status_code, _headers = list_service_offering_tags_with_http_info(id, opts)\n data\n end", "def get_invitation_tags(invitation_id, opts = {})\n data, _status_code, _headers = get_invitation_tags_with_http_info(invitation_id, opts)\n data\n end", "def skill_tags=(value)\n @skill_tags = value\n end", "def list_tag_network_adapters(id, opts = {})\n data, _status_code, _headers = list_tag_network_adapters_with_http_info(id, opts)\n data\n end", "def tags\n tags_from_words = []\n if self.id\n tags_from_words = Word.where(paradigm_id: self.id).map {|w| w.tag}\n# puts \"Tag associated with the current paradigm (#{tags_from_words.length}): #{tags_from_words.inspect}\"\n end\n\n tags_from_pdg_type = self.paradigm_type.tags\n unless tags_from_words.empty?\n # do not include NOTAG if there are other tags\n tags_from_pdg_type = tags_from_pdg_type.reject {|tag| tag.notag? }\n end\n\n (tags_from_pdg_type + tags_from_words).uniq\n end", "def list_tags_for_node(node_id, opts = {})\n data, _status_code, _headers = list_tags_for_node_with_http_info(node_id, opts)\n return data\n end", "def getTags\r\n\t\t\t\t\treturn @tags\r\n\t\t\t\tend", "def list(project_id)\n @_client.get(\"/projects/#{project_id}/tags\")\n end", "def current_hacker_tags(hacker_id)\n find_by_sql(\"SELECT DISTINCT t.* FROM tags AS t\n JOIN entries_tags AS et ON et.tag_id = t.id\n JOIN entries AS e ON e.id = et.entry_id\n WHERE e.hacker_id = #{hacker_id}\n ORDER BY t.name;\")\n end", "def get_tags(payment_id, opts = {})\n data, _status_code, _headers = get_tags_with_http_info(payment_id, opts)\n return data\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get tags for a learnerId Returns the tags for the learner.
def get_learner_tags_with_http_info(learner_id, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: LearnerApi.get_learner_tags ...' end # verify the required parameter 'learner_id' is set if learner_id.nil? fail ArgumentError, "Missing the required parameter 'learner_id' when calling LearnerApi.get_learner_tags" end # resource path local_var_path = '/learner/{learnerId}/tags'.sub('{' + 'learnerId' + '}', learner_id.to_s) # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/json']) # form parameters form_params = {} # http body (model) post_body = nil auth_names = ['APP_NORMAL', 'OAUTH'] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'TagListSchema') if @api_client.config.debugging @api_client.config.logger.debug "API called: LearnerApi#get_learner_tags\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end
[ "def get_learner_tags(learner_id, opts = {})\n data, _status_code, _headers = get_learner_tags_with_http_info(learner_id, opts)\n data\n end", "def tags(id)\n wf_source_id?(id)\n api.get([id, 'tag'].uri_concat)\n end", "def tags(id)\n wf_event_id?(id)\n api.get([id, 'tag'].uri_concat)\n end", "def gettags(tag_or_id)\n execute(:gettags, tag_or_id).to_a\n end", "def get_course_tags(course_id, opts = {})\n data, _status_code, _headers = get_course_tags_with_http_info(course_id, opts)\n data\n end", "def tags\n get.tagGuids\n end", "def list(user_id)\n @_client.get(\"/users/#{user_id}/tags\")\n end", "def machine_tags(review_id, tag_prompt_deployment_id=nil)\n tags = AnswerTag.where(answer_id: review_id).where.not(confidence_level: nil)\n tags = tags.where(tag_prompt_deployment_id: tag_prompt_deployment_id) if tag_prompt_deployment_id\n tags\n end", "def skill_tags\n return @skill_tags\n end", "def list_service_offering_tags(id, opts = {})\n data, _status_code, _headers = list_service_offering_tags_with_http_info(id, opts)\n data\n end", "def get_invitation_tags(invitation_id, opts = {})\n data, _status_code, _headers = get_invitation_tags_with_http_info(invitation_id, opts)\n data\n end", "def skill_tags=(value)\n @skill_tags = value\n end", "def list_tag_network_adapters(id, opts = {})\n data, _status_code, _headers = list_tag_network_adapters_with_http_info(id, opts)\n data\n end", "def tags\n tags_from_words = []\n if self.id\n tags_from_words = Word.where(paradigm_id: self.id).map {|w| w.tag}\n# puts \"Tag associated with the current paradigm (#{tags_from_words.length}): #{tags_from_words.inspect}\"\n end\n\n tags_from_pdg_type = self.paradigm_type.tags\n unless tags_from_words.empty?\n # do not include NOTAG if there are other tags\n tags_from_pdg_type = tags_from_pdg_type.reject {|tag| tag.notag? }\n end\n\n (tags_from_pdg_type + tags_from_words).uniq\n end", "def list_tags_for_node(node_id, opts = {})\n data, _status_code, _headers = list_tags_for_node_with_http_info(node_id, opts)\n return data\n end", "def getTags\r\n\t\t\t\t\treturn @tags\r\n\t\t\t\tend", "def list(project_id)\n @_client.get(\"/projects/#{project_id}/tags\")\n end", "def current_hacker_tags(hacker_id)\n find_by_sql(\"SELECT DISTINCT t.* FROM tags AS t\n JOIN entries_tags AS et ON et.tag_id = t.id\n JOIN entries AS e ON e.id = et.entry_id\n WHERE e.hacker_id = #{hacker_id}\n ORDER BY t.name;\")\n end", "def get_tags(payment_id, opts = {})\n data, _status_code, _headers = get_tags_with_http_info(payment_id, opts)\n return data\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add tags to a learnerId Applies the provided tags to the learner. Tags are used to easily identify resources. Adding tags can enable more refined searches when working with Reportage.
def put_learner_tags_with_http_info(learner_id, tags, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: LearnerApi.put_learner_tags ...' end # verify the required parameter 'learner_id' is set if learner_id.nil? fail ArgumentError, "Missing the required parameter 'learner_id' when calling LearnerApi.put_learner_tags" end # verify the required parameter 'tags' is set if tags.nil? fail ArgumentError, "Missing the required parameter 'tags' when calling LearnerApi.put_learner_tags" end # resource path local_var_path = '/learner/{learnerId}/tags'.sub('{' + 'learnerId' + '}', learner_id.to_s) # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/json']) # form parameters form_params = {} # http body (model) post_body = @api_client.object_to_http_body(tags) auth_names = ['APP_NORMAL', 'OAUTH'] data, status_code, headers = @api_client.call_api(:PUT, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names) if @api_client.config.debugging @api_client.config.logger.debug "API called: LearnerApi#put_learner_tags\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end
[ "def bookmarks_tags_add(id, *tags)\n request(:bookmarks_tags_add, :id => id, :tags => tags)\n end", "def add_tags(*tags)\n @tags += tags\n end", "def add_tags(tags)\n tags.each { |tag| add_tag(tag) }\n end", "def get_learner_tags_with_http_info(learner_id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: LearnerApi.get_learner_tags ...'\n end\n # verify the required parameter 'learner_id' is set\n if learner_id.nil?\n fail ArgumentError, \"Missing the required parameter 'learner_id' when calling LearnerApi.get_learner_tags\"\n end\n # resource path\n local_var_path = '/learner/{learnerId}/tags'.sub('{' + 'learnerId' + '}', learner_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'])\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 = ['APP_NORMAL', 'OAUTH']\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 => 'TagListSchema')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: LearnerApi#get_learner_tags\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def add_tags(alert_ids, tags)\n query = generate_query_params(alertIds: alert_ids, tags: tags)\n http_put('/tags' + query, {})\n end", "def add_tags(host_id, tags, source=nil)\n @tag_svc.add(host_id, tags, source)\n end", "def add_tags(resource_id, tags)\n tags_arr = tags.map { |k, v| { 'Key' => k, 'Value' => v } }\n request({\n 'Action' => 'AddTags',\n 'ResourceArns.member.1' => resource_id,\n :parser => Fog::Parsers::AWS::ELBV2::Empty.new,\n }.merge(Fog::AWS.serialize_keys(tags_arr)))\n end", "def add_tags(*tags)\n @hash_tags.concat(tags.flatten)\n end", "def add_tags(tags)\n tags = csv_to_a(tags) if tags.is_a? String\n @tags += tags\n end", "def add_tag_to_resource(id, tag)\n tag.gsub!(\" \", \"_\")\n url = \"#{@api_base_path}/resources/#{id}/tags\"\n\n handle_timeouts do\n response = self.class.post(url, headers: auth_header,\n body: { add: tag })\n JSON.parse(response.body)['new_list']\n end\n end", "def update_conversation_tags(id, tags)\n data = { tags: tags }\n put(\"conversations/#{id}/tags\", { body: data })\n end", "def tag_add(id, tag)\n wf_event_id?(id)\n wf_string?(tag)\n api.put([id, 'tag', tag].uri_concat)\n end", "def create_tag(recipe_id, tags)\n\t\t\t\tdestroy_tags = RecipeTag.where(recipe_id: recipe_id)\n\t\t\t\tif !destroy_tags.blank? \n\t\t\t\t\tdestroy_tags.delete_all\n\t\t\t\tend\n\t\t\t\ttags.each do |recipe_tag|\n\t\t\t\t\ttag = RecipeTag.new\n\t\t\t\t\ttag.recipe_id = recipe_id\n\t\t\t\t\ttag.tag = recipe_tag\n\t\t\t\t\ttag.save!\n\t\t\t\tend\n\t\t\tend", "def add_tags(tags)\n @hash_store.add_tags(tags)\n end", "def add_tags(tags)\n @interface.add_tags_to_image(self, tags)\n end", "def tags(id)\n wf_source_id?(id)\n api.get([id, 'tag'].uri_concat)\n end", "def add_tags(*new_tags)\n raise TypeError, \"Must set agent= before using tag manager\" unless @agent\n @agent.update_tags(new_tags, [])\n true\n end", "def tag *tags\n @tags += tags\n self\n end", "def tag(*tags)\n tags.each { |tag| @tags << tag }\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
It's important to regularly remove devices that Apple reports as stale. If you continue to try to notify stale devices, Apple may revoke your access to APNS!
def deactivate_stale_devices! device_tokens = client.devices Rails.logger.info "Found #{device_tokens.length} stale devices." device_tokens.each do |device_token| Rails.logger.debug("deactivating device with token: #{device_token}") devices = Device.where(notification_token: device_token) if devices.count == 0 Rails.logger.info("skipping, since no device found with token: #{device_token}") else devices.each do Rails.logger.debug("deactivated device with token: #{device_token}") device.update_attribute(active: false) end end end end
[ "def unregister_device\n # In the HTTP request is an Authorization header. Its value is the word ApplePushNotifications and the authentication token, separated by a single space. The authentication token is the same token that’s specified in your package’s website.json file. Your web service can use this authentication token to determine which user is removing their permission policy.\n # Use this authentication token to remove the device token from your database, as if the device had never registered to your service.\n \n #TODO: Delete the record with this device token. The device will no longer accept notifications.\n\n old_subscription = AppleWebNotificationSubscription.find_by(user_id: params[:user_id], device_token: params[:device_token])\n old_subscription.destroy if !old_subscription.blank?\n\n render json: {message: 'ok'}, status: 200\n end", "def remove_devices(uids, action=\"delete\")\n Puppet.debug \"Zenoss removing devices with UIDs: \" + uids.join(',')\n \n response = _router_request(\"DeviceRouter\", \"removeDevices\", [{\n \"uids\" => uids,\n \"hashcheck\" => @hashcheck,\n \"action\" => action\n # \"deleteEvents\" => true, # TODO: make configurable\n # \"deletePerf\" => true\n }])\n \n raise Puppet::Error, \"Zenoss cannot delete the device, \" + response[\"message\"] if response[\"type\"] == \"exception\"\n \n response[\"result\"]\n end", "def unregister\n puts \"APN::Device.unregister\"\n http_delete(\"/api/device_tokens/#{self.token}\")\n end", "def remove_missing\n sync do\n devices.delete_if do |dev|\n pdev = parent.devices.get(dev)\n pdev.nil? || !pdev.mode.compatible?(dev.mode)\n end\n end\n end", "def removeDevice\n # Removes the files first\n begin\n removeContent\n rescue Exception => e\n putsE(e)\n end\n \n # Remove device_auth_groups\n begin\n DeviceAuthGroup.delete_all(:device_id => @device.id)\n rescue Exception => e\n putsE(e)\n end\n \n deleteXMPPAccount\n # These are already removed by removeContent -method\n #removeThumbnails\n #removeEssence\n \n @device.delete\n return\n end", "def remove_device(device)\n\t\treturn if self.devices.empty?\n\t\tself.devices.delete_if {|h| h[device.id] == device.id}\n\t\tif self.primary_device[:device_id] == device.id.to_s\n\t\t\tset_primary(MailDeliveryClass.default_device) # removed primary reset to MAIL\n\t\tend\n\tend", "def remove_missing\n sync do\n changed = false\n\n devices.delete_if do |dev|\n pdev = parent.devices.get(dev)\n delete = pdev.nil? || !pdev.mode.compatible?(dev.mode)\n changed = true if delete\n delete\n end\n\n add_to_changeset if changed\n end\n end", "def remove_device(device)\n\t\treturn if self.devices.empty?\n\t\tself.devices.delete_if {|h| h[device.id] == device.id}\n\t\tif self.primary_device[:id] == device.id\n\t\t\tset_primary(MailClass.default_device) # removed primary reset to MAIL\n\t\tend\n\tend", "def uninstall_on_device_removal\n return @uninstall_on_device_removal\n end", "def removeDevice deviceId\n options = { 'device' => deviceId }\n post REMOVE_DEVICE, options\n end", "def remove_all_devices_from_management()\n return MicrosoftGraph::Me::RemoveAllDevicesFromManagement::RemoveAllDevicesFromManagementRequestBuilder.new(@path_parameters, @request_adapter)\n end", "def purge_unused\n end", "def removeNotificationsFrom (email)\n @users[email].removeNotifications\n end", "def devices_to_unsubscribe\n devices = []\n connection = self.create_connection(:feedback)\n connection.open\n while line = connection.read(38)\n feedback = line.unpack('N1n1H140')\n timestamp = Time.at(feedback[0])\n token = feedback[2].scan(/.{0,8}/).join(' ').strip\n if token && timestamp\n devices << {:token => token, :timestamp => timestamp}\n end\n end\n connection.close\n devices\n rescue OpenSSL::PKey::RSAError, Errno::ECONNRESET\n []\n end", "def remove_stale_data_containers\n containers_data_dir = File.join(device_data_dir, \"Containers\", \"Data\", \"Application\")\n apps = Dir.glob(\"#{containers_data_dir}/**/#{METADATA_PLIST}\")\n apps.each do |metadata_plist|\n if pbuddy.plist_read(\"MCMMetadataIdentifier\", metadata_plist) == app.bundle_identifier\n FileUtils.rm_rf(File.dirname(metadata_plist))\n end\n end\n end", "def fRemoveNotificationsFrom (email)\n @users.removeNotificationsFrom(email)\n end", "def destroy_all\n current_user.notifications.delete_all\n current_user.touch\n end", "def poll_deregistrations\n log(\"Polling deregistrations\")\n em_redis.blpop('twitterpush:old', 0).callback do |list, old_id|\n if twitter_id = twitter_store.get_twitter_id(old_id)\n streamer.remove_user(twitter_id)\n twitter_store.del_by_id(old_id)\n end\n EventMachine.next_tick {\n poll_deregistrations\n }\n end\n end", "def unregister_device\n\t\t@device = Device.where(:token => params[:device_token]).first\n\t\t@device.vendor = nil\n\t\t@device.restaurant = nil\n\t\t@device.save\n\n\t\trespond_with @device, :location => nil\n\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /categorias/1 GET /categorias/1.json
def show render json: @categoria end
[ "def show\n @categoria = Categoria.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @categoria }\n end\n end", "def show\n @categoria_cota = CategoriaCota.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @categoria_cota }\n end\n end", "def index\n if params[:categoria_producto]\n render json: Producto.find(params[:producto_id]).categorias\n else\n\t\t @categorias = Categoria.all\n render json: @categorias\n end\n\tend", "def show\n @cargo_categoria = CargoCategoria.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @cargo_categoria }\n end\n end", "def show\n @categorization = Categorization.find(params[:id])\n\n respond_to do |format|\n format.html #index.html.erb\n format.json { render json: @categorization }\n end\n end", "def show\n @categorialivro = Categorialivro.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @categorialivro }\n end\n end", "def index\n @categoria_cotas = CategoriaCota.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @categoria_cotas }\n end\n end", "def index\n @kategoria = Kategorium.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @kategoria }\n end\n end", "def show\n @subcategoria = Subcategoria.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @subcategoria }\n end\n end", "def show\n @kategorium = Kategorium.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @kategorium }\n end\n end", "def show\n @categorie_analytique = CategorieAnalytique.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @categorie_analytique }\n end\n end", "def show\n @subcategoria = Subcategoria.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @subcategoria }\n end\n end", "def show\n @categoria_producto = CategoriaProducto.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @categoria_producto }\n end\n end", "def new\n @categoria = Categoria.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @categoria }\n end\n end", "def categorize\n out = {}.to_json\n if params[:url]\n # uri_enc_url = Rack::Utils.escape(params[:url])\n endpoint = \"http://access.alchemyapi.com/calls/url/URLGetCategory\"\n q = \"#{endpoint}?apikey=#{ENV[\"ALCHEMY_KEY\"]}&url=#{params[:url]}&outputMode=json\"\n out = RestClient.get(q)\n end\n respond_to do |format|\n format.html\n format.json { render :json => out.body }\n end\n end", "def index\n get_categoria_gastos\n end", "def get_appcon_categories \n get(\"/appcon.json/categories\")\nend", "def show\n @subcategorium = Subcategorium.find(params[:id])\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @subcategorium }\n end\n end", "def show\n @subcategorization = Subcategorization.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @subcategorization }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /categorias POST /categorias.json
def create @categoria = Categoria.new(categoria_params) if @categoria.save render json: @categoria else render json: @categoria.errors, status: :unprocessable_entity end end
[ "def create\n if params[:categoria_producto]\n p = Producto.find(params[:producto_id])\n c = Categoria.find(params[:categoria_id])\n\n if p.categorias << c\n render json: c, status: :created\n else\n render json: {:errors => {categoria: [\"No se ha podido agregar categoria\"]}}, status: :unprocessable_entity\n end\n\n else\n @categoria = Categoria.new(parametros_categoria)\n\n if @categoria.save\n render json: @categoria, status: :created\n else\n render json: @categoria.errors, status: :unprocessable_entity\n end\n end\n end", "def create\n @categoria = Categoria.new(params[:categoria])\n\n respond_to do |format|\n if @categoria.save\n format.html { redirect_to @categoria, notice: 'Categoria was successfully created.' }\n format.json { render json: @categoria, status: :created, location: @categoria }\n else\n format.html { render action: \"new\" }\n format.json { render json: @categoria.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @categorium = @torneo.categoria.build(categorium_params)\n\n respond_to do |format|\n if @categorium.save\n format.html { redirect_to torneo_categoria_path(@torneo), notice: 'Categoría fue creada exitosamente.' }\n format.json { render :show, status: :created, location: @categorium }\n else\n format.html { render :new }\n format.json { render json: @categorium.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @categoria = Categoria.new(params[:categoria])\n\n respond_to do |format|\n if @categoria.save\n format.html { redirect_to [:admin, @categoria], :notice => 'Exemplo was successfully created.' }\n format.json { render :json => @categoria, :status => :created, :location => @categoria }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @categoria.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @categoria_produto = CategoriaProduto.new(categoria_produto_params)\n if @categoria_produto.save\n render json: @categoria_produto\n else\n render json: @categoria_produto.errors, status: :unprocessable_entity \n end\n end", "def create\n @cargo_categoria = CargoCategoria.new(params[:cargo_categoria])\n\n respond_to do |format|\n if @cargo_categoria.save\n format.html { redirect_to cargo_categorias_path, notice: 'Mapa de Cargo e Categoria criado com sucesso.' }\n format.json { render json: @cargo_categoria, status: :created, location: @cargo_categoria }\n else\n format.html { render action: \"new\" }\n format.json { render json: @cargo_categoria.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @categori = Categori.new(categori_params)\n @categori.cat_nom=@categori.cat_nom.capitalize\n respond_to do |format|\n if @categori.save\n format.html { redirect_to @categori, notice: 'La categoría se creo correctamente' }\n format.json { render :show, status: :created, location: @categori }\n else\n format.html { render :new }\n format.json { render json: @categori.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @categorialivro = Categorialivro.new(params[:categorialivro])\n\n respond_to do |format|\n if @categorialivro.save\n format.html { redirect_to @categorialivro, :notice => 'Categorialivro was successfully created.' }\n format.json { render :json => @categorialivro, :status => :created, :location => @categorialivro }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @categorialivro.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @categoriaprestador = Categoriaprestador.new(categoriaprestador_params)\n\n respond_to do |format|\n if @categoriaprestador.save\n format.html { redirect_to @categoriaprestador, notice: 'Categoriaprestador was successfully created.' }\n format.json { render :show, status: :created, location: @categoriaprestador }\n else\n format.html { render :new }\n format.json { render json: @categoriaprestador.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n \n @categorias_tipo = CatTipo.new(params[:cat_tipo])\n\n\t\trespond_to do |format|\n\t\t\tif @categorias_tipo.save\n \t\t\tcategories = @categorias_tipo.update_attributes(:tipo_acc_ids =>params[:tipo_accs])\n\t\t\t\t@categorias_tipo.update_attributes(:estado_ids =>params[:estados])\n\t\t\t\t\n\t\t\t\n\n format.html { redirect_to cat_tipos_path, notice: 'OK' }\n format.json { render json: @categorias_tipo, status: :created, location: @categorias_tipo }\n\t\t\telse\n format.html { render action: \"new\" }\n format.json { render json: @categorias_tipo.errors, status: :unprocessable_entity }\n \tend\t\n\t\tend\n\tend", "def create\n @categoriafinaceiro = Categoriafinaceiro.new(categoriafinaceiro_params)\n\n respond_to do |format|\n if @categoriafinaceiro.save\n format.html { redirect_to @categoriafinaceiro, notice: 'Categoria cadastrada com sucesso.' }\n format.json { render :show, status: :created, location: @categoriafinaceiro }\n else\n format.html { render :new }\n format.json { render json: @categoriafinaceiro.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @categoria_cota = CategoriaCota.new(params[:categoria_cota])\n\n savePictures\n\n respond_to do |format|\n if @categoria_cota.save\n format.html { redirect_to @categoria_cota, notice: 'Categoria cota was successfully created.' }\n format.json { render json: @categoria_cota, status: :created, location: @categoria_cota }\n else\n format.html { render action: \"new\" }\n format.json { render json: @categoria_cota.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @categoriaempresa = Categoriaempresa.new(categoriaempresa_params)\n\n respond_to do |format|\n if @categoriaempresa.save\n format.html { redirect_to @categoriaempresa, notice: 'Categoria cadastrada com sucesso.' }\n format.json { render :show, status: :created, location: @categoriaempresa }\n else\n format.html { render :new }\n format.json { render json: @categoriaempresa.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n \n @categoriaentidad = Categoriaentidad.new(categoriaentidad_params)\n \n respond_to do |format|\n if @categoriaentidad.save\n format.html { redirect_to @categoriaentidad, notice: 'Categoriaentidad was successfully created.' }\n format.json { render :show, status: :created, location: @categoriaentidad }\n else\n format.html { render :new }\n format.json { render json: @categoriaentidad.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @mk_categoria = MkCategoria.new(mk_categoria_params)\n\n respond_to do |format|\n if @mk_categoria.save\n format.html { redirect_to @mk_categoria, notice: 'Mk categoria was successfully created.' }\n format.json { render :show, status: :created, location: @mk_categoria }\n else\n format.html { render :new }\n format.json { render json: @mk_categoria.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @categoria = Categoria.new(params[:categoria])\n\n respond_to do |format|\n if @categoria.save\n format.html { redirect_to(@categoria, :notice => 'Categoria was successfully created.') }\n format.xml { render :xml => @categoria, :status => :created, :location => @categoria }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @categoria.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @categoria = Categoria.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @categoria }\n end\n end", "def create\n @categoria_post = CategoriaPost.new(categoria_post_params)\n @categoria = Categoria.find(params[:categoria_id])\n @post = Post.find(params[:post_id])\n @categoria_post.post = @post\n @categoria_post.categoria = @categoria\n\n respond_to do |format|\n if @categoria_post.save\n format.html { redirect_to @post, notice: 'As categorias foram adicionadas ao post.' }\n format.json { render :show, status: :created, location: @categoria_post }\n else\n format.html { render :new }\n format.json { render json: @post.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @categoria_cota = CategoriaCota.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @categoria_cota }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /categorias/1 PATCH/PUT /categorias/1.json
def update if @categoria.update(categoria_params) render json: @categoria else render json: @categoria.errors, status: :unprocessable_entity end end
[ "def update\n respond_to do |format|\n if @categoria.update(categoria_params)\n format.html { redirect_to @categoria, notice: 'Servico was successfully updated.' }\n format.json { render :show, status: :ok, location: @categoria }\n else\n format.html { render :edit }\n format.json { render json: @categoria.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @categoria = Categoria.find(params[:id])\n\n respond_to do |format|\n if @categoria.update_attributes(params[:categoria])\n format.html { redirect_to [:admin, @categoria], :notice => 'Exemplo was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @categoria.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @categoria = Categoria.find(params[:id])\n\n respond_to do |format|\n if @categoria.update_attributes(params[:categoria])\n format.html { redirect_to @categoria, notice: 'Categoria se ha actualizado correctamente.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @categoria.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @categoria = Categoria.find(params[:id])\n\n respond_to do |format|\n if @categoria.update_attributes(params[:categoria])\n format.html { redirect_to action: 'index', notice: 'Categoria was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @categoria.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @categorias_tipo = CatTipo.find(params[:id])\n\n respond_to do |format|\n if @categorias_tipo.update_attributes(params[:cat_tipo])\n \t\tcategories = @categorias_tipo.update_attributes(:tipo_acc_ids =>params[:tipo_accs])\n\t\t\t\t@categorias_tipo.update_attributes(:estado_ids =>params[:estados])\n format.html { redirect_to cat_tipos_path, notice: 'Categorias tipo was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @categorias_tipo.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @categorialivro = Categorialivro.find(params[:id])\n\n respond_to do |format|\n if @categorialivro.update_attributes(params[:categorialivro])\n format.html { redirect_to @categorialivro, :notice => 'Categorialivro was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @categorialivro.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @cargo_categoria = CargoCategoria.find(params[:id])\n\n respond_to do |format|\n if @cargo_categoria.update_attributes(params[:cargo_categoria])\n format.html { redirect_to cargo_categorias_path, notice: 'Mapa de Cargo e Categoria atualizado com sucesso.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @cargo_categoria.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @subcategoria = Subcategoria.find(params[:id])\n\n respond_to do |format|\n if @subcategoria.update_attributes(params[:subcategoria])\n format.html { redirect_to [:admin, @subcategoria], :notice => 'Exemplo was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @subcategoria.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @categorize = Categorize.find(params[:id])\n\n respond_to do |format|\n if @categorize.update_attributes(params[:categorize])\n format.html { redirect_to @categorize, notice: 'Categorize was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @categorize.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @cat.update(cat_params)\n render json: @cat\n end", "def update\n @categoria = Categoria.find(params[:id])\n\n respond_to do |format|\n if @categoria.update_attributes(params[:categoria])\n format.html { redirect_to(@categoria, :notice => 'Categoria was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @categoria.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @categoriafinaceiro.update(categoriafinaceiro_params)\n format.html { redirect_to @categoriafinaceiro, notice: 'Categoria alterada com sucesso.' }\n format.json { render :show, status: :ok, location: @categoriafinaceiro }\n else\n format.html { render :edit }\n format.json { render json: @categoriafinaceiro.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @sub_categoria.update(sub_categoria_params)\n format.html { redirect_to @sub_categoria.categoria, notice: 'Sub categoria was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @sub_categoria.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @cat_libri.update(cat_libri_params)\n format.html { redirect_to @cat_libri, notice: 'La categoria è stata modificata con successo.' }\n format.json { render :show, status: :ok, location: @cat_libri }\n else\n format.html { render :edit }\n format.json { render json: @cat_libri.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @categoriaprestador.update(categoriaprestador_params)\n format.html { redirect_to @categoriaprestador, notice: 'Categoriaprestador was successfully updated.' }\n format.json { render :show, status: :ok, location: @categoriaprestador }\n else\n format.html { render :edit }\n format.json { render json: @categoriaprestador.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @proyectos_categoria.update(proyectos_categoria_params)\n format.html { redirect_to @proyectos_categoria, notice: 'Proyectos categoria was successfully updated.' }\n format.json { render :show, status: :ok, location: @proyectos_categoria }\n else\n format.html { render :edit }\n format.json { render json: @proyectos_categoria.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @subcategoria = Subcategoria.find(params[:id])\n\n respond_to do |format|\n if @subcategoria.update_attributes(params[:subcategoria])\n format.html { redirect_to @subcategoria, notice: 'Subcategoria was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @subcategoria.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @sotto_categoria = SottoCategoria.find(params[:id])\n\n respond_to do |format|\n if @sotto_categoria.update_attributes(params[:sotto_categoria])\n format.html { redirect_to(@sotto_categoria, :notice => 'Sotto categoria was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @sotto_categoria.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @categoria_producto = CategoriaProducto.find(params[:id])\n\n respond_to do |format|\n if @categoria_producto.update_attributes(params[:categoria_producto])\n format.html { redirect_to @categoria_producto, notice: 'Categoria producto was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @categoria_producto.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }