text
stringlengths
10
2.61M
class CreateArchivedVehiclePositions < ActiveRecord::Migration def change create_table :archived_vehicle_positions do |t| t.integer :vehicle_id t.integer :trip_id t.float :curr_lat t.float :curr_lon t.datetime :curr_timestamp t.float :prev_lat t.float :prev_lon t.float :heading t.float :speed t.float :altitude t.float :accuracy t.float :soc t.float :dte t.float :odometer_reading t.float :distance_from_previous t.float :distance_covered t.point :the_curr_geom, :srid => 32643, :with_z => false t.point :the_prev_geom, :srid => 32643, :with_z => false t.timestamps end end end
require 'spec_helper' RSpec.describe Procedure::Outcome do subject(:outcome) { described_class.new(step_classes) } let(:passed_step) { build_step_class(passed: true) } let(:failed_step) { build_step_class(passed: false) } let(:step_classes) { [FakePassedClass, FakeFailedClass] } context 'passing procedure' do it 'passes procedure when all steps were executed successfuly' do 2.times { outcome.add(passed_step) } expect(outcome).to be_positive end it 'does not pass procedure when not yet all steps were executed' do outcome.add(passed_step) expect(outcome).not_to be_positive end it 'does not pass procedure when one of steps failed' do outcome.add(passed_step) outcome.add(failed_step) expect(outcome).not_to be_positive end end context 'aborting procedure' do it 'aborts procedure when failed step is detected' do outcome.add(failed_step) expect(outcome).to be_failure end it 'does not abort procedure when failed step was not detected' do outcome.add(passed_step) expect(outcome).not_to be_failure end end def build_step_class(passed:) double(passed?: passed) end class FakePassedClass; end class FakeFailedClass; end end
require 'rack' require_relative './lib/controller_base' require_relative './lib/router' class Train attr_reader :origin, :destination, :num_passengers def self.all @trains ||= [] end def initialize(params = {}) @origin = params["origin"] @destination = params["destination"] @num_passengers = params["num_passengers"] end def errors @errors ||= [] end def valid? errors << "Origin can't be blank" unless @origin.present? errors << "Destination can't be blank" unless @destination.present? errors << "Number of passengers can't be blank" unless @num_passengers.present? errors.empty? end def save return false unless valid? Train.all << self true end end class TrainsController < ControllerBase def new @train = Train.new render :new end def create @train = Train.new(params["train"]) if @train.save flash[:notice] = "New Train Added!" redirect_to "/trains" else flash.now[:errors] = @train.errors render :new end end def index @trains = Train.all render :index end end router = Router.new router.draw do get Regexp.new("^/trains/new$"), TrainsController, :new post Regexp.new("^/trains$"), TrainsController, :create get Regexp.new("^/$"), TrainsController, :index get Regexp.new("^/trains$"), TrainsController, :index end app = Proc.new do |env| req = Rack::Request.new(env) res = Rack::Response.new router.run(req, res) res.finish end Rack::Server.start(app: app, Port: 3000)
class AddMessagesCountToRoom < ActiveRecord::Migration def change add_column :rooms, :chats_count, :integer, null: false, default: 0 end end
require "test_helper" describe User do # let(:user) { User.new } # # it "must be valid" do # value(user).must_be :valid? # end describe "relations" do before do user = User.new end it "has a list of products" do user = product(:create) user.must_respond_to :product user.products.each do |product| product.must_be_kind_of Product end end end describe "validations" do it "requires a username" do user = User.new user.valid?.must_equal false user.errors.messages.must_include :username end it "requires a unique username" do username = "test username" user1 = User.new(username: username) # This must go through, so we use create! user1.save! user2 = User.new(username: username) result = user2.save result.must_equal false user2.errors.messages.must_include :username end end end
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure("2") do |config| config.vm.box = "peru/ubuntu-20.04-desktop-amd64" config.vm.box_version = "20220102.01" config.vm.synced_folder "data", "/home/vagrant/data", create: true, owner: "vagrant", group: "vagrant" config.vm.synced_folder "D:\pelis", "/home/vagrant/pelis", owner: "vagrant", group: "vagrant" # eztv # yts-movie config.vm.provider :virtualbox do |vb| vb.name = "ubuntu20" end # Workaround to forward ssh key from Windows Host with Git Bash if Vagrant::Util::Platform.windows? if File.exists?(File.join(Dir.home, ".ssh", "id_rsa")) # Read local machine's SSH Key (~/.ssh/id_rsa) ssh_key = File.read(File.join(Dir.home, ".ssh", "id_rsa")) # Copy it to VM as the /vagrant/.ssh/id_rsa key config.vm.provision :shell, privileged: false, :inline => "echo 'Windows-specific: Copying local SSH Key to VM for provisioning...' && mkdir -p /home/vagrant/.ssh && echo '#{ssh_key}' > /home/vagrant/.ssh/id_rsa && chmod 600 /home/vagrant/.ssh/id_rsa", run: "always" else # Else, throw a Vagrant Error. Cannot successfully startup on Windows without a SSH Key! raise Vagrant::Errors::VagrantError, "\n\nERROR: SSH Key not found at ~/.ssh/id_rsa.\nYou can generate this key manually by running `ssh-keygen` in Git Bash.\n\n" end end # Run a shell script in first run config.vm.provision "shell", privileged: false, inline: <<-SHELL set -euxo pipefail wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add - sudo sh -c 'echo "deb https://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google.list' APT_GET='sudo DEBIAN_FRONTEND=noninteractive apt-get' # Upgrade system $APT_GET update $APT_GET dist-upgrade -y $APT_GET install git google-chrome-stable -y $APT_GET autoremove -y sudo snap refresh sudo snap install vlc # Set keyboard layout gsettings set org.gnome.desktop.input-sources sources "[('xkb', 'es')]" # Set favorite apps gsettings set org.gnome.shell favorite-apps "['firefox.desktop', 'google-chrome.desktop', 'org.gnome.Nautilus.desktop', 'org.gnome.Terminal.desktop', 'vlc_vlc.desktop', 'transmission-gtk.desktop']" # Set up git & configurations git config --global user.name "Guillem Mercadal" git config --global user.email guillem.mercadal@gmail.com ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts rm -fR configurations && git clone git@github.com:akustik/configurations.git # Shared folder permissions sudo chown -R vagrant:vagrant /home/vagrant/data sudo chown -R vagrant:vagrant /home/vagrant/pelis SHELL end
require 'spec_helper' module Netzke::Basepack describe ColumnConfig do it "should implement primary?" do adapter = Netzke::Basepack::DataAdapters::ActiveRecordAdapter.new(Book) c = ColumnConfig.new(:id, adapter) c.primary?.should be_true c = ColumnConfig.new(:title, adapter) c.primary?.should be_false end it "should not set default editor for read-only columns" do adapter = Netzke::Basepack::DataAdapters::ActiveRecordAdapter.new(Book) c = ColumnConfig.new(:title, adapter) c.read_only = true c.set_defaults! c.editor.should be_nil end end end
Fabricator(:service_attribute_value) do service_attribute key { Faker::Lorem.words(1) } name { Faker::Lorem.words(1) } end
class Book < ApplicationRecord has_many :book_borrows end
FactoryGirl.define do factory :request, class: Canvas::API::Request do end factory :account_authentication_service, class: Canvas::AccountAuthenticationService do end factory :account_report, class: Canvas::AccountReport do end factory :account, class: Canvas::Account do end factory :admin, class: Canvas::Admin do end factory :analytic, class: Canvas::Analytic do end factory :assignment_group, class: Canvas::AssignmentGroup do end factory :assignment, class: Canvas::Assignment do end factory :collection, class: Canvas::Collection do end factory :communication_channel, class: Canvas::CommunicationChannel do end factory :conversation, class: Canvas::Conversation do end factory :course, class: Canvas::Course do account_id 1 name 'name' course_code 'course_code' start_at '2012-01-31T00:00:00-04:00' end_at '2013-01-31T00:00:00-04:00' license 'license' is_public true public_description 'public_description' allow_student_wiki_edits true allow_student_assignment_edits true allow_wiki_comments true allow_student_forum_attachments true open_enrollment true self_enrollment true restrict_enrollments_to_course_dates true enroll_me true sis_course_id 'sis_course_id' offer true end factory :discussion_topic, class: Canvas::DiscussionTopic do end factory :enrollment, class: Canvas::Enrollment do end factory :external_tool, class: Canvas::ExternalTool do end factory :uploaded_file, class: Canvas::UploadedFile do end factory :uploaded_folder, class: Canvas::UploadedFolder do end factory :group, class: Canvas::Group do end factory :login, class: Canvas::Login do end factory :role, class: Canvas::Role do end factory :sis_import, class: Canvas::SISImport do end factory :service, class: Canvas::Service do end factory :submission, class: Canvas::Submission do end factory :user, class: Canvas::User do end end
Spree::Taxon.class_eval do def applicable_filters(parent_color: nil ) fs = [] # fs << Spree::Core::ProductFilters.child_color_any(parent_color) # fs << Spree::Core::ProductFilters.parent_and_children_colors_any(taxon: self) fs << Spree::Core::ProductFilters.parent_color_any(taxon: self) fs << Spree::Core::ProductFilters.child_colors_any_by_taxon(taxon: self) fs << Spree::Core::ProductFilters.designer_any(taxon: self) fs << Spree::Core::ProductFilters.fit_any if has_fit? # coat optiopns fs << Spree::Core::ProductFilters.lapel_any if coats? fs << Spree::Core::ProductFilters.buttons_any if coats? # styles fs << Spree::Core::ProductFilters.coat_style_any if coats? fs << Spree::Core::ProductFilters.pant_style_any if pants? fs << Spree::Core::ProductFilters.shirt_style_any if shirts? fs << Spree::Core::ProductFilters.tie_style_any if ties? fs << Spree::Core::ProductFilters.vest_style_any if vests? fs end def simple_name self.name.downcase.gsub(' ', '_') end ALL_TAXONS = Spree::Taxon.all.map(&:simple_name) ALL_TAXONS.each do |taxon| define_method("#{taxon}?") do self.simple_name == taxon ? true : false end end def coats? ["Suits", "Jackets", "Tuxedos", "Coats and Pants"].include? self.name end def has_fit? ["Suits", "Jackets", "Tuxedos", "Pants", "Coats and Pants"].include? self.name end def self.set_positions self.all.each do |taxon| case taxon.name when "Tuxedos" taxon.update_attributes({position: 1}) when "Suits" taxon.update_attributes({position: 2}) when "Vests or Cummerbunds" taxon.update_attributes({position: 3}) when "Vests" taxon.update_attributes({position: 4}) when "Cummerbunds" taxon.update_attributes({position: 4}) when "Shirts" taxon.update_attributes({position: 5}) when "Ties" taxon.update_attributes({position: 6}) when "Shoes" taxon.update_attributes({position: 7}) when "Accessory Packages" taxon.update_attributes({position: 8}) when "Studs & Links" taxon.update_attributes({position: 9}) when "Pants" taxon.update_attributes({position: 10}) end if (taxon.position == 0) || (taxon.position == nil) taxon.update_attributes({position: 100}) end end end # def applicable_filters_without_colors # fs = [] # fs << Spree::Core::ProductFilters.designer_any # fs << Spree::Core::ProductFilters.fit_any if has_fit? # # coat optiopns # fs << Spree::Core::ProductFilters.lapel_any if coats? # fs << Spree::Core::ProductFilters.buttons_any if coats? # # styles # fs << Spree::Core::ProductFilters.coat_style_any if coats? # fs << Spree::Core::ProductFilters.pant_style_any if pants? # fs << Spree::Core::ProductFilters.shirt_style_any if shirts? # fs << Spree::Core::ProductFilters.tie_style_any if ties? # fs << Spree::Core::ProductFilters.vest_style_any if vests? # fs # end end
class Student < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :courses has_many :assessments, through: :courses #has_many :assignments, through: :courses, source: :assessments #allow us to refer to student.assignments #has_many :exams, through: :courses, source: :assessments #student.exams end
class Answer < ActiveRecord::Base belongs_to :answerable, polymorphic: true end
Pod::Spec.new do |s| s.name = 'DMOfferWallSDK' s.version = '6.1.1' s.license = 'Domob' s.summary = 'iOS SDK for Domob OfferWall' s.homepage = 'http://www.domob.cn/' s.author = { 'Domob' => 'support@domob.com' } s.source = { :git => 'https://github.com/gaoyz/DMOfferWallSDK.git', :tag => s.version.to_s } s.description = "iOS SDK for Domob OfferWall" s.platform = :ios s.source_files = '*.h' s.preserve_paths = '*.a' s.libraries = 'StoreHouseSDK', 'sqlite3', 'z' s.xcconfig = { 'LIBRARY_SEARCH_PATHS' => '"$(PODS_ROOT)/DMOfferWallSDK"' } s.frameworks = 'CoreTelephony', 'MessageUI', 'AdSupport', 'CoreMedia', 'AVFoundation', 'StoreKit', 'SystemConfiguration', 'CoreGraphics', 'CoreLocation' s.resources = 'StoreHouseBundle.bundle' end
class Question attr_accessor :id, :q, :result def initialize(params) puts "Params #{params.inspect}" @params = params text = params.split(' ') @id = text[0] @q = text[1..text.count].join(' ') @result = nil end def identify if @q.include? 'which of the following numbers is the largest:' LargestNum elsif @q.include? 'which of the following numbers is both a square and a cube' SquareCube elsif /what is (\d*) plus (\d)/.match(@q) Sum elsif /what is (\d*) minus (\d)/.match(@q) Minus elsif /which of the following numbers are primes: (.*)/.match(@q) PrimeIdentification elsif /what is \d{1,3} to the power of \d{1,3}/.match(@q) ThePowerOf elsif @params.include?('Eiffel tower') Tower else NoIdea end end end
# -*- encoding: utf-8 -*- require File.expand_path('../lib/simple-spreadsheet/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ["Andrea Mostosi"] gem.email = ["andrea.mostosi@zenkay.net"] gem.description = %q{Simple spreadsheet reader for common formats: Excel (.xls, .xlsx), Open-office (.ods) and some CSV (standard, excel, tab separated). Future versions: writing and more formats.} gem.summary = %q{Read and write most common spreadsheet format} gem.homepage = "https://github.com/zenkay/simple-spreadsheet" gem.license = "MIT" gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } gem.files = `git ls-files`.split("\n") gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") gem.name = "simple-spreadsheet" gem.require_paths = ["lib"] gem.version = SimpleSpreadsheet::VERSION # specify any dependencies here; for example: gem.add_development_dependency "bundler", "~> 1.10" gem.add_development_dependency "rake", "~> 10.1" gem.add_development_dependency "rspec","~> 3.3" gem.add_runtime_dependency "roo", "~> 2.4" gem.add_runtime_dependency "roo-xls", "~> 1.0" end
require 'perpetuity/retrieval' require 'perpetuity/mapper' module Perpetuity describe Retrieval do let(:data_source) { double('data_source') } let(:registry) { double('mapper_registry') } let(:mapper) { double(collection_name: 'Object', data_source: data_source, mapper_registry: registry) } let(:query) { double('Query', to_db: {}) } let(:retrieval) { Perpetuity::Retrieval.new mapper, query } subject { retrieval } it "sorts the results" do sorted = retrieval.sort(:name) expect(sorted.sort_attribute).to be == :name end it "reverses the sort order of the results" do sorted = retrieval.sort(:name).reverse expect(sorted.sort_direction).to be == :descending end it "limits the result set" do expect(retrieval.limit(1).result_limit).to be == 1 end it 'indicates whether it includes a specific item' do allow(subject).to receive(:to_a) { [1] } expect(subject).to include 1 end it 'can be empty' do allow(retrieval).to receive(:to_a) { [] } expect(retrieval).to be_empty end describe 'pagination' do let(:paginated) { retrieval.page(2) } it 'paginates data' do expect(paginated.result_offset).to be == 20 end it 'defaults to 20 items per page' do expect(paginated.result_limit).to be == 20 end it 'sets the number of items per page' do expect(paginated.per_page(50).result_limit).to be == 50 end end it 'retrieves data from the data source' do return_data = { id: 0, a: 1, b: 2 } return_object = Object.new allow(return_object).to receive(:id) { return_data[:id] } options = { attribute: nil, direction: nil, limit: nil, skip: nil } expect(data_source).to receive(:retrieve).with('Object', query, options). and_return([return_data]) expect(data_source).to receive(:unserialize).with([return_data], mapper) { [return_object] } allow(mapper).to receive(:id_for) results = retrieval.to_a expect(results.map(&:id)).to be == [0] end it 'clears results cache' do retrieval.result_cache = [1,2,3] retrieval.clear_cache expect(retrieval.result_cache).to be_nil end describe 'identity map' do let(:id_map) { IdentityMap.new } let(:retrieval) { Retrieval.new(mapper, query, identity_map: id_map) } it 'maintains an identity_map' do expect(retrieval.identity_map).to be id_map end it 'returns objects from the identity map with queries' do result = Object.new result.instance_variable_set :@id, '1' id_map << result allow(mapper).to receive(:id_for) { '1' } allow(data_source).to receive(:retrieve) allow(data_source).to receive(:unserialize) { [result.dup] } expect(retrieval.to_a).to include result end end end end
class BlogPost < AbstractPermalink belongs_to :user belongs_to :last_commenter, class_name: "User" image_accessor :image attr_accessible :body, :permalink, :status_id, :title, :image_attributes, :last_commenter_id, :last_commented_at, :comments_count, :user_id, :image, :tagline, :tags, :tag_ids, :image_url, :meta_title, :meta_keywords, :meta_description, :audience_ids has_many :comments, { as: :commentable, dependent: :destroy } has_and_belongs_to_many :tags has_many :blog_post_audiences, dependent: :destroy has_many :audiences, through: :blog_post_audiences after_create :send_to_bloguser validates :permalink, uniqueness: true scope :none, limit(0) def has_audience?(audience_id) return self.audience_ids.include?(audience_id) if !self.new_record? false end def clear_audiences self.audiences.delete_all end def send_to_bloguser @blog = self @blog_users = BlogUser.all @blog_users.each do |user| BlogMailer.delay(queue: 'blog_notification').notification_email(@blog, user) end end class << self def dates select('created_at, id') end def ordered order("created_at DESC") end def skinny select(["id", "title", "permalink", "user_id", "created_at", "status"]) end def published where(:status_id => 1) end def by_month(month) month = DateTime.strptime(month, '%Y-%m') where(:created_at => month.beginning_of_month..month.end_of_month) end def by_category(category) # where() joins(:tags).where('tags.permalink = ?', category) end end end # == Schema Information # # Table name: blog_posts # # id :integer not null, primary key # title :string(255) # permalink :string(255) # body :text # user_id :integer # status_id :integer # image_uid :string(255) # image_name :string(255) # created_at :datetime not null # updated_at :datetime not null # comments_count :integer # last_commented_at :datetime # last_commenter_id :integer # tagline :text # meta_title :string(255) # meta_keywords :string(255) # meta_description :string(255) #
class RemoveFaresFromTickets < ActiveRecord::Migration[6.0] def change remove_column :tickets, :fcfare remove_column :tickets, :bcfare remove_column :tickets, :ecfare end end
describe CardSheetFactory do include_context "db" let(:factory) { CardSheetFactory.new(db) } let(:pack_factory) { PackFactory.new(db) } context "Masterpieces" do let(:sheet) { factory.masterpieces_for(set_code) } let(:masterpieces) { sheet.elements.map(&:main_front) } let(:expected_masterpieces) do db.sets[masterpieces_set_code] .printings .select{|c| masterpieces_range === c.number.to_i } end context "bfz" do let(:set_code) { "bfz" } let(:masterpieces_set_code) { "exp" } let(:masterpieces_range) { 1..25 } it { masterpieces.should eq(expected_masterpieces) } end context "ogw" do let(:set_code) { "ogw" } let(:masterpieces_set_code) { "exp" } let(:masterpieces_range) { 26..45 } it { masterpieces.should eq(expected_masterpieces) } end context "kld" do let(:set_code) { "kld" } let(:masterpieces_set_code) { "mps" } let(:masterpieces_range) { 1..30 } it { masterpieces.should eq(expected_masterpieces) } end context "aer" do let(:set_code) { "aer" } let(:masterpieces_set_code) { "mps" } let(:masterpieces_range) { 31..54 } it { masterpieces.should eq(expected_masterpieces) } end context "akh" do let(:set_code) { "akh" } let(:masterpieces_set_code) { "mp2" } let(:masterpieces_range) { 1..30 } it { masterpieces.should eq(expected_masterpieces) } end context "hou" do let(:set_code) { "hou" } let(:masterpieces_set_code) { "mp2" } let(:masterpieces_range) { 31..54 } it { masterpieces.should eq(expected_masterpieces) } end end context "Dragon's Maze" do let(:land_sheet) { factory.dgm_land } let(:common_sheet) { factory.dgm_common } let(:uncommon_sheet) { factory.rarity("dgm", "uncommon") } let(:rare_mythic_sheet) { factory.dgm_rare_mythic } let(:rtr_rare_mythic_sheet) { factory.rare_mythic("rtr") } let(:gtc_rare_mythic_sheet) { factory.rare_mythic("gtc") } let(:guildgate_card) { physical_card("simic guilddate e:dgm") } let(:rtr_shockland){ physical_card("Overgrown Tomb e:rtr") } let(:gtc_shockland) { physical_card("Breeding Pool e:gtc") } let(:mazes_end) { physical_card("Maze's End e:dgm") } let(:common_card) { physical_card("Azorius Cluestone e:dgm") } let(:uncommon_card) { physical_card("Korozda Gorgon e:dgm") } let(:rare_card) { physical_card("Emmara Tandris e:dgm") } let(:mythic_card) { physical_card("Blood Baron of Vizkopa e:dgm") } # According to official data, Chance of opening "a shockland" in DGM booster # is half of what it was in DGM booster. So individually they are 4x rarer # # Presumably Maze's end should be about as frequent as other mythics, # so 1/121 packs of large set [53 rares 15 mythics] # or 1/80 packs of small set [35 rares 10 mythics] it "Special land sheet" do (5 * rtr_rare_mythic_sheet.probabilities[rtr_shockland]).should eq Rational(10, 121) (5 * gtc_rare_mythic_sheet.probabilities[gtc_shockland]).should eq Rational(10, 121) (10 * land_sheet.probabilities[rtr_shockland]).should eq Rational(5, 121) land_sheet.probabilities[mazes_end].should eq Rational(1, 121) (10*land_sheet.probabilities[guildgate_card]).should eq Rational(115, 121) end it "Rarities on other sheets (corrected for land sheet and split cards)" do common_sheet.probabilities[common_card].should eq Rational(1, 60) uncommon_sheet.probabilities[uncommon_card].should eq Rational(1, 40) rare_mythic_sheet.probabilities[rare_card].should eq Rational(2, 80) rare_mythic_sheet.probabilities[mythic_card].should eq Rational(1, 80) end it "Cards for land sheet don't appear on normal sheet" do common_sheet.probabilities[guildgate_card].should eq 0 rare_mythic_sheet.probabilities[mazes_end].should eq 0 end end context "Unhinged" do context "rare sheet" do let(:rare_sheet) { factory.rare_mythic("unh") } let(:ambiguity) { physical_card("ambiguity", false) } let(:super_secret_tech) { physical_card("super secret tech", false) } it do rare_sheet.probabilities[ambiguity].should eq Rational(1, 40) rare_sheet.probabilities[super_secret_tech].should eq 0 end end context "foil sheet" do let(:unhinged_foil_rares) { factory.unhinged_foil_rares } let(:ambiguity) { physical_card("ambiguity", true) } let(:super_secret_tech) { physical_card("super secret tech", true) } it do unhinged_foil_rares.probabilities[ambiguity].should eq Rational(1, 41) unhinged_foil_rares.probabilities[super_secret_tech].should eq Rational(1, 41) end end end context "flip cards" do let(:pack) { pack_factory.for(set_code) } let(:number_of_cards) { pack.nonfoil_cards.size } let(:number_of_basics) { factory.rarity(set_code, "basic").cards.size } let(:number_of_commons) { factory.rarity(set_code, "common").cards.size } let(:number_of_uncommons) { factory.rarity(set_code, "uncommon").cards.size } let(:number_of_rares) { factory.rare_mythic(set_code).cards.size } describe "Champions of Kamigawa" do let(:set_code) { "chk" } it do number_of_cards.should eq(88+89+110) number_of_rares.should eq(88) # TODO: Brothers Yamazaki alt art number_of_uncommons.should eq(88+1) number_of_commons.should eq(110) number_of_basics.should eq(20) end end describe "Betrayers of Kamigawa" do let(:set_code) { "bok" } it do number_of_cards.should eq(55+55+55) number_of_rares.should eq(55) number_of_uncommons.should eq(55) number_of_commons.should eq(55) end end describe "Saviors of Kamigawa" do let(:set_code) { "sok" } it do number_of_cards.should eq(55+55+55) number_of_rares.should eq(55) number_of_uncommons.should eq(55) number_of_commons.should eq(55) end end end context "physical cards are properly setup" do describe "Dissention" do let(:pack) { pack_factory.for("dis") } let(:rares) { factory.rarity("dis", "uncommon").cards } let(:uncommons) { factory.rarity("dis", "uncommon").cards } let(:commons) { factory.rarity("dis", "common").cards } it do pack.nonfoil_cards.size.should eq(60+60+60) # 5 rares are split rares.size.should eq(60) # 5 uncommons are split uncommons.size.should eq(60) commons.size.should eq(60) # split cards setup correctly uncommons.map(&:name).should include("Trial // Error") end end end # TODO: dfc / aftermath / meld cards it "Masters Edition 4" do basics = factory.rarity("me4", "basic").cards.map(&:name).uniq basics.should match_array(["Urza's Mine", "Urza's Power Plant", "Urza's Tower"]) end it "Origins" do mythics = factory.rare_mythic("ori").cards.select{|c| c.rarity == "mythic"}.map(&:name) mythics.should match_array([ "Alhammarret's Archive", "Archangel of Tithes", "Avaricious Dragon", "Chandra, Fire of Kaladesh", "Day's Undoing", "Demonic Pact", "Disciple of the Ring", "Erebos's Titan", "Kytheon, Hero of Akros", "Jace, Vryn's Prodigy", "Liliana, Heretical Healer", "Nissa, Vastwood Seer", "Pyromancer's Goggles", "Starfield of Nyx", "The Great Aurora", "Woodland Bellower" ]) end context "Innistrad" do let(:probabilities) { factory.isd_dfc.probabilities } let(:mythic) { physical_card("e:isd Garruk Relentless") } let(:rare) { physical_card("e:isd Bloodline Keeper") } let(:uncommon) { physical_card("e:isd Civilized Scholar") } let(:common) { physical_card("e:isd Delver of Secrets") } it do probabilities[mythic].should eq Rational(1, 121) probabilities[rare].should eq Rational(2, 121) probabilities[uncommon].should eq Rational(6, 121) probabilities[common].should eq Rational(11, 121) end end context "Dark Ascension" do let(:probabilities) { factory.dka_dfc.probabilities } let(:mythic) { physical_card("e:dka Elbrus, the Binding Blade") } let(:rare) { physical_card("e:dka Ravenous Demon") } let(:uncommon) { physical_card("e:dka Soul Seizer") } let(:common) { physical_card("e:dka Chosen of Markov") } it do probabilities[mythic].should eq Rational(1, 80) probabilities[rare].should eq Rational(2, 80) probabilities[uncommon].should eq Rational(6, 80) probabilities[common].should eq Rational(12, 80) end end context "ABUR basic lands" do let(:common_sheet) { factory.explicit_common(set_code).probabilities } let(:uncommon_sheet) { factory.explicit_uncommon(set_code).probabilities } let(:rare_sheet) { factory.explicit_rare(set_code).probabilities } let(:common_cards) { physical_cards("r:common e:#{set_code}") } let(:uncommon_cards) { physical_cards("r:uncommon e:#{set_code}") } let(:rare_cards) { physical_cards("r:rare e:#{set_code}") } let(:commons_once) { common_cards.map{|c| [c, Rational(1,121)] }.to_h } let(:uncommons_once) { uncommon_cards.map{|c| [c, Rational(1,121)] }.to_h } let(:rares_once) { rare_cards.map{|c| [c, Rational(1,121)] }.to_h } context "Limited Edition Alpha" do let(:set_code) { "lea" } let(:plains_286) { physical_card("e:lea plains number=286") } let(:plains_287) { physical_card("e:lea plains number=287") } let(:island_288) { physical_card("e:lea island number=288") } let(:island_289) { physical_card("e:lea island number=289") } let(:swamp_290) { physical_card("e:lea swamp number=290") } let(:swamp_291) { physical_card("e:lea swamp number=291") } let(:mountain_292) { physical_card("e:lea mountain number=292") } let(:mountain_293) { physical_card("e:lea mountain number=293") } let(:forest_294) { physical_card("e:lea forest number=294") } let(:forest_295) { physical_card("e:lea forest number=295") } it "common" do common_sheet.should eq commons_once.merge( plains_286 => Rational(5, 121), plains_287 => Rational(4, 121), island_288 => Rational(5, 121), island_289 => Rational(5, 121), swamp_290 => Rational(5, 121), swamp_291 => Rational(4, 121), mountain_292 => Rational(5, 121), mountain_293 => Rational(4, 121), forest_294 => Rational(5, 121), forest_295 => Rational(5, 121), ) end it "uncommon" do uncommon_sheet.should eq uncommons_once.merge( plains_286 => Rational(3, 121), plains_287 => Rational(3, 121), island_288 => Rational(1, 121), island_289 => Rational(1, 121), swamp_290 => Rational(3, 121), swamp_291 => Rational(3, 121), mountain_292 => Rational(3, 121), mountain_293 => Rational(3, 121), forest_294 => Rational(3, 121), forest_295 => Rational(3, 121), ) end it "rare" do rare_sheet.should eq rares_once.merge( island_288 => Rational(3, 121), island_289 => Rational(2, 121), ) end end context "Limited Edition Beta" do let(:set_code) { "leb" } let(:plains_288) { physical_card("e:leb plains number=288") } let(:plains_289) { physical_card("e:leb plains number=289") } let(:plains_290) { physical_card("e:leb plains number=290") } let(:island_291) { physical_card("e:leb island number=291") } let(:island_292) { physical_card("e:leb island number=292") } let(:island_293) { physical_card("e:leb island number=293") } let(:swamp_294) { physical_card("e:leb swamp number=294") } let(:swamp_295) { physical_card("e:leb swamp number=295") } let(:swamp_296) { physical_card("e:leb swamp number=296") } let(:mountain_297) { physical_card("e:leb mountain number=297") } let(:mountain_298) { physical_card("e:leb mountain number=298") } let(:mountain_299) { physical_card("e:leb mountain number=299") } let(:forest_300) { physical_card("e:leb forest number=300") } let(:forest_301) { physical_card("e:leb forest number=301") } let(:forest_302) { physical_card("e:leb forest number=302") } it "common" do common_sheet.should eq commons_once.merge( plains_288 => Rational(2, 121), plains_289 => Rational(3, 121), plains_290 => Rational(3, 121), island_291 => Rational(3, 121), island_292 => Rational(4, 121), island_293 => Rational(3, 121), swamp_294 => Rational(3, 121), swamp_295 => Rational(3, 121), swamp_296 => Rational(3, 121), mountain_297 => Rational(3, 121), mountain_298 => Rational(3, 121), mountain_299 => Rational(4, 121), forest_300 => Rational(3, 121), forest_301 => Rational(3, 121), forest_302 => Rational(3, 121), ) end it "uncommon" do uncommon_sheet.should eq uncommons_once.merge( plains_288 => Rational(2, 121), plains_289 => Rational(2, 121), plains_290 => Rational(2, 121), island_292 => Rational(1, 121), island_293 => Rational(1, 121), swamp_294 => Rational(2, 121), swamp_295 => Rational(2, 121), swamp_296 => Rational(2, 121), mountain_297 => Rational(2, 121), mountain_298 => Rational(2, 121), mountain_299 => Rational(2, 121), forest_300 => Rational(2, 121), forest_301 => Rational(2, 121), forest_302 => Rational(2, 121), ) end it "rare" do rare_sheet.should eq rares_once.merge( island_291 => Rational(2, 121), island_292 => Rational(2, 121), ) end end context "Unlimited / 2nd Edition" do let(:set_code) { "2ed" } let(:plains_288) { physical_card("e:2ed plains number=288") } let(:plains_289) { physical_card("e:2ed plains number=289") } let(:plains_290) { physical_card("e:2ed plains number=290") } let(:island_291) { physical_card("e:2ed island number=291") } let(:island_292) { physical_card("e:2ed island number=292") } let(:island_293) { physical_card("e:2ed island number=293") } let(:swamp_294) { physical_card("e:2ed swamp number=294") } let(:swamp_295) { physical_card("e:2ed swamp number=295") } let(:swamp_296) { physical_card("e:2ed swamp number=296") } let(:mountain_297) { physical_card("e:2ed mountain number=297") } let(:mountain_298) { physical_card("e:2ed mountain number=298") } let(:mountain_299) { physical_card("e:2ed mountain number=299") } let(:forest_300) { physical_card("e:2ed forest number=300") } let(:forest_301) { physical_card("e:2ed forest number=301") } let(:forest_302) { physical_card("e:2ed forest number=302") } it "common" do common_sheet.should eq commons_once.merge( plains_288 => Rational(2, 121), plains_289 => Rational(3, 121), plains_290 => Rational(3, 121), island_291 => Rational(3, 121), island_292 => Rational(4, 121), island_293 => Rational(3, 121), swamp_294 => Rational(3, 121), swamp_295 => Rational(3, 121), swamp_296 => Rational(3, 121), mountain_297 => Rational(4, 121), mountain_298 => Rational(3, 121), mountain_299 => Rational(3, 121), forest_300 => Rational(3, 121), forest_301 => Rational(3, 121), forest_302 => Rational(3, 121), ) end it "uncommon" do uncommon_sheet.should eq uncommons_once.merge( plains_288 => Rational(2, 121), plains_289 => Rational(2, 121), plains_290 => Rational(2, 121), island_291 => Rational(1, 121), island_292 => Rational(1, 121), swamp_294 => Rational(2, 121), swamp_295 => Rational(2, 121), swamp_296 => Rational(2, 121), mountain_297 => Rational(2, 121), mountain_298 => Rational(2, 121), mountain_299 => Rational(2, 121), forest_300 => Rational(2, 121), forest_301 => Rational(2, 121), forest_302 => Rational(2, 121), ) end it "rare" do rare_sheet.should eq rares_once.merge( island_292 => Rational(2, 121), island_293 => Rational(2, 121), ) end end context "Revised / 3rd Edition" do let(:set_code) { "3ed" } let(:plains_292) { physical_card("e:3ed plains number=292") } let(:plains_293) { physical_card("e:3ed plains number=293") } let(:plains_294) { physical_card("e:3ed plains number=294") } let(:island_295) { physical_card("e:3ed island number=295") } let(:island_296) { physical_card("e:3ed island number=296") } let(:island_297) { physical_card("e:3ed island number=297") } let(:swamp_298) { physical_card("e:3ed swamp number=298") } let(:swamp_299) { physical_card("e:3ed swamp number=299") } let(:swamp_300) { physical_card("e:3ed swamp number=300") } let(:mountain_301) { physical_card("e:3ed mountain number=301") } let(:mountain_302) { physical_card("e:3ed mountain number=302") } let(:mountain_303) { physical_card("e:3ed mountain number=303") } let(:forest_304) { physical_card("e:3ed forest number=304") } let(:forest_305) { physical_card("e:3ed forest number=305") } let(:forest_306) { physical_card("e:3ed forest number=306") } it "common" do common_sheet.should eq commons_once.merge( plains_292 => Rational(2, 121), plains_293 => Rational(3, 121), plains_294 => Rational(3, 121), island_295 => Rational(3, 121), island_296 => Rational(4, 121), island_297 => Rational(3, 121), swamp_298 => Rational(3, 121), swamp_299 => Rational(3, 121), swamp_300 => Rational(3, 121), mountain_301 => Rational(4, 121), mountain_302 => Rational(3, 121), mountain_303 => Rational(3, 121), forest_304 => Rational(3, 121), forest_305 => Rational(2, 121), forest_306 => Rational(4, 121), ) end it "uncommon" do uncommon_sheet.should eq uncommons_once.merge( plains_292 => Rational(3, 121), plains_293 => Rational(2, 121), plains_294 => Rational(1, 121), island_296 => Rational(1, 121), island_297 => Rational(1, 121), swamp_298 => Rational(3, 121), swamp_299 => Rational(3, 121), mountain_301 => Rational(2, 121), mountain_302 => Rational(2, 121), mountain_303 => Rational(2, 121), forest_304 => Rational(3, 121), forest_305 => Rational(2, 121), forest_306 => Rational(1, 121), ) end it "rare" do rare_sheet.should eq rares_once end end end end
# frozen_string_literal: true module Diplomat # Methods for interacting with the Consul node API endpoint class Node < Diplomat::RestClient @access_methods = %i[get get_all register deregister] # Get a node by it's key # @param key [String] the key # @param options [Hash] :dc string for dc specific query # @return [OpenStruct] all data associated with the node def get(key, options = {}) custom_params = options[:dc] ? use_named_parameter('dc', options[:dc]) : nil ret = send_get_request(@conn, ["/v1/catalog/node/#{key}"], options, custom_params) OpenStruct.new JSON.parse(ret.body) end # Get all the nodes # @param options [Hash] :dc string for dc specific query # @return [OpenStruct] the list of all nodes def get_all(options = {}) custom_params = options[:dc] ? use_named_parameter('dc', options[:dc]) : nil ret = send_get_request(@conn, ['/v1/catalog/nodes'], options, custom_params) JSON.parse(ret.body).map { |service| OpenStruct.new service } end # Register a node # @param definition [Hash] Hash containing definition of a node to register # @param options [Hash] options parameter hash # @return [Boolean] def register(definition, options = {}) register = send_put_request(@conn, ['/v1/catalog/register'], options, definition) register.status == 200 end # De-register a node (and all associated services and checks) # @param definition [Hash] Hash containing definition of a node to de-register # @param options [Hash] options parameter hash # @return [Boolean] def deregister(definition, options = {}) deregister = send_put_request(@conn, ['/v1/catalog/deregister'], options, definition) deregister.status == 200 end end end
############################################## # # gd.rb --Main Code File for Global Destruction. # (C) Copyright 1992, High Velocity Software, Inc. # (C) Copyright 2002, Fly-By-Night Software (Ruby Version) # ############################################## $LOAD_PATH << "." def random(r) # assume r is a range of integers first < last # this def by Mike Stok [mike@stok.co.uk] who deserves credit for it r.first + rand(r.last - r.first + (r.exclude_end? ? 0 : 1)) end class GD_thread require "gd_main.rb" require "gd_messages.rb" require "gd_cards.rb" require "gd_const.rb" require "gd_class.rb" require "gd_score.rb" require "gd_virtual.rb" include Enumerable def initialize(users,who,channel,log,c_num) reset # set_up_database @who = who @users = users @channel = channel @log = log @c_num = c_num @comp_num = 0 #Number of Computer Players @started = false @deck = Deck.new @output = [] @startnic = "" @v_players = Players.new @v_countries = [] @deck.setitup @scores = Scores.new @scores.loadscores @randoms = [] @randoms.push(Special.new(RANDTHUNDERBOLT,6,false)) @randoms.push(Special.new(RANDTHUNDERBOLT,3,true)) @randoms.push(Special.new(RANDPOPDEATH,12,true)) @randoms.push(Special.new(RANDPOPDEATH,8,false)) @randoms.push(Special.new(RANDLOSETURN,4,false)) @randoms.push(Special.new(RANDAEGIS,6,false)) @randoms.push(Special.new(RANDAEGIS,3,true)) end def reset #@comp_num = 0 #Number of Computer Players @players = Players.new @usd_country = [] #Countries that have been used. @war = false #Does a state of war exist? @turn = 0 #Who's turn is it? @turns_to_peace = 0 @complete = false #Turn complete? @turn_type = INPUT_NORMAL #What type of input are we getting? @card_in_play = NO_CARD #The last card played by the current player. @abm_in_play = 0 # The *missile* being processed by incomming @spy_mode = 0 @incomming_lock = false # Has the User been in Incomming this turn? @current_time = Time.now.to_i @turn_time = 0 @warned = false end def blat(line) j = 0 for j in 0..@channel[@c_num].usrchannel.length - 1 @users[@channel[@c_num].usrchannel[j]].page.push(line) end end def blat_anti (user,line) j = 0 for j in 0..@channel[@c_num].usrchannel.length - 1 @users[@channel[@c_num].usrchannel[j]].page.push(line) if @users[@channel[@c_num].usrchannel[j]].name != user end end def blat_anti2 (user,user2,line) j = 0 for j in 0..@channel[@c_num].usrchannel.length - 1 @users[@channel[@c_num].usrchannel[j]].page.push(line) if @users[@channel[@c_num].usrchannel[j]].name != user and @users[@channel[@c_num].usrchannel[j]].name != user2 end end def blat_usr(user,line) j = 0 doit = false for j in 0..@channel[@c_num].usrchannel.length - 1 doit = true if @channel[@c_num].usrchannel[j] == user #we want to make sure we don't page a virtual user.. because they aren't real... end @users[user].page.push(line) if doit end def remove_user (disc_user) # puts "removing user #{disc_user}" @players[disc_user].dead = true #puts "@players[disc_user]: #{@players[disc_user]}" #puts "@turn: #{@turn}" if @players[disc_user].name == @players[@turn].name puts "Trying To End Turn Of: #{@players[disc_user].name}" @complete = true do_tick # so we loop and go to the next turn end end def run startup = false puts "-Starting GD thread for channel: #{@c_num}" puts "-Adding virtual players for channel: #{@c_num}" #v_add(2) v_create_list(2) loop do do_tick sleep(0.1) # puts "GDthread: #{@started}" #waiting to start the game loop... if !@started then @channel[@c_num].g_buffer.each {|x| parray = Array.new puts "x: #{x}" puts "x.split: #{x.split.each {|x| put x}}" parray = x.split puts "DEBUG: players.length: #{@players.len}" puts "DEBUG: parray: #{parray.length}" puts "DEBUG: parray: #{parray.each {|x| puts x}}" if parray.length > 1 then if parray[1].upcase == "START" and !@started then sleep(1) puts "DEBUG: -resetting game" reset #v_add(2) puts "DEBUG: vplayers.length: #{@v_players.len}" v_combine puts "DEBUG: players.length: #{@players.len}" puts "DEBUG: parray: #{parray.length}" puts "DEBUG: parray: #{parray.each_with_index {|x,i| puts i,x}}" startit(parray[0]) @channel[@c_num].status = true puts "-Starting GD Game" end end } @channel[@c_num].g_buffer.clear end current_time = Time.now.to_i if @started then @players.each {|x| puts x.name} if (current_time - @turn_time > TIME_WARN) and !@warned and !@players[@turn].dead then m_warning(@players[@turn].name) @warned = true end if (current_time - @turn_time > TIME_LIMIT) and (!@players[@turn].dead) and (!@players[@turn].virtural) then m_kickoff_user(@players[@turn].name) m_kickoff(@players[@turn].name,@players[@turn].country) remove_user (@players[@turn].name) end @channel[@c_num].g_buffer.each {|x| parsecmd(x) } @channel[@c_num].g_buffer.clear end end end end
class AddTotalTaxAndSubPriceAndTotalPriceAndTotalTaxToOrder < ActiveRecord::Migration def change add_column :orders, :total_tax, :float, :default => 0 add_column :orders, :total_price, :float, :default => 0 add_column :orders, :sub_price, :float, :default => 0 rename_column :orders, :tip, :total_tip end end
class Admin < ApplicationRecord has_secure_password validates :name, presence: true, uniqueness: true end
class CampaignObserver < ActiveRecord::Observer def after_update(c) if c.published_state && Time.zone.now.hour.between?(AppConfig.time_window[:start_time], AppConfig.time_window[:end_time]) && eval(AppConfig.day_range).include?(Date.today.wday) ScheduledMail::MailScheduler.new(c, 'Campaign_now').mail_scheduler c.update_attribute(:emails_sent, true) end unless c.emails_sent end def after_create(camp) if camp.campaign_type == "Frequency" camp.update_attribute(:frequency_date, camp.frequency.to_i.months.from_now) end end end
class User < ActiveRecord::Base has_secure_password validates :email, presence: true, uniqueness: true validates :password, confirmation: true, presence: true validates :password_confirmation, presence: true validates :password, length: { minimum: 8 } validates :name, presence: true def downcase self.email.downcase! end before_save { name.downcase! } def self.authenticate_with_credentials(email, password) user = User.find_by email: email.delete(' ').downcase if user && user.authenticate(password) return user else return nil end end end
class AppointmentNotifier < ActionMailer::Base def work_confirmation(appointment) setup_email(appointment, appointment.customer) @subject = "#{appointment.company.name}: Appointment confirmation" end def waitlist_confirmation(appointment) setup_email(appointment, appointment.customer) @subject = "#{appointment.company.name}: Waitlist confirmation" end def waitlist_opening(appointment) setup_email(appointment, appointment.customer) @subject = "#{appointment.company.name}: Waitlist opening" end protected def setup_email(appointment, customer) @recipients = "#{customer.email}" @from = "peanut@jarna.com" # add environment info if its not production # if RAILS_ENV != "production" # @subject += " (#{RAILS_ENV}) " # end @sent_on = Time.now @body[:customer] = customer @body[:appointment] = appointment end end
BookcampingExperiments::Application.routes.draw do concern :library do resources :shelves, path: 'ver' end # http://stackoverflow.com/questions/7099397/regex-for-any-string-except-www-subdomain constraints subdomain: /^(?!www).+/ do root to: 'libraries#dashboard' end resources :memberships resources :users do get :activity, on: :member resources :notifications, only: :index end match 'timeline', to: 'users#timeline', as: :timeline resources :versions resources :shelf_items, except: :index resources :licenses resources :comments resources :subscriptions resources :tags resources :references do [:tag, :publish, :coverize].each do |action| get action, on: :member end resources :versions, only: :index resources :reviews resource :repub resources :downloads resources :links resources :shelf_items, only: :index end resources :links, only: :show match '/download/*title', to: 'downloads#fetch', as: :download, format: false resources :libraries resources :recommendations resources :followings resources :notifications, only: :index resources :password_recoveries, path: 'recuperar', except: [:index] do post :change, on: :collection end match '/recuperar/token/:id' => 'password_recoveries#recover', as: 'recovery' # Email routes match "/email/activity/:id" => "emails#activity" match "/email/test" => "emails#test" match "/email/notifications" => "emails#notifications" # Dashboards match "/buscar" => "dashboards#search", as: :search match "/buscar/:term" => "dashboards#search" match "/identificar" => "sessions#create" match "/entrar" => "sessions#new", as: :login match "/auth/:provider/callback" => "sessions#create_with_omniauth" match "/salir" => "sessions#destroy", :as => :logout match "/entrar/:id" => "sessions#new", :as => :auth match "/auth/failure" => "sessions#failure" match "/mapa" => "site#map" # BLOG REDIRECT match "/blog/*post", to: redirect("http://blog.bookcamping.cc") match "/blog", to: redirect("http://blog.bookcamping.cc") match "/blog.atom", to: redirect("http://blog.bookcamping.cc/rss") # Backdoors used in test and development match "/enter/:id" => "sessions#enter", as: :enter root to: "dashboards#site" WaxMuseum::Routes.draw scope ':library' do #, :constraints => LibraryConstraints.new do #root to: 'shelves#index' resources :shelves, path: '' do #, except: :index do resources :versions, only: :index resources :references end end end ActionDispatch::Routing::Translator.translate_from_file('config/locales/routes.yml')
class RemoveTableUserLists < ActiveRecord::Migration def change drop_table :user_lists end end
class RemoveStringsPhotosFromTables < ActiveRecord::Migration[6.0] def change remove_column :instructors, :profile_pic remove_column :activities, :main_photo remove_column :activities, :photo_1 remove_column :activities, :photo_2 remove_column :activities, :photo_3 end end
class Notification < ApplicationRecord belongs_to :receiver, foreign_key: :receiver_id, class_name: 'User' belongs_to :sender, foreign_key: :sender_id, class_name: 'User' belongs_to :post, optional: true belongs_to :response, optional: true belongs_to :user_tag, optional: true belongs_to :comment, optional: true end
module Bouncer module Identity extend self def config @config ||= { host: Bouncer.config.oauth.host } end def links @links ||= OpenStruct.new.tap do |x| x.full_logout_path = "/auth/logout" x.auth_url = "#{config[:host]}" x.logout_url = "#{config[:host]}/sessions/destroy" end end def configure &block yield(config) end def client(token = nil) Identity::Client.new(config.dup.merge({ token: token })) end end end
RootLevelType = GraphQL::ObjectType.define do name 'RootLevel' description 'Unassociated root object queries' interfaces [NodeIdentification.interface] global_id_field :id connection :comments, CommentType.connection_type do resolve ->(_object, _args, _ctx){ Comment.all_sorted } end connection :project_medias, ProjectMediaType.connection_type do resolve ->(_object, _args, _ctx){ ProjectMedia.all } end connection :sources, SourceType.connection_type do resolve ->(_object, _args, _ctx){ Source.order('created_at DESC').all } end connection :team_users, TeamUserType.connection_type do resolve ->(_object, _args, _ctx){ TeamUser.all } end connection :teams, TeamType.connection_type do resolve ->(_object, _args, _ctx){ Team.all } end connection :accounts, AccountType.connection_type do resolve ->(_object, _args, _ctx){ Account.all } end connection :account_sources, AccountSourceType.connection_type do resolve ->(_object, _args, _ctx){ AccountSource.all } end connection :medias, MediaType.connection_type do resolve ->(_object, _args, _ctx){ Media.all } end connection :projects, ProjectType.connection_type do resolve ->(_object, _args, _ctx){ Project.all } end connection :users, UserType.connection_type do resolve ->(_object, _args, _ctx){ User.all } end connection :annotations, AnnotationType.connection_type do resolve ->(_object, _args, _ctx){ Annotation.all_sorted } end connection :tags, TagType.connection_type do resolve ->(_object, _args, _ctx){ Tag.all_sorted } end connection :contacts, ContactType.connection_type do resolve ->(_object, _args, _ctx){ Contact.all } end connection :team_bots_approved, BotUserType.connection_type do resolve ->(_object, _args, _ctx){ BotUser.all.select{ |b| b.get_approved } } end end
require "rails_helper" describe VelocitasCore::ImportGpx do let(:url) { "http://www.foo.com/sample.gpx" } let(:context) { subject.context } subject do described_class.new(url: url) end let(:file) { File.open(File.join(Rails.root, "spec", "fixtures", "simple.gpx")) } describe "#call" do it "downloads gpx and imports it" do expect_any_instance_of(VelocitasCore::GpxDownloader).to \ receive(:call).and_return(true) expect_any_instance_of(VelocitasCore::GpxDownloader).to \ receive(:context) .at_least(:once) .and_return(double(success?: true, file: file)) expect_any_instance_of(VelocitasCore::GpxImporter).to \ receive(:call).and_return(true) expect_any_instance_of(VelocitasCore::StoreGpxFile).to \ receive(:call).and_return(true) expect_any_instance_of(VelocitasCore::AnalyzeTrack).to \ receive(:call).and_return(true) subject.call expect(context).to be_a_success end it "fails when download fails" do expect_any_instance_of(VelocitasCore::GpxDownloader).to \ receive(:call).and_return(true) expect_any_instance_of(VelocitasCore::GpxDownloader).to \ receive(:context) .at_least(:once) .and_return(double(success?: false, file: file)) expect { subject.call }.to raise_error(Interactor::Failure) expect(context).to be_a_failure end end end
class CreateCriticReviews < ActiveRecord::Migration def change create_table :critic_reviews do |t| t.references :movie, index: true, foreign_key: true t.string :critic t.date :date t.string :original_score t.string :freshness t.text :quote t.string :url t.timestamps null: false end end end
class Converter def convert_amount(amount,first_currency,second_currency) begin if first_currency == second_currency return "#{amount} #{second_currency}" end rates = Endpoint.new.get_exchange_rates if first_currency == 'CZK' convert_from_czk(amount,rates,second_currency) elsif second_currency == 'CZK' convert_to_czk(amount,rates,first_currency) else convert_other_currencies(amount,rates,first_currency,second_currency) end rescue return 'Oh, sorry! I cannot process your request. Example is `/csbot convert 20 EUR to CZK`' end end def convert_from_czk(amount,rates,second_currency) rate = Rater.new.get_currency_rate_in_czk(rates,second_currency) if rate.class == String return rate end return "#{number_to_currency(amount)} CZK is #{number_to_currency((amount/rate).round(2))} #{second_currency}" end def convert_to_czk(amount,rates,first_currency) rate = Rater.new.get_currency_rate_in_czk(rates,first_currency) if rate.class == String return rate end return "#{number_to_currency(amount)} #{first_currency} is #{number_to_currency((amount*rate).round(2))} CZK" end def convert_other_currencies(amount,rates,first_currency,second_currency) first_rate = Rater.new.get_currency_rate_in_czk(rates,first_currency) if first_rate.class == String return first_rate end amount_in_czk = amount*first_rate second_rate = Rater.new.get_currency_rate_in_czk(rates,second_currency) if second_rate.class == String return second_rate end return "#{number_to_currency(amount)} #{first_currency} is #{number_to_currency((amount_in_czk/second_rate).round(2))} #{second_currency}" end private def unsupported_currency(currency) return "I don't support '#{currency}' currency! To see all currencies, type `/csbot currencies`." end def number_to_currency(number) ActionController::Base.helpers.number_to_currency(number,{delimiter: ' ',unit: ''}) end end
class Book < ActiveRecord::Base attr_accessible :price, :publish, :title, :avatar has_attached_file :avatar, styles: {midium: "300x300#", thumb: "100x100#" }, path: "#{Rails.root}/public/system/:class/:id/:attachment/:style.:extension", url: "/system/:class/:id/:attachment/:style.:extension" validates_attachment :avatar, presence: true, content_type: { content_type: ['image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/x-png'] }, size: { less_than: 3.megabytes } end
class UsersController < ApplicationController def new @user = User.new end def create @user = User.new(user_params) if @user.save flash[:success] = "Pomyślnie utworzono nowe konto" Order.create(user: @user, status: "cart") #creates a shopping cart for a new user redirect_to products_path else flash.now[:danger] = "Nie udało się pomyślnie utworzyć konta. Sprawdź czy wprowadzone dane są poprawne." render 'new' end end def index @users = User.all end def show @user = User.find(params[:id]) end private def user_params params.require(:user).permit(:name, :email, :password) end end
SurveyBuilder::Engine.routes.draw do resources :survey_forms do get 'results', on: :member resources :questions do get 'new/:type', to: 'questions#new', as: 'new_typed' , on: :collection end resources :survey_responses resources :responses end end
require "goon_model_gen" module GoonModelGen module Converter class Mapping attr_reader :name, :args, :func, :requires_context, :returns_error attr_accessor :package_base_path, :package_name attr_accessor :allow_zero # for int or uint only def initialize(name, args, func, requires_context, returns_error) @name, @args, @func, @requires_context, @returns_error = name, args, func, requires_context, returns_error end def resolve_package_path(config) if func.present? && func.include?('.') self.package_base_path = requires_context ? config.store_package_path : config.model_package_path self.package_name = func.split('.', 2).first end end end end end
# frozen_string_literal: true module ObjectMatchers def match_object(current_result, value) return current_result if object.blank? (value == object) end def match_array_of(current_result, value) return current_result if object_array_type.blank? || !value.respond_to?(:all?) value.all? { |it| it.instance_of?(object_array_type) } end def match_instance_of(current_result, value) return current_result if object_type.blank? value.instance_of?(object_type) end def match_attributes(current_result, value) return current_result if object_attributes.blank? a_object_with_attributes(object_attributes).matches?(value) end end RSpec::Matchers.define :a_object_with_attributes do |attrs| match do |actual| attrs.all? { |attr, value| actual.public_send(attr.to_sym) == value } end end
require 'csv' require 'pg' if ENV["RACK_ENV"] == "production" uri = URI.parse(ENV["DATABASE_URL"]) DB_CONFIG = { host: uri.host, port: uri.port, dbname: uri.path.delete('/'), user: uri.user, password: uri.password } else DB_CONFIG = { dbname: "restaurants" } end def db_connection begin connection = PG.connect(DB_CONFIG) yield(connection) ensure connection.close end end db_connection do |conn| sql_query = "DELETE FROM restaurants" conn.exec(sql_query) end CSV.foreach('restaurants.csv', headers: true, col_sep: ";") do |row| db_connection do |conn| sql_query = "INSERT INTO restaurants(name, address, city, state, zip, description) VALUES ($1, $2, $3, $4, $5, $6)" data = row.to_hash.values conn.exec_params(sql_query, data) end end
class LinkComponentPreview < ViewComponent::Preview def default render(LinkComponent.new(text: 'Here is an example link', path: '#')) end end
require 'spec_helper' describe User do describe 'validations' do it { should have(1).error_on(:first_name) } it { should have(1).error_on(:last_name) } end # describe 'is a member of team' do # let(:user) { create(:user) } # let(:team) { create(:team) } # subject { user.is_a_member_of?(team) } # context 'it not a member of the team' do # it { should be_false } # end # context 'is a member of the team already' do # before { user.teams << team } # it { should be_true } # end # context 'is the captain of the team' do # let(:team) { create(:team, :captain => user) } # it { should be_true } # end # end end
class PolyTreeNode attr_reader :parent, :children, :value def initialize(value, parent = nil, children = [] ) @value = value @parent = parent @children = children end def parent=(parent_node) @parent.children.delete(self) unless @parent.nil? parent_node.nil? ? @parent = nil : @parent = parent_node parent_node.children << self unless parent_node.nil? end def add_child(child) child.parent = self end def inspect " #{value} " end def remove_child(child) raise "node is not a child" if child.parent.nil? child.parent = nil end def dfs(target) return self if target == @value children.each do |child| child_node = child.dfs(target) return child_node unless child_node.nil? end nil end def bfs(target) queue = [] queue << self until queue.empty? node = queue.shift return node if node.value == target queue << node.children queue.flatten! end nil end end
require 'rubygems' require 'Nokogiri' require 'selenium-webdriver' Encoding.default_external = Encoding.find('utf-8') class Bilibili_Ranklist_Tag @@count = 0 #count flag for Tag class def initialize(b_string) @@count += 1 @no = @@count #No of Tags if /(【\d?\d月】)([^\d]*)(\d?\d)/ =~ b_string @month = $1 @title = $2 @episode = $3 # get month / title / episode information from a formated string else puts "字符串匹配失败:可能匹配失败字段为month/title/episode" end if /【独家正版】/ =~ b_string @bilibilionly_flag = true else @bilibilionly_flag = false end # judge if the tag is bilibilionly if /(www.+)/ =~ b_string @link = $1 else puts "字符串匹配失败:可能匹配失败字段为link" end # get the link of tag end def Bilibili_Ranklist_Tag.count @@count end # def a classmethod for count def listinfo puts "排名:#{@no}" puts "月份:#{@month}" puts "标题:#{@title}" puts "集数:#{@episode}" puts "链接:#{@link}" if @bilibilionly_flag puts "bilibili独家:√" else puts "bilibili独家:×" end puts "--------------------" end attr_accessor:month attr_accessor:title attr_accessor:episode attr_accessor:link end begin #run a safari-driver and goto target page dr = Selenium::WebDriver.for :safari url = 'https://www.bilibili.com/v/anime/serial/?spm_id_from=333.334.primary_menu.8#/' dr.get url #parse page with nokogiri page = Nokogiri::HTML(dr.page_source) topanimation_title = page.xpath('//p[@class="ri-title"]') topanimation_link = page.xpath('//a[@class="ri-info-wrap clearfix"]/@href') #print results aa = [] i = 0 for i in 0..(topanimation_title.size()-1) aa[i]=Bilibili_Ranklist_Tag.new(topanimation_title[i].text.to_s+" www.bilibili.com"+topanimation_link[i].to_s) i = i+1 end # File.open("./bilibili_test.txt", "r+") do |io| # while line = io.gets # aa[i]=Bilibili_Ranklist_Tag.new(line.chomp) # i = i+1 # end # end aa.each do |a| a.listinfo end puts "新建类总数#{Bilibili_Ranklist_Tag.count}" rescue => errorinfo puts "诶哟出错咧!:)" puts errorinfo end
# == Schema Information # # Table name: import_request_files # # id :integer not null, primary key # file :string(255) # created_at :datetime not null # updated_at :datetime not null # class ImportRequestFile < ActiveRecord::Base attr_accessible :file mount_uploader :file, ImportFileUploader validates_presence_of :file end
class AddTutorialIdToFilter < ActiveRecord::Migration def change add_column :filters, :tutorial_id, :integer end end
# frozen_string_literal: true require "tasks/scripts/telemedicine_reports_v2" namespace :reports do desc "Generates the telemedicine report" task telemedicine: :environment do period_start = (Date.today - 1.month).beginning_of_month period_end = period_start.end_of_month report = TelemedicineReportsV2.new(period_start, period_end) report.generate end end
module Asciidoctor module Gb class Converter < ISO::Converter def standard_type(node) type = node.attr("mandate") || "mandatory" type = "standard" if type == "mandatory" type = "recommendation" if type == "recommended" type end def front(node, xml) xml.bibdata **attr_code(type: standard_type(node)) do |b| metadata node, b end metadata_version(node, xml) end def metadata_author(node, xml) author = node.attr("author") || return author.split(/, ?/).each do |author| xml.contributor do |c| c.role **{ type: "author" } c.person do |p| p.name do |n| n.surname author end end end end end def metadata_contributor1(node, xml, type, role) contrib = node.attr(type) || "GB" contrib.split(/, ?/).each do |c| xml.contributor do |x| x.role **{ type: role } x.organization do |a| a.name { |n| n << c } end end end end def metadata_copyright(node, xml) from = node.attr("copyright-year") || Date.today.year xml.copyright do |c| c.from from c.owner do |owner| owner.organization do |o| o.name "GB" end end end end def metadata_committee(node, xml) attrs = { type: node.attr("technical-committee-type") } xml.gbcommittee **attr_code(attrs) do |a| a << node.attr("technical-committee") end i = 2 while node.attr("technical-committee_#{i}") do attrs = { type: node.attr("technical-committee-type_#{i}") } xml.gbcommittee **attr_code(attrs) do |a| a << node.attr("technical-committee_#{i}") end i += 1 end end def metadata_equivalence(node, xml) isostd = node.attr("iso-standard") || return type = node.attr("equivalence") || "equivalent" m = /^(?<code>[^,]+),?(?<title>.*)$/.match isostd title = m[:title].empty? ? "[not supplied]" : m[:title] xml.relation **{ type: type } do |r| r.bibitem do |b| b.title { |t| t << title } b.docidentifier m[:code] end end end def metadata_obsoletes(node, xml) std = node.attr("obsoletes") || return m = /^(?<code>[^,]+),?(?<title>.*)$/.match std title = m[:title].empty? ? "[not supplied]" : m[:title] xml.relation **{ type: "obsoletes" } do |r| r.bibitem do |b| b.title { |t| t << title } b.docidentifier m[:code] end r.bpart node.attr("obsoletes-parts") if node.attr("obsoletes-parts") end end def get_scope(node) node.attr("scope") and return node.attr("scope") scope = if %r{^[TQ]/}.match? node.attr("prefix") m = node.attr("prefix").split(%{/}) mandate = m[0] == "T" ? "social-group" : m[0] == "Q" ? "enterprise" : nil end return scope unless scope.nil? warn "GB: no scope supplied, defaulting to National" "national" end def get_prefix(node) scope = get_scope(node) if prefix = node.attr("prefix") prefix.gsub!(%r{/[TZ]$}, "") prefix.gsub!(%r{^[TQ]/([TZ]/)?}, "") prefix.gsub!(/^DB/, "") if scope == "local" else prefix = "GB" scope = "national" warn "GB: no prefix supplied, defaulting to GB" end [scope, prefix] end def get_mandate(node) node.attr("mandate") and return node.attr("mandate") p = node.attr("prefix") mandate = %r{/T}.match?(p) ? "recommended" : %r{/Z}.match?(p) ? "guidelines" : nil if mandate.nil? mandate = "mandatory" warn "GB: no mandate supplied, defaulting to mandatory" end mandate end def get_topic(node) node.attr("topic") and return node.attr("topic") warn "GB: no topic supplied, defaulting to basic" "basic" end def metadata_gbtype(node, xml) xml.gbtype do |t| scope, prefix = get_prefix(node) t.gbscope { |s| s << scope } t.gbprefix { |p| p << prefix } t.gbmandate { |m| m << get_mandate(node) } t.gbtopic { |t| t << get_topic(node) } end end def metadata_date1(node, xml, type) date = node.attr("#{type}-date") date and xml.date **{ type: type } do |d| d.on date end end DATETYPES = %w{ published accessed created implemented obsoleted confirmed updated issued }.freeze def metadata_date(node, xml) DATETYPES.each do |t| metadata_date1(node, xml, t) end end def metadata_gblibraryids(node, xml) ccs = node.attr("library-ccs") ccs and ccs.split(/, ?/).each do |l| xml.ccs { |c| c << l } end l = node.attr("library-plan") l && xml.plannumber { |plan| plan << l } end def metadata_contributors(node, xml) metadata_author(node, xml) metadata_contributor1(node, xml, "author-committee", "author") i = 2 while node.attr("author-committee_#{i}") do metadata_contributor1(node, xml, "author-committee_#{i}", "author") i += 1 end metadata_contributor1(node, xml, "publisher", "publisher") metadata_contributor1(node, xml, "authority", "authority") metadata_contributor1(node, xml, "proposer", "proposer") metadata_contributor1(node, xml, "issuer", "issuer") end def metadata(node, xml) title node, xml metadata_source(node, xml) metadata_id(node, xml) metadata_date(node, xml) metadata_contributors(node, xml) xml.language (node.attr("language") || "zh") xml.script (node.attr("script") || "Hans") metadata_status(node, xml) metadata_copyright(node, xml) metadata_equivalence(node, xml) metadata_obsoletes(node, xml) metadata_ics(node, xml) metadata_committee(node, xml) metadata_gbtype(node, xml) metadata_gblibraryids(node, xml) end def title_intro(node, lang, t, at) node.attr("title-intro-#{lang}") and t.title_intro **attr_code(at) do |t1| t1 << asciidoc_sub(node.attr("title-intro-#{lang}")) end end def title_main(node, lang, t, at) t.title_main **attr_code(at) do |t1| t1 << asciidoc_sub(node.attr("title-main-#{lang}")) end end def title_part(node, lang, t, at) node.attr("title-part-#{lang}") and t.title_part **attr_code(at) do |t1| t1 << asciidoc_sub(node.attr("title-part-#{lang}")) end end def title(node, xml) ["en", "zh"].each do |lang| xml.title do |t| at = { language: lang, format: "plain" } title_intro(node, lang, t, at) title_main(node, lang, t, at) title_part(node, lang, t, at) end end end end end end
namespace :setup do desc "setup: copy config/master.key to shared/config" task :copy_linked_master_key do on roles(fetch(:setup_roles)) do sudo :mkdir, "-pv", shared_path upload! "config/master.key", "#{shared_path}/config/master.key" sudo :chmod, "600", "#{shared_path}/config/master.key" end end before "deploy:symlink:linked_files", "setup:copy_linked_master_key" end
require 'nokogiri' require 'open-uri' require 'pry' class BillboardScraper def initialize doc = Nokogiri::HTML(open('https://www.billboard.com/charts/hot-100')) scrape(doc) end def scrape(doc) doc.css('.chart-data .chart-row').map do |entry| song_info = {} song_info[:chart_status] = { rank: entry.css('.chart-row__current-week').text, previous_week: entry.css('.chart-row__last-week .chart-row__value').text, peak_position: entry.css('.chart-row__top-spot .chart-row__value').text, weeks_charted: entry.css('.chart-row__weeks-on-chart .chart-row__value').text } song_info[:song] = { title: entry.css('.chart-row__song').text, spotify_link: parse_spotify_link_if_present(entry), vevo_link: parse_vevo_link_if_present(entry) } song_info[:artist] = { name: entry.css(".chart-row__artist").text.strip } create_song_from_scraper(song_info) end end def create_song_from_scraper(song_info) song = Song.create(song_info[:song]) Artist.create_by_list_name(song_info[:artist]).each { |artist| song.artists << artist } song.chart_status = ChartStatus.new(song_info[:chart_status]) song.chart_status.song = song song.artists.each { |artist| artist.songs << song } end def parse_spotify_link_if_present(entry) if !entry.css('.js-spotify-play-full').empty? entry.css('.js-spotify-play-full').attr('data-href').text else "error" end end def parse_vevo_link_if_present(entry) if !entry.css('.js-chart-row-vevo').empty? entry.css('.js-chart-row-vevo').attr('data-href').text else "error" end end end
# frozen_string_literal: true # rubocop:disable Metrics/MethodLength # rubocop:disable Style/StringConcatenation # rubocop:disable Naming/VariableNumber require_relative 'test_helper' require 'fileutils' class TemplateFileOutputTest < Minitest::Test def test_file_output_1 contents_fixture = File.read(File.join([TestHelper::PATHS[:fixtures], 'erubi_1.erb'])) assert_output('') do dir_target = '/tmp/_______delete_me______________' file_path_target = dir_target + '/dasjdnass/jhfdsygffdsf/fdsafasdf/output.txt' begin TestHelper::CLI .run([ 'generate', '--source="' + contents_fixture + '"', '--file-output="' + file_path_target + '"' ]) assert(File.exist?(file_path_target), true) ensure FileUtils.rm_r(dir_target, force: true) end end end end # rubocop:enable Metrics/MethodLength # rubocop:enable Style/StringConcatenation # rubocop:enable Naming/VariableNumber
# responsible for loading price-lists and comparing them class PriceManager < Mapper::Base attr_reader :dictionary def initialize super end #зчитуємо прайси з поточної директорії, якщо директорія не вказана # в налаштуваннях, інакше зчитуємо прайси з поточної директорії def get_price_names FileUtils.cd @config['dir'] if @config['dir'].nil? == false && Dir.exists?(@config['dir']) filenames = [] p @config["extensions"].split(",") @config["extensions"].split(",").each do |extension| extensions = Dir.glob("*.{#{extension.strip}}") filenames.concat(extensions) unless extensions.empty? end raise StandardError, "No prices in #{@config['dir']} directory :( " if filenames.count == 0 filenames end def get_hash(filename) Digest::SHA256.file(filename).hexdigest end def check_price filename # отримуємо хеш файлу, щоб в подальшому порівняти з тим що міститься у базі hash = get_hash(filename) unless @price.check(filename, hash) parse(filename, hash) else @price_count -= 1 print "Price #{filename} already exists in database!" end end #парсить прайси з директорії вказаної в налаштуваннях та записує в базу def parse(filename, hash) EM.defer( proc {PriceReader.new(filename, @dictionary["headers"]).parse }, proc do |data| EM.defer( proc do @price.add(filename, hash).callback do result = Fiber.new {@storage_item.add(data, filename)}.resume result.callback do @counter += 1; print "#{filename} #{@counter} / #{@price_count}successfully added" print "Operation index has been successfully finished" if @counter == @price_count end result.errback{|error| p error} end end ) end ) end def load_prices filenames = get_price_names raise ArgumentError, "must be array of files #{filenames.kind_of?}" unless filenames.kind_of?(Array) @price_count = filenames.size @counter = 0 EM::Synchrony::FiberIterator.new(filenames, @config["concurrency"]["iterator-size"].to_i).map do |filename| check_price filename end end end
class CourseForm < ActiveRecord::Base belongs_to :course has_many :class_activities end
# encoding: UTF-8 # Copyright 2011-2013 innoQ Deutschland GmbH # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require File.join(File.expand_path(File.dirname(__FILE__)), '../test_helper') class HierarchyTest < ActionController::TestCase setup do @controller = HierarchyController.new # create a concept hierarchy concepts = YAML.load <<-EOS root: foo: bar: alpha: bravo: uno: dos: lorem: ipsum: EOS @rel_class = Iqvoc::Concept.broader_relation_class.narrower_class @concepts = create_hierarchy(concepts, @rel_class, {}) @concepts['root'].update_attribute('top_term', true) end test 'entire hierarchy' do additional_concepts = YAML.load <<-EOS boot: zoo: car: EOS @concepts.merge! create_hierarchy(additional_concepts, @rel_class, {}) @concepts['boot'].update_attribute('top_term', true) get :index, params: { lang: 'en', format: 'ttl' } assert_response 200 %w(root foo bar alpha bravo uno dos boot zoo car).each do |id| assert @response.body.include?(":#{id} a skos:Concept;"), "#{id} missing" end %w(lorem ipsum).each do |id| assert (not @response.body.include?(":#{id} a skos:Concept;")), "#{id} should not be present" end Iqvoc.config['performance.unbounded_hierarchy'] = true get :index, params: { lang: 'en', format: 'ttl' } assert_response 200 %w(root foo bar alpha bravo uno dos lorem ipsum boot zoo car).each do |id| assert @response.body.include?(":#{id} a skos:Concept;"), "#{id} missing" end end test 'permission handling' do get :show, params: { lang: 'en', format: 'html', root: 'root' } entries = get_entries('ul.concept-hierarchy > li') assert_equal ['Root'], entries entries = get_entries('ul.concept-hierarchy > li > ul > li') assert_equal ['Bar', 'Foo'], entries entries = get_entries('ul.concept-hierarchy > li > ul > li > ul > li') assert_equal ['Alpha', 'Bravo'], entries entries = get_entries('ul.concept-hierarchy > li > ul > li > ul > li > ul > li') assert_equal ['Dos', 'Uno'], entries entries = css_select('ul.concept-hierarchy > li > ul > li > ul > li > ul > li > ul > li') assert_equal 0, entries.length # exceeded default depth @concepts['bar'].update_attribute('published_at', nil) get :show, params: { lang: 'en', format: 'html', root: 'root' } entries = get_entries('ul.concept-hierarchy > li') assert_equal ['Root'], entries entries = get_entries('ul.concept-hierarchy > li > ul > li') assert_equal ['Foo'], entries entries = get_entries('ul.concept-hierarchy li > ul > li > ul > li') assert_equal 0, entries.length end test 'caching' do # ETag generation & cache control get :show, params: { lang: 'en', format: 'ttl', root: 'root' } etag = @response.headers['ETag'] assert_response 200 assert etag assert @response.headers['Cache-Control'].include?('public') get :show, params: { lang: 'en', format: 'ttl', root: 'root' } assert_response 200 assert_equal etag, @response.headers['ETag'] get :show, params: { lang: 'en', format: 'ttl', root: 'root', published: 0 } assert_response 200 assert @response.headers['Cache-Control'].include?('private') # ETag keyed on params get :show, params: { lang: 'en', format: 'ttl', root: 'root' , depth: 4 } assert_response 200 assert_not_equal etag, @response.headers['ETag'] get :show, params: { lang: 'en', format: 'ttl', root: 'root', published: 0 } assert_response 200 assert_not_equal etag, @response.headers['ETag'] # ETag keyed on (any in-scope) concept modification t0 = Time.now t1 = Time.now + 30 dummy = create_concept('dummy', 'Dummy', 'en', false) dummy.update_attribute('updated_at', t1) get :show, params: { lang: 'en', format: 'ttl', root: 'root' } assert_response 200 assert_equal etag, @response.headers['ETag'] dummy.update_attribute('published_at', t0) dummy.update_attribute('updated_at', t1) get :show, params: { lang: 'en', format: 'ttl', root: 'root' } assert_response 200 new_etag = @response.headers['ETag'] assert_not_equal etag, new_etag # conditional caching @request.env['HTTP_IF_NONE_MATCH'] = new_etag get :show, params: { lang: 'en', format: 'ttl', root: 'root' } assert_response 304 assert_equal 0, @response.body.strip.length @request.env['HTTP_IF_NONE_MATCH'] = 'dummy' get :show, params: { lang: 'en', format: 'ttl', root: 'root' } assert_response 200 end test 'RDF representations' do # Turtle get :show, params: { lang: 'en', format: 'ttl', root: 'root' } assert_response 200 assert_equal @response.media_type, 'text/turtle' assert @response.body =~ /:root[^\.]+skos:topConceptOf[^\.]+:scheme/m assert @response.body =~ /:root[^\.]+skos:prefLabel[^\.]+"Root"@en/m assert @response.body =~ /:root[^\.]+skos:narrower[^\.]+:bar/m assert @response.body =~ /:root[^\.]+skos:narrower[^\.]+:foo/m assert @response.body.include?(<<-EOS) :foo a skos:Concept; skos:prefLabel "Foo"@en. EOS assert @response.body =~ /:bar[^\.]+skos:prefLabel[^\.]+"Bar"@en/m assert @response.body =~ /:bar[^\.]+skos:narrower[^\.]+:alpha/m assert @response.body =~ /:bar[^\.]+skos:narrower[^\.]+:bravo/m assert @response.body.include?(<<-EOS) :alpha a skos:Concept; skos:prefLabel "Alpha"@en. EOS assert @response.body =~ /:bravo[^\.]+skos:prefLabel[^\.]+"Bravo"@en/m assert @response.body =~ /:bravo[^\.]+skos:narrower[^\.]+:uno/m assert @response.body =~ /:bravo[^\.]+skos:narrower[^\.]+:dos/m assert @response.body.include?(<<-EOS) :uno a skos:Concept; skos:prefLabel "Uno"@en. EOS assert @response.body.include?(<<-EOS) :dos a skos:Concept; skos:prefLabel "Dos"@en. EOS get :show, params: { lang: 'en', format: 'ttl', root: 'lorem', dir: 'up' } assert_response 200 assert_equal @response.media_type, 'text/turtle' assert @response.body.include?(<<-EOS) :lorem a skos:Concept; skos:prefLabel "Lorem"@en; skos:broader :dos. EOS assert @response.body.include?(<<-EOS) :lorem a skos:Concept; skos:prefLabel "Lorem"@en; skos:broader :dos. EOS assert @response.body.include?(<<-EOS) :dos a skos:Concept; skos:prefLabel "Dos"@en; skos:broader :bravo. EOS assert @response.body.include?(<<-EOS) :bravo a skos:Concept; skos:prefLabel "Bravo"@en; skos:broader :bar. EOS assert @response.body.include?(<<-EOS) :bar a skos:Concept; skos:prefLabel "Bar"@en. EOS # RDF/XML get :show, params: { lang: 'en', format: 'rdf', root: 'root' } assert_response 200 assert_equal @response.media_type, 'application/rdf+xml' end test 'root parameter handling' do assert_raises ActionController::UrlGenerationError do get :show, params: { format: 'html' } end get :show, params: { lang: 'en', format: 'html', root: 'N/A' } assert_response 404 assert_equal 'no concept matching root parameter', flash[:error] entries = css_select('ul.concept-hierarchy li') assert_equal 0, entries.length get :show, params: { lang: 'en', format: 'html', root: 'root' } assert_response 200 assert_nil flash[:error] entries = get_entries('ul.concept-hierarchy > li') assert_equal 1, entries.length assert_equal 'Root', entries[0] get :show, params: { lang: 'en', format: 'html', root: 'root' } entries = get_entries('ul.concept-hierarchy > li') assert_equal ['Root'], entries entries = get_entries('ul.concept-hierarchy > li > ul > li') assert_equal ['Bar', 'Foo'], entries entries = get_entries('ul.concept-hierarchy > li > ul > li > ul > li') assert_equal ['Alpha', 'Bravo'], entries entries = get_entries('ul.concept-hierarchy li > ul > li > ul > li > ul > li') assert_equal ['Dos', 'Uno'], entries entries = css_select('ul.concept-hierarchy > li > ul > li > ul > li > ul > li > ul > li') assert_equal 0, entries.length # exceeded default depth get :show, params: { lang: 'en', format: 'html', root: 'bravo' } entries = get_entries('ul.concept-hierarchy > li') assert_equal ['Bravo'], entries entries = get_entries('ul.concept-hierarchy > li > ul > li') assert_equal ['Dos', 'Uno'], entries entries = get_entries('ul.concept-hierarchy > li > ul > li > ul > li') assert_equal ['Ipsum', 'Lorem'], entries entries = css_select('ul.concept-hierarchy > li > ul > li > ul > li > ul > li') assert_equal 0, entries.length get :show, params: { lang: 'en', format: 'html', root: 'lorem' } entries = get_entries('ul.concept-hierarchy > li') assert_equal ['Lorem'], entries entries = css_select('ul.concept-hierarchy > li > ul > li') assert_equal 0, entries.length end test 'depth handling' do selector = 'ul.concept-hierarchy > li > ul > li > ul > li > ul > li > ul > li' get :show, params: { lang: 'en', format: 'html', root: 'root' } entries = css_select(selector) assert_equal 0, entries.length # default depth is 3 get :show, params: { lang: 'en', format: 'html', root: 'root', depth: 4 } entries = css_select(selector) assert_equal 2, entries.length get :show, params: { lang: 'en', format: 'html', root: 'root', depth: 1 } entries = get_entries('ul.concept-hierarchy > li') assert_equal ['Root'], entries entries = get_entries('ul.concept-hierarchy > li > ul > li') assert_equal ['Bar', 'Foo'], entries entries = css_select('ul.concept-hierarchy > li > ul > li > ul > li') assert_equal 0, entries.length old_config_value = Iqvoc.config['performance.unbounded_hierarchy'] Iqvoc.config['performance.unbounded_hierarchy'] = false get :show, params: { lang: 'en', format: 'html', root: 'root', depth: 5 } assert_response 403 assert_equal 'excessive depth', flash[:error] Iqvoc.config['performance.unbounded_hierarchy'] = old_config_value get :show, params: { lang: 'en', format: 'html', root: 'root', depth: 'invalid' } assert_response 400 assert_equal 'invalid depth parameter', flash[:error] end test 'direction handling' do get :show, params: { lang: 'en', format: 'html', root: 'root' } entries = get_entries('ul.concept-hierarchy > li') assert_equal ['Root'], entries entries = get_entries('ul.concept-hierarchy > li > ul > li > ul > li > ul > li') assert_equal ['Dos', 'Uno'], entries get :show, params: { lang: 'en', format: 'html', root: 'root', dir: 'up' } entries = get_entries('ul.concept-hierarchy li') assert_equal ['Root'], entries entries = css_select('ul.concept-hierarchy li li') assert_equal 0, entries.length get :show, params: { lang: 'en', format: 'html', root: 'lorem' } entries = get_entries('ul.concept-hierarchy li') assert_equal ['Lorem'], entries entries = css_select('ul.concept-hierarchy li li') assert_equal 0, entries.length get :show, params: { lang: 'en', format: 'html', root: 'lorem', dir: 'up' } entries = get_entries('ul.concept-hierarchy > li') assert_equal ['Lorem'], entries entries = get_entries('ul.concept-hierarchy li > ul > li > ul > li > ul > li') assert_equal ['Bar'], entries entries = css_select('ul.concept-hierarchy li > ul > li > ul > li > ul > li > ul > li') assert_equal 0, entries.length get :show, params: { lang: 'en', format: 'html', root: 'lorem', dir: 'up', depth: 4 } page.all('ul.concept-hierarchy li'). map { |node| node.native.children.first.text } entries = get_entries('ul.concept-hierarchy > li > ul > li > ul > li > ul > li > ul > li') assert_equal ['Root'], entries end test 'siblings handling' do get :show, params: { lang: 'en', format: 'html', root: 'foo' } entries = get_all_entries('ul.concept-hierarchy li') assert_equal ['Foo'], entries get :show, params: { lang: 'en', format: 'html', root: 'foo', siblings: 'true' } entries = get_all_entries('ul.concept-hierarchy li') # binding.pry assert_equal ['Bar', 'Foo'], entries get :show, params: { lang: 'en', format: 'html', root: 'lorem' } entries = get_all_entries('ul.concept-hierarchy li') assert_equal ['Lorem'], entries get :show, params: { lang: 'en', format: 'html', root: 'lorem', dir: 'up', siblings: 'true' } entries = get_all_entries('ul.concept-hierarchy li') assert_equal 8, entries.length ['Lorem', 'Ipsum', 'Uno', 'Dos', 'Alpha', 'Bravo', 'Bar', 'Foo'].each do |name| assert entries.include?(name), "missing entry: #{name}" end get :show, params: { lang: 'en', format: 'html', root: 'lorem', dir: 'up', siblings: '1', depth: 4 } entries = get_all_entries('ul.concept-hierarchy li') assert_equal 9, entries.length ['Lorem', 'Ipsum', 'Uno', 'Dos', 'Alpha', 'Bravo', 'Bar', 'Foo', 'Root'].each do |name| assert entries.include?(name), "missing entry: #{name}" end end test 'avoid duplication' do # in response to a bug report get :show, params: { lang: 'en', format: 'ttl', root: 'uno', dir: 'up' } assert_response 200 assert_equal 'text/turtle', @response.media_type assert @response.body.include?(<<-EOS) :bravo a skos:Concept; skos:prefLabel "Bravo"@en; skos:broader :bar. EOS assert (not @response.body.include?(':bravo skos:prefLabel "Bravo"@en.')) end def get_all_entries(selector) return page.all(selector).map { |node| node.native.children.first.text } end def get_entries(selector) return css_select(selector).map { |node| node.children.first.content } end def page # XXX: should not be necessary!? return Capybara::Node::Simple.new(@response.body) end def create_hierarchy(hash, rel_class, memo = nil, parent =nil) hash.each do |origin, children| concept = create_concept(origin, origin.capitalize, 'en') memo[origin] = concept if memo link_concepts(parent, rel_class, concept) if parent create_hierarchy(children, rel_class, memo, concept) unless children.blank? end return memo end def link_concepts(source, rel_class, target) rel_name = rel_class.name.to_relation_name source.send(rel_name).create_with_reverse_relation(target) end def create_concept(origin, pref_label, label_lang, published=true) concept = Iqvoc::Concept.base_class.create(origin: origin, published_at: (published ? Time.now : nil)) label = Iqvoc::Label.base_class.create(value: pref_label, language: label_lang) labeling = Iqvoc::Concept.pref_labeling_class.create(owner: concept, target: label) return concept end end
require './msg_base' require './msg_types' class MessageMessage < BaseMessage def initialize(header: nil, flags: 1, kind: 0, sections: []) @header = header @flags = flags @sections = sections if @header != nil @header.op_code = OP_MSG end end def calculate_message_size message_length = @header.my_size + 4 @sections.each do |iter_section| message_length += iter_section.calculate_message_size end message_length += 4 #For CRC, assuming non-TLS if @header != nil @header.message_length = message_length end message_length end #TODO - Create a docs custom accessor method to return the section 0 document attr_accessor :flags, :sections end
require_dependency "help/api/v1/application_controller" module Help class Api::V1::HelpOfferedsController < Api::V1::ApplicationController before_action :authorize_for_controller before_action :set_help_offered, only: [:show, :edit, :update, :destroy] # GET /help_offereds def index render json: HelpOffered.all end # GET /help_offereds/1 def show render json: @help_offered end # GET /help_offereds/new def new render json: HelpOffered.new end # POST /help_offereds def create @help_offered = HelpOffered.new(help_offered_params) if @help_offered.save render json: @help_offered else render :json => {errors: @help_offered.errors} , status: :unprocessable_entity end end # PATCH/PUT /help_offereds/1 def update if @help_offered.update(help_offered_params) render json: @help_offered else render :json => {errors: @help_offered.errors} , status: :unprocessable_entity end end # DELETE /help_offereds/1 def destroy @help_offered.destroy render json: {} end private # Use callbacks to share common setup or constraints between actions. def set_help_offered @help_offered = HelpOffered.find(params[:id]) end # Only allow a trusted parameter "white list" through. def help_offered_params params.require(:help_offered).permit(:title, :imageable_id, :imageable_type) end def authorize_for_controller end end end
require 'spec_helper' describe Ausgabe do before do @ausgabe = Ausgabe.new(ausgabedatum: Date::current, rueckgabedatum: Date::tomorrow, kommentar: "tolle Karte, tun wir jetzt mal weg") end subject { @ausgabe } it { should respond_to(:ausgabedatum) } it { should respond_to(:rueckgabedatum) } it { should respond_to(:kommentar) } end
Rails.application.routes.draw do devise_for :users, controllers:{ omniauth_callbacks: "user/omniauth_callbacks" } resources :articles root to: "home#index" get "todo", to: "articles#home_view" # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
require "uri" module SwaggerClient class JobsApi basePath = "http://api2.online-convert.com/" # apiInvoker = APIInvoker # List of jobs active for the current user identified by the key. # It will return the list of jobs for the given user. In order to get the jobs a key or token must be provided:\n - If the user key is provided all jobs for the current will be return.\n - If one token is provided it will return the job assigned to that token if any.\n \nThe request is paginated with an amount of 50 elements per page in any case.\n # @param [Hash] opts the optional parameters # @option opts [string] :status Filter the status of the job. # @option opts [string] :x_oc_token Token for authentication for the current job # @option opts [string] :x_oc_api_key Api key for the user to filter. # @option opts [number] :page Pagination for list of elements. # @return [array[Job]] def self.jobs_get(opts = {}) # resource path path = "/jobs".sub('{format}','json') # query parameters query_params = {} query_params[:'status'] = opts[:'status'] if opts[:'status'] query_params[:'page'] = opts[:'page'] if opts[:'page'] # header parameters header_params = {} # HTTP header 'Accept' (if needed) _header_accept = [] _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) header_params[:'X-Oc-Token'] = opts[:'x_oc_token'] if opts[:'x_oc_token'] header_params[:'X-Oc-Api-Key'] = opts[:'x_oc_api_key'] if opts[:'x_oc_api_key'] # form parameters form_params = {} # http body (model) post_body = nil auth_names = [] response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body response.map {|response| obj = Job.new() and obj.build_from_hash(response) } end # Creates a new Job with the user key. # # @param x_oc_api_key Api key for the user to filter. # @param body Content of the job. # @param [Hash] opts the optional parameters # @return [Job] def self.jobs_post(x_oc_api_key, body, opts = {}) # verify the required parameter 'x_oc_api_key' is set raise "Missing the required parameter 'x_oc_api_key' when calling jobs_post" if x_oc_api_key.nil? # verify the required parameter 'body' is set raise "Missing the required parameter 'body' when calling jobs_post" if body.nil? # resource path path = "/jobs".sub('{format}','json') # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) _header_accept = [] _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) header_params[:'X-Oc-Api-Key'] = x_oc_api_key # form parameters form_params = {} # http body (model) post_body = Swagger::Request.object_to_http_body(body) auth_names = [] response = Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body obj = Job.new() and obj.build_from_hash(response) end # Get information about a Job # # @param job_id ID of job that needs to be fetched # @param [Hash] opts the optional parameters # @option opts [string] :x_oc_token Token for authentication for the current job # @option opts [string] :x_oc_api_key Api key for the user to filter. # @return [Job] def self.jobs_job_id_get(job_id, opts = {}) # verify the required parameter 'job_id' is set raise "Missing the required parameter 'job_id' when calling jobs_job_id_get" if job_id.nil? # resource path path = "/jobs/{job_id}".sub('{format}','json').sub('{' + 'job_id' + '}', job_id.to_s) # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) _header_accept = [] _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) header_params[:'X-Oc-Token'] = opts[:'x_oc_token'] if opts[:'x_oc_token'] header_params[:'X-Oc-Api-Key'] = opts[:'x_oc_api_key'] if opts[:'x_oc_api_key'] # form parameters form_params = {} # http body (model) post_body = nil auth_names = [] response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body obj = Job.new() and obj.build_from_hash(response) end # Cancels a job created that haven&#39;t been started. (Allow to cancel jobs in process.) # # @param job_id ID of job that needs to be fetched # @param [Hash] opts the optional parameters # @option opts [string] :x_oc_token Token for authentication for the current job # @option opts [string] :x_oc_api_key Api key for the user to filter. # @return [Job] def self.jobs_job_id_delete(job_id, opts = {}) # verify the required parameter 'job_id' is set raise "Missing the required parameter 'job_id' when calling jobs_job_id_delete" if job_id.nil? # resource path path = "/jobs/{job_id}".sub('{format}','json').sub('{' + 'job_id' + '}', job_id.to_s) # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) _header_accept = [] _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) header_params[:'X-Oc-Token'] = opts[:'x_oc_token'] if opts[:'x_oc_token'] header_params[:'X-Oc-Api-Key'] = opts[:'x_oc_api_key'] if opts[:'x_oc_api_key'] # form parameters form_params = {} # http body (model) post_body = nil auth_names = [] response = Swagger::Request.new(:DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body obj = Job.new() and obj.build_from_hash(response) end # Modifies the job identified by the id, allows to start a created job. # # @param body Content of the job. # @param job_id ID of job that needs to be fetched # @param [Hash] opts the optional parameters # @option opts [string] :x_oc_token Token for authentication for the current job # @option opts [string] :x_oc_api_key Api key for the user to filter. # @return [Job] def self.jobs_job_id_patch(body, job_id, opts = {}) # verify the required parameter 'body' is set raise "Missing the required parameter 'body' when calling jobs_job_id_patch" if body.nil? # verify the required parameter 'job_id' is set raise "Missing the required parameter 'job_id' when calling jobs_job_id_patch" if job_id.nil? # resource path path = "/jobs/{job_id}".sub('{format}','json').sub('{' + 'job_id' + '}', job_id.to_s) # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) _header_accept = [] _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) header_params[:'X-Oc-Token'] = opts[:'x_oc_token'] if opts[:'x_oc_token'] header_params[:'X-Oc-Api-Key'] = opts[:'x_oc_api_key'] if opts[:'x_oc_api_key'] # form parameters form_params = {} # http body (model) post_body = Swagger::Request.object_to_http_body(body) auth_names = [] response = Swagger::Request.new(:PATCH, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body obj = Job.new() and obj.build_from_hash(response) end # Get list of threads defined for the current job. # # @param job_id ID of job that needs to be fetched # @param [Hash] opts the optional parameters # @option opts [string] :x_oc_token Token for authentication for the current job # @option opts [string] :x_oc_api_key Api key for the user to filter. # @return [array[Thread]] def self.jobs_job_id_threads_get(job_id, opts = {}) # verify the required parameter 'job_id' is set raise "Missing the required parameter 'job_id' when calling jobs_job_id_threads_get" if job_id.nil? # resource path path = "/jobs/{job_id}/threads".sub('{format}','json').sub('{' + 'job_id' + '}', job_id.to_s) # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) _header_accept = [] _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) header_params[:'X-Oc-Token'] = opts[:'x_oc_token'] if opts[:'x_oc_token'] header_params[:'X-Oc-Api-Key'] = opts[:'x_oc_api_key'] if opts[:'x_oc_api_key'] # form parameters form_params = {} # http body (model) post_body = nil auth_names = [] response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body response.map {|response| obj = Thread.new() and obj.build_from_hash(response) } end end end
FactoryGirl.define do factory :sport do name { FFaker::Sport.name } end end
# $Id$ module EternosBackup # DataSchedules # # Could be db-driven but for now contains static min. time intervals for each kind # of backup data set module DataSchedules # Minimum backup intervals times for each data set MinDataBackupIntervals = { EternosBackup::SiteData::General => 24.hours, # default backup interval EternosBackup::SiteData::FacebookOtherWallPosts => 24.hours, EternosBackup::SiteData::FacebookPhotoComments => 24.hours } # Minium backup intervals times for failed backups for each data set MinDataBackupRetryIntervals = { EternosBackup::SiteData::General => 4.hours, EternosBackup::SiteData::FacebookOtherWallPosts => 12.hours } class << self def min_backup_interval(ds) MinDataBackupIntervals.has_key?(ds) ? MinDataBackupIntervals[ds] : nil end def min_backup_retry_interval(ds) MinDataBackupRetryIntervals.has_key?(ds) ? MinDataBackupRetryIntervals[ds] : nil end end end end
# frozen_string_literal: true require 'spec_helper' require_relative '../../lib/app.rb' RSpec.describe Logs::Webserver do subject { described_class.new(log_path) } let(:log_path) do File.join(File.expand_path('../fixtures', __dir__), 'webserver_3_lines.log') end let(:expected_lines_array) do [ '/help_page/1 451.106.204.921', '/home 444.701.448.104', '/index 929.398.951.889' ] end let(:line_sample) do '/index 929.398.951.889' end describe '#lines' do it { expect(subject.lines).to eq expected_lines_array } end describe '#extract_ip_from' do it { expect(subject.extract_ip_from(line_sample)).to eq '929.398.951.889' } end describe '#extract_url_from' do it { expect(subject.extract_url_from(line_sample)).to eq '/index' } end end
require 'observer' module Subject def initialize @observers=[] end def add_observer(observer) @observers << observer end def delete_observer(observer) @observers.delete(observer) end def notify_observers @observers.each do |observer| observer.update(self) end end end class Payroll def update( changed_employee ) puts("Cut a new check for #{changed_employee.name}!") puts("His salary is now #{changed_employee.salary}!") end end class TaxMan def update( changed_employee ) puts("Send #{changed_employee.name} a new tax bill!") end end class Employee include Observable attr_reader :name, :address attr_reader :salary def initialize( name, title, salary) super() @name = name @title = title @salary = salary end def salary=(new_salary) old_salary = @salary @salary = new_salary if old_salary != new_salary changed notify_observers(self) end end def title=(new_title) old_title = @title @title = new_title if old_title != new_title changed = true notify_observers(self) end end end fred = Employee.new("Fred", "Crane Operator", 30000) fred.salary = 1000000 # Warning! Inconsistent state here! fred.title = 'Vice President of Sales' puts ("Freds salary: #{fred.salary}")
class NotificationMailer < ApplicationMailer default from: "golikealocal@gmail.com" # Need to insert instance variables in mail template. def notification_email(subscriptions) @subscriptions = @subscriptions mail(to: @subscriptions, subject: 'Your Pet has been located!') end end
# frozen_string_literal: true require 'client/multipart_upload/chunks_client' require_relative 'upload_client' module Uploadcare module Client # Client for multipart uploads # # @see https://uploadcare.com/api-refs/upload-api/#tag/Upload class MultipartUploaderClient < UploadClient include MultipartUpload # Upload a big file by splitting it into parts and sending those parts into assigned buckets # object should be File def upload(object, options = {}, &block) response = upload_start(object, options) return response unless response.success[:parts] && response.success[:uuid] links = response.success[:parts] uuid = response.success[:uuid] ChunksClient.upload_chunks(object, links, &block) upload_complete(uuid) end # Asks Uploadcare server to create a number of storage bin for uploads def upload_start(object, options = {}) body = HTTP::FormData::Multipart.new( Param::Upload::UploadParamsGenerator.call(options).merge(form_data_for(object)) ) post(path: 'multipart/start/', headers: { 'Content-Type': body.content_type }, body: body) end # When every chunk is uploaded, ask Uploadcare server to finish the upload def upload_complete(uuid) body = HTTP::FormData::Multipart.new( { UPLOADCARE_PUB_KEY: Uploadcare.config.public_key, uuid: uuid } ) post(path: 'multipart/complete/', body: body, headers: { 'Content-Type': body.content_type }) end private def form_data_for(file) form_data_file = super(file) { filename: form_data_file.filename, size: form_data_file.size, content_type: form_data_file.content_type } end alias api_struct_post post def post(**args) handle_throttling { api_struct_post(**args) } end end end end
class NameList def showList(nameList) nameList.map {|x| print "#{nameList.index(x)+1} - #{x}\n" } end def addName(nameList, name) name.split.each{|x| if x =~/[0-9]/ then return puts "The name can not contain numbers" end } nameList << name puts "In the list of added a new name - #{name}. Now in the list of #{nameList.size} names" end def limitTheList (nameList, sizeList) if nameList.length <= sizeList then p "List in the normal range" showList(nameList) else nameList.pop(nameList.length-sizeList) p "The list is reduced to # {sizeList} names" showList(nameList) end end def randomList (nameList,*sizeList) nameList.shuffle! if sizeList[0] == nil showList(nameList) else limitTheList(nameList, sizeList[0]) end end end nList = ["Bobik", "Sharik", "Muhtar", "Evlampiya","Mary Currie","Anatoly Petrovich Shvartsengold"] nl = NameList.new nl.showList(nList) p "==============================================" p "Add Lilia to list" nl.addName(nList, "Lilia") p "==============================================" p "list limited to 8" nl.limitTheList(nList, 8) p "==============================================" p "list limited to 5" nl.limitTheList(nList, 5) p "==============================================" p "Random list" nl.randomList(nList) p "==============================================" p "Random list limited to 3" nl.randomList(nList, 3)
module CarrierWave module BombShelter VERSION = '0.2.1'.freeze end end
require 'bike' describe Bike do context "when first created" do it 'has a broken method' do expect(Bike.new).to respond_to(:broken) end it 'broken attr defaults to false' do expect(Bike.new.broken).to eq(false) end end end
class Upload < ActiveRecord::Base attr_protected :id, :parent_id, :content_type, :filename, :thumbnail, :size, :width, :height, :user_id, :created_at, :updated_at belongs_to :user has_attachment :storage => :file_system, :partition => false, :path_prefix => 'public/files', :max_size => 100.megabytes include AttachmentFuExtensions def is_mp3? return true if %w(audio/mpeg audio/mpg).include?(content_type) end def to_s filename end def to_param "#{id}-#{to_s.parameterize}" end end
class CustomerTypesController < ApplicationController before_action :set_customer_type, only: [:show, :update, :destroy] # GET /customer_types def index @customer_types = CustomerType.all render json: @customer_types end # GET /customer_types/1 def show render json: @customer_type end # POST /customer_types def create @customer_type = CustomerType.new(customer_type_params) if @customer_type.save render json: @customer_type, status: :created, location: @customer_type else render json: @customer_type.errors, status: :unprocessable_entity end end # PATCH/PUT /customer_types/1 def update if @customer_type.update(customer_type_params) render json: @customer_type else render json: @customer_type.errors, status: :unprocessable_entity end end # DELETE /customer_types/1 def destroy @customer_type.destroy end private # Use callbacks to share common setup or constraints between actions. def set_customer_type @customer_type = CustomerType.find(params[:id]) end # Only allow a trusted parameter "white list" through. def customer_type_params params.require(:customer_type).permit(:customer_type_id, :customer_type_description, :customer_type_status) end end
require 'rails_helper' RSpec.describe Chef, type: :model do describe "validations" do it {should validate_presence_of :name} end describe "relationships" do it {should have_many :dishes} end describe "Instance Methods" do it "All Ingredients Method" do bob = Chef.create!(name: "Bob") pasta = Dish.create!(name: "Pasta", description: "Noodle Dish", chef_id: bob.id) noodles = Ingredient.create!(name: "Noodles", calories: 50) sause = Ingredient.create!(name: "Sause", calories: 100) meatballs = Ingredient.create!(name: "Meatballs", calories: 150) tacos = Dish.create!(name: "Tacos", description: "Chicken Tacos", chef_id: bob.id) shell = Ingredient.create!(name: "Taco Shell", calories: 20) chicken = Ingredient.create!(name: "Chicken Breast", calories: 120) lettuce = Ingredient.create!(name: "Romane Lettuce", calories: 30) sause = Ingredient.create!(name: "Sauce", calories: 100) DishIngredient.create!(dish_id: pasta.id, ingredient_id: noodles.id) DishIngredient.create!(dish_id: pasta.id, ingredient_id: sause.id) DishIngredient.create!(dish_id: pasta.id, ingredient_id: meatballs.id) DishIngredient.create!(dish_id: tacos.id, ingredient_id: shell.id) DishIngredient.create!(dish_id: tacos.id, ingredient_id: chicken.id) DishIngredient.create!(dish_id: tacos.id, ingredient_id: lettuce.id) DishIngredient.create!(dish_id: tacos.id, ingredient_id: sause.id) expect(bob.all_ingredients).to eq([noodles.name, meatballs.name, sause.name, shell.name, chicken.name, lettuce.name]) end end end
class Product < ActiveRecord::Base belongs_to :company has_and_belongs_to_many :branches validates :description, presence: true has_attached_file :picture, :styles => { :medium => '300x300>', :thumb => '100x100>' }, :default_url => "/images/:style/missing.png" validates_attachment_presence :picture end
class LikesController < ApplicationController before_action :authenticate_user #ログインしていないユーザに対するアクセス制限 def index @likes = Like.where(user_id: @current_user.id) end def like @like = Like.new(user_id: @current_user.id, trainer_id: params[:trainer_id]) @like.save redirect_to("/likes/index") end def unlike @like = Like.find_by(user_id: @current_user.id, trainer_id: params[:trainer_id]) @like.destroy redirect_to("/likes/index") end end
module Adminpanel class PagesController < Adminpanel::ApplicationController before_action :redefine_model def show end def edit params[:skip_breadcrumb] = true super end def update if @resource_instance.update(page_params) redirect_to page_path(@resource_instance) else params[:skip_breadcrumb] = true render 'adminpanel/templates/edit' end end private def redefine_model @model = @resource_instance.class end def page_params @model.whitelisted_attributes(params) end end end
module ApplicationHelper def colored_tags(question_tags) if question_tags.any? content_tag(:small) do "Tags: ".html_safe + question_tags.map do |qt| content_tag(:span, qt.name, style: "color: #{qt.color}") end.join(', ').html_safe end end end end
class TrialFilterForm EMPTY_FILTER_APPLIED_EVENT = "Empty Filter Applied".freeze FILTER_APPLIED_EVENT = "Filter Applied".freeze FILTER_WITH_VALUE_ALWAYS_SET = "distance_radius".freeze NON_FILTER = "session_id".freeze USER_WITHOUT_SESSION = "123456".freeze ZIP_CODE_MATCH = /\A\d{5}(-\d{4})?\z/ include ActiveModel::Model attr_accessor( :age, :control, :distance_radius, :gender, :keyword, :page, :session_id, :study_type, :zip_code, ) validates( :age, numericality: { only_integer: true, allow_blank: true, less_than_or_equal_to: 120, greater_than_or_equal_to: 1 } ) validate :valid_zip_code def valid_zip_code if zip_code.present? && zip_code_record.nil? errors.add(:zip_code, "is not a valid 5-digit zip") end end def initialize(*args) super(*args) track_events(*args) end def trials @trials ||= if valid? filtered_trials.paginate(page: page) else Trial.none end end def trial_ids filtered_trials.pluck(:id) end def coordinates if zip_code_record.present? zip_code_record.coordinates end end private def zip_code_record ZipCode.find_by(zip_code: zip_code) end def filtered_trials @_filtered_trials ||= filter_trial_query end def filter_trial_query Trial .search_for(keyword) .age(age) .control(control) .gender(gender) .study_type(study_type) .close_to(close_to_arguments) end def close_to_arguments { zip_code: zip_code, radius: distance_radius, } end def analytics Rails.application.config.analytics end def track_events(args = {}) filters = args.dup.except!(NON_FILTER) if filters.present? filters_with_value = fetch_filters_with_value(filters) track_filter_event(filters_with_value) end end def track_filter_event(filters) event = if filters.present? analytics_event.merge( event: FILTER_APPLIED_EVENT, properties: event_properties, ) else analytics_event. merge(event: EMPTY_FILTER_APPLIED_EVENT) end analytics.track(event) end def analytics_event { anonymous_id: anonymous_id } end def anonymous_id session_id || USER_WITHOUT_SESSION end def fetch_filters_with_value(filters) filters.dup.except!(FILTER_WITH_VALUE_ALWAYS_SET). keep_if { |_, value| value.present? } end def event_properties { age: age_as_integer, control_only: control, distance_radius: distance_radius.to_i, gender: gender, keyword: keyword.try(:downcase), match_count: trials.count, study_type: study_type, zip_code: zip_code, }.delete_if { |_, v| v.blank? } end def age_as_integer age.to_i if age.present? end end
FactoryGirl.define do factory :article do title "Of Mice And Men" author "John Steinbeck" end end
class UpdateParametersTable < ActiveRecord::Migration def change drop_table :request_at_times end end
require 'cinch' require 'yahoo_weatherman' class Weather include Cinch::Plugin def initialize(bot) super bot @client = Weatherman::Client.new end match /weather (.+)/ def execute(m, location) m.reply lookup location end private def lookup(location) response = @client.lookup_by_location(location) response.location.is_a?(Nokogiri::XML::Node) ? get_weather_text(response) : 'Not found' end def get_weather_text(r) "#{get_location_text r.location} :: #{get_condition_text r.condition, r.units} :: Wind: #{get_wind_text r.wind, r.units}" end def get_location_text(location) "#{location['city']}, #{location['country']}" end def get_condition_text(condition, units) "#{condition['text']}, #{condition['temp']}\u00B0#{units['temperature']}" end def get_wind_text(wind, units) "#{wind['speed']}#{units['speed']}" end end
FactoryGirl.define do factory :client do name { Faker::Company.name } abbreviation { Faker::Lorem.characters(5) } end end
require 'ffi' class Tuple < FFI::Struct layout :x, :uint32, :y, :uint32 def to_s "(#{self[:x]},#{self[:y]})" end end module Tuples extend FFI::Library ffi_lib 'target/debug/libtuples.dylib' attach_function :flip_things_around, [Tuple.by_value], Tuple.by_value end tup = Tuple.new tup[:x] = 10 tup[:y] = 20 puts Tuples.flip_things_around(tup)
class Asset < ApplicationRecord has_many :asset_fields, dependent: :destroy end
# Require gems Bundler.require(:default, ENV['RACK_ENV']) # Main entrypoint to require source files def require_recursive(path) files_list = Dir["#{File.dirname(__FILE__)}/#{path}/**/*.rb"].sort files_list.each { |f| require f } end # Configuration files require_recursive 'config' # Application files require_recursive 'app' # Lib require_recursive 'lib'
# Copyright (c) 2006, 2007 Ruffdogs Software, Inc. # Authors: Adam Lebsack <adam@holonyx.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. module MysqlTargetTree class Server < ::TreeItem def initialize(target, snapshot) @target = target # XXX don't save these! save the IDs! @snapshot = snapshot super('server', :name => "mysql://#{@target.username}@#{@target.hostname}/", :partial_name => 'browse_server', :expanded => true) end def load_children @children ||= {} @target.databases.each do |database| if (l = database.log_for_snapshot(@snapshot)) && l.event != 'D' if c = @children[database.id.to_s] c.set_snapshot(@snapshot) else self << Database.new(database, @snapshot, l) end else @children.delete(database.id.to_s) end end end def set_snapshot(snapshot) @snapshot = snapshot if expanded load_children end end end end
require_relative "./element" class Metacrunch::ULBD::Record::Beziehung < Metacrunch::ULBD::Record::Element SUBFIELDS = { p: { "Beziehungskennzeichnung" => :W }, n: { "Bemerkung" => :W }, a: { "Titel" => :NW, "Titel der in Beziehung stehenden Ressource" => :NW }, "9": { "Identifikationsnummer" => :NW, "Identifikationsnummer des Datensatzes der in Beziehung stehenden Ressource" => :NW }, Z: { "Zuordnung zum originalschriftlichen Feld" => :NW } } def get(*args) if (result = super).is_a?(Array) result.map { |element| sanitize(element) } else sanitize(result) end end private def default_value(options = {}) [ [ get("Beziehungskennzeichnung").try(:first), # there are no real examples with more than one of it get("Bemerkung").try(:first) ] .compact .join(" ") .presence, get("Titel der in Beziehung stehenden Ressource") ] .compact .join(": ") .presence .try do |result| sanitize(result) end end def sanitize(value) if value value .gsub("--->", ":") .gsub(/\.\s*\:/, ".:") .gsub(/:*\s*:/, ":") .strip end end end
require 'open-uri' require "net/http" require 'rss' namespace :rss do desc "Daemon for fetching rss feeds" task daemon: :environment do begin Feed.find_each(batch_size: 10) do |feed| begin data = open(feed.url) fetched_feed = RSS::Parser.parse(data, false) fetched_feed.channel.items.collect do | item | if Article.where(link: item.link).blank? parse_description = Nokogiri::HTML(item.description).css("body").text item_date = item.date item_date = DateTime.now if item_date.nil? new_article = Article.create( title: item.title, description: parse_description, link: item.link, date: item_date, feed_id: feed.id ) end end rescue => e p "Rescued network error: #{e.inspect}" end end rescue => e p "Rescued general error: #{e.inspect}" end end end
class ApplicationController < ActionController::Base before_action :authenticate_user! protect_from_forgery with: :exception before_action :configure_permitted_parameters, if: :devise_controller? before_action :mark_notification_as_read def mark_notification_as_read if params[:notification_id] notif = current_user.notifications.where(id: params[:notification_id]).first notif.update_attributes(read_at: Time.now) end end def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up) { |u| u.permit(:first_name,:last_name,:email, :password, :password_confirmation, :mobile,:terms_and_conditions,:img_url, roles: []) } end end
require 'puppet/parameter/boolean' Puppet::Type.newtype(:oneandone_loadbalancer) do @doc = 'Type representing a 1&1 load balancer.' ensurable newparam(:name, namevar: true) do desc 'The name of the load balancer.' validate do |value| raise('The name should be a String.') unless value.is_a?(String) end end newproperty(:rules, array_matching: :all) do desc 'The load balancer rules.' def insync?(is) if is.is_a? Array old_rules = is.sort {|i1, i2| [i1[:protocol], i1[:port_balancer]] <=> [i2[:protocol], i2[:port_balancer]]} new_rules = should.sort {|i1, i2| [i1['protocol'], i1['port_balancer']] <=> [i2['protocol'], i2['port_balancer']]} return provider.rules_deep_equal?(old_rules, new_rules) else return is == should end end end newproperty(:id) do desc 'The load balancer ID.' end newproperty(:description) do desc 'The load balancer description.' end newproperty(:datacenter, :readonly => true) do desc 'The data center where the load balancer is created.' defaultto 'US' def insync?(is) true end end newproperty(:persistence) do desc 'Persistence.' defaultto :false newvalues(:true, :false) def insync?(is) is.to_s == should.to_s end end newproperty(:persistence_time) do desc 'The persistence time in seconds.' validate do |value| raise('Persistence time must be an integer.') unless value.is_a?(Integer) end end newproperty(:health_check_test) do desc 'Type of the health check.' defaultto 'NONE' newvalues('NONE', 'TCP', 'ICMP', 'HTTP') end newproperty(:health_check_interval) do desc 'The health check period in seconds.' validate do |value| raise('Health check period must be an integer.') unless value.is_a?(Integer) end end newproperty(:method) do desc 'The Load balancing method.' validate do |value| raise('Load balancing method is required.') if value.nil? raise('Load balancing method must be a string.') unless value.is_a?(String) end munge do |value| if value.is_a?(String) value.upcase else value end end newvalues('ROUND_ROBIN', 'LEAST_CONNECTIONS') end newproperty(:health_check_path) do desc 'The URL to call for health cheking.' validate do |value| raise('The health check path must be a string.') unless value.is_a?(String) end end newproperty(:health_check_parse) do desc 'A regular expression for the health check.' validate do |value| raise('The health check regex must be a string.') unless value.is_a?(String) end end newproperty(:server_ips, array_matching: :all) do desc 'The servers/IPs attached to the load balancer.' def insync?(is) if is.is_a? Array return is.sort == should.sort else return is == should end end end end
class CreateContasReceber < ActiveRecord::Migration def change create_table :contas_receber do |t| t.references :cliente t.date :vencimento t.float :valor t.timestamps end add_index :contas_receber, :cliente_id end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe Api::V1::BillsController, type: :controller do describe 'GET #index' do context 'when there is no bill' do before { get :index, format: :json } it('returns http success') { expect(response).to have_http_status(:success) } end context 'when there are some bills' do before do create_list :bill, 2 get :index, format: :json end it('returns http success') { expect(response).to have_http_status(:success) } end end describe 'GET #show' do before { get :show, params: { id: bill_id }, format: :json } context 'when bill ID does not exist' do let(:bill_id) { 999 } it('returns http not_found') { expect(response).to have_http_status(:not_found) } end context 'when bill ID exists' do let(:bill) { create :bill } let(:bill_id) { bill.id } it('returns http success') { expect(response).to have_http_status(:success) } end end end
class ChangeDataTypeForTimeSlot < ActiveRecord::Migration def up add_column :time_slots, :start_time_tmp, :datetime add_column :time_slots, :end_time_tmp, :datetime TimeSlot.reset_column_information TimeSlot.all.each do |time_slot| time_slot.start_time_tmp = DateTime.parse(time_slot.start_time.to_s) time_slot.end_time_tmp = DateTime.parse(time_slot.end_time.to_s) time_slot.save end remove_column :time_slots, :start_time remove_column :time_slots, :end_time rename_column :time_slots, :start_time_tmp, :start_time rename_column :time_slots, :end_time_tmp, :end_time end def down add_column :time_slots, :start_time_tmp, :time add_column :time_slots, :end_time_tmp, :time TimeSlot.reset_column_information TimeSlot.all.each do |time_slot| time_slot.start_time_tmp = Time.parse(time_slot.start_time.to_s) time_slot.end_time_tmp = Time.parse(time_slot.end_time.to_s) time_slot.save end remove_column :time_slots, :start_time remove_column :time_slots, :end_time rename_column :time_slots, :start_time_tmp, :start_time rename_column :time_slots, :end_time_tmp, :end_time end end
# frozen_string_literal: true module Sam module Unicorn class Identifier def initialize @configurator = ::Unicorn::Configurator.new end def call(config_file) @configurator.instance_eval configuration(config_file) Integer(read_pidfile) end private def read_pidfile IO.readlines(@configurator.set[:pid]).join.chomp rescue Errno::ENOENT raise Errors::PidfileNotFound, "PID File #{@configurator.set[:pid]} not found" end def configuration(config_file) IO.readlines(config_file).join rescue Errno::ENOENT raise Errors::ConfigfileNotFound, "File #{config_file} not found" end end end end
require 'rails_helper' RSpec.describe SellCart, type: :model do describe "about sellcart function" do it "可以加入已存在的商品" do p1 = Product.create(title: 'ball', quantity: 10) sellcart = SellCart.new sellcart.add_sellitem(p1.id) expect(sellcart.empty?).to be false end it "加入的商品數量,都從一開始" do p1 = Product.create(title: 'ball', quantity: 10) p2 = Product.create(title: 'foot', quantity: 20) sellcart = SellCart.new sellcart.add_sellitem(p1.id) sellcart.add_sellitem(p2.id) expect(sellcart.sellitems.first.quantity).to be 1 expect(sellcart.sellitems.last.quantity).to be 1 end it "販賣車每增加一個商品,商品的數量就會減一" do p1 = Product.create(title: 'ball', quantity: 10) p2 = Product.create(title: 'foot', quantity: 20) sellcart = SellCart.new buyout = Buyout.new buyout.add_item(p1.id) buyout.add_item(p2.id) 3.times{sellcart.add_sellitem(p1.id)} 5.times{sellcart.add_sellitem(p2.id)} expect(sellcart.sellitems.first.quantity).to eq 3 expect(sellcart.sellitems.last.quantity).to eq 5 # expect(buyout.commodities.last.product.quantity).to eq 15 end it "販賣車的數量,不可以超過商品數量,否則商品加入失敗" do p1 = Product.create(title: 'ball', quantity: 10) p2 = Product.create(title: 'foot', quantity: 20) sellcart = SellCart.new 15.times{sellcart.add_sellitem(p1.id)} 15.times{sellcart.add_sellitem(p2.id)} expect(sellcart.sellitems.first.quantity).to eq 10 expect(sellcart.sellitems.last.quantity).to eq 15 end it "加入販賣車的商品,可以再取消加入" do p1 = Product.create(title: 'ball', quantity: 10) p2 = Product.create(title: 'foot', quantity: 20) sellcart = SellCart.new 5.times{sellcart.add_sellitem(p1.id)} 3.times{sellcart.dec_sellitem(p1.id)} expect(sellcart.sellitems.first.quantity).to be 2 end it "取消加入商品後,商品增加的數量會等於販賣車商品取消的數量" do end it "販賣車會自動計算價格"do end it "可以寄信給買家" it "可以查看之前的訊息紀錄" it "可以觀看買家平價" it "可以被評價" it "可以查看自己的交易紀錄" end end
require 'spec_fast_helper' require 'hydramata/works/value_presenter' require 'hydramata/works/work' require 'hydramata/works/predicate' module Hydramata module Works describe ValuePresenter do let(:work) { Work.new(work_type: 'a work type') } let(:predicate) { Predicate.new(identity: 'a predicate') } let(:value) { double('Value', to_s: 'HELLO WORLD') } let(:renderer) { double('Renderer', call: true) } let(:template) { double('Template') } subject { described_class.new(value: value, work: work, predicate: predicate, renderer: renderer) } it 'renders via the template' do expect(renderer).to receive(:call).with(template, kind_of(Hash)).and_return('YES') expect(subject.render(template)).to eq('YES') end it 'renders the value as a string' do expect(renderer).to receive(:call).with(template, kind_of(Hash)).and_yield expect(subject.render(template)).to eq(value.to_s) end it 'has a default partial prefixes' do expect(subject.partial_prefixes).to eq([['a_work_type','a_predicate'], ['a_predicate']]) end it 'has a label that delegates to the underlying object' do expect(subject.label).to eq(value.to_s) end end end end
require "test_helper" describe Work do let(:work) { works(:one) } let(:popular_work) { works(:two) } let(:vote_one) { votes(:one) } let(:vote_two) { votes(:two) } let(:vote_three) { votes(:two) } it "must be valid" do expect(work.valid?).must_equal true end describe "validations" do it "requires a title" do work.title = nil valid_work = work.valid? expect(valid_work).must_equal false expect(work.errors.messages).must_include :title expect(work.errors.messages[:title]).must_equal ["can't be blank"] end it "requires a unique title" do dup_work = Work.new(title: work.title) expect(dup_work.save).must_equal false expect(dup_work.errors.messages).must_include :title expect(dup_work.errors.messages[:title]).must_equal ["has already been taken"] end end describe "relationships" do it "can have many votes" do work.votes << vote_one work.votes << vote_two expect(work.votes.first).must_equal vote_one expect(work.votes.last).must_equal vote_two end it "can have 0 votes" do expect(work.votes.length).must_equal 0 end end describe "custom methods" do describe "vote_counter" do it "returns the correct number of votes" do work.votes << vote_one work.votes << vote_two expect(work.vote_counter).must_equal 2 end it "returns 0 when no votes have been made" do expect(work.vote_counter).must_equal 0 end end describe "spotlight_work" do it "will return the highest voted work" do popular_work.votes << vote_one popular_work.votes << vote_two work.votes << vote_three works = [work, popular_work] expect(Work.spotlight_work(works)).must_equal popular_work end it "will return nil if no one has voted yet" do works = [work, popular_work] expect(Work.spotlight_work(works)).must_equal nil end end describe "top_ten" do it "returns an array of ten works sorted by the most count by category - may include 0 votes" do works = Work.all category_one = works(:one).category top_ten_works = Work.top_ten(works, category_one) expect(top_ten_works.length).must_equal 10 expect(top_ten_works).must_include works(:ten) expect(top_ten_works).wont_include works(:eleven) expect(top_ten_works.first.category).must_equal category_one end it "returns the max number of works in category is there are less than 10 works" do works = Work.all category_two = works(:eleven).category top_works = Work.top_ten(works, category_two) expect(top_works.length).must_equal 1 end it "includes works with zero votes if the there are 10+ works in category but not all have been voted on" do works = Work.all works.first.votes << vote_one works[1].votes << vote_two top_works = Work.top_ten(works, works.first.category) expect(top_works.length).must_equal works[0..9].length expect(top_works).must_include works[9] expect(top_works).must_include works[3] end end end end
require 'google/apis/calendar_v3' require 'google/apis/oauth2_v2' require 'google/api_client/client_secrets' require 'json' require 'sinatra' require 'sinatra/base' require 'logger' require 'pry' require 'pry-byebug' require 'sequel' require 'sqlite3' require 'colorize' require 'active_support/values/time_zone' class ApplicationController < Sinatra::Base set :port, 8080 set :bind, '0.0.0.0' set :root, File.dirname(__FILE__) def logger; settings.logger end def calendar; settings.calendar; end def oauth2; settings.oauth2; end def auth; settings.authorization; end configure do log_file = File.open('calendar.log', 'a+') log_file.sync = true logger = Logger.new(log_file) logger.level = Logger::DEBUG use Rack::Session::Cookie, :key => 'rack.session', :domain => 'localhost', :path => '/', :expire_after => 60 * 60 * 1, # In seconds :secret => ENV['SESSION_SECRET'] Google::Apis::ClientOptions.default.application_name = 'Ruby Calendar sample' Google::Apis::ClientOptions.default.application_version = '1.0.0' calendar_api = Google::Apis::CalendarV3::CalendarService.new oauth2_api = Google::Apis::Oauth2V2::Oauth2Service.new client_secrets = Google::APIClient::ClientSecrets.load authorization = client_secrets.to_authorization authorization.scope = [ 'https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email' ] set :authorization, authorization set :logger, logger set :calendar, calendar_api set :oauth2, oauth2_api set :app_name, 'Nicht Arbeiten' set :time_zone, ActiveSupport::TimeZone::MAPPING['Minsk'] set :db, Sequel.connect("sqlite://db/development.sqlite3") require_relative "./models/models" end # use EventListController # use CommentsController before do # Ensure user has authorized the app puts "\n\nBEFORE | #{request.url.to_s.bold.yellow}" puts "SESSION | #{session.pretty_inspect.to_s.green}" if request.path_info == '://localhost::0' redirect to('/index') end pass if request.path_info =~ /^\/signout/ pass if request.path_info =~ /^\/oauth2/ # binding.pry if session[:access_token].nil? puts "COOKIES: #{request.cookies}" puts "MINE SESSION: #{session[:session_id].to_s.magenta.bold}" if !authorized? session[:initial_url] = request.url authorize! else session[:initial_url] = nil end end def authorize! redirect to('/oauth2authorize') end def authorized? session[:access_token] end after do puts "\n\nAFTER | #{request.url.to_s.bold.yellow}" puts "SESSION | #{session.pretty_inspect.to_s.green}" # Serialize the access/refresh token to the session and credential store. end get '/oauth2authorize' do # Request authorization auth.redirect_uri = to('/oauth2callback') redirect auth.authorization_uri.to_s, 303 end get '/oauth2callback' do # Exchange token current_auth = auth.dup current_auth.code = params[:code] if params[:code] current_auth.fetch_access_token! session[:access_token] = current_auth.access_token session[:refresh_token] = current_auth.refresh_token session[:expires_in] = current_auth.expires_in session[:issued_at] = current_auth.issued_at session[:user_info] = current_auth ? oauth2.get_userinfo(options: {authorization: current_auth}).to_h : nil redirect to(session[:initial_url]) end get '/' do redirect to('/index') end get '/login' do File.read(File.join('public', 'index_login.html')) end get '/index' do # "TEST" erb :index, :locals => {'meeting_rooms' => EventListController::MEETING_ROOMS} end def get_user user_info = session["user_info"] User.where(:email => user_info[:email]).all.first || User.create({ :name => user_info[:name], :email => user_info[:email], :picture => user_info[:picture] }) end end class EventListController < ApplicationController MEETING_ROOMS = { 'Minsk-8-Ireland-Dublin (12)' => { calendar_id: 'profitero.com_3835373939303534393136@resource.calendar.google.com', capacity: 12 }, 'Minsk-8-UK-London (6)' => { calendar_id: 'profitero.com_3336373732393733313333@resource.calendar.google.com', capacity: 6 }, 'Minsk-9-Aquarium (7)' => { calendar_id: 'profitero.com_37363937353439373536@resource.calendar.google.com', capacity: 7 }, 'Minsk-9-Canteen (9)' => { calendar_id: 'profitero.com_3737313636363735323131@resource.calendar.google.com', capacity: 9 }, 'Minsk-9-Terrarium (Little) (7)' => { calendar_id: 'profitero.com_3439323930333835373331@resource.calendar.google.com', capacity: 7 }, 'Minsk-20-Crystal (4)' => { calendar_id: 'profitero.com_3732393236333536353235@resource.calendar.google.com', capacity: 4 }, 'Minsk-20-Gems (4)' => { calendar_id: 'profitero.com_3635383335353139313231@resource.calendar.google.com', capacity: 4 }, 'Minsk-20-Marble (12)' => { calendar_id: 'profitero.com_353839323130363934@resource.calendar.google.com', capacity: 12 }, 'Minsk-20-Wood (4)' => { calendar_id: 'profitero.com_3639383539333932343034@resource.calendar.google.com', capacity: 4 }, 'Minsk-8-Ireland-Cork (2)' => { calendar_id: 'profitero.com_3733303638393130393934@resource.calendar.google.com', capacity: 2 }, 'Minsk-8-Ireland-Irish Kitchen (4)' => { calendar_id: 'profitero.com_3638363531303332353436@resource.calendar.google.com', capacity: 4 }, 'Minsk-8-UK-British Kitchen (8)' => { calendar_id: 'profitero.com_3630303336393735353139@resource.calendar.google.com', capacity: 8 }, 'Minsk-8-USA-Aliaska (2)' => { calendar_id: 'profitero.com_3735313932393532393834@resource.calendar.google.com', capacity: 2 }, 'Minsk-8-USA-Amerikan Kitchen (10)' => { calendar_id: 'profitero.com_3134373438323331313237@resource.calendar.google.com', capacity: 10 }, 'Minsk-8-USA-Boston (50)' => { calendar_id: 'profitero.com_35363534323539313233@resource.calendar.google.com', capacity: 59 } } def create_event_from_post_body(name: name, location: location, description: description, start_time: start_time, end_time: end_time, location_email: location_email) Google::Apis::CalendarV3::Event.new( summary: name, location: location, description: description, start: { date_time: start_time, time_zone: settings.time_zone }, end: { date_time: end_time, time_zone: settings.time_zone }, attendees: [ { email: get_user.email, responseStatus: 'accepted' }, { email: location_email, responseStatus: 'needsAction', resource: true } ], reminders: { use_default: false, } ) end def is_location_free?(location, start_time, end_time) time_min = nil time_max = nil time_min = start_time if start_time time_max = end_time if end_time events = calendar.list_events(location[:calendar_id], time_min: time_min, time_max: time_max, options: {authorization: auth.dup.update_token!(session)}) events.items.empty? end get "/list" do @error_message = session.delete(:flash_error) events = Event.where(:deleted => false) query = Event.where(:deleted => false) if tags = (params['tags'] && JSON(params['tags'])) query = query.join(:event_tag, event_id: :id).where(:tag_id => tags) elsif start_time = params[:start_time] query = query.where(:start_time > start_time) elsif end_time = params[:end_time] query = query.where(:end_time < end_time) end events = query.all if params[:recommend] user_tag_ids = get_user.tags.map { |tag| tag.id } events = events.all.select do |event| event_tag_ids = event.tags.map { |tag| tag.id } (user_tag_ids | event_tag_ids).size != (event_tag_ids.size + user_tag_ids.size) end end @events = events @tags = Tag.all erb :events end get "/:id" do |id| event = Event.where(:id => id).all.first if event @event = event erb :event else return [404] end end post "/create" do name = params[:name] location = params[:location] description = params[:description] start_time = DateTime.parse(params[:start_time]) rescue nil end_time = DateTime.parse(params[:end_time]) rescue nil unless !name.empty? session[:flash_error] = "No name was given when creating event" redirect to("/list") end unless !location.empty? session[:flash_error] = "No location was given when creating event" redirect to("/list") end unless start_time session[:flash_error] = "No start time was given when creating event" redirect to("/list") end unless end_time session[:flash_error] = "No end time was given when creating event" redirect to("/list") end unless start_time < end_time session[:flash_error] = "End time is before start time" redirect to("/list") end location_object = MEETING_ROOMS[location] unless location_object && is_location_free?(location_object, start_time.rfc3339, end_time.rfc3339) session[:flash_error] = "Location #{location} is busy at selected time window: #{start_time.strftime("%F %T")} - #{end_time.strftime("%F %T")}" redirect to("/list") end google_event = create_event_from_post_body( name: name, location: location, description: description, start_time: start_time.rfc3339, end_time: end_time.rfc3339, location_email: location_object[:calendar_id] ) google_event = calendar.insert_event('primary', google_event, options: {authorization: auth.dup.update_token!(session)}) event = Event.create({ name: params[:name], description: params[:description], start_time: start_time, end_time: end_time, location: params[:location], picture_url: params[:picture_url], google_id: google_event.id, deleted: false }) tags = params[:tags].empty? ? [] : params[:tags].split(',').map{|s| s.strip} tags.each do |tag_str| tag = Tag.where(:name => tag_str).all.first || Tag.create(:name => tag_str) event.add_tag tag end event.update(:creator => get_user) event.add_user get_user event.save redirect "/event/#{event[:id]}" end post "/:id" do |id| event = Event.where(:id => id).all.first if get_user.id == event.creator.id event.update(name: params[:name]) if params[:name] event.update(description: params[:description]) if params[:description] event.update(start_time: params[:start_time]) if params[:start_time] event.update(end_time: params[:end_time]) if params[:end_time] event.update(location: params[:location]) if params[:location] tags = params[:tags].empty? ? [] : params[:tags].split(',').map{|s| s.strip} tags.each do |tag_str| tag = Tag.where(:name => tag_str).all.first || Tag.create(:name => tag_str) event.add_tag tag end end redirect "/event/#{event[:id]}" end delete "/:id" do |id| event = Event.where(:id => id).all.first if get_user.id == event.creator.id event.update(:deleted => true) end end get "/subscribe/:id" do |id| event = Event.where(:id => id).all.first unless event.users.find { |sub| sub.id == get_user.id } event.add_user(get_user) return [200, {success: true}.to_json] else return [200, {success: false}.to_json] end end delete "/:id" do |id| event = Event.where(id: id).first calendar.delete_event('primary', event.google_id, options: {authorization: auth.dup.update_token!(session)}) event.delete redirect to("/list") end end class CommentsController < ApplicationController post "/create" do event = Event.where(:id => params[:event_id]).all.first comment = Comment.create({ text: params[:text] }) JSON(params[:parent_ids] || "[]").each do |parent_id| parent = Comment.where(:id => parent_id).all.first comment.add_parent parent end event.add_comment comment comment.creator = get_user redirect "/event/#{params[:event_id]}" end end
require 'test_helper' class FavoritesControllerTest < ActionController::TestCase test "can get user favorites" do get :index, format: :json, user_id: 'vikhyat', type: 'Anime' assert_response :success end test "can add anime to favorites" do sign_in users(:vikhyat) assert_difference ->{ Favorite.where(user: users(:vikhyat)).count } do post :create, format: :json, favorite: {user_id: 'vikhyat', item_id: 'sword-art-online', item_type: 'Anime'} end response = JSON.parse(@response.body)['favorite'] assert_response 200 assert_equal 'anime', response['item']['type'] assert_equal 'sword-art-online', response['item']['id'] assert_equal 9999, response['fav_rank'] end test "can delete anime from favorites" do sign_in users(:vikhyat) assert_difference ->{ Favorite.where(user: users(:vikhyat)).count }, -1 do post :destroy, format: :json, id: 1 end end test "cannot delete anime from other users favorites" do sign_in users(:josh) assert_no_difference ->{ Favorite.where(user: users(:vikhyat)).count } do post :destroy, format: :json, id: 1 end response = JSON.parse(@response.body) assert 'Unauthorized', response['error'] end test "can bulk update favorite order" do sign_in users(:vikhyat) post :update_all, favorites: "[{\"id\":\"1\", \"rank\":\"2\"},{\"id\":\"2\", \"rank\":\"1\"}]" assert_equal 2, Favorite.find(1).fav_rank assert_equal 1, Favorite.find(2).fav_rank end test "cannot bulk update other users favorite order" do sign_in users(:josh) post :update_all, favorites: "[{\"id\":\"1\", \"rank\":\"2\"},{\"id\":\"2\", \"rank\":\"1\"}]" assert_equal 1, Favorite.find(1).fav_rank assert_equal 2, Favorite.find(2).fav_rank end end
class CreateZonas < ActiveRecord::Migration[5.0] def change create_table :zonas do |t| t.string :zona t.st_polygon :area, geographic: true t.boolean :lunes ,:default => false t.boolean :martes ,:default => false t.boolean :miercoles ,:default => false t.boolean :jueves ,:default => false t.boolean :viernes ,:default => false t.boolean :sabado ,:default => false t.boolean :domingo ,:default => false t.belongs_to :contratistas, foreign_key: true t.timestamps end end end