text
stringlengths
10
2.61M
include DataMagic DataMagic.load 'disputes.yml' Given(/^I log in with single acct profile$/) do visit(LoginPage) on(LoginPage) do |page| login_data = page.data_for(:dispute_single_disputable_ods) username = login_data['username'] password = login_data['password'] ssoid = login_data['ssoid'] page.login(username, password, ssoid) end end Given(/^I log in with an account with disputable transactions$/) do visit(LoginPage) on(LoginPage) do |page| login_data = page.data_for(:related_links_dispute) username = login_data['username'] password = login_data['password'] ssoid = login_data['ssoid'] page.login(username, password, ssoid) end end And(/^I am on Transactions & Details page$/) do visit(TransactionsDetailsPage) end When(/^Customer selects a transaction to dispute based on "([^"]*)","([^"]*)","([^"]*)" and "([^"]*)"$/) do |postdate, merchant, category, amount| on(DisputesPage) do |page| @matching_transaction_id, @txn_details = page.expand_transaction_drawer_for_matching_transaction(postdate, merchant, category, amount) end end And(/^I select a transaction to dispute and click on File a dispute link$/) do |table| x = table.hashes.first matching_transaction_id, @txn_details = on(DisputesPage).expand_transaction_drawer_for_matching_transaction(x['postdate'], x['merchant'], x['category'], x['amount']) if matching_transaction_id.length == 0 fail ("No Matching transactions present") end on(DisputesPage).dispute_link_element.when_present.click end And(/^I select a transaction to dispute from default data file and click on File a dispute link$/) do on(DisputesPage) do |page| @matching_transaction_id, @txn_details = page.expand_transaction_drawer_for_matching_transaction(data_for(:txn_to_select)['date'], data_for(:txn_to_select)['merchant'], data_for(:txn_to_select)['category'], data_for(:txn_to_select)['amount']) page.click_on_file_a_dispute_link(@matching_transaction_id) end end And(/^I select a transaction to dispute$/) do on(DisputesPage) do |page| @matching_transaction_id, @txn_details = page.expand_transaction_drawer_for_matching_transaction(data_for(:txn_to_select)['date'], data_for(:txn_to_select)['merchant'], data_for(:txn_to_select)['category'], data_for(:txn_to_select)['amount']) end end Then(/^I see Merchant Name details on Disputes landing page Dispute details$/) do on(DisputesPage) do |page| @matching_transaction_id, @txn_details= on(page).expand_transaction_drawer_for_matching_transaction(data_for(:txn_to_select)['date'], data_for(:txn_to_select)['merchant'], data_for(:txn_to_select)['category'], data_for(:txn_to_select)['amount']) visit(page) on(page).wait_for_disputes_page on(page).dispute_a_charge_title == 'Dispute a Charge' on(page).dispute_details_heading == 'Dispute Details' on(page).dispute_details_sub_head == 'Complete the form below to dispute a charge.' dt_elements, dd_elements = on(page).get_txn_details_from_drawer puts @txn_details['description'] puts dd_elements[2] puts "#{@txn_details['description'] == dd_elements[2]}" @txn_details['description'].should == dd_elements[2] end end And(/^I Expand the drawer and get transaction details$/) do @txn_details = on(DisputesPage).get_transaction_data_for_disputes(@matching_transaction_id) end And(/^Expand transaction drawer$/) do on(DisputesPage) do |page| page.disable_menu_option page.select_transactions(@matching_transaction_id) end end Then(/^File a Dispute Link should be present$/) do on(DisputesPage).verify_dispute_link_present(@matching_transaction_id) puts @matching_transaction_id end And(/^Get transaction details$/) do #puts "Get Transaction Details" @txn_details = on(DisputesPage).get_transaction_data_for_disputes(@matching_transaction_id) puts @txn_details['card_name'] puts @txn_details['transaction_date'] puts @txn_details['posted_date'] puts @txn_details['txn_details'] puts @txn_details['description'] puts @txn_details['categories'] puts @txn_details['transaction_amount'] end Then(/^I see Disputes landing page$/) do on(DisputesPage) do |page| page.wait_for_disputes_page page.dispute_a_charge_title == 'Dispute a Charge' page.dispute_details_heading == 'Dispute Details' page.dispute_details_sub_head == 'Complete the form below to dispute a charge.' end end Then(/^I see E\-mail address$/) do # puts on(DisputesPage).dispute_details_page_items_element.unordered_list_element.list_item_element(:class => 'sur_yes').unless dt_elements, dd_elements = on(DisputesPage).get_txn_details_from_drawer puts "#{dt_elements[0]} : #{dd_elements[0]}" puts "#{dt_elements[1]} : #{dd_elements[1]}" puts "#{dt_elements[2]} : #{dd_elements[2]}" puts "#{dt_elements[3]} : #{dd_elements[3]}" puts "#{dt_elements[4]} : #{dd_elements[4]}" end Then(/^I click on File a Dispute link$/) do on(DisputesPage).click_on_file_a_dispute_link(@matching_transaction_id) end Then(/^I see E\-mail address details on Disputes landing page$/) do on(DisputesPage) do |page| page.wait_for_disputes_page dt_elements, dd_elements = page.get_txn_details_from_drawer #on(DisputesPage).wait_for_disputes_page email_address = data_for(:email_mocks)['email'] dt_elements[0].should == 'E-mail Address on File' dd_elements[0].split("\n").first.should == email_address end end Then(/^I see Account Name details on Disputes landing page$/) do on(DisputesPage) do |page| page.wait_for_disputes_page dt_elements, dd_elements = page.get_txn_details_from_drawer @txn_details['card_name'].should == dd_elements[1] dt_elements[1].should == 'Account Name' end end Then(/^I see Merchant Name details on Disputes landing page$/) do on(DisputesPage) do |page| page.wait_for_disputes_page dt_elements, dd_elements = page.get_txn_details_from_drawer #on(DisputesPage).wait_for_disputes_page @txn_details['description'].should == dd_elements[2] dt_elements[2].should == 'Merchant\'s Name' end end Then(/^I see Posted Transaction Date on Disputes landing page$/) do on(DisputesPage) do |page| page.wait_for_disputes_page dt_elements, dd_elements = page.get_txn_details_from_drawer puts txn_date = @txn_details['transaction_date'].split(",").last.sub(/\s+/, "") puts txn_date_TandD = Date.strptime(txn_date, "%m/%d/%Y").strftime("%m/%d/%Y") txn_date_TandD.should == dd_elements[3] dt_elements[3].should == 'Transaction Date' #puts "#{@txn_details['posted_date'] == dd_elements[3]}" puts dd_elements[3] end end Then(/^I see Transaction Amount on Disputes landing page$/) do on(DisputesPage) do |page| page.wait_for_disputes_page dt_elements, dd_elements = page.get_txn_details_from_drawer @txn_details['transaction_amount'].should == dd_elements[4] dt_elements[4].should == 'Transaction Amount' end end When(/^I select first transaction from the list to dispute$/) do @matching_transaction_id, @txn_details = on(DisputesPage).click_disputes_link_when_present end When(/^I select row "([^"]*)" posted transaction from the list to dispute$/) do |txn_row| on(DisputesPage) do |page| matching_transaction_id, @txn_details = page.selected_txn_index_value(txn_row) page.click_on_file_a_dispute_link(matching_transaction_id) end end And(/^I select a transaction$/) do |table| # table is a table.hashes.keys => [:txn_row] table.hashes.each do |x| matching_transaction_id, @txn_details = on(DisputesPage).selected_txn_index_value(x['txn_row']) puts matching_transaction_id #on(TransactionsDetailsPage).dispute_link_element.when_present.click end end Then(/^I should see error message since the amount field is zero dollar amount$/) do on(DisputesPage).dispute_amount_greater_than_txnAmt_error == data_for(:dispute_amount_errors)['dispute_amount_error_amount_equals_0'] end And(/^I click on File a Dispute link in the transaction$/) do on(DisputesPage).click_on_dispute_link('File a Dispute') on(DisputesPage).wait_for_disputes_page end And(/^I see a Disputed Amount Label$/) do on(DisputesPage).wait_for_disputes_page dt_elements, dd_elements = on(DisputesPage).get_txn_details_from_drawer dt_elements[5].should == 'Disputed Amount' end And(/^I see a disputed amount text box with the following text greyed out: "\$ ex\. (\d+)\.00"$/) do |arg| puts on(DisputesPage).dispute_amt_dollar_sign.text puts on(DisputesPage).dispute_amt_field_description.text end And(/^I select the dispute amount field field without entering any data and focus out$/) do on(DisputesPage).disputed_amount_element.click on(DisputesPage).span_element(:id => 'dispute_description').click on(DisputesPage).span_element(:id => 'dispute_description').text end And(/^I select the same row "([^"]*)" transaction from the list to dispute$/) do |txn_row| on(DisputesPage) do |page| @matching_transaction_id, @txn_details = page.selected_txn_index_value(txn_row) #puts txn_row_index page.disable_menu_option page.click_on_file_a_dispute_link(@matching_transaction_id) end end And(/^I select date range "([^"]*)" in the drop-down$/) do |value| on(TransactionsDetailsPage).sort_dropdown_select_for value end Then(/^on disputes page related links is not displayed$/) do on(DisputesPage).wait_for_disputes_page on(DisputesPage).text.should_not include "I want to" end Given(/^I login with an account and navigates to transactions selection page to verify disputes default page content$/) do visit(LoginPage) on(LoginPage) do |page| login_data = page.data_for(:dispute_single_disputable_ods) #dispute_single_DNR_charge, , disputes_linked_account username = login_data['username'] password = login_data['password'] ssoid = login_data['ssoid'] page.login(username, password, ssoid) end @authenticated = on(DisputesPage).is_summary_shown? if @authenticated[0] == false fail("#{@authenticated[1]}" "--" "#{@authenticated[2]}") end visit(TransactionsDetailsPage) on(DisputesPage) do |page| page.search_for_valid_disputable_txn_iteratively end end
require 'RMagick' include Magick module Paperclip class Colorizer < Processor def initialize file, options = {}, attachment = nil super @file = file @format = "jpg" current_format = File.extname(@file.path) @basename = File.basename(@file.path, current_format) @transform = options[:transform] puts "[paperclip] Transform: #{@transform}" end def make puts "[paperclip] Colorizer: File at #{[@basename, @format].compact.join(".")}" dst = Tempfile.new([@basename, @format].compact.join(".")) # set components (in the leakiest way possible) buffer = Magick::ImageList.new bin = File.open(@file.path, 'r'){ |f| f.read } img = buffer.from_blob(bin) gray = Image.new(img.columns, img.rows) { self.background_color = "Gray" } color = Image.new(img.columns, img.rows) { self.background_color = "hsl(#{100 * 293/360}%,100%,50%)" } # process image quantized = img.quantize(256, Magick::GRAYColorspace) blended = gray.blend(quantized, 1.5) colored = blended.blend(color, 0.75) # save result colored.write "jpg:#{dst.path}" dst end end end
module Moped module BSON class Binary SUBTYPE_MAP = { generic: "\x00", function: "\x01", old: "\x02", uuid: "\x03", md5: "\x05", user: "\x80" } attr_reader :data, :type def initialize(type, data) @type = type @data = data end class << self def __bson_load__(io) length, = io.read(4).unpack(INT32_PACK) type = SUBTYPE_MAP.invert[io.read(1)] if type == :old length -= 4 io.read(4) end data = io.read length new(type, data) end end def ==(other) BSON::Binary === other && data == other.data && type == other.type end alias eql? == def hash [data, type].hash end def __bson_dump__(io, key) io << Types::BINARY io << key io << NULL_BYTE if type == :old io << [data.length + 4].pack(INT32_PACK) io << SUBTYPE_MAP[type] io << [data.length].pack(INT32_PACK) io << data else io << [data.length].pack(INT32_PACK) io << SUBTYPE_MAP[type] io << data end end def inspect "#<#{self.class.name} type=#{type.inspect} length=#{data.length}>" end end end end
json.array!(@spaces) do |space| json.extract! space, :id, :name, :spacetype, :streetnum, :street, :city, :state, :areacode, :vacancies, :description, :price json.url space_url(space, format: :json) end
module TerraspacePluginScaleway module Logging def logger Terraspace.logger end end end
# Check for restricted tags # TODO: #360 - Fix when tag is normalized class RestrictedTagValidator < ActiveModel::Validator def validate(record) restricted = GalleryConfig.restricted_tags.include?(record.tag_text) admin = record.user&.admin? record.errors.add :tag, (options[:message] || "#{record.tag_text} tag is restricted to admins") if restricted && !admin end end
class Course < ActiveRecord::Base has_attached_file :cover_pic, default_url: "/images/missing.png" validates_attachment_content_type :cover_pic, content_type: /\Aimage\/.*\z/ def as_json(options) CourseSerializer.new(self).as_json(root: false) end end
require 'dataset' class GpdbTable < Dataset def analyze(account) table_name = '"' + schema.name + '"."' + name + '"'; query_string = "analyze #{table_name}" schema.with_gpdb_connection(account) do |conn| conn.exec_query(query_string) end [] end end
class MovieInterestsController < ApplicationController before_filter :set_movie_interest, only: [:show, :edit, :update, :destroy] load_and_authorize_resource def new @movie_interest = MovieInterest.new @user = User.find(params[:user_id]) @rating = @user.ratings.build @event = Event.new end def create @user = User.find(params[:user_id]) @movie_interest = @user.movie_interests.build(movie_interest_params) respond_to do |format| if @movie_interest.save format.html {redirect_to root_url, notice: "Movie interest created!"} format.js{} else format.html {render 'new', notice: 'Error creating movie interest'} format.js{} end end end def update if @movie_interest.update_attributes(movie_interest_params) redirect_to user_movie_interests_path(@user), notice: "Movie interest updated!" else render 'edit', notice: "Error, try again!" end end def destroy @movie_interest.destroy flash[:notice] = "Wished item deleted" redirect_to current_user end private def movie_interest_params params.require(:movie_interest).permit(:rt_id, :event_id, :user_id, :watched, :wished, :user_score) end def set_movie_interest @movie_interest = MovieInterest.find(params[:id]) end end
require_relative 'test_helper' class InvoiceTest < Minitest::Test attr_reader :invoice, :data def setup @data = { :id => 1, :customer_id => 1, :merchant_id => 26, :status => "shipped" } @invoice = Invoice.new(data, self) end def test_it_exists assert invoice end def test_it_has_an_id assert_equal 1, invoice.id end def test_it_has_a_customer_id assert_equal 1, invoice.customer_id end def test_it_has_a_merchant_id assert_equal 26, invoice.merchant_id end def test_it_has_a_status assert_equal "shipped", invoice.status end def test_it_is_connected_to_invoice_repository invoice_repository = Minitest::Mock.new invoice = Invoice.new(data, invoice_repository) invoice_repository.expect(:find_transactions_by_invoice_id, nil, [1]) invoice.transactions invoice_repository.verify end end
class UserTransactionsController < ApplicationController # before_action :authenticate_user! def index if buyer_signed_in? @transactions = current_buyer.user_transactions.order(updated_at: :desc) elsif broker_signed_in? @broker_transactions = current_broker.broker_stocks.map(&:user_transactions) elsif admin_logged_in? @transactions = UserTransaction.order(updated_at: :desc) end end end
Grape::Batch.configure do |config| config.limit = 10 config.path = '/batch' config.formatter = Grape::Batch::Response config.logger = nil config.session_proc = Proc.new {} end
require "spec_helper" module LabelGen describe FrameIter do context "with blank parameters" do subject(:frames){FrameIter.new({})} it "is not nil" do expect(frames).to_not be_nil end it "has a single frame" do expect(frames.count).to eq 1 end end context "with [random n rows, random m columns]" do let(:n_rows){rand(7)+3} let(:m_cols){rand(7)+3} let(:count){n_rows * m_cols} subject(:frames) do FrameIter.new({ :n_x => n_rows, :n_y => m_cols }) end describe "coordinates" do let(:x_col){frames.x_col} let(:y_col){frames.y_col} it "has count x values" do expect(x_col.count).to eq count end it "has alternatingly increasing x values" do x_col.each do |val0, val1| expect(val1).to_be gt val0 unless val1.nil? end end it "has count y values" do expect(y_col.count).to eq count end it "has periodically decreasing y values" do val0 = y_col[0] (0..m_cols).each do |i| ind0 = i*n_rows val1 = y_col[ind0] val1.should > val0 unless (i==0 || val1.nil?) val0 = val1 unless val0.nil? y_col.slice(ind0, n_rows).each do |val| expect(val).to eq val0 end end end end context "with random x_delta, random y_delta, frame width, frame height" do let(:n_rows){rand(7)+3} let(:m_cols){rand(7)+3} let(:frame_w){rand(7)+3} let(:frame_h){rand(7)+3} let(:delta_x){rand(7)+3} let(:delta_y){rand(7)+3} let(:count){n_rows * m_cols} subject(:frames) do FrameIter.new({ :n_x => m_cols, :n_y => n_rows, :frame_width => frame_w, :frame_height => frame_h, :delta_x => delta_x, :delta_y => delta_y }) end it "has total height of n_rows(frame_height+delta_y)" do expect(frames.total_height).to eq n_rows*(frame_h+delta_y) end it "has total width of m_cols(frame_width+delta_x)" do expect(frames.total_width).to eq m_cols*(frame_w+delta_x) end context "with random origin x and y" do let(:n_rows){rand(7)+3} let(:m_cols){rand(7)+3} let(:frame_w){rand(7)+3} let(:frame_h){rand(7)+3} let(:delta_x){rand(7)+3} let(:delta_y){rand(7)+3} let(:origin_x){rand(7)+3} let(:origin_y){rand(7)+3} let(:count){n_rows * m_cols} subject(:frames) do FrameIter.new({ :n_x => m_cols, :n_y => n_rows, :frame_width => frame_w, :frame_height => frame_h, :delta_x => delta_x, :delta_y => delta_y, :origin_x => origin_x, :origin_y => origin_y }) end let(:total_height){frames.total_height} let(:total_width){frames.total_width} it "has min y coordinate at origin_y" do expect(frames.coordinates[0,1]).to eq origin_y end it "has min x coordinate at origin_x" do expect(frames.coordinates[0,0]).to eq origin_x end it "has maximum y coordinate at (origin_y+total_height)-(frame_height+deta_y)" do expect(frames.coordinates[-1, -1]).to eq ((origin_y+total_height)-(frame_h+delta_y)) end it "has maximum x coordinate at (origin_x+total_width)-(frame_width+deta_x)" do expect(frames.coordinates[-1, 0]).to eq ((origin_x+total_width)-(frame_w+delta_x)) end end # context "with random origin x and y" do end # context "with random x_delta, random y_delta" end # context "with [random n rows, random m columns]" it "has the correct count of frames" do expect(frames.count).to eq count end end end # describe FrameIter end # module LabelGen
class ChaptersController < ApplicationController respond_to :html, :json def show end def update @chapter = Chapter.find(params[:id]) @story = Story.friendly.find(params[:story_id]) if @chapter.update(chapter_params) redirect_to edit_story_path(@story, page: params[:chapter][:page], last_chapter: params[:chapter][:position]), notice: 'Capítulo atualizado com sucesso.' else redirect_to edit_story_path(@story, page: params[:chapter][:page], last_chapter: params[:chapter][:position]), alert: { :errors => @chapter.errors.full_messages } end end def chapter_params params.require(:chapter).permit(:reference, :story_id, :content, :image, :x, :y, :color, :image_file_name, :image_content_type, :image_file_size, :image_updated_at, decisions_attributes: [:id, :destiny_num, :chapter_id, :item_validator, :_destroy], monsters_attributes: [:id, :skill, :energy, :name, :chapter_id, :_destroy], modifiers_attributes_attributes: [:id, :attr, :chapter_id, :quantity, :_destroy], modifiers_items_attributes: [:id, :chapter_id, :item_id, :quantity, :_destroy, items_attributes: [:id, :description, :name, :story_id, :_destroy]], modifiers_shops_attributes: [:id, :chapter_id, :item_id, :price, :quantity, :_destroy, items_attributes: [:id, :description, :name, :story_id, :_destroy]], items_attributes: [:id, :description, :name, :story_id, :_destroy]) end end
class CreateVendors < ActiveRecord::Migration def self.up create_table :vendors do |t| t.string :name, :null => false t.integer :status_id # vendor_status -> active, in_active # t.integer :tax_code_id # tax_code # t.integer :owner_user_id # users t.string :note t.integer :contact_id # contact t.string :address t.text :comment t.integer :updated_id # users t.integer :created_id # users t.timestamps end end def self.down drop_table :vendors end end
# frozen_string_literal: true # rubocop:todo all require 'spec_helper' describe Mongo::Collection::View::Iterable do let(:selector) do {} end let(:options) do {} end let(:view) do Mongo::Collection::View.new(authorized_collection, selector, options) end before do authorized_collection.drop end describe '#each' do context 'when allow_disk_use is provided' do let(:options) { { allow_disk_use: true } } # Other cases are adequately covered by spec tests. context 'on server versions < 3.2' do max_server_fcv '3.0' it 'raises an exception' do expect do view.each do |document| #Do nothing end end.to raise_error(Mongo::Error::UnsupportedOption, /The MongoDB server handling this request does not support the allow_disk_use option on this command/) end end end end end
## Code your solution here. def fasten_seatbelt return "Alright foaks. Make sure to fasten your seatbelt!" end def free_to_move_about_the_cabin return "Now it's safe to move about the cabin, if you so desire." end def pennsylvania return "We're flying over pimptastic Pennsylvania!" end def ohio return "We are over the one, the only.... Ohio!".upcase end def indiana return "Now we're at irreplaceable Indiana!".upcase end def illinois return "Look out now to see illusional Illinois!".reverse end def iowa return "We're at irresitable Iowa, now!" end def nebraska return "Wow. Can't belive we're at never-ending Nebraska." end def colorado return "Hold on to your hats! We're at CRAAAAAZYYYY colorado!".upcase end def utah return "Almost there, folks. Look out now for understanding Utah.".reverse end def cali return "WE DID IT! Welcome to cathartic California!"
class SimplifyUserTable < ActiveRecord::Migration[5.2] def change remove_column :users, :reset_password_sent_at, :string remove_column :users, :created_at, :datetime remove_column :users, :updated_at, :datetime remove_column :users, :fieldname, :string end end
require 'rubygems' require 'zip/zip' class PackageGenerator attr_reader :root_dir def initialize(root_dir) @root_dir = root_dir end def generate delete_previous copy_files process_code pack_js minify_js compress ensure clean_up end def delete_previous FileUtils.rm zip_file if File.exist? zip_file end def copy_files FileUtils.mkdir package_dir FileUtils.cp root_files("date_input.css", "LICENCE", "README", "CHANGELOG"), package_dir end def process_code code = File.read(root_file(plugin_file)) code.gsub!(/\/\/[^\n]+/, "") # Remove any other '//' comments (without deleting the line) code.gsub!(/\/\*.+\*\//m, "") # Remove '/* */' comments code.gsub!(/(\n +\n)( +\n)+/) { $1 } # Remove any multiple empty lines open(package_file(plugin_file), "w") do |file| file << header file << code end end def pack_js open(package_file(plugin_file("pack")), "w") do |file| file << `#{root_file("bin/packer")} #{root_file(plugin_file)}` end end def minify_js open(package_file(plugin_file("min")), "w") do |file| file << `java -jar #{root_file("bin/yuicompressor-2.2.5.jar")} #{root_file(plugin_file)} 2>/dev/null` end end def compress Zip::ZipFile.open(zip_file, Zip::ZipFile::CREATE) do |zip| zip.mkdir(code_name) Dir[package_file("*")].each do |file| zip.add(code_name + "/" + File.basename(file), file) end end puts "Generated #{zip_file}" end def clean_up FileUtils.rm_r package_dir if File.exist? package_dir end private def package_dir root_dir + "/package" end def zip_file root_dir + "/" + code_name + "-" + metadata[:version] + ".zip" end def code_name metadata[:name].downcase.gsub(" ", "_") end def metadata load_metadata unless self.class.const_defined? :Metadata Hash.new do |hash, key| eval("Metadata::" + key.to_s.upcase) rescue nil end end def load_metadata self.class.class_eval <<-STR class Metadata #{File.read(root_file("metadata.rb"))} end STR end def root_files(*files) files.map { |file| root_file(file) } end def root_file(file) root_dir + "/" + file end def package_file(file) package_dir + "/" + file end def plugin_file(type = nil) "jquery.#{code_name}#{"." + type if type}.js" end def header header = "/*\n" header << metadata[:name] + " " + metadata[:version] + "\n" header << "Requires jQuery version: " + metadata[:jquery] + "\n" unless metadata[:plugins].nil? || metadata[:plugins].empty? header << "Requires plugins:" + "\n" metadata[:plugins].each do |plugin, url| header << " * #{plugin} - #{url}\n" end end header << "\n" + File.read(root_file("LICENCE")) + "*/\n\n" end end desc "Package the plugin into a zip file which can be distributed" task :package do PackageGenerator.new(File.dirname(__FILE__)).generate end
# == Schema Information # # Table name: game_answers # # id :integer not null, primary key # game_id :integer not null # answer :string(255) not null # created_at :datetime # updated_at :datetime # regex :string(255) # class GameAnswer < ActiveRecord::Base validates_presence_of :game, :answer validates_uniqueness_of :answer, case_sensitive: false, scope: :game_id belongs_to :game, inverse_of: :answers, counter_cache: :answers_count has_many :matches, class_name: "RoundAnswerMatch", foreign_key: :answer_id, inverse_of: :answer def get_regex self.regex ? self.regex : Regexp.escape(self.answer.downcase) end def matches?(guess) !!(guess =~ /\A\s*(#{self.get_regex})\s*\Z/) end end
class Organization < ActiveRecord::Base has_many :addresses attr_accessible :title validates_presence_of :title searchable do text :title end end
class Page < ActiveRecord::Base ##### ASSOCIATIONS ##### has_many :items ##### VALIDATIONS ##### scope :visible, where(:visible => true) scope :sort, order('pages.position ASC') end
class MissionariesController < ApplicationController # GET /missionaries # GET /missionaries.json def index @missionaries = Missionary.all respond_to do |format| format.html # index.html.erb format.json { render json: @missionaries } end end # GET /missionaries/1 # GET /missionaries/1.json def show @missionary = Missionary.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @missionary } end end # GET /missionaries/new # GET /missionaries/new.json def new @missionary = Missionary.new respond_to do |format| format.html # new.html.erb format.json { render json: @missionary } end end # GET /missionaries/1/edit def edit @missionary = Missionary.find(params[:id]) end # POST /missionaries # POST /missionaries.json def create @missionary = Missionary.new(missionary_params) respond_to do |format| if @missionary.save format.html { redirect_to @missionary, notice: 'Missionary was successfully created.' } format.json { render json: @missionary, status: :created, location: @missionary } else format.html { render action: "new" } format.json { render json: @missionary.errors, status: :unprocessable_entity } end end end # PUT /missionaries/1 # PUT /missionaries/1.json def update @missionary = Missionary.find(params[:id]) respond_to do |format| if @missionary.update_attributes(missionary_params) format.html { redirect_to @missionary, notice: 'Missionary was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @missionary.errors, status: :unprocessable_entity } end end end # DELETE /missionaries/1 # DELETE /missionaries/1.json def destroy @missionary = Missionary.find(params[:id]) @missionary.destroy respond_to do |format| format.html { redirect_to missionaries_url } format.json { head :no_content } end end private def missionary_params params.require(:missionary).permit(:name, :description, :url, :prayer_card) end end
class Sale < ActiveRecord::Base # inside the where clause we are actually writing SQL, since its Action Record, it needs two arguments since we use two ?'s #@@active_sale_query = "sales.starts_on <= ? AND sales.ends_on >= ?" # AR Scope - Class Methods (starting with self.), we can reference any methods we make here in our helpers def self.active where("sales.starts_on <= ? AND sales.ends_on >= ?", Date.current, Date.current) #self.where is implied end def self.get_sale where("sales.starts_on <= ? AND sales.ends_on >= ?", Date.current, Date.current).first end # we can also do the above using scope and lambda ... # scope :active, -> { where("sales.starts_on <= ? AND sales.ends_on >= ?", Date.current, Date.current) } # The public methods defined in this Sale Model will be available # to each sale obj in the view partial # These are instance methods def finished? ends_on < Date.current end def upcoming? starts_on > Date.current end def active? !finished? && !upcoming? end end
require 'test_helper' class HtmlFormatterTest < Test::Unit::TestCase context "basic operations" do setup do @formatter = Flannel::HtmlFormatter.new end should "return html fragment with format" do assert_equal "<p id='bar'>foo</p>", @formatter.do('foo', :paragraph, "bar") end context "subdirectories" do should "handle subdirectories and not display directory info" do result = @formatter.do("I think it -cheese/tastes good>.", :paragraph) assert_equal '<p>I think it <a href="cheese/tastes-good">tastes good</a>.</p>', result end end context "blockquotes" do should "wrap a blockquoted block in blockquotes" do result = @formatter.do("Ruby is #1", :blockquote) assert_equal '<blockquote>Ruby is #1</blockquote>', result end end context "links" do should "output the link" do assert_equal '<p><a href="cheese">cheese</a></p>', @formatter.do("-cheese>", :paragraph) end should "hyphenate words" do result = @formatter.do("-cheese is good>", :paragraph) assert_equal '<p><a href="cheese-is-good">cheese is good</a></p>', result end should "replace text surrounded by - and > with a wiki link" do result = @formatter.do("red, -green>, refactor", :paragraph) assert_equal '<p>red, <a href="green">green</a>, refactor</p>',result end should "not replace text surrounded by - and > with a wiki link if spaced" do result = @formatter.do("red, - green >, refactor", :paragraph) assert_equal '<p>red, - green >, refactor</p>', result end should "not replace text surrounded by - and > with a wiki link if spaced on right" do result = @formatter.do("red, -green >, refactor", :paragraph) assert_equal '<p>red, -green >, refactor</p>', result end should "not replace surrounded by - and > with a wiki link if spaced on left" do result = @formatter.do("red, - green>, refactor", :paragraph) assert_equal '<p>red, - green>, refactor</p>', result end end context "preformatted text" do should "html escape preformatted text" do result = @formatter.do("<p>& foo</p>", :preformatted) assert_equal "<pre>&lt;p&gt;&amp; foo&lt;/p&gt;</pre>", result end end context "definition list" do should "format definition list" do result = @formatter.do("flannel - a wonderful markup dsl\nruby - a wonderful programming language", :dlist) assert_equal "<dl><dt>flannel</dt><dd>a wonderful markup dsl</dd>\n<dt>ruby</dt><dd>a wonderful programming language</dd></dl>", result end end context "image" do should "format image" do result = @formatter.do("This is a picture of a cat\n/images/cat.png", :image) assert_equal "<img src='/images/cat.png' alt='This is a picture of a cat' title='This is a picture of a cat' />", result end end context "making permalinks" do should "replace spaces with dashes" do assert_equal "get-the-box", @formatter.permalink("get the box") end should "replace multiple spaces with single dashes" do assert_equal "get-the-box", @formatter.permalink("get the box") end should "replace odd characters with dashes" do assert_equal "get-the-box", @formatter.permalink("get the @#)(* box") end should "not be greedy in matching" do result = @formatter.do "a -foo> and a -bar>.", :paragraph assert_equal '<p>a <a href="foo">foo</a> and a <a href="bar">bar</a>.</p>', result end end end end
class Flail class Configuration # for the default handler HTTP_ERRORS = [Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError, Errno::ECONNREFUSED].freeze # custom handler for payloads attr_reader :handler # endpoint for default handler (used with flail-web) attr_reader :endpoint # environment of application attr_reader :env # hostname sending the error attr_reader :hostname # is the endpoint ssl? attr_reader :secure_endpoint # api key to use with payloads attr_reader :tag def handle(&block) @handler = block end def url(endpoint) @endpoint = endpoint end def secure @secure_endpoint = true end def environment(value) @env = value end def host(value) @hostname = value end def tagged(value) @tag = value end def defaults! # configure some defaults @secure_endpoint = false handle do |payload| url = URI.parse(Flail.configuration.endpoint) http = Net::HTTP.new(url.host, url.port) http.read_timeout = 5 http.open_timeout = 2 if Flail.configuration.secure_endpoint http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_PEER else http.use_ssl = false end begin http.post(url.path, payload, {'Content-type' => 'application/json', 'Accept' => 'application/json'}) rescue *HTTP_ERRORS => e nil end end self end # end defaults! end end
# Note: In this challenge the Fibonacci sequence is zero-indexed and the first term is 0 def iterative_nth_fibonacci_number(n) return 0 if n == 0 return 1 if n == 1 fibs = [0, 1] until fibs.length == n + 1 fibs << fibs[-1] + fibs[-2] end fibs[n] end def recursive_nth_fibonacci_number(n) return 0 if n == 0 return 1 if n == 1 recursive_nth_fibonacci_number(n - 1) + recursive_nth_fibonacci_number(n - 2) end require 'benchmark' n = 40 Benchmark.bm do |x| start_time = Time.now x.report("iterative:") { iterative_nth_fibonacci_number(n) } end_time = Time.now puts "It took #{end_time - start_time} seconds to iteratively calculate the #{n}th Fibonacci number." start_time = Time.now x.report("recursive:") { recursive_nth_fibonacci_number(n) } end_time = Time.now puts "It took #{end_time - start_time} seconds to recursively calculate the #{n}th Fibonacci number." end
class Course < ApplicationRecord belongs_to :day belongs_to :dish end
#!/usr/bin/env ruby # frozen_string_literal: true def sort_config_file(filename) puts "Sort: #{filename}" org_file = File.read(filename) lines = org_file.lines while (indented_line_idx = lines.index { |l| l =~ /\A(#(?! frozen)|(\s*#)?\s*$)/ }) lines.delete_at(indented_line_idx) end while (indented_line_idx = lines.index { |l| l =~ /\A(\s{2}(#?\s{2,}|}|else|end))/ }) lines[indented_line_idx - 1] += lines[indented_line_idx] lines.delete_at(indented_line_idx) end lines.sort_by!.with_index do |l, i| case l when /\Aend/ [1000, i] when /\A\S/ [0, i] else ls = l.dup ls[/\A[\s#]+/] = '' [1, ls] end end lines.each { |l| l << "\n" if /^(# frozen|require)/.match?(l) } File.write("#{filename}-#{Time.current.strftime('%F_%R')}", org_file) File.write(filename, lines.join) end Dir['config/environments/*.rb'].each do |filename| sort_config_file(filename) end system 'rubocop --autocorrect-all config/environments/*.rb'
require File.join( File.dirname(__FILE__), '..', "spec_helper" ) describe Lecture do before do load_fixtures! Lecture.auto_migrate! @lecture = Lecture.create(:date => DateTime.now, :name => "Programming", :user => @teamon, :faculty => @w4) end it "should be valid" do @lecture.should be_valid end it "should not be valid without name" do @lecture.name = "" @lecture.should_not be_valid @lecture.errors.on(:name).should_not be_empty end it "should require user" do @lecture.user = nil @lecture.should_not be_valid @lecture.errors.on(:user).should_not be_empty end it "should require faculty" do @lecture.faculty = nil @lecture.should_not be_valid @lecture.errors.on(:faculty).should_not be_empty end end
Rails.application.routes.draw do resources :posts root 'posts#index' post 'like/:note_id' => 'likes#like', as: 'like' delete 'unlike/:note_id' => 'likes#unlink', as: 'unlink' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
class ChangeColumnToAllowNull < ActiveRecord::Migration[5.2] def up change_column :items, :image_id, :string, null: true, default: nil end def down change_column :items, :image_id, :string, null: false, default: 'no_image' end end
require 'spec_helper' require 'ostruct' describe CSV2API::Server do include Rack::Test::Methods def app CSV2API::Server end describe '/tasks' do it 'returns tasks.csv in json' do get '/tasks' expect(last_response.body).not_to be_empty expect(last_response).to be_ok end end describe '/transaction' do it 'returns transaction.csv in json' do get '/transaction' expect(last_response.body).not_to be_empty expect(last_response).to be_ok end end end
require 'tic_tac_toe_rz/core/player' module TicTacToeRZ module Core module Players class Minimax < TicTacToeRZ::Core::Player def initialize @will_block = false @can_retry = true end def get_move(board) marks = {1 => @my_mark, -1 => @other_mark} negamax(marks, board, 4, -1000, 1000, 1).first end def set_marks(my_mark, other_mark) @my_mark, @other_mark = my_mark, other_mark end def negamax(marks, node, depth, alpha, beta, color) if depth == 0 or TicTacToeRZ::Core::Rules.finished?(node) score = score_node(node, marks[color]) weight = [1, depth].max return [-1, color * score * weight] end best = [-1, -1000] node.empty_spaces.each do |index| next_child = node.speculative_move(marks[color], index) _, score = negamax(marks, next_child, depth - 1, -beta, -alpha, -color) val = -score # Invert the returned score best = [best, [index, val]].max_by { |i, s| s } alpha = [alpha, val].max if alpha >= beta break end end return best end private def score_node(node, mark) winner = TicTacToeRZ::Core::Rules.who_won?(node) if winner == @my_mark 10 elsif winner == @other_mark -10 elsif TicTacToeRZ::Core::Rules.draw?(node) 0 else win_count = get_wins(node, @my_mark).uniq.count block_count = get_wins(node, @other_mark).uniq.count win_count - block_count end end def get_wins(node, mark) attacks = node.indexed_attack_sets get_wins_from_attacks(attacks, mark) end def get_wins_from_attacks(attacks, mark) get_indices_for(attacks) do |imarks| counts = count_marks(imarks.map { |imark| imark.mark }) counts[mark] == 2 && counts[TicTacToeRZ::Core::BLANK] == 1 end end def get_indices_for(attacks) attacks.map { |imarks| empty_space(imarks) if yield(imarks) }.flatten.compact end def empty_space(imarks) imarks.select { |imark| imark.mark.blank? }.map { |imark| imark.index } end def count_marks(marks) marks.each_with_object(Hash.new(0)) { |mark, counts| counts[mark] += 1 } end end end end end
module GapIntelligence module Requestable # Makes a request to a specified endpoint # # @param [Symbol] method one of :get, :post, :put, :delete # @param [String] path URL path of request # @param [Hash] options the options to make the request with # @yield [req] The Faraday request # @raise [RequestError] If raise_errors set true and request fails for any reason def perform_request(method, path, options = {}, &block) record_class = options.delete(:record_class) raise_error = options.fetch(:raise_errors, raise_errors) options[:headers] = headers options[:raise_errors] = false options[:init_with_response_body] = options.fetch(:init_with_response_body, false) response = connection.request(method, path, options, &block) if response.error error = RequestError.new(parse_error_message(response)) raise(error) if raise_error return nil end return instantiate_record(record_class, response_body: response.body) if options[:init_with_response_body] hash = response.parsed data = hash['data'] case data when Array objects = record_class.nil? ? data : data.collect{ |object| record_class.new(object) } RecordSet.new(objects, meta: hash.fetch('meta', {})) when Hash instantiate_record(record_class, data, meta: hash.fetch('meta', {})) end end private def instantiate_record(record_class, data, options = {}) record_class.nil? ? data : record_class.new(data, options) end def default_option(opts, key, value) opts[key] = opts.fetch(key, value) end def build_resource_path(*path) URI.parse(path.join('/')).path end def parse_error_message(response) if response.parsed && response.parsed['error'] response.parsed['error'] else response.error end end end end
require 'spec_helper' module Alf class Predicate describe Predicate, ".coerce" do subject{ Predicate.coerce(arg) } describe "from Predicate" do let(:arg){ Predicate.new(Factory.tautology) } it{ should be(arg) } end describe "from true" do let(:arg){ true } specify{ expect(subject.expr).to be_kind_of(Tautology) } end describe "from false" do let(:arg){ false } specify{ expect(subject.expr).to be_kind_of(Contradiction) } end describe "from Symbol" do let(:arg){ :status } specify{ expect(subject.expr).to be_kind_of(Identifier) expect(subject.expr.name).to eq(arg) } end describe "from Proc" do let(:arg){ lambda{ status == 10 } } specify{ expect(subject.expr).to be_kind_of(Native) expect(subject.to_proc).to be(arg) } end describe "from String" do let(:arg){ "status == 10" } it 'raises an error' do expect(lambda{ subject }).to raise_error(ArgumentError) end end describe "from Hash (single)" do let(:arg){ {status: 10} } specify{ expect(subject.expr).to be_kind_of(Eq) expect(subject.expr).to eq([:eq, [:identifier, :status], [:literal, 10]]) } end describe "from Tuple (single)" do let(:arg){ Tuple(status: 10) } specify{ expect(subject.expr).to be_kind_of(Eq) expect(subject.expr).to eq([:eq, [:identifier, :status], [:literal, 10]]) } end describe "from Hash (multiple)" do let(:arg){ {status: 10, name: "Jones"} } specify{ expect(subject).to eq(Predicate.eq(status: 10) & Predicate.eq(name: "Jones")) } end describe "from Tuple (multiple)" do let(:arg){ Tuple(status: 10, name: "Jones") } specify{ expect(subject).to eq(Predicate.eq(status: 10) & Predicate.eq(name: "Jones")) } end describe "from Relation::DUM" do let(:arg){ Relation::DUM } specify{ expect(subject).to eq(Predicate.contradiction) } end describe "from Relation::DEE" do let(:arg){ Relation::DEE } specify{ expect(subject).to eq(Predicate.tautology) } end describe "from Relation (arity=1)" do let(:arg){ Relation(status: [10, 20]) } specify{ expect(subject).to eq(Predicate.in(:status, [10, 20])) } end describe "from Relation (arity>1)" do let(:arg){ Relation([ {status: 1, city: "London"}, {status: 2, city: "Paris"} ]) } let(:expected){ Predicate.eq({status: 1, city: "London"}) | Predicate.eq({status: 2, city: "Paris"}) } specify{ expect(subject).to eq(expected) } end end end end
# frozen_string_literal: true module System module ErrorReporting module_function def report_error(exception, logger: Rails.logger, **parameters) logger.error('Exception') { {exception: {class: exception.class, message: (exception.try(:message) || exception.to_s), backtrace: (exception.try(:backtrace) || [])[0..3]}, parameters: parameters} } ::Bugsnag.notify(exception) do |report| report.add_tab 'parameter', {parameters: parameters} end end class LogFormatter < ActiveSupport::Logger::SimpleFormatter def initialize super extend ActiveSupport::TaggedLogging::Formatter end # Logger interface suffers from :reek:LongParameterList and :reek:FeatureEnvy def call(severity, timestamp, progname, msg) msg = case msg when ::Exception +"#{ msg.message } (#{ msg.class })\n" << (msg.backtrace || []).join("\n") + "\n" else super end progname ? "#{progname} -- #{msg}" : msg end end end end
class ParallelWithThreads def initialize(enum) @enum = enum end def each(&block) @enum.each(&block) end def map(&block) size = @enum.size results = Array.new(size) each do |item| results << Thread.new { yield(item) } end results end class ThreadPool def initialize(max = 1) @max = max @queue = Queue.new @workers = [] end def schedule(*args, &job) @jobs << [job, args] spawn_worker if @workers.size < @max end def shutdown end def spawn_worker Thread.new { } end end end module Enumerable def parallel(&block) ParallelWithThreads.new(self, &block) end end
class EventInsController < ApplicationController before_action :set_event_in, only: [:show, :edit, :update, :destroy] # GET /event_ins # GET /event_ins.json def index @event_ins = EventIn.all end # GET /event_ins/1 # GET /event_ins/1.json def show end # GET /event_ins/new def new @event_in = EventIn.new end # GET /event_ins/1/edit def edit end # POST /event_ins # POST /event_ins.json def create @event_in = EventIn.new(event_in_params) respond_to do |format| if @event_in.save format.html { redirect_to @event_in, notice: 'Event in was successfully created.' } format.json { render :show, status: :created, location: @event_in } else format.html { render :new } format.json { render json: @event_in.errors, status: :unprocessable_entity } end end end # PATCH/PUT /event_ins/1 # PATCH/PUT /event_ins/1.json def update respond_to do |format| if @event_in.update(event_in_params) format.html { redirect_to @event_in, notice: 'Event in was successfully updated.' } format.json { render :show, status: :ok, location: @event_in } else format.html { render :edit } format.json { render json: @event_in.errors, status: :unprocessable_entity } end end end # DELETE /event_ins/1 # DELETE /event_ins/1.json def destroy @event_in.destroy respond_to do |format| format.html { redirect_to event_ins_url, notice: 'Event in was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_event_in @event_in = EventIn.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def event_in_params params.require(:event_in).permit(:valor, :coreid, :published_at_dt, :tipo, :ubicacion, :centro, :almacen) end end
# frozen_string_literal: true require 'stannum/contracts/array_contract' require 'support/examples/constraint_examples' require 'support/examples/contract_builder_examples' require 'support/examples/contract_examples' RSpec.describe Stannum::Contracts::ArrayContract do include Spec::Support::Examples::ConstraintExamples include Spec::Support::Examples::ContractExamples shared_context 'when initialized with allow_extra_items: true' do let(:constructor_options) { { allow_extra_items: true } } end shared_context 'when initialized with item_type: value' do let(:constructor_options) { { item_type: String } } end shared_context 'when the contract has one item constraint' do let(:constraints) do [ { constraint: Stannum::Constraints::Presence.new } ] end let(:definitions) do constraints.map.with_index do |definition, index| Stannum::Contracts::Definition.new( constraint: definition[:constraint], contract: contract, options: { property: index, property_type: :index, sanity: false } .merge(definition.fetch(:options, {})) ) end end let(:items_count) { constraints.count } let(:constructor_block) do constraint_definitions = constraints lambda do constraint_definitions.each do |definition| item(definition[:constraint], **definition.fetch(:options, {})) end end end end shared_context 'when the contract has many item constraints' do let(:constraints) do [ { constraint: Stannum::Constraints::Presence.new }, { constraint: Stannum::Constraints::Presence.new, options: { type: :index, key: 'value' } }, { constraint: Stannum::Constraints::Type.new(Integer), options: { type: :index, ichi: 1, ni: 2, san: 3 } } ] end let(:definitions) do constraints.map.with_index do |definition, index| Stannum::Contracts::Definition.new( constraint: definition[:constraint], contract: contract, options: { property: index, property_type: :index, sanity: false } .merge(definition.fetch(:options, {})) ) end end let(:items_count) { constraints.count } let(:constructor_block) do constraint_definitions = constraints lambda do constraint_definitions.each do |definition| item(definition[:constraint], **definition.fetch(:options, {})) end end end end subject(:contract) do described_class.new(**constructor_options, &constructor_block) end let(:constructor_block) { -> {} } let(:constructor_options) { {} } let(:expected_options) { { allow_extra_items: false, item_type: nil } } describe '::Builder' do include Spec::Support::Examples::ContractBuilderExamples subject(:builder) { described_class.new(contract) } let(:described_class) { super()::Builder } let(:contract) do Stannum::Contracts::ArrayContract.new # rubocop:disable RSpec/DescribedClass end describe '.new' do it { expect(described_class).to be_constructible.with(1).argument } end describe '#contract' do include_examples 'should define reader', :contract, -> { contract } end describe '#item' do let(:index) { 0 } let(:custom_options) do { property: index, property_type: :index } end def define_from_block(**options, &block) builder.item(**options, &block) end def define_from_constraint(constraint, **options) builder.item(constraint, **options) end it 'should define the method' do expect(builder) .to respond_to(:item) .with(0..1).arguments .and_any_keywords .and_a_block end include_examples 'should delegate to #constraint' context 'when the contract has one item constraint' do let(:index) { 1 } before(:example) { builder.item } include_examples 'should delegate to #constraint' end context 'when the contract has many item constraints' do let(:index) { 3 } before(:example) { 3.times { builder.item } } include_examples 'should delegate to #constraint' end end end describe '.new' do it 'should define the constructor' do expect(described_class) .to be_constructible .with(0).arguments .and_keywords(:allow_extra_items, :item_type) .and_any_keywords .and_a_block end describe 'with a block' do let(:builder) { instance_double(described_class::Builder, item: nil) } before(:example) do allow(described_class::Builder).to receive(:new).and_return(builder) end it 'should call the builder with the block', :aggregate_failures do described_class.new do item option: 'one' item option: 'two' item option: 'three' end expect(builder).to have_received(:item).with(option: 'one') expect(builder).to have_received(:item).with(option: 'two') expect(builder).to have_received(:item).with(option: 'three') end end end include_examples 'should implement the Constraint interface' include_examples 'should implement the Constraint methods' include_examples 'should implement the Contract methods' describe '#add_constraint' do describe 'with an invalid item index' do let(:constraint) { Stannum::Constraint.new } let(:property) { 'foo' } let(:error_message) do "invalid property name #{property.inspect}" end it 'should raise an error' do expect do contract.add_constraint( constraint, property: property, property_type: :index ) end .to raise_error ArgumentError, error_message end end describe 'with an item constraint' do let(:constraint) { Stannum::Constraint.new } let(:definition) { contract.each_constraint.to_a.last } it 'should return the contract' do expect( contract.add_constraint( constraint, property: 0, property_type: :index ) ) .to be contract end it 'should add the constraint to the contract' do expect do contract.add_constraint( constraint, property: 0, property_type: :index ) end .to change { contract.each_constraint.count } .by(1) end it 'should store the contract' do # rubocop:disable RSpec/ExampleLength contract.add_constraint( constraint, property: 0, property_type: :index ) expect(definition).to be_a_constraint_definition( constraint: constraint, contract: contract, options: { property: 0, property_type: :index, sanity: false } ) end end describe 'with an item constraint with options' do let(:constraint) { Stannum::Constraint.new } let(:options) { { key: 'value' } } let(:definition) { contract.each_constraint.to_a.last } it 'should return the contract' do expect( contract.add_constraint( constraint, property: 0, property_type: :index, **options ) ) .to be contract end it 'should add the constraint to the contract' do expect do contract.add_constraint( constraint, property: 0, property_type: :index, **options ) end .to change { contract.each_constraint.count } .by(1) end it 'should store the contract and options' do # rubocop:disable RSpec/ExampleLength contract.add_constraint( constraint, property: 0, property_type: :index, **options ) expect(definition).to be_a_constraint_definition( constraint: constraint, contract: contract, options: { property: 0, property_type: :index, sanity: false, **options } ) end end end describe '#add_index_constraint' do it 'should define the method' do expect(contract) .to respond_to(:add_index_constraint) .with(2).arguments .and_keywords(:sanity) .and_any_keywords end describe 'with an invalid item index' do let(:constraint) { Stannum::Constraint.new } let(:property) { 'foo' } let(:error_message) do "invalid property name #{property.inspect}" end it 'should raise an error' do expect { contract.add_index_constraint(property, constraint) } .to raise_error ArgumentError, error_message end end describe 'with an item constraint' do let(:constraint) { Stannum::Constraint.new } let(:definition) { contract.each_constraint.to_a.last } it 'should return the contract' do expect(contract.add_index_constraint(0, constraint)) .to be contract end it 'should add the constraint to the contract' do expect { contract.add_index_constraint(0, constraint) } .to change { contract.each_constraint.count } .by(1) end it 'should store the contract' do contract.add_index_constraint(0, constraint) expect(definition).to be_a_constraint_definition( constraint: constraint, contract: contract, options: { property: 0, property_type: :index, sanity: false } ) end end describe 'with an item constraint with options' do let(:constraint) { Stannum::Constraint.new } let(:options) { { key: 'value' } } let(:definition) { contract.each_constraint.to_a.last } it 'should return the contract' do expect(contract.add_index_constraint(0, constraint, **options)) .to be contract end it 'should add the constraint to the contract' do expect { contract.add_index_constraint(0, constraint, **options) } .to change { contract.each_constraint.count } .by(1) end it 'should store the contract and options' do # rubocop:disable RSpec/ExampleLength contract.add_index_constraint(0, constraint, **options) expect(definition).to be_a_constraint_definition( constraint: constraint, contract: contract, options: { property: 0, property_type: :index, sanity: false, **options } ) end end end describe '#allow_extra_items?' do include_examples 'should have predicate', :allow_extra_items?, false wrap_context 'when initialized with allow_extra_items: true' do it { expect(contract.allow_extra_items?).to be true } end end describe '#each_constraint' do let(:items_count) { 0 } let(:builtin_definitions) do [ an_instance_of(Stannum::Contracts::Definition).and( satisfy do |definition| expect(definition.constraint) .to be_a Stannum::Constraints::Types::ArrayType expect(definition.constraint.item_type).to be nil expect(definition.sanity?).to be true end ), an_instance_of(Stannum::Contracts::Definition).and( satisfy do |definition| expect(definition.constraint) .to be_a Stannum::Constraints::Tuples::ExtraItems expect(definition.constraint.expected_count).to be == items_count expect(definition.sanity?).to be false end ) ] end let(:expected) { builtin_definitions } it { expect(contract).to respond_to(:each_constraint).with(0).arguments } it { expect(contract.each_constraint).to be_a Enumerator } it { expect(contract.each_constraint.count).to be 2 } it 'should yield each definition' do expect { |block| contract.each_constraint(&block) } .to yield_successive_args(*expected) end wrap_context 'when initialized with allow_extra_items: true' do let(:builtin_definitions) do [ an_instance_of(Stannum::Contracts::Definition).and( satisfy do |definition| expect(definition.constraint) .to be_a Stannum::Constraints::Types::ArrayType expect(definition.constraint.item_type).to be nil expect(definition.sanity?).to be true end ) ] end it { expect(contract.each_constraint.count).to be 1 } it 'should yield each definition' do expect { |block| contract.each_constraint(&block) } .to yield_successive_args(*expected) end end wrap_context 'when initialized with item_type: value' do let(:builtin_definitions) do [ an_instance_of(Stannum::Contracts::Definition).and( satisfy do |definition| expect(definition.constraint) .to be_a Stannum::Constraints::Types::ArrayType expect(definition.constraint.item_type) .to be_a Stannum::Constraints::Type expect(definition.constraint.item_type.expected_type) .to be String expect(definition.sanity?).to be true end ), an_instance_of(Stannum::Contracts::Definition).and( satisfy do |definition| expect(definition.constraint) .to be_a Stannum::Constraints::Tuples::ExtraItems expect(definition.constraint.expected_count).to be == items_count expect(definition.sanity?).to be false end ) ] end it { expect(contract.each_constraint.count).to be 2 } it 'should yield each definition' do expect { |block| contract.each_constraint(&block) } .to yield_successive_args(*expected) end end # rubocop:disable RSpec/RepeatedExampleGroupBody wrap_context 'when the contract has one item constraint' do let(:expected) { builtin_definitions + definitions } it { expect(contract.each_constraint.count).to be(2 + constraints.size) } it 'should yield each definition' do expect { |block| contract.each_constraint(&block) } .to yield_successive_args(*expected) end wrap_context 'when initialized with allow_extra_items: true' do let(:builtin_definitions) do [ an_instance_of(Stannum::Contracts::Definition).and( satisfy do |definition| expect(definition.constraint) .to be_a Stannum::Constraints::Types::ArrayType expect(definition.constraint.item_type).to be nil expect(definition.sanity?).to be true end ) ] end it { expect(contract.each_constraint.count).to be 1 + constraints.size } it 'should yield each definition' do expect { |block| contract.each_constraint(&block) } .to yield_successive_args(*expected) end end end wrap_context 'when the contract has many item constraints' do let(:expected) { builtin_definitions + definitions } it { expect(contract.each_constraint.count).to be(2 + constraints.size) } it 'should yield each definition' do expect { |block| contract.each_constraint(&block) } .to yield_successive_args(*expected) end wrap_context 'when initialized with allow_extra_items: true' do let(:builtin_definitions) do [ an_instance_of(Stannum::Contracts::Definition).and( satisfy do |definition| expect(definition.constraint) .to be_a Stannum::Constraints::Types::ArrayType expect(definition.constraint.item_type).to be nil expect(definition.sanity?).to be true end ) ] end it { expect(contract.each_constraint.count).to be 1 + constraints.size } it 'should yield each definition' do expect { |block| contract.each_constraint(&block) } .to yield_successive_args(*expected) end end end # rubocop:enable RSpec/RepeatedExampleGroupBody end describe '#each_pair' do let(:actual) { %w[ichi ni san] } let(:items_count) { 0 } let(:builtin_definitions) do [ an_instance_of(Stannum::Contracts::Definition).and( satisfy do |definition| expect(definition.constraint) .to be_a Stannum::Constraints::Types::ArrayType expect(definition.constraint.item_type).to be nil expect(definition.sanity?).to be true end ), an_instance_of(Stannum::Contracts::Definition).and( satisfy do |definition| expect(definition.constraint) .to be_a Stannum::Constraints::Tuples::ExtraItems expect(definition.constraint.expected_count).to be == items_count expect(definition.sanity?).to be false end ) ] end let(:expected) do builtin_definitions.zip(Array.new(builtin_definitions.size, actual)) end it { expect(contract).to respond_to(:each_pair).with(1).argument } it { expect(contract.each_pair(actual)).to be_a Enumerator } it { expect(contract.each_pair(actual).count).to be 2 + items_count } it 'should yield each definition and the mapped property' do expect { |block| contract.each_pair(actual, &block) } .to yield_successive_args(*expected) end wrap_context 'when initialized with allow_extra_items: true' do let(:builtin_definitions) do [ an_instance_of(Stannum::Contracts::Definition).and( satisfy do |definition| expect(definition.constraint) .to be_a Stannum::Constraints::Types::ArrayType expect(definition.constraint.item_type).to be nil expect(definition.sanity?).to be true end ) ] end it { expect(contract.each_pair(actual).count).to be 1 + items_count } it 'should yield each definition and the mapped property' do expect { |block| contract.each_pair(actual, &block) } .to yield_successive_args(*expected) end end wrap_context 'when initialized with item_type: value' do let(:builtin_definitions) do [ an_instance_of(Stannum::Contracts::Definition).and( satisfy do |definition| expect(definition.constraint) .to be_a Stannum::Constraints::Types::ArrayType expect(definition.constraint.item_type) .to be_a Stannum::Constraints::Type expect(definition.constraint.item_type.expected_type) .to be String expect(definition.sanity?).to be true end ), an_instance_of(Stannum::Contracts::Definition).and( satisfy do |definition| expect(definition.constraint) .to be_a Stannum::Constraints::Tuples::ExtraItems expect(definition.constraint.expected_count).to be == items_count expect(definition.sanity?).to be false end ) ] end it { expect(contract.each_pair(actual).count).to be 2 + items_count } it 'should yield each definition and the mapped property' do expect { |block| contract.each_pair(actual, &block) } .to yield_successive_args(*expected) end end # rubocop:disable RSpec/RepeatedExampleGroupBody wrap_context 'when the contract has one item constraint' do let(:expected) do builtin_definitions.zip(Array.new(builtin_definitions.size, actual)) + definitions.zip(actual) end it 'should have the expected size' do expect(contract.each_pair(actual).count).to be(2 + constraints.size) end it 'should yield each definition' do expect { |block| contract.each_pair(actual, &block) } .to yield_successive_args(*expected) end wrap_context 'when initialized with allow_extra_items: true' do let(:builtin_definitions) do [ an_instance_of(Stannum::Contracts::Definition).and( satisfy do |definition| expect(definition.constraint) .to be_a Stannum::Constraints::Types::ArrayType expect(definition.constraint.item_type).to be nil expect(definition.sanity?).to be true end ) ] end it { expect(contract.each_pair(actual).count).to be 1 + items_count } it 'should yield each definition and the mapped property' do expect { |block| contract.each_pair(actual, &block) } .to yield_successive_args(*expected) end end end wrap_context 'when the contract has many item constraints' do let(:expected) do builtin_definitions.zip(Array.new(builtin_definitions.size, actual)) + definitions.zip(actual) end it 'should have the expected size' do expect(contract.each_pair(actual).count).to be(2 + constraints.size) end it 'should yield each definition' do expect { |block| contract.each_pair(actual, &block) } .to yield_successive_args(*expected) end wrap_context 'when initialized with allow_extra_items: true' do let(:builtin_definitions) do [ an_instance_of(Stannum::Contracts::Definition).and( satisfy do |definition| expect(definition.constraint) .to be_a Stannum::Constraints::Types::ArrayType expect(definition.constraint.item_type).to be nil expect(definition.sanity?).to be true end ) ] end it { expect(contract.each_pair(actual).count).to be 1 + items_count } it 'should yield each definition and the mapped property' do expect { |block| contract.each_pair(actual, &block) } .to yield_successive_args(*expected) end end end # rubocop:enable RSpec/RepeatedExampleGroupBody end describe '#item_type' do include_examples 'should have reader', :item_type, nil context 'when initialized with item_type: nil' do let(:constructor_options) { super().merge(item_type: nil) } it { expect(contract.item_type).to be nil } end context 'when initialized with item_type: a Class' do let(:item_type) { String } let(:constructor_options) { super().merge(item_type: item_type) } it { expect(contract.item_type).to be item_type } end context 'when initialized with item_type: a constraint' do let(:item_type) { Stannum::Constraint.new } let(:constructor_options) { super().merge(item_type: item_type) } it { expect(contract.item_type).to be_a item_type.class } it { expect(contract.item_type.options).to be == item_type.options } end end describe '#map_errors' do let(:errors) { Stannum::Errors.new } it { expect(contract.send :map_errors, errors).to be errors } describe 'with property_type: :index' do let(:index) { 1 } before(:example) do errors[index].add('spec.indexed_error') end it 'should return the errors for the index' do expect( contract.send( :map_errors, errors, property: index, property_type: :index ) ) .to be == errors[index] end end end describe '#map_value' do let(:value) { %w[ichi ni san] } it { expect(contract.send :map_value, value).to be value } describe 'with property_type: :index' do let(:index) { 1 } it 'should return the indexed value' do expect( contract.send( :map_value, value, property: index, property_type: :index ) ) .to be == value[index] end end end describe '#options' do let(:expected) do { allow_extra_items: false, item_type: nil } end include_examples 'should have reader', :options, -> { be == expected } wrap_context 'when initialized with allow_extra_items: true' do it 'should set the option' do expect(contract.options) .to be == expected.merge(allow_extra_items: true) end end wrap_context 'when initialized with item_type: value' do it 'should set the option' do expect(contract.options) .to be == expected.merge(item_type: String) end end end describe '#valid_property?' do it 'should define the private method' do expect(contract) .to respond_to(:valid_property?, true) .with(0).arguments .and_any_keywords end describe 'with no keywords' do it { expect(contract.send :valid_property?).to be false } end describe 'with property: nil' do it 'should return true' do expect(contract.send :valid_property?, property: nil).to be false end end describe 'with property: an Object' do it 'should return true' do expect(contract.send :valid_property?, property: Object.new.freeze) .to be false end end describe 'with property: an Integer' do it 'should return true' do expect(contract.send :valid_property?, property: 0) .to be false end end describe 'with property: an empty String' do it 'should return true' do expect(contract.send :valid_property?, property: '').to be false end end describe 'with property: a String' do it 'should return true' do expect(contract.send :valid_property?, property: 'foo').to be true end end describe 'with property: an empty Symbol' do it 'should return true' do expect(contract.send :valid_property?, property: :'').to be false end end describe 'with property: a Symbol' do it 'should return true' do expect(contract.send :valid_property?, property: :foo).to be true end end describe 'with property: an empty Array' do it 'should return false' do expect(contract.send :valid_property?, property: []).to be false end end describe 'with property: an Array with an invalid object' do it 'should return false' do expect(contract.send :valid_property?, property: [nil]).to be false end end describe 'with property: an Array with an invalid String' do it 'should return false' do expect(contract.send :valid_property?, property: ['']).to be false end end describe 'with property: an Array with an valid Strings' do it 'should return true' do expect(contract.send :valid_property?, property: %w[foo bar baz]) .to be true end end describe 'with property: an Array with an invalid Symbol' do it 'should return false' do expect(contract.send :valid_property?, property: [:'']).to be false end end describe 'with property_type: :index and property: nil' do it 'should return false' do expect( contract.send( :valid_property?, property: nil, property_type: :index ) ).to be false end end describe 'with property_type: :index and property: an Object' do it 'should return false' do expect( contract.send( :valid_property?, property: Object.new.freeze, property_type: :index ) ).to be false end end describe 'with property_type: :index and property: an Array' do it 'should return false' do expect( contract.send( :valid_property?, property: %w[foo bar baz], property_type: :index ) ).to be false end end describe 'with property_type: :index and property: an Integer' do it 'should return false' do expect( contract.send( :valid_property?, property: -1, property_type: :index ) ).to be true end end describe 'with property_type: :index and property: a String' do it 'should return false' do expect( contract.send( :valid_property?, property: 'foo', property_type: :index ) ).to be false end end describe 'with property_type: :index and property: a Symbol' do it 'should return false' do expect( contract.send( :valid_property?, property: :foo, property_type: :index ) ).to be false end end end describe '#validate_property?' do it 'should define the private method' do expect(contract) .to respond_to(:validate_property?, true) .with(0).arguments .and_any_keywords end describe 'with no keywords' do it { expect(contract.send :validate_property?).to be false } end describe 'with property: nil' do it 'should return true' do expect(contract.send :validate_property?, property: nil).to be false end end describe 'with property: an Object' do it 'should return true' do expect(contract.send :validate_property?, property: Object.new.freeze) .to be true end end describe 'with property: nil and property_type: :index' do it 'should return true' do expect( contract.send( :validate_property?, property: nil, property_type: :index ) ).to be true end end end describe '#with_options' do describe 'with allow_extra_items: value' do let(:error_message) { "can't change option :allow_extra_items" } it 'should raise an exception' do expect { contract.with_options(allow_extra_items: true) } .to raise_error ArgumentError, error_message end end describe 'with item_type: value' do let(:error_message) { "can't change option :item_type" } it 'should raise an exception' do expect { contract.with_options(item_type: true) } .to raise_error ArgumentError, error_message end end end end
configure do CONFIG = YAML::load(File.read('config.yml')).to_hash.each do |k, v| set k, v end end # Class declarations class Unfuddle class Ticket < ActiveResource::Base self.site = "http://#{CONFIG['unfuddle']['subdomain']}.unfuddle.com/api/v1/projects/#{CONFIG['unfuddle']['project_id'].to_s}" self.user = CONFIG['unfuddle']['user'] self.password = CONFIG['unfuddle']['password'] def self.ticket_url(ticket) "http://#{CONFIG['unfuddle']['subdomain']}.unfuddle.com/projects/#{CONFIG['unfuddle']['project_id']}/tickets/#{ticket.id}" end def backlog? ['new', 'reopened'].include? self.status end def development? ['accepted', 'reassigned'].include? self.status end def deployment? 'resolved' == self.status end def done? 'closed' == self.status end end end
require 'nokogiri' require 'open-uri' module Parsers class LiveScoresExtractor class << self def extract(webpage_url) content = [] puts '' puts "Extracting from #{webpage_url}" browser = Watir::Browser.new :chrome, headless: true browser.goto webpage_url sleep 5 page = Nokogiri::HTML(browser.html) items = page.css('.score-strip-list').first.css('.score-strip-game') file = File.open(Rails.root.join('tmp', 'data', "info-#{Time.zone.now.strftime('%Y-%m-%d-%H-%m-%S')}"), 'w') # Extracting info items.each do |item| data = item.css('span') file.write("#{data.map(&:text).join('|')}\n") formatted_data = format_data(data) game_data = { visitor: formatted_data[:visitor], visitor_score: formatted_data[:visitor_score], local: formatted_data[:local], local_score: formatted_data[:local_score], already_played: formatted_data[:already_played] } puts game_data content << game_data end file.close browser.close content end private def format_data(data) result = {} result[:visitor] = data[0].text i = 1 while (i < data.size-1) do if data[i].text.strip =~/^\d+$/ if result[:visitor_score] result[:local_score] = data[i].text else result[:visitor_score] = data[i].text end elsif data[i].text.strip =~/^[A-Z]+$/ result[:local] = data[i].text end i += 1 end result[:already_played] = (data[-1].text =~ /Final.*/) == 0 result end end end end
# encoding: UTF-8 # # Méthodes d'extraction des données propres au format # TEXT # class Collecte class Extractor def extract_meta_data collecte.metadata.data.each do |prop, valu| valu != nil || next # Modification de certaines valeurs valu = case prop when :auteurs valu.pretty_join else valu end write prop, valu end final_file.flush end def extract_personnages_data write RC*2 + '=== PERSONNAGES ===' film.personnages.each do |perso_id, perso| write "#{RC}Personnage #{perso.id}" Film::Personnage::PROPERTIES.each do |prop| write "#{prop}", "#{perso.send(prop)}", {before_label: "\t"} end end final_file.flush end # /extract_personnages_data def extract_brins_data write RC*2 + '=== BRINS ===' film.brins.each do |brin_id, brin| write "#{RC}Brin #{brin_id}" write "id", "#{brin.id}", {before_label: "\t"} [:libelle, :description].each do |prop| write "#{prop}", "#{brin.send(prop).to_html}", {before_label: "\t"} end end final_file.flush end # /extract_brins_data def extract_decors_data write RC*2 + '=== DÉCORS ===' film.decors.each do |decor_id, decor| write "#{RC}Décor #{decor.id}" Film::Decor::PROPERTIES.each do |prop, dprop| val_init = decor.send(prop) if val_init != nil && dprop[:value] if dprop[:args] val_init = val_init.send(dprop[:value], dprop[:args]) else val_init = val_init.send(dprop[:value]) end end write "#{prop}", "#{val_init}", {before_label: "\t"} end end final_file.flush end # /extract_decors_data def extract_scenes_data write RC*2 + '=== SCENES ===' film.scenes.each do |scene_id, scene| write "#{RC}Scene #{scene.numero}" Film::Scene::PROPERTIES.each do |prop, dprop| val_init = scene.send(prop) if val_init != nil && dprop[:value] if dprop[:args] val_init = val_init.send(dprop[:value], dprop[:args]) else val_init = val_init.send(dprop[:value]) end end write "#{prop}", "#{val_init}", {before_label: "\t"} end # Sauvegarde des paragraphes de la scène (scene.paragraphes|[]).each_with_index do |paragraphe, i| write "\tParagraphe #{i}" paragraphe.to_hash.each do |prop, valeur| write "#{prop}", "#{valeur}", {before_label: "\t\t"} end end end final_file.flush end # /extract_scenes_data end #/Extractor end #/Collecte
class AddModulToPermission < ActiveRecord::Migration def change add_column :permissions, :modul, :string end end
require File.join(File.dirname(File.expand_path(__FILE__)), "spec_helper") describe "Sequel Mock Adapter" do specify "should have an adapter method" do db = Sequel.mock db.should be_a_kind_of(Sequel::Mock::Database) db.adapter_scheme.should == :mock end specify "should have constructor accept no arguments" do Sequel::Mock::Database.new.should be_a_kind_of(Sequel::Mock::Database) end specify "should each not return any rows by default" do called = false Sequel.mock[:t].each{|r| called = true} called.should == false end specify "should return 0 for update/delete/with_sql_delete/execute_dui by default" do Sequel.mock[:t].update(:a=>1).should == 0 Sequel.mock[:t].delete.should == 0 Sequel.mock[:t].with_sql_delete('DELETE FROM t').should == 0 Sequel.mock.execute_dui('DELETE FROM t').should == 0 end specify "should return nil for insert/execute_insert by default" do Sequel.mock[:t].insert(:a=>1).should be_nil Sequel.mock.execute_insert('INSERT INTO a () DEFAULT VALUES').should be_nil end specify "should be able to set the rows returned by each using :fetch option with a single hash" do rs = [] db = Sequel.mock(:fetch=>{:a=>1}) db[:t].each{|r| rs << r} rs.should == [{:a=>1}] db[:t].each{|r| rs << r} rs.should == [{:a=>1}, {:a=>1}] db[:t].each{|r| r[:a] = 2; rs << r} rs.should == [{:a=>1}, {:a=>1}, {:a=>2}] db[:t].each{|r| rs << r} rs.should == [{:a=>1}, {:a=>1}, {:a=>2}, {:a=>1}] end specify "should be able to set the rows returned by each using :fetch option with an array of hashes" do rs = [] db = Sequel.mock(:fetch=>[{:a=>1}, {:a=>2}]) db[:t].each{|r| rs << r} rs.should == [{:a=>1}, {:a=>2}] db[:t].each{|r| rs << r} rs.should == [{:a=>1}, {:a=>2}, {:a=>1}, {:a=>2}] db[:t].each{|r| r[:a] += 2; rs << r} rs.should == [{:a=>1}, {:a=>2}, {:a=>1}, {:a=>2}, {:a=>3}, {:a=>4}] db[:t].each{|r| rs << r} rs.should == [{:a=>1}, {:a=>2}, {:a=>1}, {:a=>2}, {:a=>3}, {:a=>4}, {:a=>1}, {:a=>2}] end specify "should be able to set the rows returned by each using :fetch option with an array or arrays of hashes" do rs = [] db = Sequel.mock(:fetch=>[[{:a=>1}, {:a=>2}], [{:a=>3}, {:a=>4}]]) db[:t].each{|r| rs << r} rs.should == [{:a=>1}, {:a=>2}] db[:t].each{|r| rs << r} rs.should == [{:a=>1}, {:a=>2}, {:a=>3}, {:a=>4}] db[:t].each{|r| rs << r} rs.should == [{:a=>1}, {:a=>2}, {:a=>3}, {:a=>4}] end specify "should be able to set the rows returned by each using :fetch option with a proc that takes sql" do rs = [] db = Sequel.mock(:fetch=>proc{|sql| sql =~ /FROM t/ ? {:b=>1} : [{:a=>1}, {:a=>2}]}) db[:t].each{|r| rs << r} rs.should == [{:b=>1}] db[:b].each{|r| rs << r} rs.should == [{:b=>1}, {:a=>1}, {:a=>2}] db[:t].each{|r| r[:b] += 1; rs << r} db[:b].each{|r| r[:a] += 2; rs << r} rs.should == [{:b=>1}, {:a=>1}, {:a=>2}, {:b=>2}, {:a=>3}, {:a=>4}] db[:t].each{|r| rs << r} db[:b].each{|r| rs << r} rs.should == [{:b=>1}, {:a=>1}, {:a=>2}, {:b=>2}, {:a=>3}, {:a=>4}, {:b=>1}, {:a=>1}, {:a=>2}] end specify "should have a fetch= method for setting rows returned by each after the fact" do rs = [] db = Sequel.mock db.fetch = {:a=>1} db[:t].each{|r| rs << r} rs.should == [{:a=>1}] db[:t].each{|r| rs << r} rs.should == [{:a=>1}] * 2 end specify "should be able to set an exception to raise by setting the :fetch option to an exception class " do db = Sequel.mock(:fetch=>ArgumentError) proc{db[:t].all}.should raise_error(Sequel::DatabaseError) begin db[:t].all rescue => e end e.should be_a_kind_of(Sequel::DatabaseError) e.wrapped_exception.should be_a_kind_of(ArgumentError) end specify "should be able to set separate kinds of results for fetch using an array" do rs = [] db = Sequel.mock(:fetch=>[{:a=>1}, [{:a=>2}, {:a=>3}], proc{|s| {:a=>4}}, proc{|s| }, nil, ArgumentError]) db[:t].each{|r| rs << r} rs.should == [{:a=>1}] db[:t].each{|r| rs << r} rs.should == [{:a=>1}, {:a=>2}, {:a=>3}] db[:t].each{|r| rs << r} rs.should == [{:a=>1}, {:a=>2}, {:a=>3}, {:a=>4}] db[:t].each{|r| rs << r} rs.should == [{:a=>1}, {:a=>2}, {:a=>3}, {:a=>4}] db[:t].each{|r| rs << r} rs.should == [{:a=>1}, {:a=>2}, {:a=>3}, {:a=>4}] proc{db[:t].all}.should raise_error(Sequel::DatabaseError) end specify "should be able to set the rows returned by each on a per dataset basis using _fetch" do rs = [] db = Sequel.mock(:fetch=>{:a=>1}) ds = db[:t] ds.each{|r| rs << r} rs.should == [{:a=>1}] ds._fetch = {:b=>2} ds.each{|r| rs << r} rs.should == [{:a=>1}, {:b=>2}] end specify "should raise Error if given an invalid object to fetch" do proc{Sequel.mock(:fetch=>Class.new).get(:a)}.should raise_error(Sequel::Error) proc{Sequel.mock(:fetch=>Object.new).get(:a)}.should raise_error(Sequel::Error) end specify "should be able to set the number of rows modified by update and delete using :numrows option as an integer" do db = Sequel.mock(:numrows=>2) db[:t].update(:a=>1).should == 2 db[:t].delete.should == 2 db[:t].update(:a=>1).should == 2 db[:t].delete.should == 2 end specify "should be able to set the number of rows modified by update and delete using :numrows option as an array of integers" do db = Sequel.mock(:numrows=>[2, 1]) db[:t].update(:a=>1).should == 2 db[:t].delete.should == 1 db[:t].update(:a=>1).should == 0 db[:t].delete.should == 0 end specify "should be able to set the number of rows modified by update and delete using :numrows option as a proc" do db = Sequel.mock(:numrows=>proc{|sql| sql =~ / t/ ? 2 : 1}) db[:t].update(:a=>1).should == 2 db[:t].delete.should == 2 db[:b].update(:a=>1).should == 1 db[:b].delete.should == 1 end specify "should be able to set an exception to raise by setting the :numrows option to an exception class " do db = Sequel.mock(:numrows=>ArgumentError) proc{db[:t].update(:a=>1)}.should raise_error(Sequel::DatabaseError) begin db[:t].delete rescue => e end e.should be_a_kind_of(Sequel::DatabaseError) e.wrapped_exception.should be_a_kind_of(ArgumentError) end specify "should be able to set separate kinds of results for numrows using an array" do db = Sequel.mock(:numrows=>[1, proc{|s| 2}, nil, ArgumentError]) db[:t].delete.should == 1 db[:t].update(:a=>1).should == 2 db[:t].delete.should == 0 proc{db[:t].delete}.should raise_error(Sequel::DatabaseError) end specify "should have a numrows= method to set the number of rows modified by update and delete after the fact" do db = Sequel.mock db.numrows = 2 db[:t].update(:a=>1).should == 2 db[:t].delete.should == 2 db[:t].update(:a=>1).should == 2 db[:t].delete.should == 2 end specify "should be able to set the number of rows modified by update and delete on a per dataset basis" do db = Sequel.mock(:numrows=>2) ds = db[:t] ds.update(:a=>1).should == 2 ds.delete.should == 2 ds.numrows = 3 ds.update(:a=>1).should == 3 ds.delete.should == 3 end specify "should raise Error if given an invalid object for numrows or autoid" do proc{Sequel.mock(:numrows=>Class.new)[:a].delete}.should raise_error(Sequel::Error) proc{Sequel.mock(:numrows=>Object.new)[:a].delete}.should raise_error(Sequel::Error) proc{Sequel.mock(:autoid=>Class.new)[:a].insert}.should raise_error(Sequel::Error) proc{Sequel.mock(:autoid=>Object.new)[:a].insert}.should raise_error(Sequel::Error) end specify "should be able to set the autogenerated primary key returned by insert using :autoid option as an integer" do db = Sequel.mock(:autoid=>1) db[:t].insert(:a=>1).should == 1 db[:t].insert(:a=>1).should == 2 db[:t].insert(:a=>1).should == 3 end specify "should be able to set the autogenerated primary key returned by insert using :autoid option as an array of integers" do db = Sequel.mock(:autoid=>[1, 3, 5]) db[:t].insert(:a=>1).should == 1 db[:t].insert(:a=>1).should == 3 db[:t].insert(:a=>1).should == 5 db[:t].insert(:a=>1).should be_nil end specify "should be able to set the autogenerated primary key returned by insert using :autoid option as a proc" do db = Sequel.mock(:autoid=>proc{|sql| sql =~ /INTO t / ? 2 : 1}) db[:t].insert(:a=>1).should == 2 db[:t].insert(:a=>1).should == 2 db[:b].insert(:a=>1).should == 1 db[:b].insert(:a=>1).should == 1 end specify "should be able to set an exception to raise by setting the :autoid option to an exception class " do db = Sequel.mock(:autoid=>ArgumentError) proc{db[:t].insert(:a=>1)}.should raise_error(Sequel::DatabaseError) begin db[:t].insert rescue => e end e.should be_a_kind_of(Sequel::DatabaseError) e.wrapped_exception.should be_a_kind_of(ArgumentError) end specify "should be able to set separate kinds of results for autoid using an array" do db = Sequel.mock(:autoid=>[1, proc{|s| 2}, nil, ArgumentError]) db[:t].insert.should == 1 db[:t].insert.should == 2 db[:t].insert.should == nil proc{db[:t].insert}.should raise_error(Sequel::DatabaseError) end specify "should have an autoid= method to set the autogenerated primary key returned by insert after the fact" do db = Sequel.mock db.autoid = 1 db[:t].insert(:a=>1).should == 1 db[:t].insert(:a=>1).should == 2 db[:t].insert(:a=>1).should == 3 end specify "should be able to set the autogenerated primary key returned by insert on a per dataset basis" do db = Sequel.mock(:autoid=>1) ds = db[:t] ds.insert(:a=>1).should == 1 ds.autoid = 5 ds.insert(:a=>1).should == 5 ds.insert(:a=>1).should == 6 db[:t].insert(:a=>1).should == 2 end specify "should be able to set the columns to set in the dataset as an array of symbols" do db = Sequel.mock(:columns=>[:a, :b]) db[:t].columns.should == [:a, :b] db.sqls.should == ["SELECT * FROM t LIMIT 1"] ds = db[:t] ds.all db.sqls.should == ["SELECT * FROM t"] ds.columns.should == [:a, :b] db.sqls.should == [] db[:t].columns.should == [:a, :b] end specify "should be able to set the columns to set in the dataset as an array of arrays of symbols" do db = Sequel.mock(:columns=>[[:a, :b], [:c, :d]]) db[:t].columns.should == [:a, :b] db[:t].columns.should == [:c, :d] end specify "should be able to set the columns to set in the dataset as a proc" do db = Sequel.mock(:columns=>proc{|sql| (sql =~ / t/) ? [:a, :b] : [:c, :d]}) db[:b].columns.should == [:c, :d] db[:t].columns.should == [:a, :b] end specify "should have a columns= method to set the columns to set after the fact" do db = Sequel.mock db.columns = [[:a, :b], [:c, :d]] db[:t].columns.should == [:a, :b] db[:t].columns.should == [:c, :d] end specify "should raise Error if given an invalid columns" do proc{Sequel.mock(:columns=>Object.new)[:a].columns}.should raise_error(Sequel::Error) end specify "should not quote identifiers by default" do Sequel.mock.send(:quote_identifiers_default).should == false end specify "should allow overriding of server_version" do db = Sequel.mock db.server_version.should == nil db.server_version = 80102 db.server_version.should == 80102 end specify "should not have identifier input/output methods by default" do Sequel.mock.send(:identifier_input_method_default).should be_nil Sequel.mock.send(:identifier_output_method_default).should be_nil end specify "should keep a record of all executed SQL in #sqls" do db = Sequel.mock db[:t].all db[:b].delete db[:c].insert(:a=>1) db[:d].update(:a=>1) db.sqls.should == ['SELECT * FROM t', 'DELETE FROM b', 'INSERT INTO c (a) VALUES (1)', 'UPDATE d SET a = 1'] end specify "should clear sqls on retrieval" do db = Sequel.mock db[:t].all db.sqls.should == ['SELECT * FROM t'] db.sqls.should == [] end specify "should also log SQL executed to the given loggers" do a = [] def a.method_missing(m, *x) push(*x) end db = Sequel.mock(:loggers=>[a]) db[:t].all db[:b].delete db[:c].insert(:a=>1) db[:d].update(:a=>1) a.should == ['SELECT * FROM t', 'DELETE FROM b', 'INSERT INTO c (a) VALUES (1)', 'UPDATE d SET a = 1'] end specify "should correctly handle transactions" do db = Sequel.mock db.transaction{db[:a].all} db.sqls.should == ['BEGIN', 'SELECT * FROM a', 'COMMIT'] db.transaction{db[:a].all; raise Sequel::Rollback} db.sqls.should == ['BEGIN', 'SELECT * FROM a', 'ROLLBACK'] proc{db.transaction{db[:a].all; raise ArgumentError}}.should raise_error(ArgumentError) db.sqls.should == ['BEGIN', 'SELECT * FROM a', 'ROLLBACK'] proc{db.transaction(:rollback=>:reraise){db[:a].all; raise Sequel::Rollback}}.should raise_error(Sequel::Rollback) db.sqls.should == ['BEGIN', 'SELECT * FROM a', 'ROLLBACK'] db.transaction(:rollback=>:always){db[:a].all} db.sqls.should == ['BEGIN', 'SELECT * FROM a', 'ROLLBACK'] db.transaction{db.transaction{db[:a].all; raise Sequel::Rollback}} db.sqls.should == ['BEGIN', 'SELECT * FROM a', 'ROLLBACK'] db.transaction{db.transaction(:savepoint=>true){db[:a].all; raise Sequel::Rollback}} db.sqls.should == ['BEGIN', 'SAVEPOINT autopoint_1', 'SELECT * FROM a', 'ROLLBACK TO SAVEPOINT autopoint_1', 'COMMIT'] db.transaction{db.transaction(:savepoint=>true){db[:a].all}; raise Sequel::Rollback} db.sqls.should == ['BEGIN', 'SAVEPOINT autopoint_1', 'SELECT * FROM a', 'RELEASE SAVEPOINT autopoint_1', 'ROLLBACK'] end specify "should correctly handle transactions when sharding" do db = Sequel.mock(:servers=>{:test=>{}}) db.transaction{db.transaction(:server=>:test){db[:a].all; db[:t].server(:test).all}} db.sqls.should == ['BEGIN', 'BEGIN -- test', 'SELECT * FROM a', 'SELECT * FROM t -- test', 'COMMIT -- test', 'COMMIT'] end specify "should yield a mock connection object from synchronize" do c = Sequel.mock.synchronize{|conn| conn} c.should be_a_kind_of(Sequel::Mock::Connection) end specify "should deal correctly with sharding" do db = Sequel.mock(:servers=>{:test=>{}}) c1 = db.synchronize{|conn| conn} c2 = db.synchronize(:test){|conn| conn} c1.server.should == :default c2.server.should == :test end specify "should disconnect correctly" do db = Sequel.mock db.test_connection proc{db.disconnect}.should_not raise_error end specify "should accept :extend option for extending the object with a module" do Sequel.mock(:extend=>Module.new{def foo(v) v * 2 end}).foo(3).should == 6 end specify "should accept :sqls option for where to store the SQL queries" do a = [] Sequel.mock(:sqls=>a)[:t].all a.should == ['SELECT * FROM t'] end specify "should include :append option in SQL if it is given" do db = Sequel.mock(:append=>'a') db[:t].all db.sqls.should == ['SELECT * FROM t -- a'] end specify "should append :arguments option to execute to the SQL if present" do db = Sequel.mock db.execute('SELECT * FROM t', :arguments=>[1, 2]) db.sqls.should == ['SELECT * FROM t -- args: [1, 2]'] end specify "should have Dataset#columns take columns to set and return self" do db = Sequel.mock ds = db[:t].columns(:id, :a, :b) ds.should be_a_kind_of(Sequel::Mock::Dataset) ds.columns.should == [:id, :a, :b] end specify "should be able to load dialects based on the database name" do begin qi = class Sequel::Database; @quote_identifiers; end ii = class Sequel::Database; @identifier_input_method; end io = class Sequel::Database; @identifier_output_method; end Sequel.quote_identifiers = nil class Sequel::Database; @identifier_input_method=nil; end class Sequel::Database; @identifier_output_method=nil; end Sequel.mock(:host=>'access').select(Date.new(2011, 12, 13)).sql.should == 'SELECT #2011-12-13#' Sequel.mock(:host=>'cubrid').from(:a).offset(1).sql.should == 'SELECT * FROM "a" LIMIT 1,4294967295' Sequel.mock(:host=>'db2').select(1).sql.should == 'SELECT 1 FROM "SYSIBM"."SYSDUMMY1"' Sequel.mock(:host=>'firebird')[:a].distinct.limit(1, 2).sql.should == 'SELECT DISTINCT FIRST 1 SKIP 2 * FROM "A"' Sequel.mock(:host=>'informix')[:a].distinct.limit(1, 2).sql.should == 'SELECT SKIP 2 FIRST 1 DISTINCT * FROM A' Sequel.mock(:host=>'mssql')[:a].full_text_search(:b, 'c').sql.should == "SELECT * FROM [A] WHERE (CONTAINS ([B], 'c'))" Sequel.mock(:host=>'mysql')[:a].full_text_search(:b, 'c').sql.should == "SELECT * FROM `a` WHERE (MATCH (`b`) AGAINST ('c'))" Sequel.mock(:host=>'oracle')[:a].limit(1).sql.should == 'SELECT * FROM (SELECT * FROM "A") "T1" WHERE (ROWNUM <= 1)' Sequel.mock(:host=>'postgres')[:a].full_text_search(:b, 'c').sql.should == "SELECT * FROM \"a\" WHERE (to_tsvector(CAST('simple' AS regconfig), (COALESCE(\"b\", ''))) @@ to_tsquery(CAST('simple' AS regconfig), 'c'))" Sequel.mock(:host=>'sqlanywhere').from(:a).offset(1).sql.should == 'SELECT TOP 2147483647 START AT (1 + 1) * FROM "A"' Sequel.mock(:host=>'sqlite')[:a___b].sql.should == "SELECT * FROM `a` AS 'b'" ensure Sequel.quote_identifiers = qi Sequel::Database.send(:instance_variable_set, :@identifier_input_method, ii) Sequel::Database.send(:instance_variable_set, :@identifier_output_method, io) end end specify "should automatically set version for adapters nedding versions" do Sequel.mock(:host=>'postgres').server_version.should == 90400 Sequel.mock(:host=>'mssql').server_version.should == 11000000 Sequel.mock(:host=>'mysql').server_version.should == 50617 Sequel.mock(:host=>'sqlite').sqlite_version.should == 30804 end specify "should stub out the primary_key method for postgres" do Sequel.mock(:host=>'postgres').primary_key(:t).should == :id end specify "should stub out the bound_variable_arg method for postgres" do Sequel.mock(:host=>'postgres').bound_variable_arg(:t, nil).should == :t end specify "should handle creating tables on oracle" do proc{Sequel.mock(:host=>'oracle').create_table(:a){String :b}}.should_not raise_error end end
#!/usr/local/bin/macruby # -*- coding: utf-8 -*- require "rubygems" require "mopencl" require "benchmark" opencl = OpenCL.new # When true is set in use_cpu, the program is executed on CPU. opencl.use_cpu = true opencl.program <<EOF __kernel sum(__global float *in, __global float *out, int total) { int i = get_global_id(0); if (i < total) out[i] = ((float)in[i] + 0.5) / 3.8 + 2.0; } EOF DATA_SIZE = 10000000 data = (1..DATA_SIZE).to_a input = opencl.set_input(data, DATA_SIZE) output = opencl.set_output(DATA_SIZE) # result = data.map {|x| (x.to_f + 0.5) / 3.8 + 2.0 } # p result.last # opencl.sum(input, output, DATA_SIZE) # p output.result.last Benchmark.bmbm do |x| x.report("map ") { data.map {|x| (x.to_f + 0.5) / 3.8 + 2.0 } } x.report("OpenCL(cpu)") { opencl.sum(input, output, DATA_SIZE) } end
class ApiController < ApplicationController ALLOWED_ORIGN = 'http://www.ahmedfelicettawedding.com' respond_to :json prepend_before_action :return_json skip_before_action :authenticate_user! skip_before_action :verify_authenticity_token before_action :underscore_params! after_action :set_cors_headers private def underscore_params! underscore_hash = -> (hash) do hash.transform_keys!(&:underscore) hash.each do |key, value| if value.is_a?(ActionController::Parameters) underscore_hash.call(value) elsif value.is_a?(Array) value.each do |item| next unless item.is_a?(ActionController::Parameters) underscore_hash.call(item) end end end end underscore_hash.call(params) end def return_json request.format = :json end def set_cors_headers headers['Access-Control-Allow-Origin'] = origin if cors_allowed? end def cors_allowed? origin == ALLOWED_ORIGN || Rails.env.development? end def origin request.headers['HTTP_ORIGIN'] || '' end end
require 'rails_helper' RSpec.describe Bill, type: :model do # Validations Tests it { should validate_presence_of(:ext_id) } it { should validate_presence_of(:description) } # Associations Tests it { should belong_to(:user) } end
Node = Struct.new(:word, :definition, :next_node) class LinkedList attr_accessor :head, :last def initialize(first_node = nil) @head = first_node @last = first_node end # Big O time = O(n) def read(index = 99999999999) counter = 0 current_node = @head while index >= counter puts "Node at index #{counter}: #{current_node.word}" break if current_node.next_node.nil? current_node = current_node.next_node counter += 1 end end def count counter = 1 current_node = @head loop do break if current_node.next_node.nil? current_node = current_node.next_node counter += 1 end counter end # Big O time = O(1) def add_first_node(word) @head = Node.new(word, nil) @last = @head end # Big O time = O(n) def add_at_index(index, word) counter = 0 current_node = @head loop do if counter+1 == index new_node = Node.new(word, current_node.next_node) current_node.next_node = new_node current_node = new_node break end current_node = current_node.next_node counter += 1 break if current_node.next_node.nil? end end def add_node(word) if @head.nil? add_first_node(word) else new_node = Node.new(word, nil) @last.next_node = new_node @last = new_node end # puts "Added a node with value #{word}" end def add_definition(word, definition) counter = 0 current_node = @head until current_node.word == word if current_node.next_node.nil? puts "Cannot find #{word}" break end current_node = current_node.next_node counter += 1 end current_node.definition = definition current_node end def find(word) counter = 0 current_node = @head until current_node.word == word if current_node.next_node.nil? puts "Cannot find #{word}" break end current_node = current_node.next_node counter += 1 end puts "It took #{counter+1} steps to find #{word}." unless current_node.next_node.nil? current_node end # Big O time = O(n) - is "in place" and iterates once through list def reverse #Get the last item in the new reversed list temp_head = self.shift temp_head.next_node = nil @last = temp_head until @head == nil temp = self.shift temp.next_node = temp_head temp_head = temp end @head = temp_head end def shift temp = @head @head = @head.next_node temp end end class HashTable attr_reader :counter, :buckets def initialize(buckets = []) @buckets = buckets @render = {} @counter = 0 end def hash(word) word[0].downcase.ord - 97 end def insert(word) @buckets[hash(word)] = LinkedList.new if @buckets[hash(word)].nil? @buckets[hash(word)].add_node(word) end def render_list 26.times do |i| next if @buckets[i].nil? @render[(i + 97).chr] = @buckets[i].count end p @render end def define(word) definition = @buckets[hash(word)].find(word).definition if definition.nil? puts "Sorry, definition not found" else puts "The definition of #{word} is '#{definition}'." definition end end def add_definition(word, definition) @buckets[hash(word)].add_definition(word,definition) end end class Dictionary_Loader def initialize(file) @file = file end def load dict = File.open(@file, "r") words = dict.readlines words.map! { |word| word.strip } end end table = HashTable.new dictionary = Dictionary_Loader.new("dictionary.txt") dictionary.load.each do |word| table.insert(word) end table.render_list word = "Szechwan" t = Time.now 10000.times {|i| table.buckets[table.hash(word)].find(word); puts i} total = Time.now - t print "It took an average of #{(Time.now - t)/10000} seconds" print " and a total time of #{total} seconds\n"
class ProductsController < ApplicationController def index @products = Product.where("active = true") respond_to do |format| format.html format.csv { render text: @products/index.to_csv } end end def create price = product_params[:price] @product = Product.new(product_params) @product.active = true price = (price.to_f * 100).to_i @product.price = price if @product.save redirect_to products_path else render :new end end def new end def edit @product = Product.find(params[:id]) @product.price = sprintf('%.2f', (@product.price/100).to_f) end def update @product = Product.find(params[:id]) h = product_params.to_h price = h[:price] price = (price.to_f * 100).to_i h[:price] = price puts h if @product.update(h) redirect_to products_path else render :edit end end private def product_params params.require(:product).permit(:name, :stock, :price, :active) end end
class RemoveAuthorTableAddAuthorToBook < ActiveRecord::Migration def up drop_table :authors add_column :books, :author, :string remove_column :books, :author_id end def down create_table :authors t.string :first_name t.string :last_name t.timestamps remove_column :books, :author add_column :books, :author_id, :integer end end
class RemoveRedundantFromOrders < ActiveRecord::Migration def change remove_column :orders, :payment_type_id_id, :string end end
class CustomersController < ApplicationController def index @customers = Customer.all end def alphabetized @ordered_customers = Customer.order("name") end def missing_email @missing_emails = Customer.where("email IS ''") end end
class CurrencyConverter attr_accessor :dollar, :euro, :number @number = 15 @conversions = {} def initialize(number,from_currency,to_currency) @number = number @from_currency = from_currency @to_currency = to_currency @conversions = {:euro => 0.79,:yen => 108.14,:pound => 0.62,:gold => 0.00082} end def get_conversion (@number * @conversions[@to_currency]).round(2) end end class Currency #c = CurrencyConverter.new(15,:dollar,:euro) p "15 dollars is equivalent of #{CurrencyConverter.new(15,:dollar,:euro).get_conversion} euros" #c = CurrencyConverter.new(15,:dollar,:yen) p "15 dollars is equivalent of #{CurrencyConverter.new(15,:dollar,:yen).get_conversion} yen" #c = CurrencyConverter.new(15,:dollar,:pound) p "15 dollars is equivalent of #{CurrencyConverter.new(15,:dollar,:pound).get_conversion} pound" #c = CurrencyConverter.new(15,:dollar,:gold) p "15 dollars is equivalent of #{CurrencyConverter.new(15,:dollar,:gold).get_conversion} ounce of Gold" end
class AddPointsToGrades < ActiveRecord::Migration def change add_column :grades, :points, :decimal, precision: 3, scale: 1 # precision: number of digits in the total number (biggest is 10.0); scale: number of digits after dot (from .0 to .9) end end
require "rails_helper" RSpec.describe Api::V4::CallResultTransformer do describe "#from_request" do context "when patient_id is missing in payload" do it "adds a fallback patient_id using the appointment_id if missing" do appointment = create(:appointment) expect(Api::V4::CallResultTransformer.from_request( {"appointment_id" => appointment.id, "patient_id" => nil} )["patient_id"]).to eq(appointment.patient_id) end it "includes discarded appointments while filling up fallback patient_id" do appointment = create(:appointment, deleted_at: Time.now) expect(Api::V4::CallResultTransformer.from_request( {"appointment_id" => appointment.id, "patient_id" => nil} )["patient_id"]).to eq(appointment.patient_id) end it "returns the hash as is if the appointment is missing" do expect(Api::V4::CallResultTransformer.from_request( {"appointment_id" => SecureRandom.uuid, "patient_id" => nil} )["patient_id"]).to eq(nil) end end context "when patient_id is supplied in payload" do it "doesn't use a fallback patient_id" do patient_id = SecureRandom.uuid expect(Api::V4::CallResultTransformer.from_request( {"appointment_id" => SecureRandom.uuid, "patient_id" => patient_id} )["patient_id"]).to eq(patient_id) end end context "when facility_id is missing in payload" do it "adds a fallback facility ID if it is supplied" do fallback_id = SecureRandom.uuid expect(Api::V4::CallResultTransformer.from_request( {"appointment_id" => SecureRandom.uuid, "facility_id" => nil}, fallback_facility_id: fallback_id )["facility_id"]).to eq(fallback_id) end end context "when facility_id is supplied in payload" do it "doesn't add the fallback facility ID" do facility_id = SecureRandom.uuid expect(Api::V4::CallResultTransformer.from_request( {"appointment_id" => SecureRandom.uuid, "facility_id" => facility_id} )["facility_id"]).to eq(facility_id) end end end end
# encoding: utf-8 require 'spec_helper' describe TTY::Table::Operation::Wrapped, '#wrap' do let(:padding) { TTY::Table::Padder.parse } let(:instance) { described_class.new([], padding) } let(:text) { 'ラドクリフ、マラソン五輪代表に1万m出場にも含み' } subject { instance.wrap(text, width) } context 'without wrapping' do let(:width) { 8 } it { is_expected.to eq("ラドクリフ、マラ\nソン五輪代表に1\n万m出場にも含み") } end context 'with wrapping' do let(:width) { 100 } it { is_expected.to eq(text) } end end
class Demographic < ActiveRecord::Base belongs_to :participant belongs_to :race validates_presence_of :race, :sex, :participant delegate :name, :to => :race, :prefix => true acts_as_reportable :except => ['created_at', 'updated_at'] end
json.metadata do json.total_pages @pagy.pages json.current_page @pagy.page json.per_page @pagy.items json.count @pagy.count end json.book_activity do json.borrower_id @conversation.borrower_id json.borrower_type @conversation.borrower_type json.borrower_name @conversation.borrower.full_name json.lender_id @conversation.lender_id json.lender_type @conversation.lender_type json.lender_name @conversation.lender.full_name json.book_title @book_activity.book.title end json.messages do json.array! @messages do |message| json.id message.id json.conversation_id message.conversation_id json.content message.content json.sender_type message.sender_type json.sender_id message.sender_id json.sender_name message.sender_name json.created_at message.created_at end end
require 'rails_helper' describe QuestionsController, type: :controller do let(:user) { create(:user) } let(:question) { create(:question, user: user) } describe 'GET #index' do let(:questions) { create_list(:question, 12) } before { get :index } it('should populate questions') { expect(assigns(:questions)).to match_array questions.reverse.take(10) } it('should render index view') { expect(response).to render_template :index } end describe 'GET #show' do before do sign_in user get :show, id: question end it('should assign existing question as @question') { expect(assigns(:question)).to eq(question) } end describe 'GET #new' do before do sign_in user get :new end it('should assign new question as @question') { expect(assigns(:question)).to be_a_new(Question) } end describe 'GET #edit' do it 'should assign existing question as @question' do sign_in user xhr :get, :edit, id: question expect(assigns(:question)).to eq(question) end end describe 'POST #create' do context 'with valid attributes' do before { sign_in user } it 'should create a Question ' do expect do post :create, question: attributes_for(:question) end.to change(Question, :count).by(1) end it 'should redirect to show' do post :create, question: attributes_for(:question) expect(response).to redirect_to question_path(assigns(:question)) end it 'should set current user as question creator' do post :create, question: attributes_for(:question) expect(Question.last.user).to eq user end end context 'with invalid attributes' do before { sign_in user } it 'should not save invalid question' do post :create, question: attributes_for(:invalid_question) expect(assigns(:question)).to be_a_new Question end it 're-renders the \'new\' template' do post :create, question: attributes_for(:invalid_question) expect(response).to render_template('new') end end end describe 'PATCH #update' do before { sign_in user } context 'with valid attributes' do it 'should assign requested question to @question' do xhr :patch, :update, id: question, question: attributes_for(:question) expect(assigns(:question)).to eq question expect(response).to be_ok end it 'changes question attributes' do xhr :patch, :update, id: question, question: {title: 'changed title', body: 'changed body'} question.reload expect(question.title).to eq 'changed title' expect(question.body).to eq 'changed body' end end context 'with invalid attributes' do it 'should assign requested question to @question' do xhr :patch, :update, id: question, question: {title: nil, body: nil} expect(assigns(:question)).to eq question expect(response).to render_template('questions/update') end end end describe 'DELETE #destroy' do before { sign_in user } it 'should delete the question' do question expect { delete :destroy, id: question }.to change(Question, :count).by(-1) expect(response).to redirect_to questions_path end end end
class Ingredient < ActiveRecord::Base has_many :foods has_many :recipes, :through => :foods validates :name, :presence => true attr_accessor :value def as_json(options={}) {:value => name} end class << self def names_to_ids(ingredients, to_s = false) where(:name => ingredients).select('id').map{|e| (to_s && e.id.to_s) || e.id} end end end
class Grid def initialize width, height @width = width @height = height @grid = {} @grid.default = false end def alive_neighbours x, y n = 0 neighbour_coordinates(x, y) { | cx, cy | n = n+1 if alive?(cx, cy) } n end def alive? x, y @grid[{x: x, y: y}] end def alive! x, y @grid[{x: x, y: y}] = true end def cells for i in 0..@width-1 do for j in 0..@height-1 do yield i, j end end end def new_of_same_size Grid.new @width, @height end def eq? other @grid == other.grid end alias_method :==, :eql? def grid @grid end private def neighbour_coordinates x, y for i in -1..1 do for j in -1..1 do yield x+i, y+j if i != 0 or j != 0 end end end end
require File.join(File.dirname(__FILE__), 'spec_helper') require 'barby/outputter/rmagick_outputter' include Barby class TestBarcode < Barcode def initialize(data) @data = data end def encoding @data end end describe RmagickOutputter do before :each do @barcode = TestBarcode.new('10110011100011110000') @outputter = RmagickOutputter.new(@barcode) end it "should register to_png, to_gif, to_jpg, to_image" do Barcode.outputters.should include(:to_png, :to_gif, :to_jpg, :to_image) end it "should have defined to_png, to_gif, to_jpg, to_image" do @outputter.should respond_to(:to_png, :to_gif, :to_jpg, :to_image) end it "should return a string on to_png and to_gif" do @outputter.to_png.should be_an_instance_of(String) @outputter.to_gif.should be_an_instance_of(String) end it "should return a Magick::Image instance on to_image" do @outputter.to_image.should be_an_instance_of(Magick::Image) end it "should have a width equal to the length of the barcode encoding string * x dimension" do @outputter.xdim.should == 1#Default @outputter.width.should == @outputter.barcode.encoding.length @outputter.xdim = 2 @outputter.width.should == @outputter.barcode.encoding.length * 2 end it "should have a full_width equal to the width + left and right margins" do @outputter.xdim.should == 1 @outputter.margin.should == 10 @outputter.full_width.should == (@outputter.width + 10 + 10) end it "should have a default height of 100" do @outputter.height.should == 100 @outputter.height = 200 @outputter.height.should == 200 end it "should have a full_height equal to the height + top and bottom margins" do @outputter.full_height.should == @outputter.height + (@outputter.margin * 2) end end describe "Rmagickoutputter#to_image" do before :each do @barcode = TestBarcode.new('10110011100011110000') @outputter = RmagickOutputter.new(@barcode) @image = @outputter.to_image end it "should have a width and height equal to the outputter's full_width and full_height" do @image.columns.should == @outputter.full_width @image.rows.should == @outputter.full_height end end
#This class allows us to create products passed through the admin interface and get information and udpate. CRUD. class ProductsController < ApplicationController respond_to :json acts_as_token_authentication_handler_for User, except: [:index, :show] #This method allows us to create all products from given array in JSON to db. def create product = Product.create(product_params) #Respond with status with given json if product(s) created if product.all?(&:save) render json: { status: 200, message: "Successfully created the product(s)."}.to_json else render json: { status: 400, message: "Error, could not save the product. Please check all fields." }.to_json end end #This method allows us to pull products by id and display information def show product = Product.find(params[:id]) render json: product end #This method gets list of all products def index products = Product.all render json: products end #This method allows us to update price attribute of given product def update product = Product.find(params[:id]) product.price = params[:price] product.save #Respond with status with given json if saved. if product.save render json: { status: 200, message: "Successfully updated the price."}.to_json else render json: { status: 400, message: "Error, could not update the price. Please check all fields." }.to_json end end private def product_params params.permit(products: [:name, :brand, :model, :sku, :price, :desc]).require(:products) end end
# frozen_string_literal: true # Contains the version of NdrError. Sourced by the gemspec. module NdrError VERSION = '2.2.1'.freeze end
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html get "/aboutUs", to: "pages#aboutUs" get "/contact_us", to: "pages#contact_us" get "/main", to: "pages#main" end
class QuestionResource < JSONAPI::Resource attributes :html, :position, :out_of, :objectives, :test_paper has_one :main_question end
# filename: test_initialize.rb require "minitest/autorun" require_relative "../../Word.rb" ## # tests the initialize method class TestInitialize < Minitest::Test # instantiating a new tile group # like an @Before in JUnit4 def setup @newTileGroup = Word.new end # unit tests for the TileGroup:: initialize method def test_create_empty_word assert true,@newTileGroup.tiles.empty? end end
class Piece attr_accessor :position attr_reader :color def initialize(color, position, board) @color = color @position = position @board = board end def inspect { color: @color, pos: @position } end def moves raise NotImplementedError.new end def empty? false end end class SlidingPiece < Piece def moves moves = [] move_dirs.each do |direction| new_pos = @position until @board.hit_enemy_piece?(new_pos, @color) new_pos = [new_pos[0] + direction[0], new_pos[1] + direction[1]] break if @board.hit_object?(new_pos, @color) moves << new_pos end end moves end def move_dirs raise NotImplementedError.new end end class Queen < SlidingPiece def move_dirs [[1,0],[0,1],[1,1],[1,-1],[-1,0],[0,-1],[-1,-1],[-1,1]] end def to_s @color == :b ? "♛" : "♕" end end class Rook < SlidingPiece def move_dirs [[1,0],[0,1],[-1,0],[0,-1]] end def to_s @color == :b ? "♜" : "♖" end end class Bishop < SlidingPiece def move_dirs [[1,1],[1,-1],[-1,-1],[-1,1]] end def to_s @color == :b ? "♝" : "♗" end end class SteppingPiece < Piece def moves moves = [] move_diffs.each do |diff| new_pos = @position new_pos = [new_pos[0] + diff[0], new_pos[1] + diff[1]] moves << new_pos unless @board.hit_object?(new_pos, @color) end moves end def move_diffs puts "this is the SteppingPiece superclass" end end class Knight < SteppingPiece def move_diffs [[2,1],[2,-1],[-2,1],[-2,-1],[1,2],[1,-2],[-1,2],[-1,-2]] end def to_s @color == :b ? "♞" : "♘" end end class King < SteppingPiece def move_diffs [[1,0],[0,1],[1,1],[1,-1],[-1,0],[0,-1],[-1,-1],[-1,1]] end def to_s @color == :b ? "♚" : "♔" end end class Pawn < Piece def moves direction = (@color == :b ? 1 : -1) forward_moves(direction) + diagonal_moves(direction) end def to_s @color == :b ? "♟" : "♙" end private def forward_moves(direction) moves = [] row, col = @position moved = (@color == :b ? row != 1 : row != 6) # move one space forward new_pos = [row + 1 * direction, col] unless @board.off_board?(new_pos) || @board.occupied?(new_pos) moves << new_pos # move 2 spaces forward (only if moving 1 space works) new_pos = [row + 2 * direction, col] unless @board.off_board?(new_pos) || @board.occupied?(new_pos) || moved moves << new_pos end end moves end def diagonal_moves(direction) moves = [] [-1, 1].each do |i| new_pos = [@position[0] + 1 * direction, @position[1] + i] moves << new_pos if @board.hit_enemy_piece?(new_pos, @color) end moves end end class EmptySquare def initialize end def to_s " " end def empty? true end def moves raise "this is an empty square" end end
class Article < ActiveRecord::Base has_many :collections has_many :users, through: :collections end
require_relative "../lib/scraper.rb" require_relative "../lib/student.rb" require 'nokogiri' require 'colorize' class CommandLineInterface INDEX_URL = "http://learn-co-curriculum.github.io/student-scrape-site/" BASE_PROFILE_URL = "http://learn-co-curriculum.github.io/student-scrape-site/profile.html" BASE_URL = "http://students.learn.co" def run self.make_students self.add_attributes_to_students self.display_students make_students add_attributes_to_students display_students end def make_students students_array = Scraper.scrape_index_page(INDEX_URL) students_array = Scraper.scrape_index_page(BASE_URL) Student.create_from_collection(students_array) end def add_attributes_to_students Student.all.each do |student| profile_url = BASE_PROFILE_URL # + "#{student.name}" attributes = Scraper.scrape_profile_page(profile_url) attributes = Scraper.scrape_profile_page(student.profile_url) student.add_student_attributes(attributes) end end @@ -40,4 +37,4 @@ def display_students end end end
class Export::ActivityImplementingOrganisationColumn def initialize(activities_relation:) @activities = valid_activities(activities_relation) end def headers ["Implementing organisations"] end def rows return [] if @activities.empty? @activities.includes(:extending_organisation, :implementing_organisations).map { |activity| implementing_organisation_names = if activity.programme? extending_organisation_name_for_activity(activity) else implementing_organisation_names_for_activity(activity) end [activity.id, [implementing_organisation_names.join("|")]] }.to_h end private def extending_organisation_name_for_activity(activity) [activity.extending_organisation.name] end def implementing_organisation_names_for_activity(activity) activity.implementing_organisations.map { |organisation| organisation.name } end def valid_activities(activities) raise ArgumentError.new("activities must be an ActiveRecord:Relation") unless activities.is_a?(ActiveRecord::Relation) activities end end
class NewStructureChangeContext < BaseContext attr_accessor :audit_report, :measure_selection delegate :measure, :measure_name, to: :measure_selection def available_structure_types measure.structure_types.select do |structure_type| structure_type_definition = measure.structure_type_definition_for(structure_type) if !structure_type_definition.multiple? && measure_selection.has_structure_change_for(structure_type) false else true end end end def grouped_structures_options(structure_type) grouped_structures_for_structure_type(structure_type).map do |structure| [structure.description_with_quantity, structure.id] end + [['New structure...', '']] end private def all_structures_for_structure_type(structure_type) audit_report.all_structures.select do |temp_structure| temp_structure.structure_type.api_name == structure_type.api_name || temp_structure.structure_type.genus_api_name == structure_type.api_name end end def grouped_structures_for_structure_type(structure_type) structures = all_structures_for_structure_type(structure_type) StructureListGrouper.new(measure_selection, structure_type, structures) .grouped_structures end memoize :grouped_structures_for_structure_type end
class Space class << self attr_accessor :width, :height, :background_color, :things def size [@width, @height] end def size=(value) @width, @height = value end end attr_accessor :width, :height, :background_color, :things def initialize @width, @height = self.class.size @background_color = self.class.background_color || Color['#ccc'] @things = self.class.things.inject([]) do |memo, data| type, positions = data positions.each do |position| memo << type.new(*position) end memo end end def update(elapsed, game) @things.each do |thing| thing.update(game) end end def draw(display) display.fill_color = @background_color display.clear @things.each { |t| t.draw(display) } end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe 'Visitor signs up', type: :feature do scenario 'with valid email and password' do sign_up_with 'valid@example.com', 'password' expect(page).to have_content('Mon Espace Client') end scenario 'with invalid email' do sign_up_with 'invalid_email', 'password' expect(page).to have_content('S\'inscrire') end scenario 'with blank password' do sign_up_with 'valid@example.com', '' expect(page).to have_content('S\'inscrire') end end
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure(2) do |config| config.vm.box = "ubuntu/trusty64" config.vm.network "private_network", ip: "192.168.77.7" config.vm.provision "shell", path: ".bin/bootstrap.sh" config.vm.provision "shell", privileged: false, inline: "curl -s -o- https://raw.githubusercontent.com/creationix/nvm/v0.31.1/install.sh | bash" end
namespace :db do desc "Fill database with sample data" task populate: :environment do make_users make_relationships make_posts make_comments end end def make_users User.create!(username: "FinalDevil", email: "anhhung1303@gmail.com", password: "naruto", password_confirmation: "naruto") 99.times do |n| username = Faker::Name.first_name email = "example-#{n+1}@railstutorial.org" password = "password" User.create!(username: username, email: email, password: password, password_confirmation: password) end end def make_posts users = User.limit(10) 50.times do title = Faker::Lorem.sentence(2) body = Faker::Lorem.paragraph(15) users.each { |user| user.posts.create!(title: title, body: body) } end end def make_relationships users = User.all user = users.first followed_users = users[2..50] followers = users[3..50] followed_users.each { |followed| user.follow!(followed) } followers.each { |follower| follower.follow!(user) } end def make_comments users = User.limit(10) posts = Post.limit(20) 30.times do content = Faker::Lorem.paragraph(3) posts.each do |post| post.comments.create!(user_id: Faker::Number.number(2), content: content) end end end
# frozen_string_literal: true # == Schema Information # # Table name: interviewees # # id :bigint(8) not null, primary key # auth_code :string # created_at :datetime not null # updated_at :datetime not null # user_id :bigint(8) # # Indexes # # index_interviewees_on_user_id (user_id) # # Foreign Keys # # fk_rails_... (user_id => users.id) # class Interviewee < ApplicationRecord belongs_to :user has_many :attempts validates_presence_of :user_id before_save :set_auth_code def set_auth_code self.auth_code = ("A".."Z").to_a.sample(8).join if auth_code.nil? end def full_name user.full_name end end
class ApplicationController < ActionController::Base include Pundit protect_from_forgery before_action :configure_sanitized_parameters, if: :devise_controller? before_action :set_locale after_action :verify_authorized, unless: :devise_controller? after_action :track_action # Used to set meta data in headers. def injectable_meta set_meta_tags title: "#{controller_name.humanize.titleize + ' - ' + action_name.capitalize}", description: 'NoBull Software Co.\'s NoBull Website Ordering Thingy™!👋' , keywords: 'webapp, web site development, business information', index: false, nofollow: true, icon: [ { href: "#{ActionController::Base.helpers.asset_path('favicon.ico')}"}, { href: "#{ActionController::Base.helpers.asset_path('favicon-96x96.png')}", sizes: '32x32 96x96', type: 'image/png' }, { href: "#{ActionController::Base.helpers.asset_path('apple-icon.png')}", rel: 'apple-touch-icon-precomposed', sizes: '32x32', type: 'image/png' }, ] end # def get_location_detected_locale # location = request.location # return nil unless location.present? && location.country_code.present? && I18n.available_locales.include?(location.country_code) # location.country_code.include?("-") ? location.country_code : location.country_code.downcase # end protected def configure_sanitized_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:name, :business_name, :direct_phone_number, :has_current_website, :current_website, :city, :region, :postal_code]) devise_parameter_sanitizer.permit(:account_update, keys: [:name, :business_name, :direct_phone_number, :has_current_website, :current_website, :city, :region, :postal_code]) end def track_action ahoy.track "Ran action", request.path_parameters end def set_locale # explicit param can always override existing setting # otherwise, make sure to allow a user preference to override any automatic detection # then detect by location, and header # if all else fails, fall back to default I18n.locale = params[:locale] || session[:locale] || location_detected_locale session[:locale] = I18n.locale end def location_detected_locale location = request.location if location.present? && location.country_code.present? && location.country_code == "GB" location.country_code.downcase elsif location.present? && location.region.present? && location.region == "British Columbia" location.region.downcase.split.join('_') elsif location.present? && location.region.present? && location.region == "Alberta" location.region.downcase else I18n.default_locale end end end
numbers = (1..10).to_a def my_select(array) results =[] array.each do |element| results << element if yield(element) end results end puts my_select(numbers) { |n| n.even? }
describe TodoBot::List, type: :model do describe 'relations' do it { is_expected.to belong_to(:chat) } it { is_expected.to belong_to(:user) } it { is_expected.to have_many(:tasks) } end end
# frozen_string_literal: true # This file was generated by the `rspec --init` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # The generated `.rspec` file contains `--require spec_helper` which will cause # this file to always be loaded, without a need to explicitly require it in any # files. # # Given that it is always loaded, you are encouraged to keep this file as # light-weight as possible. Requiring heavyweight dependencies from this file # will add to the boot time of your test suite on EVERY test run, even for an # individual file that may not need all of that loaded. Instead, consider making # a separate helper file that requires the additional dependencies and performs # the additional setup, and require it from the spec files that actually need # it. require "simplecov" SimpleCov.start require "tempfile" require "pdf-reader" require "./lib/renalware/forms" def pdf_reader_from(prawn_doc) file = Tempfile.new("pdf") prawn_doc.render_file file PDF::Reader.new(file) end def test_prawn_doc Prawn::Document.new( page_size: "A4", page_layout: :portrait, margin: 15 ) end def default_test_arg_values { provider: :generic, version: 1, modality: "HD", telephone: "", hospital_number: nil, nhs_number: nil, consultant: nil, postcode: nil, hospital_department: nil, hospital_telephone: nil, prescriber_name: nil, po_number: "134", administration_device: nil, given_name: "John", family_name: "SMITH", title: "Mr", no_known_allergies: true, allergies: [], drug_type: :esa, born_on: "2019-01-01", prescription_date: "2019-01-01" }.dup end def extract_text_from_prawn_doc(doc) pdf_reader_from(doc).pages.map(&:text).join end # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration RSpec.configure do |config| config.expect_with :rspec do |expectations| expectations.include_chain_clauses_in_custom_matcher_descriptions = true end config.mock_with :rspec do |mocks| mocks.verify_partial_doubles = true end config.shared_context_metadata_behavior = :apply_to_host_groups end
ServieSales::Admin.controllers :servers do get :index do @title = "Servers" @servers = Server.all render 'servers/index' end get :new do @title = pat(:new_title, :model => 'server') @server = Server.new render 'servers/new' end post :create do @server = Server.new(params[:server]) if @server.save @title = pat(:create_title, :model => "server #{@server.id}") flash[:success] = pat(:create_success, :model => 'Server') params[:save_and_continue] ? redirect(url(:servers, :index)) : redirect(url(:servers, :edit, :id => @server.id)) else @title = pat(:create_title, :model => 'server') flash.now[:error] = pat(:create_error, :model => 'server') render 'servers/new' end end get :edit, :with => :id do @title = pat(:edit_title, :model => "server #{params[:id]}") @server = Server.find(params[:id]) if @server render 'servers/edit' else flash[:warning] = pat(:create_error, :model => 'server', :id => "#{params[:id]}") halt 404 end end put :update, :with => :id do @title = pat(:update_title, :model => "server #{params[:id]}") @server = Server.find(params[:id]) if @server if @server.update_attributes(params[:server]) flash[:success] = pat(:update_success, :model => 'Server', :id => "#{params[:id]}") params[:save_and_continue] ? redirect(url(:servers, :index)) : redirect(url(:servers, :edit, :id => @server.id)) else flash.now[:error] = pat(:update_error, :model => 'server') render 'servers/edit' end else flash[:warning] = pat(:update_warning, :model => 'server', :id => "#{params[:id]}") halt 404 end end delete :destroy, :with => :id do @title = "Servers" server = Server.find(params[:id]) if server if server.destroy flash[:success] = pat(:delete_success, :model => 'Server', :id => "#{params[:id]}") else flash[:error] = pat(:delete_error, :model => 'server') end redirect url(:servers, :index) else flash[:warning] = pat(:delete_warning, :model => 'server', :id => "#{params[:id]}") halt 404 end end delete :destroy_many do @title = "Servers" unless params[:server_ids] flash[:error] = pat(:destroy_many_error, :model => 'server') redirect(url(:servers, :index)) end ids = params[:server_ids].split(',').map(&:strip) servers = Server.find(ids) if Server.destroy servers flash[:success] = pat(:destroy_many_success, :model => 'Servers', :ids => "#{ids.to_sentence}") end redirect url(:servers, :index) end end
Rails.application.routes.draw do # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". get "secrets/new" root "application#hello" get "/login" => "sessions#new" post "/login" => "sessions#create" post "/logout" => "sessions#destroy" get "/secret" => "secrets#show" end
def prompt(message) puts "=> #{message}" end def valid_number?(string) string == (string.to_i).to_s end def number?(string) string == (string.to_f).to_s end def english(count) result = case count when 1 "#{count}st" when 2 "#{count}nd" when 3 "#{count}rd" when 4 "#{count}th" when 5 "#{count}th" end result end count = 1 number_array = [] number = '' loop do loop do prompt("Enter #{english(count)} number:") number = gets.chomp if valid_number?(number) || number?(number) break else prompt("Invalid input.") end end number_array << number.to_i count += 1 break if count == 6 end puts "Enter number the last number:" number = gets.chomp puts number_array.include?(number.to_i) ? "The number #{number.to_i} appears in #{number_array}." : "The number #{number.to_i} does not appear in #{number_array}."
class QuotePdfExportMailer < ApplicationMailer def quote_pdf_export(representative_id, user_id, account_ids) @representative = Representative.find(representative_id) @user = User.find(user_id) @account_ids = account_ids @num_accounts = @account_ids.length @zip_file_url = @representative.zip_file.url mail(:to => @user.email, :subject => "#{ @representative.abbreviated_name} Quote Zip File") end end
describe StateMachines::Machine do before(:each) do klass = Class.new do def self.name @name ||= "Vehicle_#{rand(1_000_000)}" end end @machine = StateMachines::Machine.new(klass, initial: :parked) @machine.event :ignite do transition parked: :idling end end it 'should not raise exception' do expect { @machine.draw }.not_to raise_error end end
class User < ApplicationRecord # GEM PARANOIA acts_as_paranoid # END GEM PARANOIA #cloudiary photo has_attachment :photo # VALIDATIONS AND ASSOCIATIONS FROM DEVISE GEM # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable # :facebook is an array, you can add twitter etc. devise :omniauthable, omniauth_providers: [:facebook] # END VALIDATIONS AND ASSOCIATIONS FROM DEVISE GEM # VALIDATIONS AND ASSOCIATIONS validates :first_name, :last_name, presence: true has_many :hotels_as_owner, foreign_key: :user_id, class_name: 'Hotel', dependent: :destroy has_many :stays has_many :messages, through: :stays has_many :hotels, through: :stays has_many :rooms, through: :stays has_many :bookings has_many :services, through: :bookings # END VALIDATIONS AND ASSOCIATIONS FROM # facebook sign in sign up def self.find_for_facebook_oauth(auth) user_params = auth.slice(:provider, :uid) user_params.merge! auth.info.slice(:email, :first_name, :last_name) user_params[:facebook_picture_url] = auth.info.image user_params[:token] = auth.credentials.token user_params[:token_expiry] = Time.at(auth.credentials.expires_at) user_params = user_params.to_h user = User.find_by(provider: auth.provider, uid: auth.uid) user ||= User.find_by(email: auth.info.email) # User did a regular sign up in the past. if user user.update(user_params) else user = User.new(user_params) user.password = Devise.friendly_token[0,20] # Fake password for validation user.save end return user end def koala @graph = Koala::Facebook::API.new(token) end end
require "rails_helper" describe API::V1::CardsAPI do let(:user) { build :user } let(:card) { build :card, user: user } let(:card_interactor) { instance_spy CardInteractor } let(:card_repository) { instance_spy CardRepository } before do Grape::Endpoint::before_each do |endpoint| allow(endpoint).to receive(:card_interactor).and_return(card_interactor) allow(endpoint).to receive(:card_repository).and_return(card_repository) allow(endpoint).to receive(:validate_api_key).and_return(user) allow(endpoint).to receive(:current_user).and_return(user) end end after { Grape::Endpoint.before_each(nil) } endpoint "GET /api/v1/cards" do let(:make_request) { get path } describe "response body" do before do allow(card_repository).to receive(:find_by_user).with(user).and_return([card]) end subject { response.body } it do make_request expect(subject).to include_json([{name: card.name, status: card.status}]) end end end endpoint "POST /api/v1/cards" do let(:task_01) { build :task, name: "task_01", description: nil } let(:tasks) { [ { name: task_01.name } ] } let(:params) { { name: card.name, tasks: tasks } } let(:make_request) { post path, params: params } describe "response body" do before do allow(card_interactor).to receive(:create).and_return(card) end subject { response.body } it do make_request expect(subject).to include_json(name: card.name, status: card.status) end end end endpoint "GET /api/v1/cards/:id" do let(:card) { build :card, id: 1 } let(:make_request) { get "/api/v1/cards/#{card.id}" } describe "response body" do before do allow(card_interactor).to receive(:find_by_user_and_card_id).and_return(card) end subject { response.body } it do make_request expect(subject).to include_json(name: card.name, status: card.status) end context "when card not found" do before do allow(card_interactor).to receive(:find_by_user_and_card_id) .and_raise(CardInteractor::CardNotFound) end subject { response.body } it do make_request expect(subject).to include_json(error:"Card not found") end end end end endpoint "PUT /api/v1/cards/:id" do let(:card) { build :card, id: 1 } let(:params) do { id: card.id, name: "My new card name", status: "enabled" } end let(:card_updated) { build :card, params } let(:make_request) { put "/api/v1/cards/#{card.id}", params: params } describe "response body" do before do allow(card_interactor).to receive(:update_from_user_and_attributes) .with(user, params).and_return(card_updated) end subject { response.body } it do make_request attrs = {name: params[:name], status: params[:status]} expect(subject).to include_json(attrs) end context "when card not found" do before do allow(card_interactor).to receive(:update_from_user_and_attributes) .and_raise(CardInteractor::CardNotFound) end subject { response.body } it do make_request expect(subject).to include_json(error:"Card not found") end end end end endpoint "DELETE /api/v1/cards/:id" do let(:card) { build :card, id: 1 } let(:make_request) { delete "/api/v1/cards/#{card.id}" } describe "response body" do before do allow(card_interactor).to receive(:remove_from_user_and_card_id).and_return(card) end subject { response.body } it do make_request expect(subject).to include_json(name: card.name, status: card.status) end context "when card not found" do before do allow(card_interactor).to receive(:remove_from_user_and_card_id) .and_raise(CardInteractor::CardNotFound) end subject { response.body } it do make_request expect(subject).to include_json(error:"Card not found") end end end end end
# Write a program called name.rb that asks the user to type # in their name and then prints out a greeting message with their name included. puts "Please write your name!" name = gets.chomp puts "Hello #{name}, nice to meet you!" # Write a program called age.rb that asks a user # how old they are and then tells them how old they # will be in 10, 20, 30 and 40 years. Below is the # output for someone 20 years old. puts "how old are you?" age = gets.chomp puts "in 10 years you will be" puts age.to_i + 10 puts "in 20 years you will be" puts age.to_i + 20 puts "in 30 years you will be" puts age.to_i + 30 puts "in 40 years you will be" puts age.to_i + 40 # Add another section onto name.rb that prints the name of the user 10 times. # You must do this without explicitly writing the puts method 10 times in a row. name = "john" 10.times {|n| puts name} # Modify name.rb again so that it first asks the user for their # first name, saves it into a variable, and then does the same for # the last name. Then outputs their full name all at once. puts "whats yourfirst name" first_name = gets.chomp puts "what's your last name" last_name = gets.chomp full_name = first_name + " " + last_name puts full_name #What does x print to the screen in each case? Do they # both give errors? Are the errors different? Why? #Answer => the first one shows the number "1" three times. The second # one gives an error because the x was not assigned a value and it was # created within the method
module Components module ProductCard class ProductCardComponent < Middleman::Extension helpers do def product_card(opts) product = opts[:product] concat( link_to("/webshop/#{product.slug}/", class: 'bg-white p-6') do content_tag(:figure, class: 'relative') do product_discount(product, 'absolute right-3 top-3') + image(product) end + content_tag(:div, class: 'flex') do content_tag(:h2, product.title, class: 'flex-grow font-bold mr-2') + content_tag(:div, product.price ? product_price(product) : "", class: 'flex flex-col items-end') end end ) end private def image(product) image_url = product.images.first.url image_tag("#{image_url}?fm=webp&h=540&w=540&auto=enhance&fit=max", alt: product.title, class: 'mb-3', height: '540', width: '540', loading: 'lazy', srcset: "#{image_url}?fm=webp&h=540&w=540&auto=enhance&fit=max&dpr=1 1x, #{image_url}?fm=webp&h=540&w=540&auto=enhance&fit=max&dpr=2 2x, #{image_url}?fm=webp&h=540&w=540&auto=enhance&fit=max&dpr=3 3x") end end end end end ::Middleman::Extensions.register(:product_card_component, Components::ProductCard::ProductCardComponent)
# frozen_string_literal: true if File.exist?("#{File.basename(__dir__)}.gemspec") require 'bundler/gem_tasks' require 'rspec/core/rake_task' RSpec::Core::RakeTask.new(:spec) end require 'rake/version_task' Rake::VersionTask.new require 'rubocop/rake_task' RuboCop::RakeTask.new # -- require 'erb' require 'yaml' # Renders templates class TemplateRenderer def initialize @variables = YAML.load_file('.templates.yml') @variables.each { |key, value| @variables[key] = value.strip } end def method_missing(name) @variables[name.to_s] || super end def respond_to_missing?(name, include_private = false) @variables.key?(name.to_s) || super end def file(path) File.read(path).chomp end def render(path) contents = File.read(path) document = ERB.new(contents) document.result(binding) end end TEMPLATE_RENDERER = TemplateRenderer.new TEMPLATE_INPUT_PATHS = FileList['templates/*.erb'] TEMPLATE_OUTPUT_PATHS = TEMPLATE_INPUT_PATHS.map { |path| File.basename(path, '.erb') } TEMPLATE_PATHS = Hash[TEMPLATE_INPUT_PATHS.zip(TEMPLATE_OUTPUT_PATHS)] TEMPLATE_PATHS.each do |input_path, output_path| file output_path => input_path do puts "Rendering `#{output_path}`" contents = TEMPLATE_RENDERER.render(input_path) File.open(output_path, 'w+') { |file| file.write(contents) } end end desc 'Render templates' task 'templates:build' => TEMPLATE_OUTPUT_PATHS desc 'Clean templates' task 'templates:clean' do TEMPLATE_OUTPUT_PATHS.each do |path| rm_f path end end # -- task default: %w[spec templates:build rubocop:auto_correct]
class HabitDescription < ActiveRecord::Base default_scope { where(ended_at: nil) } belongs_to :user has_many :habits, dependent: :destroy has_many :habit_logs, dependent: :destroy has_many :users, through: :habit_logs has_many :taggings, as: :taggable has_many :tags, through: :taggings before_validation :set_uniquable_name # Validate associations validates :user, presence: true # Validate attributes validates :name, presence: true, length: { maximum: 50 } validates :uniquable_name, uniqueness: { scope: :user } validates :summary, presence: true, length: { maximum: 100 } validates :description, presence: true def in_use? habits_in_use + habit_logs_in_use > 0 end def tag_list tags.all.collect(&:name).sort.join(", ") end def tag_list=(value) end def self.search_by_tags(tag_list:) SearchTaggableByTags.new(tag_list: tag_list).call end private def habits_in_use Habit.where(habit_description_id: id).count end def habit_logs_in_use HabitLog.where(habit_description_id: id).count end def set_uniquable_name self.uniquable_name = Normalizer.new(text: name).call if name_changed? end end
class AddHideButtonsToEvents < ActiveRecord::Migration def change add_column :events, :hide_buttons, :boolean end end
class AiBooksController < ApplicationController before_action :set_ai_book, only: %i[show edit update destroy] # GET /ai_books # GET /ai_books.json def index @ai_books = AiBook.all end # GET /ai_books/1 # GET /ai_books/1.json def show; end # GET /ai_books/new def new @ai_book = AiBook.new end # GET /ai_books/1/edit def edit; end # POST /ai_books # POST /ai_books.json def create @ai_book = AiBook.new(ai_book_params) respond_to do |format| if @ai_book.save format.html { redirect_to @ai_book, notice: 'Ai book was successfully created.' } format.json { render :show, status: :created, location: @ai_book } else format.html { render :new } format.json { render json: @ai_book.errors, status: :unprocessable_entity } end end end # PATCH/PUT /ai_books/1 # PATCH/PUT /ai_books/1.json def update respond_to do |format| if @ai_book.update(ai_book_params) format.html { redirect_to @ai_book, notice: 'Ai book was successfully updated.' } format.json { render :show, status: :ok, location: @ai_book } else format.html { render :edit } format.json { render json: @ai_book.errors, status: :unprocessable_entity } end end end # DELETE /ai_books/1 # DELETE /ai_books/1.json def destroy @ai_book.destroy respond_to do |format| format.html { redirect_to ai_books_url, notice: 'Ai book was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_ai_book @ai_book = AiBook.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def ai_book_params params.require(:ai_book).permit(:name, :summary, :page_count) end end
class Game < ActiveRecord::Base belongs_to :player has_many :pieces, dependent: :destroy after_create :populate_board! belongs_to :white, class_name: 'Player', foreign_key: 'white_player' belongs_to :black, class_name: 'Player', foreign_key: 'black_player' def populate_board! 0.upto(7) do |x| Pawn.create( game_id: self.id, x_position: x, y_position: 1, player_id: self.white_player, color: "white", captured: false) Pawn.create( game_id: self.id, x_position: x, y_position: 6, player_id: self.black_player, color: "black", captured: false) end Rook.create( game_id: self.id, x_position: 7, y_position: 0, player_id: self.white_player, color: "white", captured: false) Rook.create( game_id: self.id, x_position: 7, y_position: 0, player_id: self.white_player, color: "white", captured: false) Rook.create( game_id: self.id, x_position: 0, y_position: 7, player_id: self.black_player, color: "black", captured: false) Rook.create( game_id: self.id, x_position: 0, y_position: 7, player_id: self.black_player, color: "black", captured: false) Bishop.create( game_id: self.id, x_position: 7, y_position: 2, player_id: self.white_player, color: "white", captured: false) Bishop.create( game_id: self.id, x_position: 7, y_position: 5, player_id: self.white_player, color: "white", captured: false) Bishop.create( game_id: self.id, x_position: 0, y_position: 2, player_id: self.black_player, color: "black", captured: false) Bishop.create( game_id: self.id, x_position: 0, y_position: 5, player_id: self.black_player, color: "black", captured: false) Knight.create( game_id: self.id, x_position: 7, y_position: 1, player_id: self.white_player, color: "white", captured: false) Knight.create( game_id: self.id, x_position: 7, y_position: 6, player_id: self.white_player, color: "white", captured: false) Knight.create( game_id: self.id, x_position: 0, y_position: 1, player_id: self.black_player, color: "black", captured: false) Knight.create( game_id: self.id, x_position: 0, y_position: 6, player_id: self.black_player, color: "black", captured: false) King.create( game_id: self.id, x_position: 0, y_position: 4, player_id: self.white_player, color: "white", captured: false) King.create( game_id: self.id, x_position: 7, y_position: 4, player_id: self.black_player, color: "black", captured: false) Queen.create( game_id: self.id, x_position: 0, y_position: 3, player_id: self.white_player, color: "white", captured: false) Queen.create( game_id: self.id, x_position: 7, y_position: 3, player_id: self.black_player, color: "black", captured: false) end end
require 'pry' class Ingredient @@all = [] attr_reader :name def initialize(name) @name =name @@all << self end def self.all @@all end def self.most_common_allergen Allergy.all.each_with_object({}) do |allergy, hash| if hash[allergy.ingredient].nil? hash[allergy.ingredient] = 1 else hash[allergy.ingredient] += 1 end end.max_by { |key, num| num }[0] end end # def self.most_common_allergen # # itirating all # # my_allergy= Allergy.all.select do |allergy| # allergy.ingredient == self # end # binding.pry # my_allergy.max_by {|allergy| ingredient.allergy} # # end # end
# frozen_string_literal: true class CargoWagon < Wagon TYPE = :cargo UNIT = 'м3' def initialize(place) super(TYPE, place) end def take_place(amount) @taken_place += amount if free_place >= amount end end
module Alf module Operator::Relational class Wrap < Alf::Operator() include Operator::Relational, Operator::Transform signature do |s| s.argument :attributes, AttrList, [] s.argument :as, AttrName, :wrapped end protected # (see Operator::Transform#_tuple2tuple) def _tuple2tuple(tuple) wrapped, others = @attributes.split(tuple) others[@as] = wrapped others end end # class Wrap end # module Operator::Relational end # module Alf
require 'rails_helper' describe "merchant discount show page" do before :each do @merchant1 = Merchant.create!(name: 'Knows Hair') @discount_1 = Discount.create!(name: "TENoffTEN", percentage_discount: 10, quantity_threshold: 10, merchant_id: @merchant1.id) @discount_2 = Discount.create!(name: "TWENTYoffTWENTY", percentage_discount: 20, quantity_threshold: 20, merchant_id: @merchant1.id) end it "displays all the discount's attributes including name, percentage discount, and quantity threshold" do visit merchant_discount_path(@merchant1, @discount_1) expect(page).to have_content(@discount_1.name) expect(page).to have_content(@discount_1.percentage_discount) expect(page).to have_content(@discount_1.quantity_threshold) expect(page).to_not have_content(@discount_2.name) visit merchant_discount_path(@merchant1, @discount_2) expect(page).to have_content(@discount_2.name) expect(page).to have_content(@discount_2.percentage_discount) expect(page).to have_content(@discount_2.quantity_threshold) expect(page).to_not have_content(@discount_1.name) end it "has a link to update discount info" do visit merchant_discount_path(@merchant1, @discount_1) click_link "Update Discount" expect(current_path).to eq(edit_merchant_discount_path(@merchant1.id, @discount_1.id)) end end