text
stringlengths
10
2.61M
class Genre < ApplicationRecord has_many :items # 如想要刪除該Genre時,底下的items也一並刪除,加入dependent: :destroy, validates_presence_of :name end
# frozen_string_literal: true # class creates major model class Major < ActiveRecord::Base belongs_to :department has_many :students end
class CreateCombatStats < ActiveRecord::Migration def change create_table :combat_stats do |t| t.string :category t.string :status t.integer :range t.integer :range_bonus t.integer :aoe t.integer :aoe_bonus t.integer :damage t.integer :damage_bonus t.belongs_to :spell end end end
class AddAuthorRefToTests < ActiveRecord::Migration[5.2] def change add_reference :tests, :author, foreign_key: { to_table: :users } # remove_column :tests, :user_id, :integer # remove_column :tests, :test_author_id, :integer end end
module Api module V1 class ServicesController < ApplicationController def index @service = Service.all render json: {status: 'SUCCESS', message:'Services lock and loaded', data:@service}, status: :ok end def show @service = Service.find(params[:id]) render json: {status: 'SUCCESS', message:'Specific service loaded', data:@service}, status: :ok end def create @service = Service.new(service_params) if @service.save render json: {status: 'SUCCESS', message:'Saved new service, user-san', data:@service}, status: :ok else render json: {status: 'ERROR', message:'Service not saved, wonder why', data:@service.error}, status: :unprocessable_entity end end def destroy @service = Service.find(params[:id]) @service.destroy render json: {status: 'SUCCESS', message:'Service succesfully erased from existance', data:@service}, status: :ok end def update @service = Service.find(params[:id]) if @service.update_attributes(service_params) render json: {status: 'SUCCESS', message:'Updated service, move along', data:@service}, status: :ok else render json: {status: 'ERROR', message:'Could not update, blame the dev', data:@service.errors}, status: :unprocessable_entity end end def search @services = Service.where("name ILIKE ? AND costumer ILIKE ? AND equipment LIKE ? AND company ILIKE ?", "%#{params[:name]}%", "%#{params[:costumer]}%", "%#{params[:equipment]}%", "%#{params[:company]}%") if params[:year1] != '' @services = @services.where('extract(year from done_at) = ?', "#{params[:year1]}") end if params[:month1] != '' @services = @services.where('extract(month from done_at) = ?', "#{params[:month1]}") end if params[:day1] != '' @services = @services.where('extract(day from done_at) = ?', "#{params[:day1]}") end if params[:year2] != '' @services = @services.where('extract(year from next_service) = ?', "#{params[:year2]}") end if params[:month2] != '' @services = @services.where('extract(month from next_service) = ?', "#{params[:month2]}") end if params[:day2] != '' @services = @services.where('extract(day from next_service) = ?', "#{params[:day2]}") end render json: {status: 'SUCCESS', message:'services searched!', data:@services}, status: :ok end private def service_params params.permit(:name, :cost, :costumer, :equipment, :company, :done_at, :next_service) end end end end
module God module System @@kb_per_page = 4 # TODO: Need to make this portable @@hertz = 100 @@total_mem = nil @@num_of_cpu = nil @@uptime = nil @@meminfo = nil MeminfoPath = '/proc/meminfo' CpuinfoPath = '/proc/cpuinfo' UptimePath = '/proc/uptime' LoadAveragePath = '/proc/loadavg' RequiredPaths = [MeminfoPath, CpuinfoPath, UptimePath] # FreeBSD has /proc by default, but nothing mounted there! # So we should check for the actual required paths! # Returns true if +RequiredPaths+ are readable. def self.usable? RequiredPaths.all? do |path| test(?r, path) && readable?(path) end end # in seconds def self.uptime File.read(UptimePath).split[0].to_f end # in seconds def self.load_average(pos = 1) File.read(LoadAveragePath).split[pos].to_f end def self.total_mem return @@meminfo[:MemTotal] if @@meminfo @@meminfo = get_meminfo return @@meminfo[:MemTotal] end def self.num_of_cpu return @@num_of_cpu if @@num_of_cpu @@num_of_cpu = File.read(CpuinfoPath).split(/\n/).grep(/^processor/).size end def self.total_swap return @@meminfo[:SwapTotal] if @@meminfo @@meminfo = get_meminfo return @@meminfo[:SwapTotal] end def self.free_swap @@meminfo = get_meminfo return @@meminfo[:SwapFree] end private def self.get_meminfo block = {} File.open(MeminfoPath) do |f| while(line = f.gets) do elem = line.split(/:/) block[elem[0].to_sym] ||= 0 block[elem[0].to_sym] += elem[1].match(/(\d+)/).to_a[1].to_i end end return block rescue => e p 'Error:' + e.to_s + " at " + e.backtrace {} end # Some systems (CentOS?) have a /proc, but they can hang when trying to # read from them. Try to use this sparingly as it is expensive. def self.readable?(path) begin timeout(1) { File.read(path) } rescue Timeout::Error false end end end end
namespace :station_attendant do desc "Extracts and loads all agencies from the GTFS Data Exchange API." task :find_data_exchange_feeds => :environment do DataExchangeExtractor.perform end desc "Extracts and loads all agencies and feeds from the Google Transit Data Feed wiki." task :find_google_transit_data_feeds => :environment do GoogleTransitDataFeedExtractor.perform end desc "Consumes feeds from known sources." task :consume_feeds => :environment do FeedConsumer.perform end desc "Finds feeds and consumes them." task :find_and_consume => :environment do DataExchangeExtractor.perform GoogleTransitDataFeedExtractor.perform FeedConsumer.perform(:transit_data_feed => true, :data_exchange => true) end desc "Finds feeds and consumes them and loads them." task :find_and_consume_and_load => :environment do DataExchangeExtractor.perform GoogleTransitDataFeedExtractor.perform FeedConsumer.perform(:transit_data_feed => true, :data_exchange => true, :load => true) end end
require 'spec_helper' describe GdprService do let(:service) { described_class.new(user, ip) } let(:user) { nil } describe '#cookies_allowed?' do subject { service.cookies_allowed? } context 'UK' do let(:ip) { '82.1.185.172' } it 'should not allow cookies' do expect(subject).to eq false end context 'user is logged in' do let(:user) { create :user } it 'should allow cookies' do expect(subject).to eq true end end end context 'US' do let(:ip) { '204.48.19.88' } it 'should not allow cookies' do expect(subject).to eq true end end end end
class AddDeletedAtToUsersCourses < ActiveRecord::Migration def change add_column :users_courses, :deleted_at, :datetime add_index :users_courses, :deleted_at end end
class AddAttachmentHighlightedToConfiguration < ActiveRecord::Migration def self.up add_column :configurations, :highlighted_file_name, :string add_column :configurations, :highlighted_content_type, :string add_column :configurations, :highlighted_file_size, :integer add_column :configurations, :highlighted_updated_at, :datetime end def self.down remove_column :configurations, :highlighted_file_name remove_column :configurations, :highlighted_content_type remove_column :configurations, :highlighted_file_size remove_column :configurations, :highlighted_updated_at end end
require 'rails_helper' RSpec.describe "Users", type: :request do describe "GET /users" do subject { get '/users' } it_behaves_like 'HTTP 200 OK' end describe 'GET /users/:id' do context 'when user exists' do subject { get "/users/#{user.login}" } let(:user) { create(:user) } it_behaves_like 'HTTP 200 OK' end xcontext 'when user does not exist' do subject { get "/users/bad-name" } it_behaves_like 'HTTP 404 Not Found' end end end
def check_customer_token if @customer_token != nil @has_customer_token = true else @has_customer_token = false end end def check_payment_token if @payment_token != nil @has_payment_token = true else @has_payment_token = false end end # This either loads the merchant value from the directory object or sets it to the default per application. def load_assigned_merchant_or_set_default if @merchant_directory == "BAR" || @merchant_directory == "PTD" @merchant = @merchant_directory elsif @database == "BC" || @database == "CS" || @database == "DATA" @merchant = "BAR" elsif @database == "PTD" @merchant = "PTD" else @merchant = "MISSING" end end # This ensures that the directory and payment method records have been assigned to a merchant. # It also clears the @merchant variable if they don't match. # Without a @metchant variable, the transaction_ready method will prevent the tranaction from proceeding. def check_directory_and_payment_method_merchants if @merchant_payment_method == @merchant_directory && @merchant_directory != nil && @merchant_payment_method != nil @merchant = @merchant_directory elsif @merchant_payment_method != @merchant_directory @merchant = "MISMATCH" else @merchant = "MISSING" end end # This determines whether or not to process this payment or not. def process_or_skip # Check if this payment is by ids or card. card_or_token if @card_or_tokens == "tokens" || @card_or_tokens == "card" @process_or_skip = "Process" process_payment else @process_or_skip = "Skip" end end # This determines if this transaction should be processed using Authorize IDs or a CC. def card_or_token # If this record has (Authorize.net) IDs, validate them. if @customer_token && @payment_token # Validate the IDs. validate_tokens if @valid_tokens == true @card_or_tokens = "tokens" else @card_or_tokens = "error" end # If this record has credit card values, use them. else @card_or_tokens = "card" end end # SET the GL Codes. def set_gl_codes if @database == "BC" bc_gl_code elsif @database == "CS" cs_gl_code elsif @database == "DL" dl_gl_code elsif @database == "PTD" ptd_gl_code end end # This GL Code is referenced in the process_payment method. # This GL Code is used to categorize tranasactions. def ptd_gl_code date = Time.now month = date.month year = date.year nextyear = year + 1 # From Angela on Slack on 09/26/19 # PTD19 coding should stay the same. # PTD20 should be 242. And yes, 242 is correct until December 31, On January 1 it should then go to 241. The new codes are a change in the Finance process, that I didn't have changed halfway through 2019, and am now using this opportunity to change/correct it. # If it is too much to change/fix, October 1 is a few days away and I can just continue running a daily analysis and break out the '19 from the '20. But I do need the actual codes to change to 241 and 242. # October is when the GL Code swithces to 424. month_ptd = 10 # New code from 10/29/19 if (month >= month_ptd) @gl_code = "242" @invoice = "PTD#{short_year(nextyear)}" else @gl_code = "241" @invoice = "PTD#{short_year(year)}" end # Old code from before 10/29/19 # if (month >= month_ptd) # @gl_code = "424" # @invoice = "PTD#{short_year(nextyear)}" # else # @gl_code = "423" # @invoice = "PTD#{short_year(year)}" # end end def bc_gl_code date = Time.now year = date.year if @gl_override_flag == true && @gl_override_code != nil @gl_code = @gl_override_code elsif @event_year.to_i > year # If the event is next year. @gl_code = "421" else @gl_code = "422" end puts "[EVENT_YEAR] #{@event_year}" puts "[EVENT_ABBR] #{@event_abbr}" @invoice = "BCOMP#{@event_abbr}#{short_year(@event_year)}" end def cs_gl_code date = Time.now year = date.year unless @class_date.nil? if @today < @class_date @gl_code = "403" elsif @today < @class_date + 7 @gl_code = "402" else @gl_code = "401" end else @gl_code = "401" end # @invoice is set in the load_payment_date method for CS records. end def dl_gl_code unless @program.nil? if @program == "BC" bc_gl_code # elsif @program == "CS" # cs_gl_code # Not yet developed. Not sure how the @invoice variable would be set. elsif @program == "PTD" ptd_gl_code end else @gl_code = "99" @invoice = "Program Missing" end end def short_year (yr) yr.to_s.split(//).last(2).join("").to_s end def set_response @status = @status_code @body = @status_message end def clear_response @authorize_response = nil @authorize_response_kind = nil @authorize_response_code = nil @authorize_response_message = nil @result = nil @avs_code = nil @cvv_code = nil @transaction_id = nil @authorization_code = nil @status_code = nil @status_message = nil end def to_boolean (string) unless string.nil? string.downcase == 'true' || string == '1' else false end end def mask_card_date unless @update_card_date == true @card_mmyy = 'XXXX' end end def nil_card_cvv unless @update_card_cvv == true @card_cvv = nil end end def log_result_to_console puts "\n\n\n\n\n" puts "----------------------------------------" puts "[DATABASE] #{@database}" puts "[DIRECTORY] #{@directory_id}" puts "[LEAD] #{@lead_id}" puts "[GUEST] #{@guest_id}" puts "[PAYMENTMETHOD] #{@payment_method_id}" puts "[PAYMENTDATE] #{@payment_date_id}" puts "[RECORD] #{@serial}" puts "[MERCHANT] #{@merchant}" puts "[CUSTOMERTOKEN] #{@customer_token}" puts "[PAYMENTTOKEN] #{@payment_token}" puts "\n" puts "[RESPONSE] #{@authorize_response_kind}" puts "[AUTHORIZATION] #{@authorization_code}" puts "[CODE] #{@authorize_response_code}" puts "[ERROR] #{@authorize_response_message}" puts "[P or S] #{@process_or_skip}" puts "\n" puts "[GLCODE] #{@gl_code}" puts "[INVOICE] #{@invoice}" puts "[CLASSDATE] #{@class_date}" puts "[PROGRAM] #{@program}" puts "\n" puts "[STATUSCODE] #{@status_code}" puts "[STATUSMESSAGE] #{@status_message}" puts "[TIMESTAMP] #{Time.now}" puts "----------------------------------------" end
require 'test_helper' class SurfCampReviewTest < ActiveSupport::TestCase def setup @user = users(:jeramae) @surf_camp = surf_camps(:first_surf_camp) @surf_camp_review = SurfCampReview.new(rating: 5, title: "Sample Review", comment: "Lorem ipsum", user_id: @user.id, surf_camp_id: @surf_camp.id) end test "should be valid" do assert @surf_camp_review.valid? end test "user id should be present" do @surf_camp_review.user_id = nil assert_not @surf_camp_review.valid? end test "surf camp id should be present" do @surf_camp_review.surf_camp_id = nil assert_not @surf_camp_review.valid? end test "rating should be present" do @surf_camp_review.rating = " " assert_not @surf_camp_review.valid? end test "title should be present" do @surf_camp_review.title = " " assert_not @surf_camp_review.valid? end test "comment should be present" do @surf_camp_review.comment = " " assert_not @surf_camp_review.valid? end test "order should be most recent first" do assert_equal surf_camp_reviews(:most_recent), SurfCampReview.first end end
class User < ActiveRecord::Base has_many :roles, dependent: :delete_all has_many :groups, through: :roles def self.import(file) CSV.foreach(file.path, headers: true) do |row| u = User.find_or_create_by(first_name: row['First Name'], last_name: row['Last Name']) g = Group.find_or_create_by(name: row['Group Name']) Role.create!({ :group_id => g.id, :user_id => u.id, :title => row['Role in Group'] }) end end end
class UserInfo attr_accessor :username, :password def initialize @username = "Ironhack" @password = "1234" @user_text = "" end def validation puts "What is your username? " username_input = gets.chomp puts "What is your password? " password_input = gets.chomp if username_input == @username && password_input == @password get_text end end def get_text puts "Enter some text: " @user_text = gets.chomp option_list end def option_list puts "What do you want to do? " puts "1.Count words, 2.Count letters, 3.Reverse text, 4.Uppercase the text, 5.Lowercase the text. (Just put the number)" user_choice = gets.chomp if user_choice == "1" count_words elsif user_choice == "2" count_letters elsif user_choice == "3" reverse_text elsif user_choice == "4" upper_case elsif user_choice == "5" down_case else puts "Choose a valid option between 1-5" option_list end end def count_words number_of_words = @user_text.split(' ').length puts "Your text contains #{number_of_words} words." end def count_letters number_of_letters =@user_text.split(" ").join.length puts "There are #{number_of_letters} letters" end def reverse_text reversed_text = @user_text.reverse puts "#{reversed_text}" end def upper_case uppered_case = @user_text.upcase puts "#{uppered_case}" end def down_case downed_case = @user_text.downcase puts "#{downed_case}" end end user = UserInfo.new user.validation
require 'id_generator' class Category attr_reader :id, :has_errors attr_accessor :name, :errors def initialize(name:) @id = generate_id @name = name @errors = [] @has_errors = false add_error if name.nil? end def self.create(name) new(name: name) end private def add_error @errors.push("Name can't be blank") @has_errors = true end end
class ParamountMailer < ActionMailer::Base destination = false default from: 'inqueries@paramount.com.ph' layout 'mailer' def contact_email(contactData) @contactData = contactData @destination = destination(contactData[:sourcePage]) if @destination != false subject = contactData[:contactName] + "(" + contactData[:isPolicyholder] + ") would like to be contacted." mail(to: @destination, subject: subject) end end def product_email(productData) @productData = productData @destination = destination(productData[:sourcePage]) if @destination != false subject = "A potential customer is interested in " + productData[:product].to_s mail(to: @destination, subject: subject) end end def general_apply_email(generalCareerData) @generalCareerData = generalCareerData @destination = destination(generalCareerData[:sourcePage]) if @destination != false subject = generalCareerData[:firstName].to_s + ' ' + generalCareerData[:lastName].to_s + " has submitted a general job application." mail(to: @destination, subject: subject) end end def lpp_apply_email(lppCareerData) @lppCareerData = lppCareerData @destination = destination(lppCareerData[:sourcePage]) if @destination != false subject = lppCareerData[:firstName].to_s + ' ' + lppCareerData[:lastName].to_s + " has submitted an lpp job application." mail(to: @destination, subject: subject) end end def ofw_compulsory_email(productData) @productData = productData subject = "BM OFW INQUIRY" mail(to: "paramountcomphofwinsurance@paramountdirect.freshdesk.com", subject: subject) end private def destination(destination) destinations = { apply: "apply@paramount.com.ph", life: "insure@paramount.com.ph", nonlife: "insure@paramount.com.ph", special: "insure@paramount.com.ph", contact:"insure@paramount.com.ph" } if destinations[destination.to_sym] return destinations[destination.to_sym] else return false end end end
require_relative 'menumodule' class ChangePaymentDueDatePage include PageObject include MenuPanel include AccountsSubMenu include ServicesSubMenu include MyInfoSubMenu include MessagesAlertsSubMenu include PaymentsSubMenu table(:heading, :id => 'tblMain') select_list(:futureduedate, :id => 'ctlWorkflow_Edit_ddlFutureDueDate') span(:errormessage, :id=> 'ctlWorkflow_Step2_vamCheckAgreeTerms_Txt') checkbox(:iagree, :id => 'ctlWorkflow_Step2_chkAgree') button(:changemyduedatebutton, :id =>'ctlWorkflow_btnEdit_Next') div(:confirmationmessage, :class =>'instructionsContainer') select_list(:accountname, :id => 'ctlWorkflow_Edit_ddlAccounts') image(:pimage, :id => 'ttSpan_ctlWorkflow_litDueDate_timage') def get_object(object) self.send "#{object.downcase.gsub(' ','')}_element" end end
task :populate_future_revenues => :environment do Stripe.api_key = AppConfig.stripe[:api_key] if File.exist?(Rails.root.to_s + '/log/populate_future_revenues.log') File.delete(Rails.root.to_s + '/log/populate_future_revenues.log') end FutureRevenue.delete_all! Account.all.each do |account| begin next unless account.transaction_id upcoming = Stripe::Invoice.upcoming(:customer => account.transaction_id) account.create_future_revenue(:date => Time.at(upcoming["date"]), :customer => account.transaction_id, :total => upcoming["total"], :description => upcoming["description"] ) rescue Exception => e log_file = File.open(Rails.root.to_s + '/log/populate_future_revenues.log', 'a+') log_file.write("\n*#{Date.today}******AccountId****#{account.id}*****TransactionId*********#{account.transaction_id}*************************************\n") log_file.write("Stripe Error: #{e.message}") log_file.flush next end end end
# frozen_string_literal: true require "spec_helper" # These specs run on all Postgres versions RSpec.describe ActiveRecord::ConnectionAdapters::PostgreSQLAdapter do let(:table_name) { "t_#{SecureRandom.hex(6)}" } let(:child_table_name) { "t_#{SecureRandom.hex(6)}" } let(:sibling_table_name) { "t_#{SecureRandom.hex(6)}" } let(:grandchild_table_name) { "t_#{SecureRandom.hex(6)}" } let(:table_like_name) { "t_#{SecureRandom.hex(6)}" } let(:template_table_name) { "#{table_name}_template" } let(:current_date) { Date.current } let(:start_range) { current_date } let(:end_range) { current_date + 1.month } let(:values) { (1..3) } let(:uuid_values) { [SecureRandom.uuid, SecureRandom.uuid] } let(:timestamps_block) { ->(t) { t.timestamps null: false, precision: nil } } let(:index_prefix) { "i_#{SecureRandom.hex(6)}" } let(:index_threads) { nil } let(:uuid_function) do if Rails.gem_version >= Gem::Version.new("5.1") "gen_random_uuid()" else "uuid_generate_v4()" end end before do ActiveRecord::Base.primary_key_prefix_type = :table_name_with_underscore end after do ActiveRecord::Base.primary_key_prefix_type = nil adapter.execute("DROP TABLE IF EXISTS #{table_name} CASCADE") adapter.execute("DROP TABLE IF EXISTS #{child_table_name} CASCADE") adapter.execute("DROP TABLE IF EXISTS #{sibling_table_name} CASCADE") adapter.execute("DROP TABLE IF EXISTS #{grandchild_table_name} CASCADE") adapter.execute("DROP TABLE IF EXISTS #{table_like_name} CASCADE") adapter.execute("DROP TABLE IF EXISTS #{template_table_name} CASCADE") end subject(:adapter) { ActiveRecord::Base.connection } subject(:create_range_partition) do adapter.create_range_partition( table_name, partition_key: ->{ "(created_at::date)" }, primary_key: :custom_id, id: :uuid, template: false, &timestamps_block ) end subject(:create_list_partition) do adapter.create_list_partition( table_name, partition_key: "#{table_name}_id", id: :serial ) end subject(:create_range_partition_of) do create_range_partition adapter.create_range_partition_of( table_name, name: child_table_name, primary_key: :custom_id, start_range: start_range, end_range: end_range ) end subject(:create_range_partition_of_subpartitioned_by_list) do adapter.create_range_partition( table_name, partition_key: ->{ "(created_at::date)" }, primary_key: :custom_id, id: :uuid, &timestamps_block ) adapter.create_range_partition_of( table_name, name: child_table_name, primary_key: :custom_id, start_range: start_range, end_range: end_range, partition_type: :list, partition_key: :custom_id ) adapter.create_list_partition_of( child_table_name, name: grandchild_table_name, values: uuid_values ) adapter.create_range_partition_of( table_name, name: sibling_table_name, primary_key: :custom_id, start_range: end_range, end_range: end_range + 1.month ) end subject(:create_list_partition_of) do create_list_partition adapter.create_list_partition_of( table_name, name: child_table_name, values: values ) end subject(:create_range_table_like) do create_range_partition_of adapter.create_table_like(child_table_name, table_like_name) end subject(:create_list_table_like) do create_list_partition_of adapter.create_table_like(child_table_name, table_like_name) end subject(:attach_range_partition) do create_range_partition adapter.execute("CREATE TABLE #{child_table_name} (LIKE #{table_name})") adapter.attach_range_partition( table_name, child_table_name, start_range: start_range, end_range: end_range ) end subject(:attach_list_partition) do create_list_partition adapter.execute("CREATE TABLE #{child_table_name} (LIKE #{table_name})") adapter.attach_list_partition( table_name, child_table_name, values: values ) end subject(:detach_partition) do create_range_partition create_range_partition_of adapter.detach_partition(table_name, child_table_name) end subject(:add_index_on_all_partitions) do create_range_partition_of_subpartitioned_by_list adapter.add_index_on_all_partitions table_name, :updated_at, name: index_prefix, using: :hash, in_threads: index_threads, algorithm: :concurrently, where: "created_at > '#{current_date.to_time.iso8601}'" end describe "#create_range_partition" do let(:create_table_sql) do <<-SQL CREATE TABLE #{table_name} ( custom_id uuid DEFAULT #{uuid_function} NOT NULL, created_at timestamp without time zone NOT NULL, updated_at timestamp without time zone NOT NULL ) PARTITION BY RANGE (((created_at)::date)); SQL end subject do create_range_partition PgDumpHelper.dump_table_structure(table_name) end it { is_expected.to include_heredoc(create_table_sql) } it { is_expected.to_not include("SET DEFAULT nextval") } describe "template table" do subject do create_range_partition PgDumpHelper.dump_table_structure(template_table_name) end it { is_expected.to be_empty } end end describe "#create_list_partition" do let(:create_table_sql) do <<-SQL CREATE TABLE #{table_name} ( #{table_name}_id integer NOT NULL ) PARTITION BY LIST (#{table_name}_id); SQL end let(:incrementing_id_sql) do <<-SQL ALTER TABLE ONLY #{table_name} ALTER COLUMN #{table_name}_id SET DEFAULT nextval('#{table_name}_#{table_name}_id_seq'::regclass); SQL end subject do create_list_partition PgDumpHelper.dump_table_structure(table_name) end it { is_expected.to include_heredoc(create_table_sql) } it { is_expected.to include_heredoc(incrementing_id_sql) } describe "template table" do let(:create_table_sql) do <<-SQL CREATE TABLE #{template_table_name} ( #{table_name}_id integer DEFAULT nextval('#{table_name}_#{table_name}_id_seq'::regclass) NOT NULL ); SQL end let(:primary_key_sql) do <<-SQL ALTER TABLE ONLY #{template_table_name} ADD CONSTRAINT #{template_table_name}_pkey PRIMARY KEY (#{table_name}_id); SQL end subject do create_list_partition PgDumpHelper.dump_table_structure(template_table_name) end it { is_expected.to include_heredoc(create_table_sql) } it { is_expected.to include_heredoc(primary_key_sql) } context 'when config.create_template_tables = false' do before { PgParty.config.create_template_tables = false } after { PgParty.config.create_template_tables = true } it { is_expected.not_to include_heredoc(create_table_sql) } it { is_expected.not_to include_heredoc(primary_key_sql) } end end end describe "#create_range_partition_of" do let(:create_table_sql) do <<-SQL CREATE TABLE #{child_table_name} ( custom_id uuid DEFAULT #{uuid_function} NOT NULL, created_at timestamp without time zone NOT NULL, updated_at timestamp without time zone NOT NULL ); SQL end let(:attach_table_sql) do <<-SQL ALTER TABLE ONLY #{table_name} ATTACH PARTITION #{child_table_name} FOR VALUES FROM ('#{start_range}') TO ('#{end_range}'); SQL end let(:primary_key_sql) do <<-SQL ALTER TABLE ONLY #{child_table_name} ADD CONSTRAINT #{child_table_name}_pkey PRIMARY KEY (custom_id); SQL end subject do create_range_partition_of PgDumpHelper.dump_table_structure(child_table_name) end it { is_expected.to include_heredoc(create_table_sql) } it { is_expected.to include_heredoc(attach_table_sql) } it { is_expected.to include_heredoc(primary_key_sql) } context 'when subpartitioning' do let(:create_table_sql) do <<-SQL CREATE TABLE #{child_table_name} ( custom_id uuid DEFAULT #{uuid_function} NOT NULL, created_at timestamp without time zone NOT NULL, updated_at timestamp without time zone NOT NULL ) PARTITION BY LIST (custom_id); SQL end subject do create_range_partition_of_subpartitioned_by_list PgDumpHelper.dump_table_structure(child_table_name) end it { is_expected.to include_heredoc(create_table_sql) } it { is_expected.to include_heredoc(attach_table_sql) } it { is_expected.not_to include_heredoc(primary_key_sql) } end context 'when an unsupported partition_type: is specified' do subject(:create_range_partition_of) do create_range_partition adapter.create_range_partition_of( table_name, name: child_table_name, partition_type: :something_invalid, partition_key: :custom_id, start_range: start_range, end_range: end_range, ) end it 'raises ArgumentError' do expect { subject }.to raise_error ArgumentError, 'Supported partition types are range, list, hash' end end context 'when partition_type: is specified but not partition_key:' do subject(:create_range_partition_of) do create_range_partition adapter.create_range_partition_of( table_name, name: child_table_name, partition_type: :list, start_range: start_range, end_range: end_range, ) end it 'raises ArgumentError' do expect { subject }.to raise_error ArgumentError, '`partition_key` is required when specifying a partition_type' end end end describe "#create_list_partition_of" do let(:create_table_sql) do <<-SQL CREATE TABLE #{child_table_name} ( #{table_name}_id integer DEFAULT nextval('#{table_name}_#{table_name}_id_seq'::regclass) NOT NULL ); SQL end let(:attach_table_sql) do <<-SQL ALTER TABLE ONLY #{table_name} ATTACH PARTITION #{child_table_name} FOR VALUES IN (1, 2, 3); SQL end let(:primary_key_sql) do <<-SQL ALTER TABLE ONLY #{child_table_name} ADD CONSTRAINT #{child_table_name}_pkey PRIMARY KEY (#{table_name}_id); SQL end subject do create_list_partition_of PgDumpHelper.dump_table_structure(child_table_name) end it { is_expected.to include_heredoc(create_table_sql) } it { is_expected.to include_heredoc(attach_table_sql) } it { is_expected.to include_heredoc(primary_key_sql) } end describe "#create_table_like" do context "range partition" do let(:create_table_sql) do <<-SQL CREATE TABLE #{table_like_name} ( custom_id uuid DEFAULT #{uuid_function} NOT NULL, created_at timestamp without time zone NOT NULL, updated_at timestamp without time zone NOT NULL ); SQL end let(:primary_key_sql) do <<-SQL ALTER TABLE ONLY #{table_like_name} ADD CONSTRAINT #{table_like_name}_pkey PRIMARY KEY (custom_id); SQL end subject do create_range_table_like PgDumpHelper.dump_table_structure(table_like_name) end it { is_expected.to include_heredoc(create_table_sql) } it { is_expected.to include_heredoc(primary_key_sql) } end context "list partition" do let(:create_table_sql) do <<-SQL CREATE TABLE #{table_like_name} ( #{table_name}_id integer DEFAULT nextval('#{table_name}_#{table_name}_id_seq'::regclass) NOT NULL ); SQL end let(:primary_key_sql) do <<-SQL ALTER TABLE ONLY #{table_like_name} ADD CONSTRAINT #{table_like_name}_pkey PRIMARY KEY (#{table_name}_id); SQL end subject do create_list_table_like PgDumpHelper.dump_table_structure(table_like_name) end it { is_expected.to include_heredoc(create_table_sql) } it { is_expected.to include_heredoc(primary_key_sql) } end end describe "#attach_range_partition" do let(:attach_table_sql) do <<-SQL ALTER TABLE ONLY #{table_name} ATTACH PARTITION #{child_table_name} FOR VALUES FROM ('#{start_range}') TO ('#{end_range}'); SQL end subject do attach_range_partition PgDumpHelper.dump_table_structure(child_table_name) end it { is_expected.to include_heredoc(attach_table_sql) } end describe "#attach_list_partition" do let(:attach_table_sql) do <<-SQL ALTER TABLE ONLY #{table_name} ATTACH PARTITION #{child_table_name} FOR VALUES IN (1, 2, 3); SQL end subject do attach_list_partition PgDumpHelper.dump_table_structure(child_table_name) end it { is_expected.to include_heredoc(attach_table_sql) } end describe "#detach_partition" do let(:create_table_sql) do <<-SQL CREATE TABLE #{child_table_name} ( custom_id uuid DEFAULT #{uuid_function} NOT NULL, created_at timestamp without time zone NOT NULL, updated_at timestamp without time zone NOT NULL ); SQL end subject do detach_partition PgDumpHelper.dump_table_structure(child_table_name) end it { is_expected.to include_heredoc(create_table_sql) } it { is_expected.to_not include("ATTACH") } end describe '#parent_for_table_name' do let(:traverse) { false } before { create_range_partition_of_subpartitioned_by_list } it 'fetches the parent of the given table' do expect(adapter.parent_for_table_name(grandchild_table_name)).to eq child_table_name expect(adapter.parent_for_table_name(child_table_name)).to eq table_name expect(adapter.parent_for_table_name(table_name)).to be_nil end context 'when traverse: true argument is specified' do it 'returns top-level ancestor' do expect(adapter.parent_for_table_name(grandchild_table_name, traverse: true)).to eq table_name expect(adapter.parent_for_table_name(child_table_name, traverse: true)).to eq table_name expect(adapter.parent_for_table_name(table_name, traverse: true)).to be_nil end end end describe '#partitions_for_table_name' do let(:traverse) { false } before do create_range_partition_of_subpartitioned_by_list end context 'when include_subpartitions: false' do it 'fetches the partitions of the table specified' do expect(adapter.partitions_for_table_name(table_name, include_subpartitions: false)).to eq( [child_table_name, sibling_table_name] ) expect(adapter.partitions_for_table_name(child_table_name, include_subpartitions: false)).to eq( [grandchild_table_name] ) expect(adapter.partitions_for_table_name(grandchild_table_name, include_subpartitions: false)).to be_empty end end context 'when include_subpartitions: true' do it 'fetches all partitions and subpartitions of the table specified' do expect(adapter.partitions_for_table_name(table_name, include_subpartitions: true)).to eq( [child_table_name, grandchild_table_name, sibling_table_name] ) expect(adapter.partitions_for_table_name(child_table_name, include_subpartitions: true)).to eq( [grandchild_table_name] ) expect(adapter.partitions_for_table_name(grandchild_table_name, include_subpartitions: true)).to be_empty end end end describe "#add_index_on_all_partitions" do let(:grandchild_index_sql) do <<-SQL CREATE INDEX #{index_prefix}_#{Digest::MD5.hexdigest(grandchild_table_name)[0..6]} ON #{grandchild_table_name} USING hash (updated_at) WHERE (created_at > '#{current_date} 00:00:00'::timestamp without time zone) SQL end let(:sibling_index_sql) do <<-SQL CREATE INDEX #{index_prefix}_#{Digest::MD5.hexdigest(sibling_table_name)[0..6]} ON #{sibling_table_name} USING hash (updated_at) WHERE (created_at > '#{current_date} 00:00:00'::timestamp without time zone) SQL end before { allow(adapter).to receive(:execute).and_call_original } subject do add_index_on_all_partitions PgDumpHelper.dump_indices end it { is_expected.to include_heredoc(sibling_index_sql) } it { is_expected.to include_heredoc(grandchild_index_sql) } it 'creates the indices using CONCURRENTLY directive because `algorthim: :concurrently` args are present' do subject expect(adapter).to have_received(:execute).with( "CREATE INDEX CONCURRENTLY \"#{index_prefix}_#{Digest::MD5.hexdigest(grandchild_table_name)[0..6]}\" "\ "ON \"#{grandchild_table_name}\" USING hash (\"updated_at\") "\ "WHERE created_at > '#{current_date.to_time.iso8601}'" ) expect(adapter).to have_received(:execute).with( "CREATE INDEX CONCURRENTLY \"#{index_prefix}_#{Digest::MD5.hexdigest(sibling_table_name)[0..6]}\" "\ "ON \"#{sibling_table_name}\" USING hash (\"updated_at\") "\ "WHERE created_at > '#{current_date.to_time.iso8601}'" ) end context 'when unique: true index option is used' do subject(:add_index_on_all_partitions) do create_list_partition_of adapter.add_index_on_all_partitions table_name, "#{table_name}_id", name: index_prefix, in_threads: index_threads, algorithm: :concurrently, unique: true end it 'creates a unique index' do subject expect(adapter).to have_received(:execute).with( "CREATE UNIQUE INDEX CONCURRENTLY \"#{index_prefix}_#{Digest::MD5.hexdigest(child_table_name)[0..6]}\" "\ "ON \"#{child_table_name}\" (\"#{table_name}_id\")" ) end end context 'when in_threads: is provided' do let(:index_threads) { ActiveRecord::Base.connection_pool.size - 1 } before do allow(Parallel).to receive(:map).with([child_table_name, sibling_table_name], in_threads: index_threads) .and_yield(child_table_name).and_yield(sibling_table_name) end it 'calls through Parallel.map' do subject expect(Parallel).to have_received(:map) .with([child_table_name, sibling_table_name], in_threads: index_threads) end it { is_expected.to include_heredoc(sibling_index_sql) } it { is_expected.to include_heredoc(grandchild_index_sql) } context 'when in a transaction' do it 'raises ArgumentError' do ActiveRecord::Base.transaction do expect { subject }.to raise_error(ArgumentError, '`in_threads:` cannot be used within a transaction. If running in a migration, use '\ '`disable_ddl_transaction!` and break out this operation into its own migration.' ) end end end context 'when in_threads is equal to or greater than connection pool size' do let(:index_threads) { ActiveRecord::Base.connection_pool.size } it 'raises ArgumentError' do expect { subject }.to raise_error(ArgumentError, 'in_threads: must be lower than your database connection pool size' ) end end end end describe '#table_partitioned?' do before { create_range_partition_of_subpartitioned_by_list } it 'returns true for partitioned tables; false for partitions themselves' do expect(adapter.table_partitioned?(table_name)).to be true expect(adapter.table_partitioned?(child_table_name)).to be true expect(adapter.table_partitioned?(sibling_table_name)).to be false expect(adapter.table_partitioned?(grandchild_table_name)).to be false end end end
class Product < ApplicationRecord has_many :line_items has_many :orders, through: :line_items before_create :has_avatar before_update :has_avatar before_destroy :ensure_not_referenced_by_any_line_item extend FriendlyId friendly_id :title, use: :slugged validates :title, :description, presence: true validates :price, numericality: {greater_than_or_equal_to: 0.01} validates :quantity, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 0 } validates :title, uniqueness: true # validates :image_url, allow_blank: true, format: { # with: %r{\.(gif|jpg|png)\Z}i, # message: 'must be a URL for GIF, JPG, or PNG image.' # } has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png" validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\z/ validates_with AttachmentSizeValidator, attributes: :avatar, less_than: 2.megabytes def quantity_update(product, qty) if product.quantity-qty >= 0 product.quantity -= qty product.save else errors.add(:base, 'Brak takiej ilości towaru na magazynie.') throw :abort end product end private # ensure that there are no line items referencing this product def ensure_not_referenced_by_any_line_item unless line_items.empty? errors.add(:base, 'Line Items present') throw :abort end end def has_avatar if avatar? image_url = avatar.name end end # Search function for products by name def self.search(search) where("title LIKE ?", "%#{search}%") end end
class ChargesController < ApplicationController layout 'application' before_action :require_user, only: [:new, :create] before_action :set_user, only: [:new] def new @@user = @user end def create # Amount in cents @amount = @@user.balance*100 customer = Stripe::Customer.create( :email => params[:stripeEmail], :source => params[:stripeToken] ) #user = User.find_by(email: :email) charge = Stripe::Charge.create( :customer => customer.id, :amount => @amount, :description => 'Thindustrial Registration Payment', :currency => 'usd' ) if charge["paid"] == true @pay_dollars = @amount/100 @payment = Payment.new(user_id: @@user.id, email: customer.email, token: charge.id, amount: @pay_dollars) if @payment.save @@user.balance = @@user.balance - @pay_dollars if @@user.save flash[:success] = "Payment was successfully made for " + @@user.firstname + " " + @@user.lastname redirect_to user_path(@@user) end end end rescue Stripe::CardError => e flash[:error] = e.message redirect_to new_charges_path end private def set_user @user = User.find(params[:user_id]) end end
option = { "r" => "rock", "p" => "paper", "s" => "scissor"} def given_answer(x) case x when "r" puts " Rock, Crashes Scissor!" when "s" puts " Scisor, Cuts Paper!" when "p" puts " Paper Cuts Rock!" end end loop do begin puts "Choose R-ock, P-aper, S-cissor" answer = gets.chomp.downcase end until option.keys.include?(answer) random = option.keys.sample if answer == random puts " Its a tie" elsif (answer == "r" && random == "s") || (answer == "s" && random == "p") || (answer == "p" && random == "r") given_answer(answer) puts "You win the game!" else given_answer(random) puts "Sorry you lost the game" end puts " Try again?" quit = gets.chomp if quit == "n" puts "ok goodbye" break end end =begin Lines 37-42 are indented a bit too much. I would also maybe change your method name for "given_answer" to "display_result". Something more indicative of what the method will do Tyler L. o and change the name of your hash to options, collections in ruby are usually plural. That's about it, the rest looks good o also line 28: Your elsif is indented a bit too much as well. =end
class User < ApplicationRecord include Rails.application.routes.url_helpers validates :name, presence: true, length: {maximum: 20} VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i.freeze validates :email, length: {maximum: 255}, format: {with: VALID_EMAIL_REGEX}, uniqueness: {case_sensitive: false} has_one_attached :avatar def avatar_url # if文を一行で書いている avatar.attached? ? url_for(avatar) : nil end end
class StoresController < ApplicationController before_action :set_store, only: [:show, :edit, :update, :destroy] def index @stores = current_user.stores end def new @store = Store.new @store.sellers.build end def create @store = Store.new(store_params) if params[:add_new_seller] @store.sellers.build render :new elsif @store.save redirect_to stores_path, notice: "Loja criada com sucesso!" else render :new, notice: @store.errors end end def edit end def update if params[:add_new_seller] @store.sellers.build render :new elsif if @store.update(store_params) redirect_to @store, notice: "Loja atualizada com sucesso!" else render :edit, @store.errors end end end def destroy @store.destroy redirect_to stores_path, notice: "Loja removida com sucesso!" end private def store_params params.require(:store).permit(:name, :sellers_attributes => [:id, :name, :store_id, :_destroy]).merge(user: current_user) end def set_store @store = Store.find(params[:id]) end end
require 'spec_helper' describe HighriseCRM::Client do subject { HighriseCRM::Client.new } let(:token) { '12345abcde' } let(:base_site){ 'https://test.highrisehq.com' } let(:client) { HighriseCRM::Client.new(base_site, token) } let(:bad_token) { '12345abcd'} let(:bad_client) { HighriseCRM::Client.new(base_site, bad_token) } describe '#initialize' do it 'stores the token' do expect(client.token).to eq(token) end end describe '#ping' do context 'good token' do it 'returns true' do response = client.ping expect(response).to be_truthy end end context 'bad_token' do it 'returns false' do response = bad_client.ping expect(response).to be_falsey end end end describe '#people' do it 'returns the collection of people' do response = client.people expect(response['people'].size).to be > 0 end context 'wrong token' do it "returns an error message" do response = bad_client.people expect(response['error']).to eq('Wrong Token brah!') end end end describe '#users' do it 'return the collection of users' do response = client.users expect(response.has_key?('users')).to be_truthy end context 'wrong token' do it "returns an error message" do response = bad_client.users expect(response['error']).to eq('Wrong Token brah!') end end end describe '#custom_fields' do it 'returns the collection of custom fields' do response = client.custom_fields expect(response.has_key?('subject_fields')).to be_truthy end context 'wrong token' do it "returns an error message" do response = bad_client.custom_fields expect(response['error']).to eq('Wrong Token brah!') end end end describe '#me' do it 'returns a user with email and name' do response = client.me expect(response.has_key?('user')).to be_truthy end it 'has email' do response = client.me expect(response['user']['email_address'].nil?).to be_falsey end end end
require 'spec_helper' require_relative '../checkout' describe Checkout do let(:items) { %w(VOUCHER TSHIRT VOUCHER VOUCHER MUG TSHIRT TSHIRT) } context 'when all the items are valid' do context 'and bulk_discount and two_for_one are active' do it 'calculates the total with discounts' do checkout = Checkout.new(discounts: [:bulk_discount, :group_discount]) items.each { |item| checkout.scan(item) } expect(checkout.total).to eql(74.50) end end context 'and no discount is active' do it 'calculates the total without discounts' do checkout = Checkout.new() items.each { |item| checkout.scan(item) } expect(checkout.total).to eql(82.50) end end end context 'when an item is invalid' do it 'raises an error' do checkout = Checkout.new expect { checkout.scan('NEW_ITEM') }.to raise_error(ArgumentError) end end end
class User < ApplicationRecord def self.from_omniauth(hash) where(hash.slice(:uid)).first_or_initialize.tap do |user| user.uid = hash.uid user.email = hash.info.email user.token = hash.credentials.token user.expires_at = Time.at(hash.credentials.expires_at) user.save! end end end
# create the card class class Card attr_accessor :suit, :value def initialize(value, suit) @suit = suit @value = value end def to_s "#{value} of #{suit}" end end # create a deck class and populate with all cards class Deck attr_accessor :cards def initialize @cards = [] suits = [:hearts, :clubs, :diamonds, :spades] values = [:ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, :jack, :queen, :king] suits.each do |suit| values.each do |values| @cards << Card.new(values, suit) end end end def shuffle @cards.shuffle! end def deal(n=1) @cards.slice!(0, n) end end class Player attr_accessor :name, :hand def initialize(name) @name = name @hand = [] end def to_s "#{@name}: #{@hand.join(', ')}" end end #creates and shuffles deck deck1 = Deck.new deck1.shuffle # prints out the deck deck1.cards.each do |card| puts card end # create players and deal some cards players = [Player.new("Tim"),Player.new("Bingo"),Player.new("James")] players.each do |player| player.hand = deck1.deal 8 end # show each player hand players.each do |player| puts player # the to_s method added to the players class makes these following two lines ot needed # puts "Player - #{player.name}" # puts player.hand.join end #create the deck deck1 = Deck.new #shuffle the deck deck1.cards.shuffle! deck1.cards.each do |card| puts card end # c1 = Card.new(9, :diamonds) # deck1.cards.push c1 # c2 = Card.new(9, :diamonds) # deck1.cards.push c2 deck1.cards.each do |card| puts card end # i survived week i # i += 1
# frozen_string_literal: true # Copyright (C) 2015-2020 MongoDB Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative 'percentiles' require_relative 'summary' module Mongo module Benchmarking # These tests focus on BSON encoding and decoding; they are client-side only and # do not involve any transmission of data to or from the server. module BSON extend self # Runs all of the benchmarks specified by the given mapping. # # @example Run a collection of benchmarks. # Benchmarking::BSON.run_all( # flat: %i[ encode decode ], # deep: %i[ encode decode ], # full: %i[ encode decode ] # ) # # @return [ Hash ] a hash of the results for each benchmark def run_all(map) {}.tap do |results| map.each do |type, actions| results[type] = {} actions.each do |action| results[type][action] = run(type, action) end end end end # As defined by the spec, the score for a given benchmark is the # size of the task (in MB) divided by the median wall clock time. # # @param [ Symbol ] type the type of the task # @param [ Mongo::Benchmarking::Percentiles ] percentiles the Percentiles # object to query for the median time. # @param [ Numeric ] scale the number of times the operation is performed # per iteration, used to scale the task size. # # @return [ Numeric ] the score for the given task. def score_for(type, percentiles, scale: 10_000) task_size(type, scale) / percentiles[50] end # Run a BSON benchmark test. # # @example Run a test. # Benchmarking::BSON.run(:flat) # # @param [ Symbol ] type The type of test to run. # @param [ :encode | :decode ] action The action to perform. # # @return [ Hash<:timings,:percentiles,:score> ] The test results for # the requested benchmark. def run(type, action) timings = send(action, file_for(type)) percentiles = Percentiles.new(timings) score = score_for(type, percentiles) Summary.new(timings, percentiles, score) end # Run an encoding BSON benchmark test. # # @example Run an encoding test. # Benchmarking::BSON.encode(file_name) # # @param [ String ] file_name The name of the file with data for the test. # @param [ Integer ] repetitions The number of test repetitions. # # @return [ Array<Numeric> ] The list of the results for each iteration def encode(file_name) data = Benchmarking.load_file(file_name) document = ::BSON::Document.new(data.first) Benchmarking.benchmark do 10_000.times { document.to_bson } end end # Run a decoding BSON benchmark test. # # @example Run an decoding test. # Benchmarking::BSON.decode(file_name) # # @param [ String ] file_name The name of the file with data for the test. # @param [ Integer ] repetitions The number of test repetitions. # # @return [ Array<Numeric> ] The list of the results for each iteration def decode(file_name) data = Benchmarking.load_file(file_name) buffer = ::BSON::Document.new(data.first).to_bson Benchmarking.benchmark do 10_000.times do ::BSON::Document.from_bson(buffer) buffer.rewind! end end end private # The path to the source file for the given task type. # # @param [ Symbol ] type the task type # # @return [ String ] the path to the source file. def file_for(type) File.join(Benchmarking::DATA_PATH, "#{type}_bson.json") end # As defined by the spec, the size of a BSON task is the size of the # file, multipled by the scale (the number of times the file is processed # per iteration), divided by a million. # # "the dataset size for a task is the size of the single-document source # file...times 10,000 operations" # # "Each task will have defined for it an associated size in # megabytes (MB)" # # @param [ Symbol ] type the type of the task # @param [ Numeric ] scale the number of times the operation is performed # per iteration (e.g. 10,000) # # @return [ Numeric ] the score for the task, reported in MB def task_size(type, scale) File.size(file_for(type)) * scale / 1_000_000.0 end end end end
module PipefyAdapters require 'rest_client' class BaseAdapter include ApplicationHelper cattr_accessor :base_url, :request self.base_url = ENV.fetch("PIPEFY_API_BASE_URL") def self.execute_request(pipefy_acess_token, values) begin headers = {:content_type => 'application/json', :authorization => 'Bearer ' + pipefy_acess_token} response = self.request = RestClient.post self.base_url, values, headers response.code == 200 or raise Error::ApiResponseError response end end end end
#We know the problem will be solved when each input equals the correct output for the aformentioned rules #We want to use the software by inputing user prompts and relay back the correct output #Set ready to quit variable to false #display welcome message #get a user input #Begin while condition with ready to quit variable #if user input equals an empty string then the program outputs "Hello?!" #elsif user input has any lower case letter then the program outputs "I AM HAVING A HARD TIME HEARING YOU." #elsif user input equals all upper case letters then the program outputs "NO, THIS IS NOT A PET STORE." #else program outputs error message and prompts user for input again #if user input equals "GOODBYE!" then the program outputs "Anything else I can help you with?" #if user inputs equals "GOODBYE!" again the program outputs "Thank you for calling" and sets the ready to quit variable to true and exits the program #else program outputs error message and prompts user for input again
class AddRejectedToStates < ActiveRecord::Migration[5.2] def change add_column :states, :rejected, :boolean, default: false end end
require 'spec_helper' RSpec.describe Indocker do before { setup_indocker(debug: true) } it "returns the list of invalid and missing containers" do result = Indocker.check(servers: [:external]) expect(result[:missing_containers]).to include("external_bad_container_start") end end
class ChangeGameTeamsName < ActiveRecord::Migration def change rename_table :game_team, :game_teams end end
# -*- coding: utf-8 -*- # # Copyright 2013 whiteleaf. All rights reserved. # require_relative "../inventory" require_relative "../commandbase" module Command class Init < CommandBase def self.oneline_help if Narou.already_init? "AozoraEpub3 の再設定を行います" else "現在のフォルダを小説用に初期化します" end end def initialize super("") if Narou.already_init? initialize_already_init else initialize_init_yet end end def initialize_init_yet @opt.separator <<-EOS ・現在のフォルダを小説格納用フォルダとして初期化します。 ・初期化されるまでは他のコマンドは使えません。 Examples: narou init EOS end def initialize_already_init @opt.separator <<-EOS ・AozoraEpub3 の再設定を行います。 Examples: narou init EOS end def execute(argv) super if Narou.already_init? init_aozoraepub3(true) else Narou.init puts "-" * 30 init_aozoraepub3 puts "初期化が完了しました!" puts "現在のフォルダ下で各種コマンドが使用出来るようになりました。" puts "まずは narou help で簡単な説明を御覧ください。" end end def init_aozoraepub3(force = false) @global_setting = Inventory.load("global_setting", :global) if !force && @global_setting["aozoraepub3dir"] return end puts "<bold><green>AozoraEpub3の設定を行います</green></bold>".termcolor unless @global_setting["aozoraepub3dir"] puts "<bold><red>#{"!!!WARNING!!!".center(70)}</red></bold>".termcolor puts "AozoraEpub3の構成ファイルを書き換えます。narouコマンド用に別途新規インストールしておくことをオススメします" end aozora_path = ask_aozoraepub3_path unless aozora_path puts "設定をスキップしました。あとで " + "<bold><yellow>narou init</yellow></bold>".termcolor + " で再度設定出来ます" return end puts rewrite_aozoraepub3_files(aozora_path) @global_setting["aozoraepub3dir"] = aozora_path @global_setting.save puts "<bold><green>AozoraEpub3の設定を終了しました</green></bold>".termcolor end def rewrite_aozoraepub3_files(aozora_path) # chuki_tag.txt の書き換え custom_chuki_tag_path = File.join(Narou.get_preset_dir, "custom_chuki_tag.txt") chuki_tag_path = File.join(aozora_path, "chuki_tag.txt") custom_chuki_tag = open(custom_chuki_tag_path, "r:BOM|UTF-8") { |fp| fp.read } chuki_tag = open(chuki_tag_path, "r:BOM|UTF-8") { |fp| fp.read } embedded_mark = "### Narou.rb embedded custom chuki ###" if chuki_tag =~ /#{embedded_mark}/ chuki_tag.gsub!(/#{embedded_mark}.+#{embedded_mark}/m, custom_chuki_tag) else chuki_tag << "\n" + custom_chuki_tag end File.write(chuki_tag_path, chuki_tag) puts "(次のファイルを書き換えました)" puts chuki_tag_path puts # ファイルコピー src = ["AozoraEpub3.ini", "vertical_font.css", "DMincho.ttf"] dst = ["AozoraEpub3.ini", "template/OPS/css_custom/vertical_font.css", "template/OPS/fonts/DMincho.ttf"] puts "(次のファイルをコピーor上書きしました)" src.size.times do |i| src_full_path = File.join(Narou.get_preset_dir, src[i]) dst_full_path = File.join(aozora_path, dst[i]) FileUtils.install(src_full_path, dst_full_path) puts dst_full_path end end def ask_aozoraepub3_path puts print "<bold><green>AozoraEpub3のあるフォルダを入力して下さい:</green></bold>\n(未入力でスキップ".termcolor if @global_setting["aozoraepub3dir"] puts "、:keep で現在と同じ場所を指定)" print "(現在の場所:#{@global_setting["aozoraepub3dir"]}" end print ")\n>" while input = $stdin.gets.rstrip.gsub(/"/, "") path = File.expand_path(input) case when input == ":keep" aozora_dir = @global_setting["aozoraepub3dir"] if aozora_dir && Narou.aozoraepub3_directory?(aozora_dir) return aozora_dir end when Narou.aozoraepub3_directory?(path) return path when input == "" break end print "\n<bold><green>入力されたフォルダにAozoraEpub3がありません。" \ "もう一度入力して下さい:</green></bold>\n&gt;".termcolor end nil end end end
class Product < ApplicationRecord has_attached_file :main_image, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png" validates_attachment_content_type :main_image, content_type: /\Aimage\/.*\z/ before_save :set_image_url private def set_image_url self.image_url = self.main_image.url end end
class AddNotesToBooks < ActiveRecord::Migration def change add_column :books, :notes, :string add_column :books, :author_id, :integer remove_column :books, :author_name, :string end end
require 'spec_helper' RSpec::Matchers.define :all_be_close do |expected| match do |actual| # Wrap in Array to also use for scalars actual = [actual] expected = [expected] return false unless _same_shape?(actual, expected) # TODO: allow custom absolute tolerance. For now using TensorFlow default. a_tol = 1e-6 _all_close?(actual, expected, a_tol) # TODO: allow relative/percent tolerance compare, r_tol = 1e-6 end end describe 'all_be_close' do context 'scalars' do it 'is the same scalar' do expect(5.0).to all_be_close(5.0) end it 'is within tolerance' do expect(5.0).to all_be_close(5.0 + 1e-7) end it 'is outside tolerance' do expect(0.4).not_to all_be_close(0.4 + 2e-6) end it 'is the same scalar' do expect(12_000).not_to all_be_close([12_000]) end end context '1D array' do it 'is the same array' do expect([1.0, -2.0, 3.4e5]) .to all_be_close([1.0, -2.0, 3.4e5]) end it 'is within tolerance' do expect([1.0, -2.0, 3.4e5]) .to all_be_close([1.0 + 1e-7, -2.0 + 1e-7, 3.4e5 - 1e-7]) end it 'is outside tolerance' do expect([1.0, -2.0, 3.4e5]) .not_to all_be_close([1.0 + 2e-6, -2.0, 3.4e5 - 1e-7]) end end context '2D array' do it 'is the same array' do expect([[1.0, -2.0, 3.4e5], [1.0, -2.0, 3.4e5]]) .to all_be_close([[1.0, -2.0, 3.4e5], [1.0, -2.0, 3.4e5]]) end it 'is within tolerance' do expect([[1.0, -2.0, 3.4e5], [1.0, -2.0, 3.4e5]]) .to all_be_close([ [1.0 + 0.5e-6, -2.0, 3.4e5], [1.0, -2.0, 3.4e5 - 0.52e-6] ]) end it 'is outside tolerance' do expect([[1.0, -2.0, 3.4e5], [1.0, -2.0, 3.4e5]]) .not_to all_be_close([[1.0, -2.0, 3.4e5], [1.0, -2.0 + 2e-6, 3.4e5]]) end end describe 'shape and higher dimensions' do context '1D' do it 'is the same array' do expect([1.0, -2.0]) .to all_be_close([1.0, -2.0]) end it 'has wrong # of elements' do expect([1.0, -2.0]) .not_to all_be_close([1.0, -2.0, 7.0]) end end context '(2,N) and (N,2)' do it 'is the same array' do expect([[1.0, -2.0], [1.9999999, -2.0, 4.5]]) .to all_be_close([[1.0, -2.0], [1.9999999, -2.0, 4.5]]) end it 'has wrong # of columns' do expect([[1.0, -2.0, 5.0], [1.0, -2.0, 4.5]]) .not_to all_be_close([[1.0, -2.0], [1.0, -2.0]]) end it 'has wrong # of rows' do expect([[1.0, -2.0], [1.9999, -2.0], [1.0, -2.0]]) .not_to all_be_close([[1.0, -2.0], [1.9999, -2.0]]) end end context '(n,n,n)' do it 'is the same (1,1,1) array' do expect([[[[-1.000001]]]]) .to all_be_close([[[[-1.000001]]]]) end it 'is the same (2,3,4) array' do ar_2_3_4 = three_d_array ar_2_3_4_dup = Marshal.load(Marshal.dump(ar_2_3_4)) expect(ar_2_3_4).to all_be_close(ar_2_3_4_dup) end it 'is the same (2,3,4) array' do ar_2_3_4 = three_d_array ar_2_3_4_dup = Marshal.load(Marshal.dump(ar_2_3_4)) ar_2_3_4_dup[0][1][0] += 0.0001 expect(ar_2_3_4).not_to all_be_close(ar_2_3_4_dup) end end end end private def _same_shape?(a, b) return false unless a.size == b.size same_shape = true a.zip(b) do |ael, bel| break unless same_shape = if ael.is_a?(Array) && bel.is_a?(Array) _same_shape?(ael, bel) else !ael.is_a?(Array) && !bel.is_a?(Array) end end same_shape end def _all_close?(a, b, a_tol = 1e-6) a.flatten.zip(b.flatten).each do |ael, bel| break unless (ael - bel).abs <= a_tol end end def three_d_array ar_2_3_4 = [] 2.times do ar_3_4 = [] 3.times { ar_3_4 << [1.0, 2.0, 3.0, 4.0] } ar_2_3_4 << ar_3_4 end ar_2_3_4 end
class Address < ApplicationRecord belongs_to :customer validates :postal_code, presence: true, length: { is: 7 }, numericality: { only_integer: true } validates :address, :name, presence: true end
require_relative "spec_helper" Sequel.extension :migration describe "pg_enum extension" do mod = Module.new do private def schema_parse_table(*) [[:a, {:oid=>1, :type=>:enum}], [:b, {:oid=>1234}]] end def _metadata_dataset super.with_fetch([[{:v=>1, :enumlabel=>'a'}, {:v=>1, :enumlabel=>'b'}, {:v=>1, :enumlabel=>'c'}], [{:typname=>'enum1', :v=>212389}]]) end end before do @db = Sequel.connect('mock://postgres') @db.extend_datasets{def quote_identifiers?; false end} @db.extend(mod) @db.extension(:pg_array, :pg_enum) @db.sqls end it "should parse enum labels respecting the sort order" do @db.send(:parse_enum_labels) @db.sqls.must_equal ["SELECT CAST(enumtypid AS integer) AS v, enumlabel FROM pg_enum ORDER BY enumtypid, enumsortorder", "SELECT typname, CAST(typarray AS integer) AS v FROM pg_type WHERE ((1 = 0) AND (typarray != 0))"] end it "should parse enum labels without the sort order on PostgreSQL < 9.1" do def @db.server_version(_=nil); 90000; end @db.send(:parse_enum_labels) @db.sqls.must_equal ["SELECT CAST(enumtypid AS integer) AS v, enumlabel FROM pg_enum ORDER BY enumtypid", "SELECT typname, CAST(typarray AS integer) AS v FROM pg_type WHERE ((1 = 0) AND (typarray != 0))"] end it "should add enum values to parsed schema columns" do @db.schema(:foo).must_equal [[:a, {:oid=>1, :ruby_default=>nil, :type=>:enum, :enum_values=>["a", "b", "c"]}], [:b, {:oid=>1234, :ruby_default=>nil}]] end it "should typecast objects to string" do @db.typecast_value(:enum, :a).must_equal 'a' end it "should add array parsers for enum values" do @db.conversion_procs[212389].call('{a,b,c}').must_equal %w'a b c' end it "should not add array parser if there is already a conversion proc" do @db = Sequel.connect('mock://postgres') @db.extend_datasets{def quote_identifiers?; false end} @db.extend(mod) pr = proc{} @db.conversion_procs[212389] = pr @db.extension(:pg_array, :pg_enum) @db.conversion_procs[212389].must_equal pr @db.sqls.must_equal ["SELECT CAST(enumtypid AS integer) AS v, enumlabel FROM pg_enum ORDER BY enumtypid, enumsortorder", "SELECT typname, CAST(typarray AS integer) AS v FROM pg_type WHERE ((oid IN (1)) AND (typarray != 0))"] end it "should not add array parsers for enum values if pg_array extension is not used" do @db = Sequel.connect('mock://postgres') @db.extend_datasets{def quote_identifiers?; false end} @db.extend(mod) @db.extension(:pg_enum) @db.conversion_procs[212389].must_be_nil @db.sqls.must_equal ["SELECT CAST(enumtypid AS integer) AS v, enumlabel FROM pg_enum ORDER BY enumtypid, enumsortorder"] end it "should support #create_enum method for adding a new enum" do @db.create_enum(:foo, [:a, :b, :c]) @db.sqls.first.must_equal "CREATE TYPE foo AS ENUM ('a', 'b', 'c')" @db.create_enum(Sequel[:sch][:foo], %w'a b c') @db.sqls.first.must_equal "CREATE TYPE sch.foo AS ENUM ('a', 'b', 'c')" end with_symbol_splitting "should support #create_enum method for adding a new enum with qualified symbol" do @db.create_enum(:sch__foo, %w'a b c') @db.sqls.first.must_equal "CREATE TYPE sch.foo AS ENUM ('a', 'b', 'c')" end it "should support #rename_enum method for renameing an enum" do @db.rename_enum(:foo, :bar) @db.sqls.first.must_equal "ALTER TYPE foo RENAME TO bar" @db.rename_enum(Sequel[:sch][:foo], Sequel[:sch][:bar]) @db.sqls.first.must_equal "ALTER TYPE sch.foo RENAME TO sch.bar" end it "should support #rename_enum_value method for renameing an enum value" do @db.rename_enum_value(:foo, :b, :x) @db.sqls.first.must_equal "ALTER TYPE foo RENAME VALUE 'b' TO 'x'" end it "should support #drop_enum method for dropping an enum" do @db.drop_enum(:foo) @db.sqls.first.must_equal "DROP TYPE foo" @db.drop_enum(Sequel[:sch][:foo], :if_exists=>true) @db.sqls.first.must_equal "DROP TYPE IF EXISTS sch.foo" @db.drop_enum('foo', :cascade=>true) @db.sqls.first.must_equal "DROP TYPE foo CASCADE" end with_symbol_splitting "should support #drop_enum method for dropping an enum with a splittable symbol" do @db.drop_enum(:sch__foo, :if_exists=>true) @db.sqls.first.must_equal "DROP TYPE IF EXISTS sch.foo" end it "should support #add_enum_value method for adding value to an existing enum" do @db.add_enum_value(:foo, :a) @db.sqls.first.must_equal "ALTER TYPE foo ADD VALUE 'a'" end it "should support :before option for #add_enum_value method for adding value before an existing enum value" do @db.add_enum_value('foo', :a, :before=>:b) @db.sqls.first.must_equal "ALTER TYPE foo ADD VALUE 'a' BEFORE 'b'" end it "should support :after option for #add_enum_value method for adding value after an existing enum value" do @db.add_enum_value(Sequel[:sch][:foo], :a, :after=>:b) @db.sqls.first.must_equal "ALTER TYPE sch.foo ADD VALUE 'a' AFTER 'b'" end with_symbol_splitting "should support :after option for #add_enum_value method for adding value after an existing enum value with splittable symbol" do @db.add_enum_value(:sch__foo, :a, :after=>:b) @db.sqls.first.must_equal "ALTER TYPE sch.foo ADD VALUE 'a' AFTER 'b'" end it "should support :if_not_exists option for #add_enum_value method for not adding the value if it exists" do @db.add_enum_value(:foo, :a, :if_not_exists=>true) @db.sqls.first.must_equal "ALTER TYPE foo ADD VALUE IF NOT EXISTS 'a'" end it "should reverse a create_enum directive in a migration" do m = Sequel.migration{change{create_enum(:type_name, %w'value1 value2 value3')}} m.apply(@db, :up) @db.sqls.must_equal ["CREATE TYPE type_name AS ENUM ('value1', 'value2', 'value3')", "SELECT CAST(enumtypid AS integer) AS v, enumlabel FROM pg_enum ORDER BY enumtypid, enumsortorder", "SELECT typname, CAST(typarray AS integer) AS v FROM pg_type WHERE ((1 = 0) AND (typarray != 0))"] m.apply(@db, :down) @db.sqls.must_equal ["DROP TYPE type_name", "SELECT CAST(enumtypid AS integer) AS v, enumlabel FROM pg_enum ORDER BY enumtypid, enumsortorder", "SELECT typname, CAST(typarray AS integer) AS v FROM pg_type WHERE ((1 = 0) AND (typarray != 0))"] end it "should reverse a rename_enum directive in a migration" do m = Sequel.migration{change{rename_enum(:old_type_name, :new_type_name)}} m.apply(@db, :up) @db.sqls.must_equal ["ALTER TYPE old_type_name RENAME TO new_type_name", "SELECT CAST(enumtypid AS integer) AS v, enumlabel FROM pg_enum ORDER BY enumtypid, enumsortorder", "SELECT typname, CAST(typarray AS integer) AS v FROM pg_type WHERE ((1 = 0) AND (typarray != 0))"] m.apply(@db, :down) @db.sqls.must_equal ["ALTER TYPE new_type_name RENAME TO old_type_name", "SELECT CAST(enumtypid AS integer) AS v, enumlabel FROM pg_enum ORDER BY enumtypid, enumsortorder", "SELECT typname, CAST(typarray AS integer) AS v FROM pg_type WHERE ((1 = 0) AND (typarray != 0))"] end end
class CardsController < ApplicationController protect_from_forgery with: :null_session def index @cards = Card.where get_conditions params p @cards render json: @cards end def create @card = Card.new params.require(:card).permit(:title, :card_group_id) if @card.save render json: { status: :success, id: @card.id } else render json: { status: error, erros: @card.errors } end end def show @card = Card.find params[:id] render json: @card end def update @card = Card.find params[:id] if @card.update params.require(:card).permit(:title, :description) render json: { status: :success, id: @card.id } else render json: { status: error, erros: @card.errors } end end def destroy card = Card.find params[:id] card.destroy render json: { status: :success, id: card.id } end private def get_conditions (params) conditions = [] if params['card_group_id'].present? conditions.push "card_group_id = #{params['card_group_id']}" end if params['created_at_from'].present? conditions.push "DATE(created_at) >= '" + Date.parse(params['created_at_from']).to_s + "'" end if params['created_at_to'].present? conditions['created_at <='] = Date.parse(params['created_at_to']).to_time end p conditions; conditions end end
#!/usr/bin/env ruby libdir = File.dirname(__FILE__) + "/../lib" libdir = File.expand_path(libdir) $: << libdir require 'pcapr_local' require 'optparse' PcaprLocal::Config.assert_environment include PcaprLocal config_file = nil opts = OptionParser.new do |opts| opts.banner = "Usage: #{$0} [-f config_file]" opts.on('-f', '--config_file FILE', 'Config file') do |f| config_file = f end opts.on_tail('-h', '--help', 'Show this message') do puts opts exit 0 end end opts.parse! config_file ||= PcaprLocal::Config.user_config_path if File.exist?(config_file) config = PcaprLocal::Config.config config_file PcaprLocal.stop config end
require_relative '../lib/grid.rb' require_relative '../lib/ship.rb' class Game attr_accessor :command_line attr_reader :state, :shots STATES = %w(initialized ready error terminated gameover) GRID_SIZE = 10 HIT_CHAR = 'X' MISS_CHAR = '_' NO_SHOT_CHAR = '.' SHIPS_DEFS = [ { size: 4, type: 'Battleship'}, { size: 4, type: 'Battleship' }, { size: 5, type: 'Aircraft carrier' } ] STATES.each { |state| define_method("#{state}?") { @state==state } } def initialize(options = {}) @state = 'initialized' @command_line = nil @shots = [] @fleet = [] play end def play begin @hits_counter = 0 @matrix = Array.new(GRID_SIZE){ Array.new(GRID_SIZE, ' ') } @matrix_oponent = Array.new(GRID_SIZE){ Array.new(GRID_SIZE, NO_SHOT_CHAR) } @grid_oponent = Grid.new @state = 'ready' add_fleet begin console case @command_line when 'D' @grid_oponent.status_line = "" show(debug: true) when 'Q' @state = 'terminated' when 'I' @state = 'initialized' @grid_oponent.status_line = "Initialized" show when /^[A-J]([1-9]|10)$/ shoot @grid_oponent.status_line = "[#{ @state }] Your input: #{ @command_line }" show else @grid_oponent.status_line = "Error: Incorrect input" show clear_error end end while not(gameover? || terminated? || initialized? || ENV['RACK_ENV'] == 'test') end while initialized? report self end def show(options = {}) @grid_oponent.build(@matrix_oponent).show() if options[:debug] @grid = Grid.new.build(@matrix, @fleet) @grid.status_line = "DEBUG MODE" @grid.show end end # just some user input validations def << (str) if not str then return end @command_line = str.upcase end private def add_fleet @fleet = [] SHIPS_DEFS.each do |ship_definition| ship = Ship.new(@matrix, ship_definition).build @fleet.push(ship) @hits_counter += ship.xsize # need for game over check for coordinates in ship.location @matrix[coordinates[0]][coordinates[1]] = true end end end def console return nil if ENV['RACK_ENV'] == 'test' input = [(print "Enter coordinates (row, col), e.g. A5 (I - initialize, Q to quit): "), gets.rstrip][1] self << input end def shoot if xy = convert @shots.push(xy) @fleet.each do |ship| if ship.location.include? xy @matrix_oponent[xy[0]][xy[1]] = HIT_CHAR @hits_counter -= 1 Grid.row("You sank my #{ ship.type }!") if (ship.location - @shots).empty? @state = 'gameover' if game_over? return else @matrix_oponent[xy[0]][xy[1]] = MISS_CHAR end end end end def game_over? @hits_counter.zero? end def convert x = @command_line[0] y = @command_line[1..-1] [x.ord - 65, y.to_i-1] end def clear_error @state = 'ready' end def report msg = if terminated? "Terminated by user after #{@shots.size} shots!" elsif gameover? "Well done! You completed the game in #{@shots.size} shots" end Grid.row(msg) msg end end
module IOTA module Models class Bundle < Base attr_reader :transactions, :persistence, :attachmentTimestamp def initialize(transactions) if transactions.class != Array raise StandardError, "Invalid transactions array" end @transactions = [] transactions.each do |trx| trx = Transaction.new(trx) if trx.class != IOTA::Models::Transaction @transactions << trx end @persistence = @transactions.first.persistence @attachmentTimestamp = @transactions.first.attachmentTimestamp end def extractJSON utils = IOTA::Utils::Utils.new # Sanity check: if the first tryte pair is not opening bracket, it's not a message firstTrytePair = transactions[0].signatureMessageFragment[0] + transactions[0].signatureMessageFragment[1] return nil if firstTrytePair != "OD" index = 0 notEnded = true trytesChunk = '' trytesChecked = 0 preliminaryStop = false finalJson = '' while index < transactions.length && notEnded messageChunk = transactions[index].signatureMessageFragment # We iterate over the message chunk, reading 9 trytes at a time (0...messageChunk.length).step(9) do |i| # get 9 trytes trytes = messageChunk.slice(i, 9) trytesChunk += trytes # Get the upper limit of the tytes that need to be checked # because we only check 2 trytes at a time, there is sometimes a leftover upperLimit = trytesChunk.length - trytesChunk.length % 2 trytesToCheck = trytesChunk[trytesChecked...upperLimit] # We read 2 trytes at a time and check if it equals the closing bracket character (0...trytesToCheck.length).step(2) do |j| trytePair = trytesToCheck[j] + trytesToCheck[j + 1] # If closing bracket char was found, and there are only trailing 9's # we quit and remove the 9's from the trytesChunk. if preliminaryStop && trytePair == '99' notEnded = false break end finalJson += utils.fromTrytes(trytePair) # If tryte pair equals closing bracket char, we set a preliminary stop # the preliminaryStop is useful when we have a nested JSON object if trytePair === "QD" preliminaryStop = true end end break if !notEnded trytesChecked += trytesToCheck.length; end # If we have not reached the end of the message yet, we continue with the next transaction in the bundle index += 1 end # If we did not find any JSON, return nil return nil if notEnded finalJson end end end end
# Author: Jim Noble # jimnoble@xjjz.co.uk # # Player.rb # # A Rock/Paper/Scissors player. # # Valid strategies include: R, r, P, p, S, s # # p = Player.new("Jim Noble", "r") # # puts p class Player attr_accessor :name, :strategy def initialize(name, strategy) @name = name @strategy = strategy end def to_s "#{@name} [#{@strategy.upcase}]" end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe Rider do it { should have_db_column(:first_name) } it { should have_db_column(:last_name) } it { should belong_to(:pickup_route_stop) } it { should belong_to(:dropoff_route_stop) } it { should validate_presence_of(:first_name) } it { should validate_presence_of(:last_name) } it { should validate_presence_of(:pickup_route_stop) } it { should validate_presence_of(:dropoff_route_stop) } end
Promotion.class_eval do has_attached_file :leaderboard has_attached_file :half_leaderboard has_attached_file :full validates_attachment_content_type :leaderboard,{:content_type=> ["image/png","image/jpg","image/jpeg"], :message => I18n::t('flash.image_not_correct_content_type',:locale=>:it), :if => "leaderboard_file_name_changed?"} validates_attachment_content_type :half_leaderboard,{:content_type=> ["image/png","image/jpg","image/jpeg"], :message => I18n::t('flash.image_not_correct_content_type',:locale=>:it), :if => "half_leaderboard_file_name_changed?"} validates_attachment_content_type :full,{:content_type=> ["image/png","image/jpg","image/jpeg"], :message => I18n::t('flash.image_not_correct_content_type',:locale=>:it), :if => "leaderboard_file_name_changed?"} scope :today,where("starts_at >= ? and starts_at <= ?",Time.zone.now.beginning_of_day,Time.zone.now.end_of_day) scope :active_from_today, where("expires_at > ?", Time.zone.now.end_of_day) end
class Player attr_accessor :name, :score, :is_human, :tag def initialize name, tag, is_human=false @name = name @is_human = is_human #is the user an human? @tag = tag # Each user has a tag @score = 0 end end
class Medium < ApplicationRecord belongs_to :media_provider belongs_to :game end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception include SessionsHelper before_action :require_login, except: [:home, :new, :create] def home if logged_in? redirect_to lists_path end end private def require_login unless logged_in? flash[:danger] = "Please login to continue" redirect_to root_path end end end
class OrderExecution < ApplicationRecord MAX_VALID_TIME = 5.minutes extend Enumerize include AASM validates_presence_of :user_id, :exchange_id, :action scope :unfinished, -> {where.not(status: 'done')} belongs_to :user belongs_to :trader enumerize :action, in: [:open_position, :close_position] aasm column: :status do state :created, initial: true state :new_order # no open order exist state :close_order_placed state :close_order_finished state :open_order_placed state :done event :close do transitions from: :created, to: :close_order_placed end event :open_new_order do transitions from: :created, to: :new_order end event :close_finish do transitions from: :close_order_placed, to: :close_order_finished end event :open_order do transitions from: [:new_order, :close_order_finished], to: :open_order_placed end event :finish do transitions from: [:created, :new_order, :open_order_placed, :close_order_placed], to: :done after do WeixinNotificationJob.perform_async(self.id) end end end def logs OrderExecutionLog.where(order_execution_id: id) end end
module Monsove class Filesystem # Initialize a ne Filesystem object. # # @return [Filesytem] def initialize end # Compress the dump to an tar.bz2 archive. # # @param [String] path the path, where the dump is located. # # @return [nil] def compress(path) Monsove.logger.info("Compressing database #{path}") system("cd #{path} && tar -cjpf #{path}.tar.bz2 .") raise "Error while compressing #{path}" if $?.to_i != 0 end def decompress(path) Monsove.logger.info("Decompressing databse dump #{path}") system("cd #{File.dirname(path)} && tar -xjpf #{path}") raise "Error while decompressing #{path}" if $?.to_i != 0 end # Generate tmp path for dump. # # @return [String] def get_tmp_path "#{Dir.tmpdir}/#{Time.now.to_i * rand}" end # Remove dump and archive from tmp path. # # @param [String] path the path, where the dump/archive is located. # # @return [nil] def cleanup(path) Monsove.logger.info("Cleaning up local path #{path}") FileUtils.rm_rf(path) File.delete("#{path}.tar.bz2") end end end
module Netzke module Basepack # Common parts of FieldConfig and ColumnConfig class AttrConfig < ActiveSupport::OrderedOptions def initialize(c, data_adapter) c = {name: c.to_s} if c.is_a?(Symbol) || c.is_a?(String) c[:name] = c[:name].to_s self.replace(c) @data_adapter = data_adapter || NullDataAdapter.new(nil) end def primary? @data_adapter.primary_key_attr?(self) end def association? @data_adapter.association_attr?(self) end def set_defaults! set_read_only! if read_only.nil? end def set_read_only! self.read_only = primary? || !responded_to_by_model? && !association? end private def responded_to_by_model? # if no model class is provided, assume the attribute is being responded to @data_adapter.model_class.nil? || !setter.nil? || @data_adapter.model_class.instance_methods.include?(:"#{name}=") || @data_adapter.model_class.attribute_names.include?(name) end end end end
require 'printrun/core' module Printrun include Core extend self # careful of the bug of sourcify with double quotes (if still there at time of reading)... # @example # Printrun.on(STDOUT) do # a = 3 # puts a # end def on(io, world = proc { binding }[], &block) i = 0 line_eval(world, proc { |line| io.puts "#{i += 1} >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>#{line}\n --- " proc { |ans| io.puts "#{ans}\ndone!" } }, &block) end def out(world = nil, &block) world ? on(STDOUT, world, &block) : on(STDOUT, &block) end def err(world = nil, &block) world ? on(STDERR, world, &block) : on(STDERR, &block) end end
class HistoryVideo < ActiveRecord::Base attr_accessible :user_id, :video_id belongs_to :video belongs_to :user end
require 'spec_helper' describe PostsController do describe 'GET query' do context "with a location, start, and end" do let(:location) {"Test Location"} let(:start) {Time.current} let(:end_time) {Time.current+3.hours} let(:post1) {} before do post1 get :query, :format => :json, :location => location, :start => start.iso8601, :end => end_time.iso8601 end context "and there are matching posts" do let(:post1) {create(:post, :meeting_time => Time.current-1.hour, :end_time => Time.current+4.hours, :location => location)} it "should return it" do expect(JSON.parse(response.body).length).to eq 1 end end end end describe "#update" do let(:post_1) { create(:post) } let(:username) {} let(:post_params) do { :title => "banana" } end before do controller.stub(:current_user).and_return(username) if username patch :update, :id => post_1.id, :post => post_params end context "when logged in" do let(:username) { "test1"} context "and they don't own the post" do it "should redirect" do expect(response).to be_redirect end it "should set a flash message" do expect(flash[:error]).to eq t("post.errors.permissions") end end context "and they own the post" do let(:post_1) { create(:post, :onid => username) } it "should not set a flash message" do expect(flash[:error]).to be_nil end end end end describe "#destroy" do let(:post_1) { create(:post) } let(:username) {} before do controller.stub(:current_user).and_return(username) if username delete :destroy, :id => post_1.id end context "when logged in" do let(:username) { "test1"} context "and they don't own the post" do it "should redirect" do expect(response).to be_redirect end it "should set a flash message" do expect(flash[:error]).to eq t("post.errors.permissions") end end context "and they own the post" do let(:post_1) { create(:post, :onid => username) } it "should not set a flash message" do expect(flash[:error]).to be_nil end end end end describe "#edit" do let(:post_1) { create(:post) } let(:username) {} before do controller.stub(:current_user).and_return(username) if username get :edit, :id => post_1.id end context "when not logged in" do it "should redirect" do expect(response).to be_redirect end end context "when logged in" do let(:username) { "test1" } context "and they don't own the post" do it "should redirect" do expect(response).to be_redirect end it "should set a flash message" do expect(flash[:error]).to eq t("post.errors.permissions") end end end end end
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :post do title "Post Title" link "http://post.link.com/hello.html" end end
class DropTokens < ActiveRecord::Migration[5.2] def change drop_table :tokens do t.references :user, foreign_key: true, null: false t.string :body, null: false t.datetime :last_used_at, null: false t.timestamps t.datetime :deleted_at t.index :deleted_at t.index :body, unique: true end end end
require 'test_helper' class ChassisControllerTest < ActionDispatch::IntegrationTest setup do @chassis = chassis(:one) end test "should get index" do get chassis_index_url assert_response :success end test "should get new" do get new_chassis_url assert_response :success end test "should create chassis" do assert_difference('Chassis.count') do post chassis_index_url, params: { chassis: { description: @chassis.description, name: @chassis.name } } end assert_redirected_to chassis_url(Chassis.last) end test "should show chassis" do get chassis_url(@chassis) assert_response :success end test "should get edit" do get edit_chassis_url(@chassis) assert_response :success end test "should update chassis" do patch chassis_url(@chassis), params: { chassis: { description: @chassis.description, name: @chassis.name } } assert_redirected_to chassis_url(@chassis) end test "should destroy chassis" do assert_difference('Chassis.count', -1) do delete chassis_url(@chassis) end assert_redirected_to chassis_index_url end end
FactoryGirl.define do factory :experience, class: Experience do association :experienceable, factory: :user description { "Experience #{rand 1000}" } end end
require "spec_helper" module Scenic module Adapters describe Postgres, :db do describe "create_view" do it "successfully creates a view" do Postgres.create_view("greetings", "SELECT text 'hi' AS greeting") expect(Postgres.views.map(&:name)).to include("greetings") end end describe "drop_view" do it "successfully drops a view" do Postgres.create_view("greetings", "SELECT text 'hi' AS greeting") Postgres.drop_view("greetings") expect(Postgres.views.map(&:name)).not_to include("greetings") end end describe "views" do it "finds views and builds Scenic::View objects" do ActiveRecord::Base.connection.execute "CREATE VIEW greetings AS SELECT text 'hi' AS greeting" expect(Postgres.views).to eq([ View.new( "viewname" => "greetings", "definition" => "SELECT 'hi'::text AS greeting;", ), ]) end end end end end
class CreateJoinTableTeamsDivisions < ActiveRecord::Migration[5.2] def change create_join_table :teams, :divisions do |t| t.index [:team_id, :division_id] t.index [:division_id, :team_id] end end end
require 'rails_helper' RSpec.describe "As a user" do describe "when i visit the homepage and select a house" do scenario "i see count of members and list of members" do visit "/" click_on "Search For Members" expect(current_path).to eq("/search") expect(page).to have_content("21 members") expect(page).to have_content("Harry") expect(page).to have_content("Ron") expect(page).to have_content("Hermione") end end end # As a user, # When I visit "/" # And I Select “Gryffindor” from the select field # (Note: Use the existing select field) # And I click "Search For Members“ # Then I should be on page “/search” # Then I should see a total of the number of members for that house. (21 for Gryffindor) # And I should see a list of the 21 members of the Order of the Phoenix for house Gryffindor.
require 'rails_helper' RSpec.describe Ability, :type => :model do let(:user) { nil } subject(:ability) { Ability.new(user) } describe "as not-signed-in user" do it { should be_able_to(:index, Post.new) } it { should_not be_able_to(:show, Post.new) } end describe "as signed-in user" do let(:user) { User.create!(username:'Name', password: 'password', password_confirmation: 'password', email: 'user@email.com', address: 'Address', confirmed_at: Time.now) } it { should be_able_to(:index, Post.new) } it { should be_able_to(:show, Post.new(user: user)) } end end
class CreateContests < ActiveRecord::Migration[5.1] def change create_table :contests do |t| t.string :NameofContest t.string :ContestLevel t.string :ContestLocation t.string :NumberOfPlayers t.timestamps end end end
class Hindrance < ActiveRecord::Base belongs_to :hindrance_type has_and_belongs_to_many :characters has_and_belongs_to_many :modifiers scope :non_racial, -> { joins(:hindrance_type).where('hindrance_types.name != ?', 'Racial') } def self.method_missing(method_name, *args, &block) find_by(name: method_name.to_s.titleize) end def add_modifier(modifier) if not self.modifiers.include? modifier then self.modifiers << modifier end end end
cookbook_file "script to install Firefox" do source "gtk-firefox.sh" path "/tmp/gtk-firefox.sh" end bash "install_firefox" do user "root" cwd "/tmp" code <<-EOH . /tmp/gtk-firefox.sh EOH end
module V1 class TodosController < ApplicationController def index @todos = current_user.todos.order(created_at: :desc).all render json: @todos, each_serializer: TodoSerializer end def show @todo = Todo.find(params[:id]) render json: @todo, serializer: TodoSerializer end def create @todo = Todo.new(todo_params) if @todo.save render json: @todo, serializer: TodoSerializer else render json: { error: t('todo_create_error') }, status: :unprocessable_entity end end def destroy @todo = Todo.find(params[:id]) @todo.destroy render json: @todo, serializer: TodoSerializer end private def todo_params params.permit(:body).merge(user: current_user) end end end
#!/usr/bin/env gem build lib = File.expand_path '../lib', __FILE__ $:.unshift lib unless $:.include? lib require 'shopware/version' Gem::Specification.new 'shopware', Shopware::VERSION do |spec| spec.summary = 'Ruby API client and CLI for Shopware' spec.author = 'Maik Kempe' spec.email = 'mkempe@bitaculous.com' spec.homepage = 'https://bitaculous.github.io/shopware/' spec.license = 'MIT' spec.files = Dir['{bin,lib,resources}/**/*', 'LICENSE', 'README.md'] spec.executables = ['shopware'] spec.extra_rdoc_files = ['LICENSE', 'README.md'] spec.required_ruby_version = '~> 2.1' spec.required_rubygems_version = '~> 2.4' spec.add_runtime_dependency 'thor', '~> 0.19.1' spec.add_runtime_dependency 'httparty', '~> 0.13.5' spec.add_runtime_dependency 'valid', '~> 0.5.0' spec.add_runtime_dependency 'terminal-table', '~> 1.5.2' spec.add_development_dependency 'bundler', '~> 1.10' spec.add_development_dependency 'rake', '~> 10.4.2' spec.add_development_dependency 'rspec', '~> 3.3.0' end
class Vaga < ApplicationRecord belongs_to :apartamento validates_presence_of :local, :apartamento_id, :modelo_carro, :car_carro, :placa_carro end
class AddNicknameToIndexUsers < ActiveRecord::Migration[5.1] def change add_column :index_users, :nickname, :string end end
class User < ApplicationRecord has_many :group_users has_many :groups, through: :group_users has_many :messages, dependent: :delete_all end
class ChangeTermOfOrders < ActiveRecord::Migration[5.2] def change change_column :orders, :term, :string, default: "0" end end
require 'net/smtp' module Smitty def self.smtp_connect(server, port, ssl, username, password, ignorecert) begin smtp_server = server.nil? ? 'localhost' : server smtp_port = port.nil? ? 25 : port.to_i smtp_conn = Net::SMTP.new(smtp_server, smtp_port) if ssl if ignorecert context = Net::SMTP.default_ssl_context context.verify_mode = OpenSSL::SSL::VERIFY_NONE smtp_conn.enable_starttls(context) else smtp_conn.enable_starttls() end end if username Smitty.croak('No password provided') if password.nil? if ssl smtp_conn.start(smtp_server, username, password, :login) else smtp_conn.start(smtp_server, username, password, :plain) end else smtp_conn.start() end smtp_conn rescue Exception => e Smitty.croak("Could not connect to SMTP server #{smtp_server}:#{smtp_port}", e.message) end end end
require 'spec_helper' describe UserProfile do before(:each) do @profile = Factory(:user_profile) end it { should belong_to(:user) } it { should belong_to(:avatar) } it { should validate_presence_of(:language) } it { should allow_value('en').for(:language) } it { should allow_value('ar').for(:language) } it { should_not allow_value('es').for(:language) } it "should build a default avatar if none is choosen" do @profile.avatar.should_not be_nil @profile.avatar.url.should == Avatar.default.url end context 'with existing user profiles and matching criteria' do before(:each) do @religion_agnostic = Factory(:religion, :i18n_name => 'agnostic') @religion_islam = Factory(:religion, :i18n_name => 'islam') @gender_male = Factory(:gender, :i18n_name => 'male') @gender_female = Factory(:gender, :i18n_name => 'female') @sexual_orientaton_straight = Factory(:sexual_orientation, :i18n_name => 'straight') @sexual_orientation_gay = Factory(:sexual_orientation, :i18n_name => 'gay') @age_range_12_16 = Factory(:age, :range => '12-16') @age_range_17_18 = Factory(:age, :range => '17-18') @political_view_liberal = Factory(:political_view, :i18n_name => 'liberal') @political_view_conservative = Factory(:political_view, :i18n_name => 'conservative') @user_profile_1 = Factory(:user_profile, :religion => @religion_agnostic, :gender => @gender_male, :sexual_orientation => @sexual_orientation_straight, :age => @age_range_12_16, :political_view => @political_view_liberal ) @user_profile_2 = Factory(:user_profile, :religion => @religion_islam, :gender => @gender_female, :sexual_orientation => @sexual_orientation_gay, :age => @age_range_17_18, :political_view => @political_view_conservative ) @user_profile_3 = Factory(:user_profile, :religion => @religion_islam, :gender => @gender_female, :sexual_orientation => @sexual_orientation_gay, :age => @age_range_17_18, :political_view => @political_view_conservative ) end it 'should match data accorfing to filters' do UserProfile.get_matching_profiles_from_params({ :religion_id => @religion_islam.id, :gender_id => @gender_female.id, :sexual_orientation_id => @sexual_orientation_gay.id, :age_id => @age_range_17_18.id, :political_view_id => @political_view_conservative.id }).should == [@user_profile_2, @user_profile_3] end end end
module Refinery module Careers module Admin class CareersController < ::Refinery::AdminController crudify :'refinery/careers/career', :title_attribute => 'career_title' private # Only allow a trusted parameter "white list" through. def career_params params.require(:career).permit(:career_image_id, :career_title, :body, :button_text, :link_url, :video_code) end end end end end
module Reportable def has_full_report? File.exists?(full_report_path) end end
# frozen_string_literal: true require 'rspec/sleeping_king_studios/concerns/shared_example_group' require 'support/examples' module Spec::Support::Examples module ContractBuilderExamples extend RSpec::SleepingKingStudios::Concerns::SharedExampleGroup shared_examples 'should delegate to #constraint' do let(:options) { {} } let(:expected_options) do defined?(custom_options) ? custom_options.merge(options) : options end before(:example) do allow(builder).to receive(:constraint) end describe 'with a block' do let(:implementation) { -> {} } it 'should delegate to #constraint' do define_from_block(&implementation) expect(builder) .to have_received(:constraint) .with(nil, **expected_options) end it 'should pass the implementation' do allow(builder).to receive(:constraint) do |*_args, &block| block.call end expect { |block| define_from_block(&block) }.to yield_control end end describe 'with a block and options' do let(:implementation) { -> {} } let(:options) { { key: 'value' } } it 'should delegate to #constraint' do define_from_block(**options, &implementation) expect(builder) .to have_received(:constraint) .with(nil, **expected_options) end end describe 'with a constraint' do let(:constraint) { Stannum::Constraints::Base.new } it 'should delegate to #constraint' do define_from_constraint(constraint) expect(builder) .to have_received(:constraint) .with(constraint, **expected_options) end end describe 'with a constraint and options' do let(:constraint) { Stannum::Constraints::Base.new } let(:options) { { key: 'value' } } it 'should delegate to #constraint' do define_from_constraint(constraint, **options) expect(builder) .to have_received(:constraint) .with(constraint, **expected_options) end end end end end
# Copyright 2011-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. When /^I batch put (\d+) items to the table$/ do |count| @table.batch_put((1..count.to_i).map{|n| { :id => n.to_s }}) end When /^I batch delete (\d+) items from the table$/ do |count| @table.batch_delete((1..count.to_i).to_a.map(&:to_s)) end Then /^the table should have (\d+) items$/ do |count| eventually do @table.items.count.should == count.to_i end end When /^I batch put (\d+) items to each table$/ do |count| put = (1..count.to_i).map{|n| { :id => n.to_s, :counts => [n, n+1] }} @dynamo_db.batch_write do |batch| @created_tables.each do |table| batch.write(table, :put => put) end end end Then /^the tables should have (\d+) items each$/ do |count| @created_tables.each do |table| table.items.count.should == count.to_i end end
class ProductsController < InheritedResources::Base after_filter :update_cart_total, :only => [:add_to_cart, :remove_from_cart, :clear_cart] def filter_products @products = Product.order(:name) category_id = Category.where("name = :name", {:name => "#{params[:category]}"}).first.id @products = @products.where(:category_id => category_id) unless params[:category].downcase == 'all' @products = @products.where('discount is not null AND discount > 0') if params[:on_sale] @products = @products.where(:created_at => (Time.now - 1.day)..Time.now) if params[:new] @products = @products.where(:updated_at => (Time.now - 1.minute)..Time.now) if params[:recently_updated] end def add_to_cart @cart.add_cart_item(Product.find(params[:product_id])) redirect_to root_url end def remove_from_cart @cart.remove_cart_item(Product.find(params[:product_id])) redirect_to root_url end def clear_cart @cart.clear_cart_items redirect_to root_url end def update_cart_total @cart.update_sub_total end def search_results @keyword = params[:keyword] @products = Product.where("name LIKE :keyword OR description LIKE :keyword OR image LIKE :keyword", {:keyword => "%#{@keyword}%"}) end end
Rails.application.routes.draw do get 'logs/index' get 'sales/index' get 'drivers/index' devise_for :users # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root to: "indices#home" get 'drivers', to: 'drivers#index', as: 'drivers' get 'drivers/new', to: 'drivers#new', as: 'new_driver' get 'drivers/:id', to: 'drivers#show', as: 'driver' post 'drivers', to:'drivers#create' get 'drivers/:id/edit', to: 'drivers#edit', as: 'edit_driver' patch 'drivers/:id', to: 'drivers#update' get 'sales', to: 'sales#index', as: 'sales' get 'sales/new', to: 'sales#new', as: 'new_sale' get 'sales/:id', to: 'sales#show', as: 'sale' post 'sales', to:'sales#create' get 'sales/:id/edit', to: 'sales#edit', as: 'edit_sale' patch 'sales/:id', to: 'sales#update' get 'logs', to: 'logs#index', as: 'logs' get 'logs/new', to: 'logs#new', as: 'new_log' get 'logs/:id', to: 'logs#show', as: 'log' post 'logs', to:'logs#create' get 'logs/:id/edit', to: 'logs#edit', as: 'edit_log' patch 'logs/:id', to: 'logs#update' end
require 'rails_helper' RSpec.describe GameResult do let(:successful_result) { GameResult.new(success: true) } let(:game_full_result) { GameResult.new(success: false, error_type: :game_full) } describe '#success?' do it 'is successful' do expect(successful_result.success?).to be true end end describe '#game_full' do it 'returns true' do expect(game_full_result.game_full?).to be true end it 'is unsuccessful' do expect(game_full_result.success?).to be false end end describe '#error_message' do it 'returns the correct error message' do expect(game_full_result.error_message).to eq(GameResult::ERROR_TYPES[:game_full]) end end describe '.game_full_result' do let(:game_result) { GameResult.game_full_result } it 'is unsuccessful' do expect(game_result.success?).to be false end it 'has game_full error_type' do expect(game_result.error_type).to eq(:game_full) end end describe '.successful_result' do let(:game_result) { GameResult.successful_result } it 'is successful' do expect(game_result.success?).to be true end end end
# require 'spec_helper' # describe RechargesController do # describe "GET #new" do # context "logged in" do # it "renders new template" do # testorder = FactoryGirl.create(:order) # ApplicationController.any_instance.stub(:current_user).and_return(testorder.user) # get :new, orderid: testorder.id # expect(response).to render_template('new') # end # end # context "not logged in" do # it "redirects to login" do # testorder = FactoryGirl.create(:order) # ApplicationController.any_instance.stub(:current_user).and_return(nil) # get :new, orderid: testorder.id # expect(response).to redirect_to(new_login_path(:return_to => new_recharge_path)) # end # end # end # describe "GET #create" do # context "with valid attributes" do # it "creates new recharge" do # testorder = FactoryGirl.create(:order) # params = {orderid:testorder.id,phonenumber:"9501499829",phone_operator: 1} # get :create, params # expect(Recharge.count).to eq(1) # end # it "redirects to dashboard" do # testorder = FactoryGirl.create(:order) # params = {orderid:testorder.id,phonenumber:"9501499829",phone_operator: 1} # get :create, params # expect(response).to redirect_to(url_for({:controller => "users",:action => "dashboard",:only_path => true})) # end # end # context "with invalid attributes" do # it "doesn't create new recharge" do # testorder = FactoryGirl.create(:order) # params = {orderid:testorder.id,phonenumber:"950149982",phone_operator: 1} # get :create, params # expect(Recharge.count).to eq(0) # end # it "renders new template again" do # testorder = FactoryGirl.create(:order) # params = {orderid:testorder.id,phonenumber:"950149982",phone_operator: 1} # get :create, params # expect(response).to render_template('new') # end # end # end # describe "GET #edit" do # context "with valid recharge ID" do # it "renders edit template" do # testrecharge = FactoryGirl.create(:recharge) # ApplicationController.any_instance.stub(:current_user).and_return(testrecharge.order.user) # params = {id:testrecharge.id} # get :edit, params # expect(response).to render_template('edit') # end # end # context "with invalid recharge ID" do # it "redirects to orders page" do # testrecharge = FactoryGirl.create(:recharge) # ApplicationController.any_instance.stub(:current_user).and_return(testrecharge.order.user) # params = {id: 5} # get :edit, params # expect(response).to redirect_to(url_for({:controller => "orders",:action => "index",:only_path => true})) # end # end # end # describe "POST #update" do # context "with valid attributes" do # it "updates recharge" do # testrecharge = FactoryGirl.create(:recharge) # params = {id: testrecharge.id,phonenumber: "9501499823",phone_operator: 1} # post :update, params # testrecharge.reload # expect(testrecharge.phonenumber).to eq("9501499823") # end # it "redirects to orders index" do # testrecharge = FactoryGirl.create(:recharge) # params = {id: testrecharge.id,phonenumber: "9501499829",phone_operator: 1} # post :update, params # expect(response).to redirect_to(url_for({:controller => "recharges",:action => "show", :id => testrecharge.id ,:only_path => true})) # end # end # context "with invalid attributes" do # it "doesn't updates recharge" do # testrecharge = FactoryGirl.create(:recharge) # params = {id: testrecharge.id,phonenumber: "95014993",phone_operator: 1} # post :update, params # testrecharge.reload # expect(testrecharge.phonenumber).to eq("9501499829") # end # it "redirects to orders index" do # testrecharge = FactoryGirl.create(:recharge) # params = {id: testrecharge.id,phonenumber: "950149982",phone_operator: 1} # post :update, params # expect(response).to render_template('edit') # end # end # end # describe "GET #show" do # context "with valid recharge ID" do # it "renders show template" do # testrecharge = FactoryGirl.create(:recharge) # ApplicationController.any_instance.stub(:current_user).and_return(testrecharge.order.user) # params = {id:testrecharge.id} # get :show, params # expect(response).to render_template('show') # end # end # context "with invalid recharge ID" do # it "redirects to orders page" do # ApplicationController.any_instance.stub(:current_user).and_return(FactoryGirl.create(:user)) # get :show, id: 5 # expect(response).to redirect_to(orders_path) # end # end # end # end
class Ability include CanCan::Ability def initialize(user) user ||= Use.new cannot :manage, :all can :read, :all cannot :read, User if user.permissions.where(:name => "allow_importing_spare_part").count > 0 can :create, Inventory end if user.permissions.where(:name => "allow_withdraw_spare_part").count > 0 can :update, Inventory end if user.permissions.where(:name => "allow_work_request").count > 0 can :create, Workorder end if user.permissions.where(:name => "allow_work_update").count > 0 can :update, Workorder end if user.permissions.where(:name => "allow_manage_asset_and_inventory").count > 0 can :manage, Asset can :manage, Inventory can :manage, InvType end # role base permission if user.role? :manager or user.role? :admin can :manage, :all elsif user.role? :staff cannot :manage, User # cannot :create, MaintenanceRequestForm end end end
namespace :nofrag do desc 'Import Nofrag news' task(:import => :environment) do require 'rss' rss = RSS::Parser.parse('http://www.nofrag.com/fb/nofrag.rss', true) rss.items.each do |item| remote_id = /\/([0-9]+)\/$/.match(item.guid.content)[1].to_s.to_i begin ImportedNofragItem.create! do |n| n.remote_id = remote_id n.title = item.title n.url = item.guid.content n.description = item.description n.published_at = DateTime.parse(item.pubDate.to_s) end puts "Added #{remote_id}" rescue ActiveRecord::StatementInvalid puts "Ignored #{remote_id}" end end end desc 'Create topics from Nofrag news' task(:create_topics => :environment) do include ActionView::Helpers::TextHelper include ActionView::Helpers::SanitizeHelper include ActionView::Helpers::SanitizeHelper::ClassMethods forum = Forum.find_by_stripped_title('nofrag') or raise ActiveRecord::RecordNotFound user = User.find_by_login('nofrag') or raise ActiveRecord::RecordNotFound ImportedNofragItem.unposted.all(:order => 'published_at ASC').each do |item| description = strip_tags(item.description.gsub(/<br\s*\/?\s*>/, "\n").gsub(/\n\n+/, "\n\n")).strip description.sub!("\n\nLire la suite sur Nofrag...", '') description += "\n\n[url=#{item.url}]Lire toute la news sur Nofrag.com...[/url]" Topic.transaction do topic = forum.topics.create! do |t| t.user_id = user.id t.title = truncate(strip_tags(item.title).strip, :length => 90) t.body = description end item.update_attributes!(:topic_id => topic.id) puts "Created topic for \"#{topic.title}\"" end end puts "Topics created." end desc 'Delete topics from Nofrag news' task(:delete_topics => :environment) do ImportedNofragItem.posted.each do |item| Topic.transaction do item.topic.destroy if item.topic item.destroy end end end end
require 'test_helper' class EventTest < ActiveSupport::TestCase should have_one :ticket should have_many :conflicts_as_conflicting should have_many :conflicts should have_many :event_attachments should have_many :event_feedbacks should have_many :event_people should have_many :event_ratings should have_many :links should have_many :people should have_many :videos should belong_to :conference should belong_to :track should belong_to :room should accept_nested_attributes_for :event_people should accept_nested_attributes_for :links should accept_nested_attributes_for :event_attachments should accept_nested_attributes_for :ticket should validate_presence_of :title should validate_presence_of :time_slots setup do ActionMailer::Base.deliveries = [] end def setup_notification_event @notification = create(:notification) @event = create(:event, conference: @notification.conference) @speaker = create(:person) create(:event_person, event: @event, person: @speaker, event_role: 'speaker') @coordinator = create(:person) end test 'acceptance processing sends email if asked to' do setup_notification_event @event.process_acceptance(send_mail: true) assert !ActionMailer::Base.deliveries.empty? end test 'acceptance processing sends german email if asked to' do setup_notification_event @speaker.languages << Language.new(code: 'de') @event.conference.languages << Language.new(code: 'de') notification = create(:notification, locale: 'de') @notification.conference.notifications << notification @event.process_acceptance(send_mail: true) assert !ActionMailer::Base.deliveries.empty? end test 'acceptance processing does not send email by default' do setup_notification_event @event.process_acceptance(send_mail: false) assert ActionMailer::Base.deliveries.empty? end test 'acceptance processing sets coordinator' do setup_notification_event assert_difference 'EventPerson.count' do @event.process_acceptance(coordinator: @coordinator) end end test 'rejection processing sends email if asked to' do setup_notification_event @event.process_rejection(send_mail: true) assert !ActionMailer::Base.deliveries.empty? end test 'rejection processing does not send email by default' do setup_notification_event @event.process_rejection(send_mail: false) assert ActionMailer::Base.deliveries.empty? end test 'rejection processing sets coordinator' do setup_notification_event assert_difference 'EventPerson.count' do @event.process_rejection(coordinator: @coordinator) end end test 'correctly detects overlapping of events' do event = create(:event) other_event = create(:event) other_event.start_time = event.start_time.ago(30.minutes) assert event.overlap?(other_event) other_event.start_time = event.start_time.ago(1.hour) refute event.overlap?(other_event) end test 'event conflicts are updated if availabilities change' do conference = create(:three_day_conference_with_events) first_event = conference.events.first assert_empty first_event.conflicts event_person = create(:event_person, event: first_event) refute_empty first_event.reload.conflicts availability = create(:availability, person: event_person.person, conference: conference, start_date: conference.days.first.start_date, end_date: conference.days.last.end_date) assert_empty first_event.reload.conflicts availability.update(start_date: conference.days.last.start_date) refute_empty first_event.reload.conflicts end end
# encoding: utf-8 require 'spec_helper' describe TTY::Table::Operation::Filter, '#call' do let(:object) { described_class } let(:field) { TTY::Table::Field.new('a1') } let(:filter) { Proc.new { |val, row, col| 'new' } } let(:value) { 'new' } subject { object.new(filter) } it 'changes field value' do subject.call(field, 0, 0) expect(field.value).to eql(value) end end
class SessionsController < ApplicationController skip_before_action :authenticate_user def login login_service = Login.new(params.permit(:name, :email, :password)) respond login_service.call end def refresh_token respond RefreshToken.new(params[:refresh_token]).call end end
# frozen_string_literal: true require_relative 'color' # Player class class Player private attr_reader :num public attr_accessor :name def initialize(name, num) @name = num == 1 ? name.yellow : name.red @num = num end def first? num == 1 end end
class Food < ApplicationRecord validates :name, :description, :date, presence: true mount_uploader :image, ImageUploader end
require "elevators/version" module Elevators class Elevator # TODO - would like to have a queue of request stops # TODO - would like to have functionality so that elevators can report # the cost for them to satisfy a new request. attr_accessor :current_floor attr_accessor :target_floor attr_accessor :trip_count attr_accessor :status @@OPERATIONAL = "OPERATIONAL" @@MAINTENANCE = "MAINTENANCE" @@MAX_TRIPS = 100 def initialize(num_floors = 1) raise "Must specify number of floors of 1 or greater" unless num_floors > 0 @current_floor = 1 @target_floor = 1 @num_floors = num_floors @trip_count = 0 @status = "OPERATIONAL" end def move return if @status == @@MAINTENANCE direction = @target_floor <=> @current_floor case direction when 1 # need to move up @current_floor = [@current_floor + 1, @num_floors].min report_floor_change when -1 # need to move down @current_floor = [@current_floor - 1, 1].max report_floor_change when 0 # at target floor report_door_open @trip_count += 1 @status = @@MAINTENANCE if @trip_count > @@MAX_TRIPS end end def report_door_close report("Door Close") end def report_door_open report("Door Open") end def report_floor_change report("Floor Change") end def report(msg = "") # just puts for now, could use a visitor patter here for something better... puts "Elevator on Floor #{@current_floor} #{msg}" end end class Controller def initialize(num_floors = 1, num_elevators = 1) @elevators = (1..num_elevators).each { Elevator.new(num_floors) } end def move(requests = []) # expect a list of floor stop requests on each iteration. end end end
class CreateFileExtensionCache < ActiveRecord::Migration[5.0] def change create_table :cache_file_extension_stats_by_collection, id: false do |t| t.integer :collection_id, index: true t.integer :file_extension_id t.string :extension t.integer :file_count t.decimal :file_size end add_index :cache_file_extension_stats_by_collection, :file_extension_id, name: 'index_cache_file_extension_stats_by_collection_fe_id' end end
class RemoveColumn < ActiveRecord::Migration[5.2] def change remove_column :subs, :moderator_id end end
# frozen_string_literal: true require 'spec_helper' require 'vagrant-bolt/config' require 'vagrant-bolt/provisioner' describe VagrantBolt::Provisioner do include_context 'vagrant-unit' subject { described_class.new(machine, config) } let(:iso_env) do env = isolated_environment env.vagrantfile <<-VAGRANTFILE Vagrant.configure('2') do |config| config.vm.define :server end VAGRANTFILE env.create_vagrant_env end let(:machine) { iso_env.machine(:server, :dummy) } let(:config) { double :config } let(:runner) { double :runner } before(:each) do allow(machine).to receive(:env).and_return(:iso_env) allow(config).to receive(:name).and_return('foo') allow(config).to receive(:command).and_return('task') end context 'provision' do before(:each) do allow(VagrantBolt::Runner).to receive(:new).with(:iso_env, machine, config).and_return(runner) allow(runner).to receive(:run).with('task', 'foo').and_return('runner created') end it 'creates a new runner' do expect(subject.provision).to eq('runner created') end end end
require "rails_helper" RSpec.describe InvalidPhoneNumberResponse do describe "#to_s" do it "generates xml that contains a message" do result = described_class.new.to_s expect(result).to include("</Say>") end end end
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root to: 'pages#show' # get 'home', to: 'pages#about' get "/api/v1/pronostic", to: 'pages#api' end
require 'text' require 'twilio-ruby' describe Text do it { is_expected.to respond_to :time } it { is_expected.to respond_to :send_text} describe '#send_text' do it 'should send text when order is placed' do client = double :client allow(client).to receive_message_chain(:messages, :create) expect(Twilio::REST::Client).to receive(:new).and_return(client) subject.send_text end end end
require 'rails_helper' require 'database_cleaner' RSpec.describe Api::V1::Items::MostRevenueController, type: :controller do describe "GET /items/most_revenue" do it "returns the top x items ranked by total revenue generated" do c1 = Customer.create c2 = Customer.create m1 = Merchant.create m2 = Merchant.create inv1 = Invoice.create(status: "shipped", customer_id: c1.id, merchant_id: m1.id) inv2 = Invoice.create(status: "other", customer_id: c2.id, merchant_id: m2.id) it1 = Item.create(name: "this", description: "cool", unit_price: 9000, merchant_id: m1.id) it2 = Item.create(name: "that", description: "cooler", unit_price: 2000, merchant_id: m2.id) ii1 = InvoiceItem.create(quantity: 3, unit_price: 9000, item_id: it1.id, invoice_id: inv1.id) ii3 = InvoiceItem.create(quantity: 3, unit_price: 9000, item_id: it1.id, invoice_id: inv1.id) ii2 = InvoiceItem.create(quantity: 4, unit_price: 2000, item_id: it2.id, invoice_id: inv2) t1 = Transaction.create(invoice_id: inv1.id, credit_card_number: 4654405418249632, result: "good") t2 = Transaction.create(invoice_id: inv2.id, credit_card_number: 4580251236515201, result: "bad") get :index, quantity: 2, format: :json body = JSON.parse(response.body) item_ids = body.map {|m| m["id"]} expect(response.status).to eq 200 expect(invoice_item_ids).to match_array([it1.id, it2.id]) end end end
# == Schema Information # # Table name: audit_items # # id :integer not null, primary key # audit_id :integer # paragraph_id :integer # created_at :datetime not null # updated_at :datetime not null # class AuditItem < ActiveRecord::Base # Relations/Associations with other models belongs_to :audit belongs_to :paragraph end