text
stringlengths
10
2.61M
class WithdrawConfirmService class WithdrawRequestIdNotFound < StandardError; end attr_reader :token, :account_withdraw_request, :possibility def initialize(token:, account_withdraw_request:, possibility:) @token = token @account_withdraw_request = account_withdraw_request @possibility = possibility end def self.confirm(...) new(...).confirm end def confirm return unless same_user? create_withdraw_transaction end private def user @user ||= User.find_by(token: token) end def account @account ||= account_withdraw_request.account end def create_withdraw_transaction ActiveRecord::Base.transaction do account_transaction = AccountTransaction.create( account: account, amount: account_withdraw_request.amount ) account_transaction.withdraw! update_withdraw_request(account_transaction.id) update_balance account_transaction end end def update_withdraw_request(account_transaction_id) account_withdraw_request.update( account_transaction_id: account_transaction_id ) end def update_balance account.update(balance: account.balance - account_withdraw_request.amount) end def same_user? user == account.user end end
Rails.application.routes.draw do root to: 'invoices#index' resources :invoices, only: [:index, :new, :edit, :destroy] get "invoices/new_full" => "invoices#new_full" end
Given(/^there is an? (\w+) page$/) do |url| @content_page = create(:content_page, title: 'About', url: url) end When(/^I go to the (\w+) page$/) do |page| visit "/#{page}" end Then(/^I should see the (\w+\s?\w+) page$/) do |found_page| page.should have_content(@content_page.title) page.should have_content(@content_page.subtitle) page.should have_content(@content_page.text) end When(/^I submit the contact form$/) do fill_in 'contact_enquiry_name', with: 'Jane Bloggs' fill_in 'contact_enquiry_email', with: 'example@example.com' fill_in 'contact_enquiry_message', with: 'message' click_button 'Send' end
class CreateLinks < ActiveRecord::Migration[6.1] def change create_table :links do |t| t.text :url t.integer :visits, default: 0 t.timestamps end end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe 'User Authentication', type: :system, js: false, clean: true do include ActiveSupport::Testing::TimeHelpers let(:user) { FactoryBot.create(:user) } context 'an unauthenticated user' do it 'gets the omniauth redirect endpoint for Yale CAS authentication' do visit search_catalog_path expect(page).to have_button('Log in') end end context 'an authenticated user' do it 'gets a logout option' do login_as user visit search_catalog_path expect(page).to have_button('Log out') end it 'expires the user session' do login_as user visit search_catalog_path travel(13.hours) visit search_catalog_path expect(page).to have_button('Log in') travel_back end end end
class AddIntoToPayment < ActiveRecord::Migration def change add_column :purchases, :driver_id, :integer add_column :purchases, :vehicle_id, :integer add_column :purchases, :comments, :text end end
require_relative "spec_helper" describe "pg_auto_constraint_validations plugin" do def create_model(ds) @ds = ds @ds.send(:columns=, [:id, :i]) @db.fetch = @metadata_results.dup c = Sequel::Model(@ds) c.plugin :pg_auto_constraint_validations c end before do info = @info = {:schema=>'public', :table=>'items'} @db = Sequel.mock(:host=>'postgres') def @db.schema(*) [[:i, {}], [:id, {}]] end @set_error = lambda{|ec, ei| @db.fetch = @db.autoid = @db.numrows = ec; info.merge!(ei)} @db.define_singleton_method(:error_info){|e| info} @metadata_results = [ [{:constraint=>'items_i_check', :column=>'i', :definition=>'CHECK i'}, {:constraint=>'items_i_id_check', :column=>'i', :definition=>'CHECK i + id < 20'}, {:constraint=>'items_i_id_check', :column=>'id', :definition=>'CHECK i + id < 20'}, {:constraint=>'items_i_foo_check', :column=>nil, :definition=>'CHECK foo() < 20'}], [{:name=>'items_i_uidx', :unique=>true, :column=>'i', :deferrable=>false}, {:name=>'items_i2_idx', :unique=>false, :column=>'i', :deferrable=>false}], [{:name=>'items_i_fk', :column=>'i', :on_update=>'a', :on_delete=>'a', :table=>'items2', :refcolumn=>'id', :schema=>'public'}], [{:name=>'items2_i_fk', :column=>'id', :on_update=>'a', :on_delete=>'a', :table=>'items2', :refcolumn=>'i', :schema=>'public'}], [{:nspname=>'public', :relname=>'items'}] ] @c = create_model(@db[:items]) end it "should handle check constraint failures as validation errors when creating" do o = @c.new(:i=>12) @set_error[Sequel::CheckConstraintViolation, :constraint=>'items_i_check'] proc{o.save}.must_raise Sequel::ValidationFailed o.errors.must_equal(:i=>['is invalid']) end it "should handle check constraint failures as validation errors when updating" do o = @c.load(:i=>3) @set_error[Sequel::CheckConstraintViolation, :constraint=>'items_i_check'] proc{o.update(:i=>12)}.must_raise Sequel::ValidationFailed o.errors.must_equal(:i=>['is invalid']) end it "should handle unique constraint failures as validation errors when creating" do o = @c.new(:i=>2) @set_error[Sequel::UniqueConstraintViolation, :constraint=>'items_i_uidx'] proc{o.save}.must_raise Sequel::ValidationFailed o.errors.must_equal(:i=>['is already taken']) end it "should handle unique constraint failures as validation errors when updating" do o = @c.load(:id=>5, :i=>3) @set_error[Sequel::UniqueConstraintViolation, :constraint=>'items_i_uidx'] proc{o.update(:i=>2)}.must_raise Sequel::ValidationFailed o.errors.must_equal(:i=>['is already taken']) end it "should handle not null constraint failures as validation errors when creating" do o = @c.new(:i=>5) @set_error[Sequel::NotNullConstraintViolation, :column=>'i'] proc{o.save}.must_raise Sequel::ValidationFailed o.errors.must_equal(:i=>['is not present']) end it "should handle not null constraint failures as validation errors when updating" do o = @c.load(:i=>3) @set_error[Sequel::NotNullConstraintViolation, :column=>'i'] proc{o.update(:i=>nil)}.must_raise Sequel::ValidationFailed o.errors.must_equal(:i=>['is not present']) end it "should handle foreign key constraint failures as validation errors when creating" do o = @c.new(:i=>3) @set_error[Sequel::ForeignKeyConstraintViolation, :constraint=>'items_i_fk', :message_primary=>'insert or'] proc{o.save}.must_raise Sequel::ValidationFailed o.errors.must_equal(:i=>['is invalid']) end it "should handle foreign key constraint failures as validation errors when updating" do o = @c.load(:i=>1) @set_error[Sequel::ForeignKeyConstraintViolation, :constraint=>'items_i_fk', :message_primary=>'insert or'] proc{o.update(:i=>3)}.must_raise Sequel::ValidationFailed o.errors.must_equal(:i=>['is invalid']) end it "should handle foreign key constraint failures in other tables as validation errors when updating" do o = @c.load(:i=>1) @set_error[Sequel::ForeignKeyConstraintViolation, :constraint=>'items2_i_fk', :message_primary=>'update or', :schema=>'public', :table=>'items2'] proc{o.update(:i=>3)}.must_raise Sequel::ValidationFailed o.errors.must_equal(:i=>['cannot be changed currently']) end it "should handle symbol, string, and identifier table names" do [@db[:items], @db.from('items'), @db.from{items}, @db.from{public[:items]}].each do |ds| c = create_model(ds) @set_error[Sequel::CheckConstraintViolation, :constraint=>'items_i_check'] o = c.new(:i=>3) proc{o.save}.must_raise Sequel::ValidationFailed o.errors.must_equal(:i=>['is invalid']) end end it "should skip handling of other table types such as subqueries and functions" do [@db.from{foo(:bar)}, @db[:a, :b]].each do |ds| @db.fetch = @metadata_results.dup @c.dataset = ds o = @c.new(:i=>3) @set_error[Sequel::CheckConstraintViolation, :constraint=>'items_i_check'] proc{o.save}.must_raise Sequel::CheckConstraintViolation end end it "should skip handling if the error_info method is not supported" do @db.singleton_class.send(:remove_method, :error_info) c = create_model(@db[:items]) @set_error[Sequel::CheckConstraintViolation, :constraint=>'items_i_check'] o = c.new(:i=>3) proc{o.save}.must_raise Sequel::CheckConstraintViolation end it "should not handle constraint failures if they can't be converted" do o = @c.new(:i=>12) @set_error[Sequel::NotNullConstraintViolation, {}] proc{o.save}.must_raise Sequel::NotNullConstraintViolation @set_error[Sequel::CheckConstraintViolation, {}] proc{o.save}.must_raise Sequel::CheckConstraintViolation @set_error[Sequel::UniqueConstraintViolation, {}] proc{o.save}.must_raise Sequel::UniqueConstraintViolation @set_error[Sequel::ForeignKeyConstraintViolation, {}] proc{o.save}.must_raise Sequel::ForeignKeyConstraintViolation @set_error[Sequel::ForeignKeyConstraintViolation, :constraint=>'items_i_fk', :message_primary=>'foo'] proc{o.save}.must_raise Sequel::ForeignKeyConstraintViolation @set_error[Sequel::ForeignKeyConstraintViolation, :constraint=>'items_i_fk', :message_primary=>'update or'] proc{o.save}.must_raise Sequel::ForeignKeyConstraintViolation @set_error[Sequel::ForeignKeyConstraintViolation, :constraint=>'items_x_fk', :message_primary=>'insert or'] proc{o.save}.must_raise Sequel::ForeignKeyConstraintViolation end it "should reraise original exception if there is an error" do o = @c.new(:i=>12) def o.add_pg_constraint_validation_error; end @set_error[Sequel::NotNullConstraintViolation, :column=>'i'] proc{o.save}.must_raise Sequel::NotNullConstraintViolation end it "should not handle constraint failures if schema or table do not match" do o = @c.new(:i=>12) @set_error[Sequel::CheckConstraintViolation, :constraint=>'items_i_check', :schema=>'x'] proc{o.save}.must_raise Sequel::CheckConstraintViolation @set_error[Sequel::CheckConstraintViolation, :constraint=>'items_i_check', :schema=>'public', :table=>'x'] proc{o.save}.must_raise Sequel::CheckConstraintViolation end it "should handle constraint failures when disabling insert returning" do c = create_model(@db[:items].disable_insert_returning) o = c.new(:i=>12) o.id = 1 @set_error[Sequel::CheckConstraintViolation, :constraint=>'items_i_check'] proc{o.save}.must_raise Sequel::ValidationFailed o.errors.must_equal(:i=>['is invalid']) end it "should handle multi-column constraint failures as validation errors" do o = @c.new(:i=>12) @set_error[Sequel::CheckConstraintViolation, :constraint=>'items_i_id_check'] proc{o.save}.must_raise Sequel::ValidationFailed o.errors.must_equal([:i, :id]=>['is invalid']) end it "should handle multi-column constraint failures as validation errors when using the error_splitter plugin" do @c.plugin :error_splitter o = @c.new(:i=>12) @set_error[Sequel::CheckConstraintViolation, :constraint=>'items_i_id_check'] proc{o.save}.must_raise Sequel::ValidationFailed o.errors.must_equal(:i=>['is invalid'], :id=>['is invalid']) end it "should handle overridden constraint failures as validation errors when updating" do o = @c.load(:i=>3) @c.pg_auto_constraint_validation_override(:items_i_ocheck, :i, "foo bar") @set_error[Sequel::CheckConstraintViolation, :constraint=>'items_i_ocheck'] proc{o.update(:i=>12)}.must_raise Sequel::ValidationFailed o.errors.must_equal(:i=>['foo bar']) end it "should handle dumping cached metadata and loading metadata from cache" do cache_file = "spec/files/pgacv-spec-#{$$}.cache" begin @ds = @db[:items] @ds.send(:columns=, [:id, :i]) @db.fetch = @metadata_results.dup c = Sequel::Model(@ds) def c.name; 'Foo' end @db.sqls c.plugin :pg_auto_constraint_validations, :cache_file=>cache_file @db.sqls.length.must_equal 5 o = c.new(:i=>12) @set_error[Sequel::CheckConstraintViolation, :constraint=>'items_i_id_check'] proc{o.save}.must_raise Sequel::ValidationFailed c.dump_pg_auto_constraint_validations_cache @db.fetch = [] c = Sequel::Model(@ds) def c.name; 'Foo' end @db.sqls c.plugin :pg_auto_constraint_validations, :cache_file=>cache_file @db.sqls.must_be_empty o = c.new(:i=>12) @set_error[Sequel::CheckConstraintViolation, :constraint=>'items_i_id_check'] proc{o.save}.must_raise Sequel::ValidationFailed ensure File.delete(cache_file) if File.file?(cache_file) end end it "should sort cache file by table name" do cache_file = "spec/files/pgacv-spec-#{$$}.cache" begin c = Class.new(Sequel::Model) c.plugin :pg_auto_constraint_validations, :cache_file=>cache_file @ds = @db[:items] @ds.send(:columns=, [:id, :i]) @db.fetch = @metadata_results.dup @db.sqls c1 = c::Model(@ds) def c1.name; 'Foo' end @db.sqls.length.must_equal 5 @ds = @db[:bars] @ds.send(:columns=, [:id, :i]) @db.fetch = @metadata_results.dup @db.sqls c2 = c::Model(@ds) c2.set_dataset @ds def c2.name; 'Bar' end @db.sqls.length.must_equal 5 c.instance_variable_get(:@pg_auto_constraint_validations_cache).keys.must_equal %w["items" "bars"] c.dump_pg_auto_constraint_validations_cache c.instance_variable_get(:@pg_auto_constraint_validations_cache).keys.must_equal %w["items" "bars"] c3 = Class.new(Sequel::Model) c3.plugin :pg_auto_constraint_validations, :cache_file=>cache_file c3.instance_variable_get(:@pg_auto_constraint_validations_cache).keys.must_equal %w["bars" "items"] ensure File.delete(cache_file) if File.file?(cache_file) end end it "should raise error if attempting to dump cached metadata when not using caching" do proc{@c.dump_pg_auto_constraint_validations_cache}.must_raise Sequel::Error end it "should allow loading into models without a dataset" do c = Class.new(Sequel::Model) c.plugin :pg_auto_constraint_validations c.pg_auto_constraint_validations.must_be_nil end end
class Channel < ActiveRecord::Base has_many :subscriptions # This is how you get channel.fuckers to return a list #of user instances has_many :fuckers, through: :subscriptions, source: :user end # xchannel= Channel.all.first # xchannel.fuckers #the above commands will return a list of users
class LocalArtist < ApplicationRecord has_many :local_artist_songs has_many :local_gigs has_secure_password # validates :username, presence: true, uniqueness: true def self.search(search) where("zipcode LIKE ?", "%#{search}%") end end
class CreateTopicTopicProperties < ActiveRecord::Migration def self.up create_table :topics_property_types do |t| t.integer :topic_id, :property_type_id end end def self.down drop_table :topics_property_types end end
class CompaniesController < ApplicationController def index @companies = Company.all end def show @company = Company.find(params[:id]) end private helper_method :current_company def current_company @current_company ||= Company.find(params[:id]) end end
class Institution < ApplicationRecord has_many :repositories, dependent: :destroy validates :name, uniqueness: true, presence: true end
require File.dirname(__FILE__) + '/../../spec_helper' require File.dirname(__FILE__) + '/fixtures/classes' describe "Kernel#abort" do it "is a private method" do Kernel.should have_private_instance_method(:abort) end it "prints the message to stderr" do ruby_exe("abort('abort message')").chomp.should == '' ruby_exe("abort('abort message')", :args => "2>&1").chomp.should == 'abort message' end it "does not allow the message to be nil" do lambda { abort(nil) }.should raise_error(TypeError) end it "sets the exit code to 1" do ruby_exe("abort") $?.exitstatus.should == 1 end end describe "Kernel.abort" do it "needs to be reviewed for spec completeness" end
class OrderTicket < ActiveRecord::Base belongs_to :order belongs_to :ticket end
When /^I fill out the new product form with sizes$/ do click_link "New Product" fill_in "Name", :with => "Shirt" fill_in "Price", :with => "12.00" fill_in "Size", :with => "Small,Medium,Large" attach_file("Picture", File.join(Rails.root, 'spec', 'fixtures', 'shirt.png')) click_button "Create Product" end Then /^the product should be listed$/ do page.should have_content "Shirt" page.should have_content "$12.00" end Then /^the product should have a sizes select menu$/ do page.should have_content "Size" end When /^I fill out the new product form without sizes$/ do click_link "New Product" fill_in "Name", :with => "Shirt" fill_in "Price", :with => "12.00" attach_file("Picture", File.join(Rails.root, 'spec', 'fixtures', 'shirt.png')) click_button "Create Product" end Then /^the product should not have a sizes select menu$/ do page.should_not have_content "Size" end
require File.dirname(__FILE__) + "/../spec_helper" class InvalidProfile include Preflight::Profile profile_name "invalid" rule String, 1.3 end describe "Profile with an invalid rule" do it "should raise an exception" do filename = pdf_spec_file("version_1_4") preflight = InvalidProfile.new lambda { preflight.check(filename) }.should raise_error(RuntimeError) end end
require 'rails_helper' RSpec.describe Relationship, type: :model do describe "validations" do it{expect :follower_id} it{expect :followed_id} end end
#!/usr/bin/env ruby lib = File.expand_path( '../../lib/', __FILE__ ) $:.unshift lib unless $:.include?( lib ) require 'text_to_noise' player = TextToNoise::Player.new begin ARGV.each do |sound| sound += ".wav" unless sound =~ /\.wav$/ player.play sound sleep 1 end rescue TextToNoise::Player::SoundNotFound => e $stderr.puts e.message $stderr.puts "Sorry, but I know how to play these sounds:\n" $stderr.print "\t" $stderr.puts player.available_sounds.join( "\n\t" ) end sleep 1 while player.playing?
class ParticipantsController < ApplicationController def create @draw = current_user.draws.find(params[:participant][:draw_id]) redirect_to @draw, alert: "This draw has already been made." if @draw.drawn @participant = @draw.participants.build(params[:participant]) @participant.save end def destroy @participant = Participant.find(params[:id]) redirect_to @participant.draw, alert: "This draw has already been made." if @participant.draw.drawn redirect_to root_url, alert: "Access denied" if @participant.draw.user != current_user @participant.delete end end
# -*- coding: utf-8 -*- module Plugin::Score extend self def score_by_score(model, target_note=model) @score_cache ||= TimeLimitedStorage.new(Array, Object, 60) @score_cache[[model, target_note]] ||= score_by_score_nocache(model, target_note).to_a.freeze end def score_by_score_nocache(model, target_note=model) _, _, available_score_list = Plugin.filtering(:score_filter, model, target_note, Set.new) selected_score = choose_best_score(available_score_list) if selected_score && !selected_score.all? { |s| s.is_a?(Plugin::Score::TextNote) } score_expand(selected_score, model) elsif target_note.is_a?(Plugin::Score::TextNote) [target_note] else score_by_score(model, Plugin::Score::TextNote.new(description: model.description)) end end # _score_list_ の中から、利用すべきScoreをひとつだけ返す。 # 一つも該当するものがない場合は nil を返す。複数該当する場合は、結果は不定。 def choose_best_score(score_list) selected = max_score_count(smallest_leading_text_size(score_list)) selected.first end # 最初にTextNote以外が出てくるまでに出てきたTextNoteのdescriptionの文字数の合計が少ないもののみを列挙する。 def smallest_leading_text_size(score_list) min_all(score_list, &method(:leading_text_size)) end # Scoreを構成するNoteの数が一番多いもののみを列挙する。 def max_score_count(score_list) max_all(score_list, &:count) end private def score_expand(score, model) score.flat_map do |note| if note.is_a? Plugin::Score::TextNote score_by_score(model, note) else [note] end end end def leading_text_size(score) score.inject(0) do |index, note| if note.is_a?(Plugin::Score::TextNote) index + note.description.size else break index end end end def min_all(list, &proc) return list if list.size <= 1 order = Hash.new{|h,k| h[k] = proc.(k) } _, result = list.sort_by{|node| order[node] }.chunk{|node| order[node] }.first result end def max_all(list, &proc) min_all(list){|x| -proc.(x) } end end
require 'nokogiri' require 'open-uri' require 'action_view' class Agon def self.load radios = [] radio_station = RadioStation.find_parse_url_type('agon').first() return radios unless radio_station.present? doc = Nokogiri::HTML(open(radio_station.parse_url)) doc.xpath('//a[@class="cb_link"]').each do |node| radio = parse(node.attribute('href').text, radio_station) radios.push(radio) if radio.present? end radios end def self.parse(url, radio_station) # ラジオ詳細ページの URL をチェックする return unless url.start_with?('http://ondemand.joqr.co.jp/AG-ON/contents/') doc = Nokogiri::HTML(open(url)) node = doc.xpath('//div[@id="secinfo"]') return nil if node.blank? name = sanitize(node.xpath('div[@id="right"]/div[@id="Nleft"]//h3[@class="sinf_title"]').inner_text) description = sanitize(node.xpath('div[@id="left"]/p[@class="sinf_txt"]').inner_text) thumbnail = get_thumbnail(node.xpath('div[@id="left"]//img')) published_at = get_published_at(node.xpath('div[@id="right"]/div[@id="Nleft"]//ul[@class="sinf_det"]/li')) { name: name, description: description, url: url, image_url: thumbnail, published_at: published_at, radio_station: radio_station } end def self.get_published_at(nodes) nodes.each do |node| label = sanitize(node.xpath('span[@class="detli"]').inner_text) if label.start_with?('公開日') text = sanitize(node.xpath('span[@class="detlitxt"]').inner_text) begin return Time.strptime(text, '%Y年%m月%d日').to_datetime rescue Exception => e return nil end end end nil end def self.get_thumbnail(imgs) imgs.each do |img| src = img.attribute('src').text return src if src.start_with?('http://ondemand.joqr.co.jp/AG-ON/bangumi/assets_c/') end nil end def self.sanitize(text) ActionView::Base.full_sanitizer.sanitize(text) end end
class AddDetailsToMasterFinances < ActiveRecord::Migration[5.2] def change rename_column :master_finances, :balance_cents, :initial_balance_cents add_column :master_finances, :final_balance_cents, :integer, null: true add_column :master_finances, :done, :boolean, default: false end end
# # Cookbook Name:: redmine # Recipe:: default # # Copyright 2014, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute # include_recipe "devTools::default" %w{openssl-devel readline-devel zlib-devel curl-devel libyaml-devel}.each do |pkg| package pkg do action :install end end include_recipe "mysql-server::default" include_recipe "httpd::default" include_recipe "ImageMagick::default" include_recipe "ipa-pgothic-fonts" template "create database user sql" do path "/home/#{node['mysql']['user']}/createDatabaseUserForRedmine.sql" source "createDatabaseUserForRedmine.sql.erb" owner node['mysql']['user'] group node['mysql']['group'] mode 0644 not_if { File.exists?("/home/#{node['mysql']['user']}/createDatabaseUserForRedmine.sql") } end include_recipe "mysql-server::createDatabaseForRedmine" bash "download redmine" do code <<-EOH cd #{Chef::Config[:file_cache_path]} wget http://www.redmine.org/releases/redmine-#{node['redmine']['version']}.tar.gz EOH not_if { File.exists?("#{Chef::Config[:file_cache_path]}/redmine-#{node['redmine']['version']}.tar.gz") } end bash "install redmine" do code <<-EOH cd #{Chef::Config[:file_cache_path]} tar xzf redmine-#{node['redmine']['version']}.tar.gz mv redmine-#{node['redmine']['version']} redmine mv redmine #{node['redmine']['install_dir']} EOH not_if { Dir.exists?("#{node['redmine']['install_dir']}") } end template "database.yml" do path "#{node['redmine']['install_dir']}/config/database.yml" source "database.yml.erb" owner node['redmine']['user'] group node['redmine']['group'] mode 0644 not_if { File.exists?("#{node['redmine']['install_dir']}/config/database.yml") } end template "configuration.yml" do path "#{node['redmine']['install_dir']}/config/configuration.yml" source "configuration.yml.erb" owner node['redmine']['user'] group node['redmine']['group'] mode 0644 not_if { File.exists?("#{node['redmine']['install_dir']}/config/configuration.yml") } end bash "create log file" do code <<-EOH touch #{node['redmine']['install_dir']}/log/development.log touch #{node['redmine']['install_dir']}/log/production.log chown #{node['redmine']['user']}:#{node['redmine']['group']} #{node['redmine']['install_dir']}/log/development.log chown #{node['redmine']['user']}:#{node['redmine']['group']} #{node['redmine']['install_dir']}/log/production.log chmod 0666 #{node['redmine']['install_dir']}/log/development.log chmod 0666 #{node['redmine']['install_dir']}/log/production.log EOH not_if { File.exists?("#{node['redmine']['install_dir']}/log/development.log") } end bash "install related gems" do code <<-EOH cd #{node['redmine']['install_dir']} /usr/local/bin/bundle install --without development test EOH end bash "create secret token" do code <<-EOH cd #{node['redmine']['install_dir']} /usr/local/bin/bundle exec /usr/local/bin/rake generate_secret_token RAILS_ENV=production /usr/local/bin/bundle exec /usr/local/bin/rake db:migrate EOH end execute "install passenger module" do command "/usr/local/bin/passenger-install-apache2-module < /bin/echo '1'" not_if 'find /usr/local/lib/ruby/gems -name mod_passenger.so | grep passenger' end execute "create passenger.conf" do command <<-EOH /usr/local/bin/passenger-install-apache2-module --snippet > /etc/httpd/conf.d/passenger.conf EOH not_if { File.exists?("/etc/httpd/conf.d/passenger.conf") } end #include_recipe "redmine_plugins::default" execute "change owner of redmine" do command <<-EOH chown -R apache:apache #{node['redmine']['install_dir']} chmod 555 /home/#{node['redmine']['user']} EOH end template "httpd.conf" do path "/etc/httpd/conf/httpd.conf" source "httpd.conf.erb" owner "root" group "root" mode 0644 end execute "restart httpd" do command "/etc/init.d/httpd restart" end
class M0300b1 attr_reader :options, :name, :field_type, :node def initialize @name = "Number of stage 2 pressure ulcers (M0300b1) (If 0 or NA skip to M0300c, stage 3)" @field_type = TEXT @node = "M0300B1" @options = [] @options << FieldOption.new("") end def set_values_for_type(klass) return "0" end end
class CreateUserActions < ActiveRecord::Migration def change create_table :user_actions do |t| t.integer :story_id, null: false t.integer :node_id t.integer :user_id t.integer :action_type, null: false t.timestamps end add_index :user_actions, :story_id add_index :user_actions, :node_id add_index :user_actions, :user_id end end
require 'rails_helper' describe IncomingController do describe '#create' do before do @user = create(:user) end it "should create bookmark with url, user_id and tags" do email = @user.email subject = '#programming #cis' body = 'https://www.bloc.io/web-development \n\n \n \n\n________________________________\n\nJohn Smith\ne john@example.com\np 555.555.1234' post :create, {:sender => email, :subject => subject, 'body-plain' => body} bookmark = @user.bookmarks.first expect(@user.bookmarks.count).to eq(1) expect(bookmark.tags.map(&:label)).to eq(['cis','programming']) expect(bookmark.url).to eq('https://www.bloc.io/web-development') end it "should filter only hashtags" do email = @user.email subject = 'Fw: #programming #javascript awesome article #webdevelopment' body = 'http://lifehacker.com/eloquent-javascript-teaches-you-javascript-for-free-1614045478 \n\n \n \n\n________________________________\n\nJohn Smith\ne john@example.com\np 555.555.1234' post :create, {:sender => email, :subject => subject, 'body-plain' => body} bookmark = @user.bookmarks.first expect(bookmark.tags.map(&:label)).to eq(['webdevelopment','javascript','programming']) end it "should associate bookmark with existing tag if it exists" do email = @user.email subject = '#programming' body = 'http://lifehacker.com/eloquent-javascript-teaches-you-javascript-for-free-1614045478 \n\n \n \n\n________________________________\n\nJohn Smith\ne john@example.com\np 555.555.1234' tag = Tag.create(label: "programming") post :create, {:sender => email, :subject => subject, 'body-plain' => body} bookmark = @user.bookmarks.first expect(bookmark.tags.map(&:id)).to include(tag.id) end end end
class LinksController < ApplicationController after_action :popup_seen skip_before_action :verify_authenticity_token before_action :set_orientation, only: [:index, :search] def index @link = Link.new per_page = bot_request? ? 100 : 20 if params[:q].present? @links = Link.search(params[:q], orientation).paginate(page: params[:page], per_page: per_page) @count = Link.search_count params[:q], orientation if params[:crawl].present? Searcher.perform_later params[:q] end elsif params[:video_id].present? @links = Link.where(hidden: false, id: params[:video_id]).paginate(per_page: 1, page: 1) @count = 1 else @links = Link.normal.with_orientation(orientation).limit(8).paginate(per_page: per_page, page: 1) @count = Link.normal.count end end def show @link = Link.find(params[:id]) end def search if request.format.html? redirect_to root_path(q: params[:q]) else if params[:q].present? @links = Link.search(params[:q], orientation, params[:order]).paginate(page: params[:page], per_page: 20) @count = Link.search_count params[:q], orientation #if @links.blank? || @links.next_page.blank? if params[:crawl].present? Searcher.perform_later params[:q] elsif params[:random].present? @links = Link.normal.with_orientation(orientation).order(Arel.new('random()')).paginate(per_page: 20, page: 1) end else @links = Link.normal.with_orientation(orientation).paginate(per_page: 20, page: params[:page]) end render 'search', layout: false end end def comments @link = Link.unscoped.find(params[:id]) @comments = @link.comments render 'comment_section', layout: false end def create_comment comment_params = params.require(:comment).permit(:kind, :text) link_id = params[:id] @Link = Link.find(link_id) @comment = @Link.comments.create(comment_params.merge(user_id: current_user.id, kind: 'videoresponse', post_id: link_id)) render 'posts/comments/comment', layout: false end def hidden if true @links = Link.unscoped.where(hidden: true).paginate(per_page: 8, page: params[:page]) else redirect_to root_path end end def mark_fav if true @link = Link.unscoped.find(params[:id]) @link.update(favourite: !@link.favourite) render 'hide', layout: false end end def mark_nsfw link = Link.find(params[:id]) link.update(nsfw: true) if link.nsfw link.update(nsfw: false) if link.nsfw render head: :ok end def feature featuring = Link.find(params[:id]) if featuring.present? && current_user.try(:admin?) current = Link.where(featured: true).first current.update(featured: false) if current.present? featuring.update(featured: true) end render plain: 'ok' end def favourite @links = Link.favourite.paginate(per_page: 8, page: params[:page]) @count = Link.favourite.count render plain: 'made to favourite list' end def create @link = Link.new link_params if @link.save redirect_to links_path(video_id: @link.id) else render 'new', layout: false, status: 422 end end def tag link = Link.find(params[:id]) new_tagset = link.tags.to_s + ' ' + params[:value] link.update(tags: new_tagset) end def retry render plain: Link.find(params[:id]).generate_source_url_now end def desc TextRecord.where(name: 'meta_desc').first_or_create.update(value: params.permit(:value)[:value]) render plain: params[:value] end def destroy if true @link = Link.unscoped.find(params[:id]) @link.update(hidden: true) render 'hide', layout: false end end def hide if true @link = Link.unscoped.find(params[:id]) @link.update(hidden: true) render 'hide', layout: false end end def report @link = Link.find(params[:id]) render json: {message: 'report success'} end def unhide if current_user && current_user.admin? @link = Link.unscoped.find(params[:id]) @link.update(hidden: false) render 'hide', layout: false end end def untag link = Link.unscoped.find(params[:id]) if current_user && current_user.admin? link.update(tags: link.tags.gsub(params[:tag].strip, '')) end end def statistics render json: { daily: Visitor.where(created_at: 1.days.ago..Time.now).count } end def set_nsfw link = Link.find(params[:id]) link.update(nsfw: !link.nsfw) render plain: "OK" end protected def popup_seen cookies[:popup_seen] = true end def orientation @orientation = cookies[:orientation] @orientation end def set_orientation if params[:orientation].present? cookies[:orientation] = params[:orientation] elsif params[:q].to_s.include?('gay') cookies[:orientation] = 'gay' elsif params[:q].to_s.include?('lesb') cookies[:orientation] = 'lesbian' elsif params[:q].to_s.include?('straight') cookies[:orientation] = nil end end def link_params params.require(:link).permit(:name, :url, :tags, :text, :body) end end
module ExportHelpers def value_for_header(header_name) values = subject.rows.fetch(@activity.id) values[subject.headers.index(header_name)] end def actuals_from_table(table) CSV.parse(table, col_sep: "|", headers: true).each do |row| case row["transaction"].strip when "Actual" create(:actual, fixture_attrs(row)) when "Adj. Act." create(:adjustment, :actual, fixture_attrs(row)) when "Adj. Ref." create(:adjustment, :refund, fixture_attrs(row)) when "Refund" create(:refund, fixture_attrs(row)) else raise "don't know what to do" end end end def forecasts_for_report_from_table(report, table) CSV.parse(table, col_sep: "|", headers: true).each do |row| ForecastHistory.new( @activity, report: report, financial_quarter: row["financial_quarter"].to_i, financial_year: row["financial_year"].to_i ).set_value(row["value"].to_i) end end def fixture_attrs(row) { parent_activity: @activity, value: row["value"].strip, financial_quarter: row["financial_period"][/\d/], financial_year: 2020, report: instance_variable_get("@#{row["report"].strip}_report") } end end
# RubIRCd - An IRC server written in Ruby # Copyright (C) 2013 Lloyd Dilley (see authors.txt for details) # http://www.rubircd.rocks/ # # 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 3 of the License, or # (at your option) any later version. # # 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. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. require 'openssl' require 'resolv' require 'socket' require_relative 'commands' require_relative 'numerics' require_relative 'options' require_relative 'server' require_relative 'utility' # Handles client connections class Network @ipv6_enabled = false @listen_address = nil class << self attr_reader :ipv6_enabled, :listen_address end def self.start begin if !Options.listen_host.nil? plain_server = TCPServer.open(Options.listen_host, Options.listen_port) else plain_server = TCPServer.open(Options.listen_port) local_ip_addresses = Socket.ip_address_list local_ip_addresses.each do |address| @ipv6_enabled = true if address.ipv6? end end rescue Errno::EADDRNOTAVAIL => e puts "Invalid listen_host: #{Options.listen_host}" Log.write(4, "Invalid listen_host: #{Options.listen_host}") Log.write(4, e) exit! rescue SocketError => e puts "Invalid listen_host: #{Options.listen_host}" Log.write(4, "Invalid listen_host: #{Options.listen_host}") Log.write(4, e) exit! rescue => e puts "Unable to listen on TCP port: #{Options.listen_port}" Log.write(4, "Unable to listen on TCP port: #{Options.listen_port}") Log.write(4, e) exit! end if Options.enable_starttls.to_s == 'true' begin tls_context = OpenSSL::SSL::SSLContext.new tls_context.cert = OpenSSL::X509::Certificate.new(File.read('cfg/cert.pem')) tls_context.key = OpenSSL::PKey::RSA.new(File.read('cfg/key.pem')) tls_server = OpenSSL::SSL::SSLServer.new(plain_server, tls_context) tls_server.start_immediately = false # don't start SSL handshake until client issues "STARTTLS" plain_server = tls_server # plain_server is now an SSLServer rescue => e puts "Failed to enable TLS socket: #{e}" Log.write(4, "Failed to enable TLS socket: #{e}") end end unless Options.ssl_port.nil? begin if !Options.listen_host.nil? base_server = TCPServer.open(Options.listen_host, Options.ssl_port) *_, @listen_address = base_server.addr else base_server = TCPServer.open(Options.ssl_port) *_, @listen_address = base_server.addr end ssl_context = OpenSSL::SSL::SSLContext.new ssl_context.cert = OpenSSL::X509::Certificate.new(File.read('cfg/cert.pem')) ssl_context.key = OpenSSL::PKey::RSA.new(File.read('cfg/key.pem')) ssl_server = OpenSSL::SSL::SSLServer.new(base_server, ssl_context) rescue => e puts "Unable to listen on SSL port: #{Options.ssl_port}" Log.write(4, "Unable to listen on SSL port: #{Options.ssl_port}") Log.write(4, e) exit! end end _connection_check_thread = Thread.new { Network.connection_checker } if Options.io_type.to_s == 'thread' plain_thread = Thread.new { Network.plain_connections(plain_server) } unless Options.ssl_port.nil? ssl_thread = Thread.new { Network.ssl_connections(ssl_server) } end # Wait until threads complete before exiting program plain_thread.join ssl_thread.join unless Options.ssl_port.nil? else # if io_type == event, then use select handle_select(plain_server, ssl_server) end end def self.handle_select(plain_server, ssl_server) timeout = 10 if ssl_server.nil? fds = [plain_server] else fds = [plain_server, ssl_server] end loop do begin ios = select(fds, [], [], timeout) unless ios.nil? ios[0].each do |client| if client == plain_server plain_client = plain_server.accept fds << plain_client Server.increment_clients user = Network.register_connection(plain_client, nil) if user.nil? fds.delete(plain_client) Network.close(user, 'Connection closed', true) break end Network.check_for_kline(user) unless Server.kline_mod.nil? Network.welcome(user) elsif !ssl_server.nil? && client == ssl_server begin ssl_client = ssl_server.accept rescue Log.write(2, 'Client disconnected before completing SSL handshake.') break end fds << ssl_client Server.increment_clients user = Network.register_connection(ssl_client, nil) if user.nil? fds.delete(ssl_client) Network.close(user, 'Connection closed', true) break end Network.check_for_kline(user) unless Server.kline_mod.nil? Network.welcome(user) elsif client.eof? client.close else # handle clients that are already connected # Find user by socket Server.users.each { |u| user = u if client == u.socket } if user.nil? fds.delete(client) # user didn't exist, so remove the socket from file descriptor list Network.close(user, 'Connection closed', true) break end input = Network.recv(user) break if input.nil? break if input.empty? puts input if Options.debug_mode # output raw commands to foreground for debugging purposes input = input.chomp.split(' ', 2) # input[0] should contain command and input[1] contains the rest if input[0].to_s.upcase == 'PING' user.last_ping = Time.now.to_i else user.update_last_activity end Command.parse(user, input) end end end rescue # client disconnected, so remove socket from file descriptor list fds.each do |sock| fds.delete(sock) if sock.closed? end end end end # Periodic PING check def self.connection_checker loop do Server.users.each do |u| next unless !u.nil? && u.registered Network.send(u, "PING :#{Options.server_name}") ping_diff = Time.now.to_i - u.last_ping if ping_diff >= Limits::PING_STRIKES * Limits::PING_INTERVAL Network.close(u, "Ping timeout: #{ping_diff} seconds", false) end end sleep Limits::PING_INTERVAL end end def self.plain_connections(plain_server) loop do Thread.start(plain_server.accept) do |plain_socket| Server.increment_clients user = Network.register_connection(plain_socket, Thread.current) Network.check_for_kline(user) unless Server.kline_mod.nil? Network.welcome(user) Network.main_loop(user) end end rescue SocketError puts 'Open file descriptor limit reached!' Log.write(4, 'Open file descriptor limit reached!') # we likely cannot write to the log file in this state, but try anyway... end def self.ssl_connections(ssl_server) loop do begin Thread.start(ssl_server.accept) do |ssl_socket| Server.increment_clients user = Network.register_connection(ssl_socket, Thread.current) Network.check_for_kline(user) unless Server.kline_mod.nil? Network.welcome(user) Network.main_loop(user) end rescue SocketError puts 'Open file descriptor limit reached!' Log.write(4, 'Open file descriptor limit reached!') # we likely cannot write to the log file in this state, but try anyway... rescue # Do nothing here since a plain-text connection likely came in... just continue on with the next connection Log.write(2, 'Incoming client failed to complete SSL handshake.') end end end def self.recv(user) # data = user.socket.gets("\r\n").chomp("\r\n") data = user.socket.gets.chomp("\r\n") # ircII fix -- blocking should be fine here until client sends EoL when in threaded mode data = data[0..Limits::MAXMSG - 1] if data.length > Limits::MAXMSG unless data.nil? Server.add_data_recv(data.length) user.data_sent += data.length end return data # Handle exception in case socket goes away... rescue Network.close(user, 'Connection closed', true) end def self.send(user, data) data = data[0..Limits::MAXMSG - 1] if data.length > Limits::MAXMSG unless data.nil? Server.add_data_sent(data.length) user.data_recv += data.length end user.socket.write(data + "\x0D\x0A") # Handle exception in case socket goes away... rescue Network.close(user, 'Connection closed', true) end def self.close(user, reason, lost_socket) user.socket.close rescue => e # The exception below usually produces "closed stream" messages which occur during high load. # Connection throttling and z-lining if client floods are detected should prevent any server hangs. Log.write(2, e) ensure Server.users.each do |u| if !u.nil? && u.admin && u.umodes.include?('v') && u.socket.closed? == false && !lost_socket Network.send(u, ":#{Options.server_name} NOTICE #{u.nick} :*** QUIT: #{user.nick}!#{user.ident}@#{user.hostname} has disconnected: #{reason}") end end if !user.nil? && user.channels_length > 0 user_channels = user.channels_array user_channels.each do |c| chan = Server.channel_map[c.to_s.upcase] next if chan.nil? chan.users.each do |u| # Do not broadcast QUIT for invisible administrators in a channel who disconnect. # Only do this for other administrators user_is_invisible = chan.invisible_nick_in_channel?(u.nick) if !user.nil? && !u.nil? && user.nick != u.nick && u.socket.closed? == false && user_is_invisible && u.admin Network.send(u, ":#{user.nick}!#{user.ident}@#{user.hostname} QUIT :#{reason}") end # Checking if user and 'u' are nil below prevent a "SystemStackError: stack level too deep" exception. # However, this may need to be fixed since stale nicks may hang around in channels when no client is actually connected. # So, FixMe: Figure out why user and/or 'u' objects become nil in the first place and prevent this from happening. next if user_is_invisible if !user.nil? && !u.nil? && user.nick != u.nick && u.socket.closed? == false Network.send(u, ":#{user.nick}!#{user.ident}@#{user.hostname} QUIT :#{reason}") end end chan.remove_user(user) chan.remove_invisible_user(user) unless chan.modes.include?('r') || chan.users.length > 0 Server.remove_channel(chan.name.upcase) end end end whowas_loaded = Command.command_map['WHOWAS'] unless whowas_loaded.nil? # Checking if user object is nil below prevents a "NoMethodError: undefined method `nick' for nil:NilClass" when using JRuby. if !user.nil? && !user.nick.nil? && user.nick != '*' Server.whowas_mod.add_entry(user, Time.now.asctime) end end Server.decrement_clients if Server.remove_user(user) Thread.kill(user.thread) unless user.nil? || user.thread.nil? end def self.register_connection(client_socket, connection_thread) if Options.enable_starttls.to_s == 'true' allowed_commands = %w(CAP CAPAB NICK PASS QUIT SERVER STARTTLS USER) else allowed_commands = %w(CAP CAPAB NICK PASS QUIT SERVER USER) end _sock_domain, _client_port, client_hostname, client_ip = client_socket.peeraddr user = User.new('*', nil, client_hostname, client_ip, nil, client_socket, connection_thread) Log.write(1, "Received connection from #{user.ip_address}.") if Server.client_count >= Options.max_connections Network.send(user, 'ERROR :Closing link: [Server too busy]') Server.decrement_clients Network.close(user, 'Server too busy', false) end unless Server.zline_mod.nil? Server.zline_mod.list_zlines.each do |zline| next unless zline.target.casecmp(client_ip) == 0 Network.send(user, "ERROR :Closing link: #{client_ip} [Z-lined (#{zline.reason})]") Server.users.each do |u| if u.admin || u.operator Network.send(u, ":#{Options.server_name} NOTICE #{u.nick} :*** BROADCAST: #{client_ip} was z-lined: #{zline.reason}") end end Log.write(2, "#{client_ip} was z-lined: #{zline.reason}") Server.decrement_clients Network.close(user, "Z-lined #{client_ip} (#{zline.reason})", false) end end # Thanks to darabiesvampire for contributing the clone detection code below unless Options.max_clones.nil? clone_count = 0 Server.users.each do |u| next unless u.ip_address == user.ip_address clone_count += 1 next unless clone_count >= Options.max_clones Network.send(user, 'ERROR :Closing link: [Maximum number of connections from the same IP address exceeded]') Server.users.each do |su| if su.admin || su.operator Network.send(su, ":#{Options.server_name} NOTICE #{su.nick} :*** BROADCAST: Maximum number of connections from #{user.ip_address} exceeded.") end end Log.write(1, "Maximum number of connections from #{user.ip_address} exceeded.") Server.decrement_clients Network.close(user, 'Maximum number of connections from the same IP address exceeded', false) end end Server.add_user(user) Network.send(user, ":#{Options.server_name} NOTICE Auth :*** Looking up your hostname...") begin hostname = Resolv.getname(client_ip) rescue Network.send(user, ":#{Options.server_name} NOTICE Auth :*** Couldn't look up your hostname") hostname = client_ip else Network.send(user, ":#{Options.server_name} NOTICE Auth :*** Found your hostname (#{hostname})") ensure user.hostname = hostname end registered = false timer_thread = Thread.new { Network.registration_timer(user) } good_pass = false until registered input = Network.recv(user) if input.nil? # client disconnected Network.close(user, 'Connection closed', true) return nil end redo if input.empty? input = input.chomp.split(' ', 2) # input[0] should contain command and input[1] contains the rest # Do not allow access to any other commands until the client is registered unless allowed_commands.any? { |c| c.casecmp(input[0].to_s.upcase) == 0 } unless Command.command_map[input[0].to_s.upcase].nil? Network.send(user, Numeric.err_notregistered(input[0].to_s.upcase)) redo end redo end if input[0].to_s.casecmp('PASS') == 0 pass_cmd = Command.command_map['PASS'] unless pass_cmd.nil? if input.length > 1 good_pass = pass_cmd.call(user, input[1..-1]) else good_pass = pass_cmd.call(user, '') end end elsif input[0].to_s.casecmp('STARTTLS') == 0 handle_tls(user) else Command.parse(user, input) end if user.nick != '*' && !user.ident.nil? && !user.gecos.nil? && !user.negotiating_cap if !Options.server_hash.nil? && !good_pass Network.send(user, 'ERROR :Closing link: [Access denied]') Network.close(user, 'Access denied', false) end registered = true else if user.nick != '*' && !user.ident.nil? && !user.gecos.nil? && user.negotiating_cap Network.send(user, Numeric.err_notregistered('CAP')) # user has not closed CAP with END end redo end end # until # Ensure we get a valid ping response during registration ping_time = Time.now.to_i Network.send(user, "PING :#{ping_time}") Network.send(user, ":#{Options.server_name} NOTICE #{user.nick} :*** If you are having problems connecting due to ping timeouts, please type /quote PONG #{ping_time} or /raw PONG #{ping_time} now.") loop do ping_response = Network.recv(user).split redo if ping_response.empty? if ping_response[0] =~ /(^pong$)/i && ping_response.length == 2 if ping_response[1] == ":#{ping_time}" || ping_response[1] == "#{ping_time}" Thread.kill(timer_thread) user.registered = true user.last_ping = Time.now.to_i # Set umode +i if auto_invisible is enabled. user.add_umode('i') if Options.auto_invisible.to_s == 'true' # Set cloak_host if auto_cloak is true or umode is +x. # This must be taken care of before virtual hosts are used to avoid overwriting the user's virtual host. unless Options.cloak_host.nil? unless user.umode?('x') if Options.auto_cloak.to_s == 'true' user.add_umode('x') user.virtual_hostname = Options.cloak_host end end end # Set vhost if module is loaded and user criteria is met... unless Server.vhost_mod.nil? vhost = Server.vhost_mod.find_vhost(user.ident, user.hostname) unless vhost.nil? if Utility.valid_hostname?(vhost) || Utility.valid_address?(vhost) user.virtual_hostname = vhost else Log.write(3, "Virtual host was not set for #{user.nick}!#{user.ident}@#{user.hostname} since vhost is invalid: #{vhost}") end end end return user else redo # ping response incorrect end else redo # wrong number of args or not a pong end end end def self.handle_tls(user) if Options.enable_starttls.to_s == 'true' begin Network.send(user, Numeric.rpl_starttls(user.nick)) user.socket.accept user.capabilities[:tls] = true rescue => e Log.write(2, "STARTTLS failed for #{user.ip_address}: #{e}") # It may be more secure to close the connection since it prevents # fallback to plain text if the user fails to handshake properly. Network.close(user, 'Failed TLS handshake', true) # Cannot send the numeric below since the socket went away # Network.send(user, Numeric.err_starttlsfailure(user.nick)) end end end def self.registration_timer(user) Kernel.sleep Limits::REGISTRATION_TIMEOUT Network.send(user, 'ERROR :Closing link: [Registration timeout]') Network.close(user, 'Registration timeout', false) end def self.check_for_kline(user) Server.kline_mod.list_klines.each do |kline| tokens = kline.target.split('@', 2) # 0 = ident and 1 = host next unless (tokens[0].casecmp(user.ident) == 0 && tokens[1] == '*') || (tokens[0].casecmp(user.ident) == 0 && tokens[1].casecmp(user.hostname) == 0) Network.send(user, "ERROR :Closing link: #{kline.target} [K-lined (#{kline.reason})]") Server.users.each do |u| if u.admin || u.operator Network.send(u, ":#{Options.server_name} NOTICE #{u.nick} :*** BROADCAST: #{kline.target} was k-lined: #{kline.reason}") end Log.write(2, "#{kline.target} was k-lined: #{kline.reason}") Network.close(user, "K-lined #{kline.target} (#{kline.reason})", false) end end end def self.welcome(user) Server.users.each do |u| if u.admin && u.umodes.include?('v') Network.send(u, ":#{Options.server_name} NOTICE #{u.nick} :*** CONNECT: #{user.nick}!#{user.ident}@#{user.hostname} has connected.") end end Network.send(user, Numeric.rpl_welcome(user.nick)) Network.send(user, Numeric.rpl_yourhost(user.nick)) Network.send(user, Numeric.rpl_created(user.nick)) Network.send(user, Numeric.rpl_myinfo(user.nick)) Network.send(user, Numeric.rpl_isupport1(user.nick, Options.server_name)) Network.send(user, Numeric.rpl_isupport2(user.nick, Options.server_name)) # If WALLCHOPS/WALLVOICES module not loaded, don't bother sending a third ISUPPORT unless Mod.find('WALLCHOPS').nil? && Mod.find('WALLVOICES').nil? Network.send(user, Numeric.rpl_isupport3(user.nick, Options.server_name)) end Network.send(user, Numeric.rpl_luserclient(user.nick)) Network.send(user, Numeric.rpl_luserop(user.nick)) Network.send(user, Numeric.rpl_luserchannels(user.nick)) Network.send(user, Numeric.rpl_luserme(user.nick)) Network.send(user, Numeric.rpl_localusers(user.nick)) Network.send(user, Numeric.rpl_globalusers(user.nick)) motd_cmd = Command.command_map['MOTD'] motd_cmd.call(user, '') unless motd_cmd.nil? fjoin_cmd = Command.command_map['FJOIN'] unless fjoin_cmd.nil? unless Options.auto_join.nil? arg_array = [] arg_array[0] = "#{user.nick} #{Options.auto_join}" fjoin_cmd.call(Options.server_name, arg_array) end end end def self.main_loop(user) loop do input = Network.recv(user) return if input.nil? redo if input.empty? puts input if Options.debug_mode # output raw commands to foreground for debugging purposes input = input.chomp.split(' ', 2) # input[0] should contain command and input[1] contains the rest if input[0].to_s.upcase == 'PING' user.last_ping = Time.now.to_i else user.update_last_activity end Command.parse(user, input) end end end
# Write a method that returns an Array that contains every other element # of an Array that is passed in as an argument. The values in the returned # list should be those values that are in the 1st, 3rd, 5th, and so on elements # of the argument Array. # Notes # itterate through the array and return ever odd index def oddities(array) array.select { |v| array.index(v).even? } end p oddities([2, 3, 4, 5, 6]) == [2, 4, 6] p oddities([1, 2, 3, 4, 5, 6]) == [1, 3, 5] p oddities(['abc', 'def']) == ['abc'] p oddities([123]) == [123] p oddities([]) == []
class Findings < Cask url 'http://downloads.findingsapp.com/Findings_2133_1.0.zip' homepage 'http://findingsapp.com' version '1.0' sha256 'f46d73e1f384d08136ef95c0d2881c422122d677c2bf78fe524e8c47aad98259' link 'Findings.app' end
module UnionFSProbe UNIONFS_SUPER_OFFSET = 1024 UNIONFS_MAGIC_OFFSET = 52 UNIONFS_MAGIC_SIZE = 4 UNIONFS_MAGIC = 0xf15f083d def self.probe(dobj) return false unless dobj.kind_of?(MiqDisk) # Assume UnionFS - read magic at offset. dobj.seek(UNIONFS_SUPER_OFFSET + UNIONFS_MAGIC_OFFSET) magic = dobj.read(UNIONFS_MAGIC_SIZE)&.unpack('L') raise "UnionFS is Not Supported" if magic == UNIONFS_MAGIC # No UnionFS. false end end
class Area < ApplicationRecord has_one :shop end
require "height/parser" require "height/parsers/base" require "height/parsers/metric" require "height/parsers/imperial" require "height/formatters/base" require "height/formatters/imperial" require "height/formatters/metric" require "height/units/base" require "height/units/millimeters" require "height/units/centimeters" require "height/units/meters" require "height/units/inches" require "height/units/feet" require "height/version" require "height/core_extensions" class Height include Comparable MILLIMETERS_IN_CENTIMETER = 10 CENTIMETERS_IN_METER = 100 MILLIMETERS_IN_METER = MILLIMETERS_IN_CENTIMETER * CENTIMETERS_IN_METER MILLIMETERS_IN_INCH = 25.4 INCHES_IN_FOOT = 12 class << self attr_accessor :system_of_units, :units_precision end self.system_of_units = :metric self.units_precision = { millimeters: 0, centimeters: 0, meters: 2, inches: 0, feet: 2, } def initialize(input) if input.respond_to? :to_millimeters @millimeters = input.to_millimeters else @millimeters = Parser.new(input).millimeters end end def millimeters @millimeters end def centimeters millimeters.to_centimeters end def meters millimeters.to_meters end def inches millimeters.to_inches end def feet millimeters.to_feet end def +(other) centimeters = (millimeters + other.millimeters).to_centimeters self.class.new(centimeters) end def -(other) centimeters = (millimeters - other.millimeters).to_centimeters self.class.new(centimeters) end def <=>(other) millimeters <=> other.millimeters end def to_s(format = :default, system_of_units = nil) system_of_units ||= self.class.system_of_units case system_of_units when :metric Formatters::Metric.new(millimeters).format(format) when :imperial Formatters::Imperial.new(millimeters).format(format) else raise ::ArgumentError.new('Invalid system of units provided, use either :metric or :imperial') end end end
require_relative 'find_by' require_relative 'errors' require 'csv' class Udacidata # Your code goes here! @@data_path = File.dirname(__FILE__) + "/../data/data.csv" def self.create(ops={}) new_product = true product_info = Product.new(ops) CSV.read(@@data_path).each do |row| new_product = false if row[0] == product_info.id end if !new_product product_info else CSV.open(@@data_path, "ab") do |csv| csv << ["#{product_info.id}", "#{product_info.brand}","#{product_info.name}", "#{product_info.price}"] end product_info end end def self.all items = [] #what is the difference between foreach and read CSV.foreach(@@data_path, headers: true) do |row| items.push(Product.new(id: row[0], brand:row[1], name: row[2], price: row[3])) end items end def self.first(n_times=1) if n_times ==1 self.all.first else self.all.first(n_times) end end def self.last(n_times=1) if n_times == 1 self.all.last else self.all.last(n_times) end end def self.find(id) find = false self.all.each {|product| return product if product.id == id } raise ProductNotFoundError end def self.destroy(id) exist = false delete_item = nil self.all.each do |product| if product.id == id exist = true delete_item = product end end if !exist raise ProductNotFoundError else table = CSV.table(@@data_path) table.delete_if do |row| row[:id] == id end File.open(@@data_path, 'w') do |f| f.write(table.to_csv) end end delete_item end def self.where(ops={}) matched_prodcuts = [] self.all.each do |product| if product.brand == ops[:brand] || product.name == ops[:name] || product.price == ops[:price] matched_prodcuts.push(product) end end matched_prodcuts end def update(ops={}) @brand = ops[:brand] if ops[:brand] @name = ops[:name] if ops[:name] @price = ops[:price] if ops[:price] Product.destroy(@id) Product.create(id: @id, brand:@brand, name: @name, price: @price) end end
class AddSlots < ActiveRecord::Migration[6.0] def change create_table :slots, id: :uuid do |t| t.references :station, null: false, type: :uuid, foreign_key: true, index: true t.references :bike, null: true, type: :uuid t.integer :number, null: false t.timestamps end end end
# frozen_string_literal: true module Quilt class TrustedUiServerCsrfStrategy def initialize(controller) @controller = controller end def handle_unverified_request return if node_server_side_render? fallback_handler.handle_unverified_request end private def node_server_side_render? @controller.request.headers["x-shopify-server-side-rendered"] == "1" end def fallback_handler ActionController::RequestForgeryProtection::ProtectionMethods::Exception.new(@controller) end end end
class Address < ApplicationRecord belongs_to :user, optional: true validates :last_name, presence: true, format: { with: /[ぁ-んァ-ンa-zA-Z一-龥]+/ } validates :first_name, presence: true, format: { with: /[ぁ-んァ-ンa-zA-Z一-龥]+/ } validates :last_name_kana, presence: true, format: { with: /[ァ-ン]+/ } validates :first_name_kana, presence: true, format: { with: /[ァ-ン]+/ } #validates :phone_number, presence: true, format: { with: /0\d{1,4}-\d{1,4}-\d{4}/ }, on: :create? validates :post_code, presence: true, format: { with: /\A\d{3}-*\d{4}\Z/ } validates :prefecture, presence: true validates :city, presence: true validates :block, presence: true end
class RoomSellList < ApplicationRecord belongs_to :list_sell end
class UserAccountWorker include Sidekiq::Worker def perform(user_id, password) user = User.find_by_id(user_id) UserMailer.notificate_user_account(user, password).deliver end end
require 'pathname' module PrivateGemServer module Sanity def self.check! # Make sure the git binary is installed fail! 'Please install git' if `which git` == '' # Make sure the gem executable is present fail! 'Cannot run `gem`' if `which gem` == '' # Make sure we have a valid config file begin config = YAML.load_file ENV['GEM_SOURCES'] rescue fail! 'Please supply a path to your gem sources YAML file in the GEM_SOURCES environment variable.' end # Make sure config has a hash of gems fail! 'Config file includes no gems' unless Hash === config && Hash === config['gems'] && !config['gems'].empty? # Make sure we can write to our working dir store = ENV['GEM_STORE'] fail! 'Please set GEM_STORE to a readable/writable directory' unless store && File.directory?(store) && File.readable?(store) && File.writable?(store) && File.executable?(store) # Make sure the log is writable log_path = ENV['GEM_SERVER_LOG'] if log_path log_path = Pathname(log_path) if log_path.exist? fail! "Server log (#{log_path}) is not writable" unless log_path.writable? else log_path.parent.mkpath rescue fail! "Cannot create server log directory (#{log_path.parent})" log_path.write '' rescue fail! "Cannot create server log (#{log_path})" end end end private def self.fail!(reason) STDERR << reason << "\n" exit 1 end end end
class Cart < ApplicationRecord has_many :cartsitems has_many :items, through: :cartsitems belongs_to :user end
require 'rails_helper' RSpec.describe ShortUrlsController, type: :controller do describe "these operations require an logged in user" do it "index" do get :index expect(response.status).to eq(401) end it "create" do get :create expect(response.status).to eq(401) end it "destroy" do get :destroy, {id: 1} expect(response.status).to eq(401) end it "show" do get :show, {id: 1} expect(response.status).to eq(401) end end describe "user is logged in" do before(:all) do @user = FactoryGirl.create(:user) end before(:each) do request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Token.encode_credentials(@user.api_token) @user.reload end after(:all) do @user.destroy end it "can create a short url" do get :create, {original_url: "http://www.asdfasdf.com"} expect(JSON.parse(response.body)["error"].present?).to eq(false) expect(ShortUrl.count).to be(1) end it "will list with pagination" do 12.times do FactoryGirl.create(:short_url, {user: @user}) end get :index, {api_token: @user.api_token, email: @user.email, page: 1} expect(JSON.parse(response.body)['data'].length).to eq(10) get :index, {api_token: @user.api_token, email: @user.email, page: 2} expect(JSON.parse(response.body)['data'].length).to eq(2) end it "show my url" do short_url = FactoryGirl.create(:short_url, {user: @user}) get :show, {api_token: @user.api_token, email: @user.email, id: short_url.id} expect(JSON.parse(response.body)['data']['attributes']['original-url']).to eq(short_url.original_url) end it "translates my url" do short_url = FactoryGirl.create(:short_url, {user: @user}) get :visit, {shorty: short_url.shorty} expect(response.location).to match(short_url.original_url) expect(ShortVisit.count).to be(1) end end end
class NoteSerializer include FastJsonapi::ObjectSerializer attributes :note_body belongs_to :recipe end
# frozen_string_literal: true # == Schema Information # # Table name: organizations # # id :integer not null, primary key # deleted_at :datetime # image :string default("https://placeholdit.imgix.net/~text?txtsize=23&txt=200%C3%97200&w=200&h=200") # mlid :string(3) not null # organization_name :string not null # created_at :datetime not null # updated_at :datetime not null # # Indexes # # organizations_mlid_key (mlid) UNIQUE # class Organization < ApplicationRecord include PgSearch::Model pg_search_scope :search, against: [:organization_name], using: { tsearch: { prefix: true } } resourcify validates :organization_name, presence: true, uniqueness: true validates :mlid, presence: true, uniqueness: true, format: { with: /\A[A-Za-z0-9]+\Z/ } has_many :chapters, dependent: :restrict_with_error def add_user_with_role(email, role) return false unless Role::LOCAL_ROLES.key? role user = User.find_or_create_by!(email: email) return false if user.member_of?(self) RoleService.update_local_role user, role, self end def members User.includes(:roles_users, :roles).where('roles.resource_id' => id) end end
require 'spreadsheet' class ListPull < ActiveRecord::Base attr_accessor :scrub_file, :zip_code_file serialize :tag_names, Array serialize :like_tags, Array serialize :user_attributes, Array serialize :zip_codes, Array serialize :scrubs, Array validates_numericality_of :impressions, :allow_nil => true validates_numericality_of :files SORT_OPTIONS = [ ['unsorted - (all users)', '' ], ['random - (all users, shuffled)', 'random' ], ['login - (date of last login)', 'daily login' ], ['active - (date of last review)', 'active' ] ] def validate errors.add(:sort_by, 'must be unsorted, random, active, or login') unless sort_by.blank? or ['random', 'active', 'daily login'].include?(sort_by) validate_dates end def validate_dates ## start_date.beginning_of_day.to_s(:db)}' AND '#{end_date.end_of_day.to_s(:db)}') if self.reviews_start_date if self.reviews_start_date > Date.today errors.add(:reviews_start_date, "Specified start date is after today") end if self.reviews_end_date.blank? self.reviews_end_date = Time.now end if self.reviews_end_date < self.reviews_start_date errors.add(:reviews_end_date, "Specified end date is after start date") end else if self.reviews_end_date errors.add(:reviews_start_date, "Please specify start date") end end end def path_to_file filename ? File.join(Rails.root, 'tmp', 'reports', filename) : nil end def scrub_file=(uploads) list = [] [*uploads].each do |upload| until upload.eof? do list << upload.readline.split(",")[0].downcase.chomp end if upload.respond_to?(:readline) end self.scrubs = list.compact end def zip_code_file=(upload) codes = [] if File.extname(upload.original_filename) == '.xls' book = Spreadsheet.open(upload) sheet = book.worksheet(0) sheet.each { |row| codes << row[0][/\d+/,0] } else until upload.eof? do codes << upload.readline.chomp end if upload.respond_to?(:readline) end self.zip_codes = codes.compact end [:tag_names, :like_tags, :user_attributes, :zip_codes, :scrubs].each do |attribute| define_method attribute do array = read_attribute(attribute) array.blank? ? [] : array end end def run joins = [] conditions = ["users.account_status = 'active' AND users.email_opt_in IS TRUE AND users.cobrand_id = ?", cobrand_id] unless tag_names.blank? joins << :user_tags conditions[0] << " AND (user_tags.kind = 'about_me' AND user_tags.value IN (?))" conditions << tag_names end unless like_tags.blank? joins << :user_tags unless joins.include?(:user_tags) conditions[0] << " AND (user_tags.kind = 'about_me' AND (" + (["LOWER(user_tags.value) LIKE ?"] * like_tags.size).join(' OR ') + "))" conditions += like_tags.map { |tag| '%' + tag.downcase + '%' } end unless email_list_id.blank? joins << :email_list_memberships conditions[0] << " AND email_list_memberships.email_list_id = ?" conditions << email_list_id end unless zip_codes.blank? conditions[0] << " AND users.zip_code IN (?)" conditions << zip_codes end if reviews_start_date && reviews_end_date joins << :reviews conditions[0] << " AND reviews.status = 'active' AND reviews.published_at BETWEEN ? and ?" conditions << reviews_start_date.beginning_of_day.to_s(:db) conditions << reviews_end_date.end_of_day.to_s(:db) end order = if 'active' == sort_by joins << :user_stat conditions[0] << " AND user_stats.most_recent_review_at IS NOT NULL" 'user_stats.most_recent_review_at DESC' elsif 'daily login' == sort_by joins << :reputable_events conditions[0] << " AND reputable_events.action = 'daily_visit'" 'reputable_events.created_at DESC' elsif 'random' == sort_by 'rand()' end select = ['auth_email'] + user_attributes users = User.all( :select => "DISTINCT users.id, #{select.map {|a| 'users.' + a}.join(', ')}", :conditions => conditions, :joins => joins, :order => order ) users.reject! { |user| scrubs.include?(user.auth_email) } unless scrubs.blank? users.reject! { |user| user.affiliate_user && !user.affiliate_user.completed_review_program? } if exclude_active_affiliate_users? users = users[0,impressions] if impressions users.map { |user| select.map { |a| user.send(a.to_sym) } } end end
class Admin::PageController < Admin::BaseController load_and_authorize_resource before_action :fetch_page, only: [:edit, :update, :show, :destroy] def index @pages = Page.all end def new @page = Page.new end def create @page = Page.new(page_params) if page_params[:preview] == "1" @issue = Setting.current_issue render :action => "show", :layout => $layout elsif @page.save redirect_to new_admin_page_url, notice: 'Page was successfully created.' else render action: "new" end end def edit end def update if page_params[:preview] == "1" @issue = Setting.current_issue @page = Page.new(page_params) render :action => "show", :layout => $layout elsif @page.update_attributes(page_params) redirect_to admin_pages_url, notice: 'Page was successfully updated.' else render action: "edit" end end def show @issue = Setting.current_issue render :action => "show", :layout => $layout end def destroy @page.destroy redirect_to admin_pages_url, notice: "Page was successfully deleted." end private def page_params params.require(:page).permit! end def fetch_page @page = Page.find(params[:id]) end end
class StoriesController < ApplicationController invisible_captcha only: [:create, :update] before_filter :require_login, except: [:new, :create, :index, :show] include StoriesHelper def index @stories = Story.order('created_at DESC').paginate(:page => params[:page], :per_page => 7) @story = Story.new end def show @story = Story.find(params[:id]) end def new @story = Story.new end def create @story = Story.new(story_params) @story.save @message = Message.new(story_params) MessageMailer.new_message(@message).deliver flash.notice = "Thank you for submitting your story!" redirect_to stories_path end def destroy @story = Story.find(params[:id]) @story.destroy flash.notice = "Story '#{@story.title}' deleted." redirect_to stories_path end def edit @story = Story.find(params[:id]) end def update @story = Story.find(params[:id]) @story.update(story_params) flash.notice = "Story '#{@story.title}' updated!" redirect_to story_path(@story) end end
class OrdersController < ApplicationController # before_action :set_order_item, only: [:update] def show @document = OrderDocument.new respond_to do |format| format.html format.pdf { render pdf: "show", layout: "pdf.html.slim" } end end def update if params[:clear] client_order.order_items.destroy_all elsif params[:count] params[:count].each do |id, value| item = OrderItem.find_by(id: id) || next value.to_i > 0 ? item.update(count: value) : item.destroy end end respond_to do |format| format.html do client_order.real = true if !params[:clear] && client_order.update(order_params) OrderMailer.new_order(client_order).deliver session["store.current_order_id"] = nil redirect_to cart_path, notice: <<-MSG Спасибо, мы заказ приняли. В течение ближайшего дня специалист свяжется с Вами и уточнит детали заказа. Чтобы ускорить работу – Вы можете связаться по телефону #{Setting.get("contacts.phone")} MSG else @document = OrderDocument.new render :show end end format.pdf do redirect_to order_url(client_order, format: "pdf") end end end private def order_params params.require(:order).permit(:company_name, :name, :phone, :email, :details_file) end end
class Order < ActiveRecord::Base attr_accessible :checkin, :checkout, :order_name, :order_phone, :price, :room_id, :room_num, :status, :user_id belongs_to :room belongs_to :user validates :checkin, :checkout, :order_name, :order_phone, :room_num, :presence => true validates :room_id, :presence => true delegate :desc, :to => :room, :allow_nil => true, :prefix => true delegate :email, :to => :user, :allow_nil => true, :prefix => true # ORDER_STATES = [unpay, payed, checked, cancel] # class << self # ORDER_STATES.each do |status| # end # end include AASM aasm column: 'status', skip_validation_on_save: true do state :unpay, initial: true state :payed state :checked state :canceled event :pay do transitions :from => :unpay, :to => :payed end event :check do transitions :from => :payed, :to => :checked end event :cancel do transitions :from => [:unpay, :payed], :to => :canceled end end end
# Below we have given you an array and a number. Write a program that checks to see if the number appears in the array. arr = [1, 3, 5, 7, 9, 11] number = 3 puts arr.include?(number) # .include evaluates to true or false and will let us know if the agrument is in the arr variable. Should I be verbose like the given answers are?
class ConferencesController < ApplicationController load_resource :user load_resource :tenant load_and_authorize_resource :conference, :through => [:user, :tenant] before_filter :set_and_authorize_parent before_filter :spread_breadcrumbs def index end def show @phone_numbers = @conference.phone_numbers end def new @conference = @parent.conferences.build @conference.name = generate_a_new_name(@parent, @conference) @conference.start = nil @conference.end = nil @conference.open_for_anybody = true @conference.max_members = GsParameter.get('DEFAULT_MAX_CONFERENCE_MEMBERS') @conference.pin = random_pin @conference.open_for_anybody = true @conference.announce_new_member_by_name = true @conference.announce_left_member_by_name = true end def create @conference = @parent.conferences.build(params[:conference]) if @conference.save m = method( :"#{@parent.class.name.underscore}_conference_path" ) redirect_to m.( @parent, @conference ), :notice => t('conferences.controller.successfuly_created') else render :new end end def edit end def update if @conference.update_attributes(params[:conference]) m = method( :"#{@parent.class.name.underscore}_conference_path" ) redirect_to m.( @parent, @conference ), :notice => t('conferences.controller.successfuly_updated') else render :edit end end def destroy @conference.destroy m = method( :"#{@parent.class.name.underscore}_conferences_url" ) redirect_to m.( @parent ), :notice => t('conferences.controller.successfuly_destroyed') end private def set_and_authorize_parent @parent = @tenant || @user authorize! :read, @parent end def spread_breadcrumbs if @parent && @parent.class == User add_breadcrumb t("users.index.page_title"), tenant_users_path(@user.current_tenant) add_breadcrumb @user, tenant_user_path(@user.current_tenant, @user) add_breadcrumb t("conferences.index.page_title"), user_conferences_path(@user) if @conference && !@conference.new_record? add_breadcrumb @conference, user_conference_path(@user, @conference) end end if @parent && @parent.class == Tenant add_breadcrumb t("conferences.index.page_title"), tenant_conferences_path(@tenant) if @conference && !@conference.new_record? add_breadcrumb @conference, tenant_conference_path(@tenant, @conference) end end end end
class GnuBarcode < Formula homepage "http://www.gnu.org/software/barcode/" url "http://ftpmirror.gnu.org/barcode/barcode-0.98.tar.gz" mirror "http://ftp.gnu.org/gnu/barcode/barcode-0.98.tar.gz" sha1 "15b9598bcaa67bcff1f63309d1a18840b9a12899" def install system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make" system "make", "MAN1DIR=#{man1}", "MAN3DIR=#{man3}", "INFODIR=#{info}", "install" end test do (testpath/"test.txt").write("12345") system "#{bin}/barcode", "-e", "CODE39", "-i", "test.txt", "-o", "test.ps" assert File.read("test.ps").start_with?("") end end
class CreateBuddyRequestSubjects < ActiveRecord::Migration def change create_table :buddy_request_subjects do |t| t.string :requester_name, null: false t.integer :requester_id, null: false t.integer :requested_id, null: false t.timestamps null: false end end end
require 'dmtd_vbmapp_data/request_helpers' module DmtdVbmappData # Provides for the retrieving of VB-MAPP Area Question on the VB-MAPP Data Server. class ProtocolAreaQuestion # @!attribute [r] client # @return [Client] the associated client attr_reader :client # @!attribute [r] area # @return [Symbol] the area of the question (e.g. :milestones, :barriers, :transitions, :eesa) attr_reader :area # @!attribute [r] group # @return [Symbol] the group of the question (e.g. :mand, :tact, :group1, etc.) attr_reader :group # @!attribute [r] definition # @return [String] the formal definition for the question attr_reader :definition # @!attribute [r] example # @return [String] an example of administering the question attr_reader :example # @!attribute [r] materials # @return [String] the materials required to administer the question attr_reader :materials # @!attribute [r] objective # @return [String] The objective of the question attr_reader :objective # @!attribute [r] number # @return [Integer] the question number (0...n) attr_reader :number # @!attribute [r] text # @return [String] the text of the question itself attr_reader :text # @!attribute [r] title # @return [String] a title to display at the top of a grid column attr_reader :title # @!attribute [r] level # @return [Integer] the level number of the question (only when area == :milestones) attr_reader :level # @!attribute [r] skills # @return [Skill] the set of Task Analysis Skills for the question attr_reader :skills # Creates an accessor for the VB-MAPP Area Question on the VB-MAPP Data Server # # @note This method does *not* block, simply creates an accessor and returns # # @option opts [Client] :client A client instance # @option opts [String | Symbol] :area The vbmapp area of the group ('milestones', 'barriers', 'transitions', 'eesa') # @option opts [String | Symbol] :group The vbmapp area group name (i.e. 'mand', 'tact', 'group1', etc.) # @option opts [Hash] :question_json The vbmapp question json for the question in the format described at # {https://datamtd.atlassian.net/wiki/pages/viewpage.action?pageId=18710549 /1/protocol/area_question - GET REST api - Fields} def initialize(opts) @client = opts.fetch(:client) @area = opts.fetch(:area).to_sym @group = opts.fetch(:group).to_sym question_json = opts.fetch(:question_json) @definition = question_json[:definition] @objective = question_json[:objective] @example = question_json[:example] @materials = question_json[:materials] @number = question_json[:number].to_i @text = question_json[:text] @title = question_json[:title] @level = question_json[:level] @responses_json_array = question_json[:responses] skills = question_json[:skills] @skills = if skills.nil? [] else question_json[:skills].map do |skill| ProtocolAreaSkill.new(question_json: skill) end end end # @note This method does *not* block. # # @return [Array<ProtocolAreaResponse>] all of the VB-MAPP question's possible responses def responses @responses = @responses_json_array.map { |response_json| ProtocolAreaResponse.new(area: area, response_json: response_json) } if @responses.nil? @responses end end end
require 'matrix' module Battleship class Board attr_reader :size, :positions def initialize(size) @size = size @positions = Matrix.build(size, size) { nil } end def add_ship(ship, x, y, horizontal = true) Add.new(self, ship).execute(x, y, horizontal) end def has_ship?(x, y) !positions[x, y].nil? end def hit!(x, y) positions.send(:[]=, x, y, :hit) end def destroyed? positions.each do |position| return false if !position.nil? end return true end end end
# # Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands. # # This file is part of New Women Writers. # # New Women Writers 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 3 of the License, or # (at your option) any later version. # # New Women Writers 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. # # You should have received a copy of the GNU General Public License # along with New Women Writers. If not, see <http://www.gnu.org/licenses/>. # module Rails module Generator class SimpleLogger # :nodoc: attr_reader :out attr_accessor :quiet def initialize(out = $stdout) @out = out @quiet = false @level = 0 end def log(status, message, &block) @out.print("%12s %s%s\n" % [status, ' ' * @level, message]) unless quiet indent(&block) if block_given? end def indent(&block) @level += 1 if block_given? begin block.call ensure outdent end end end def outdent @level -= 1 if block_given? begin block.call ensure indent end end end private def method_missing(method, *args, &block) log(method.to_s, args.first, &block) end end end end
require 'test_helper' class SurfShopReviewsControllerTest < ActionDispatch::IntegrationTest def setup @user = users(:steve) @surf_shop_review = surf_shop_reviews(:good_review) @surf_shop = surf_shops(:first_surf_shop) end test "should redirect new when not logged in" do get new_surf_shop_surf_shop_review_path(@surf_shop) assert_redirected_to login_url end test "should redirect create when not logged in" do assert_no_difference 'SurfShopReview.count' do post surf_shop_surf_shop_reviews_path(@surf_shop), params: { surf_shop_reviews: { rating: 5, title: "Sample Review", comment: "Lorem ipsum" } } end assert_redirected_to login_url end test "should redirect edit when not logged in" do get edit_surf_shop_surf_shop_review_path(@surf_shop_review.surf_shop, @surf_shop_review) assert_redirected_to login_url end test "should redirect edit when logged in as wrong user" do log_in_as(@user) get edit_surf_shop_surf_shop_review_path(@surf_shop_review.surf_shop, @surf_shop_review) assert flash.empty? assert_redirected_to surf_shop_url(@surf_shop) end test "should redirect update when not logged in" do assert_no_difference 'SurfShopReview.count' do patch surf_shop_surf_shop_review_path(@surf_shop_review.surf_shop, @surf_shop_review), params: { surf_shop_reviews: { rating: 5, title: "Sample Review", comment: "Lorem ipsum" } } end assert_redirected_to login_url end test "should redirect update when logged in as wrong user" do log_in_as(@user) assert_no_difference 'SurfShopReview.count' do patch surf_shop_surf_shop_review_path(@surf_shop_review.surf_shop, @surf_shop_review), params: { surf_shop_reviews: { rating: 5, title: "Sample Review", comment: "Lorem ipsum" } } end assert_redirected_to surf_shop_url(@surf_shop) end test "should redirect destroy when not logged in" do assert_no_difference 'SurfShopReview.count' do delete surf_shop_surf_shop_review_path(@surf_shop_review.surf_shop, @surf_shop_review) end assert_redirected_to login_url end test "should redirect destroy when logged in as wrong user" do log_in_as(@user) assert_no_difference 'SurfShopReview.count' do delete surf_shop_surf_shop_review_path(@surf_shop_review.surf_shop, @surf_shop_review) end assert_redirected_to surf_shop_url(@surf_shop) end end
# == Schema Information # # Table name: sites # # id :bigint not null, primary key # country_code :string # lat :decimal(, ) # lng :decimal(, ) # name :string # superseded_by :integer # created_at :datetime not null # updated_at :datetime not null # # Indexes # # index_sites_on_country_code (country_code) # index_sites_on_name (name) # index_sites_on_superseded_by (superseded_by) # FactoryBot.define do factory :site do name { Faker::Verb.unique.base } lat { Faker::Address.latitude } lng { Faker::Address.longitude } country_code { Faker::Address.country_code } after(:create) {|site| site.site_types = [create(:site_type)]} end end
require 'rubygems' require 'coderay' module WLang class EncoderSet # # Allows coderay highlighter to be used as encoder. When using standard dialects, # these encoders are installed under <tt>xhtml/coderay/ruby</tt>, # <tt>xhtml/coderay/html</tt>, etc. qualified names. # # Available languages are: java, ruby, html, yaml. # module CodeRayEncoderSet # Coderay recognized formats RECOGNIZED = ["java", "ruby", "html", "yaml", "sql", "css", "javascript", "json", "php", "xml"] # Default encoders DEFAULT_ENCODERS = {} RECOGNIZED.each{|f| DEFAULT_ENCODERS[f] = f.to_sym} # Upcase encoding def self.coderay(src, options) /([a-z]+)$/ =~ options['_encoder_'] encoder = $1.to_sym tokens = CodeRay.scan src, encoder highlighted = tokens.html({ :wrap => :div, :css => :class} ) return highlighted end RECOGNIZED.each{|f| module_eval <<-EOF def self.#{f}(src, options) WLang::EncoderSet::CodeRayEncoderSet.coderay(src, options.merge('_encoder_' => #{f.inspect})) end EOF } end # module CodeRay end end
class AlbumsController < ApplicationController # @http_method XHR POST # @url /documents def create # if current_user # @album = Album.create!(album_params) # end if current_user @album = current_user.albums.create!(album_params) @album.photos.create(direct_upload_url: @album.direct_upload_url, rating_amount: 0) redirect_to :back else redirect_to root_url end end def show @album = Album.find(params[:id]) @photo = Photo.new end private def album_params params.require(:album).permit(:direct_upload_url, :name) end end
get '/' do if session[:user_id] @user = User.find(session[:user_id]) end erb :index end get '/sign_in' do # the `request_token` method is defined in `app/helpers/oauth.rb` redirect request_token.authorize_url end get '/sign_out' do session.clear redirect '/' end get '/auth' do # the `request_token` method is defined in `app/helpers/oauth.rb` @access_token = request_token.get_access_token(:oauth_verifier => params[:oauth_verifier]) # our request token is only valid until we use it to get an access token, so let's delete it from our session session.delete(:request_token) @user = User.find_or_create_by( oauth_token: @access_token.token, oauth_secret: @access_token.secret, username: @access_token.params[:screen_name]) session[:user_id] = @user.id erb :index end post '/post_tweet' do user = User.find(session[:user_id]) twitter_user = Twitter::Client.new( oauth_token: user.oauth_token, oauth_token_secret: user.oauth_secret ) if twitter_user.update(params[:tweet]) session[:status_message] = "Successfully posted your tweet" else session[:status_message] = "Sorry. Something went wrong" end redirect to '/' end
require 'spec_helper' describe 'postgresql::params', type: :class do let :facts do { osfamily: 'Debian', operatingsystem: 'Debian', operatingsystemrelease: '8.0', } end it { is_expected.to contain_class('postgresql::params') } end
require 'mifparserutils' class MifTableParser include MifParserUtils def get_tables doc @format_info = {} table_formats = (doc/'TblCatalog/TblFormat') table_formats.each do |format| handle_format format end tables = (doc/'Tbls/Tbl') tables.inject({}) do |hash, table| handle_table(table, hash) end end def handle_format node current_tag = clean(node.at('TblTag/text()')) border_top = clean(node.at('TblTRuling/text()')) border_left = clean(node.at('TblLRuling/text()')) border_bottom = clean(node.at('TblBRuling/text()')) border_right = clean(node.at('TblRRuling/text()')) hf_separator = clean(node.at('TblHFRowRuling/text()')) col_border = clean(node.at('TblColumnRuling/text()')) row_border = clean(node.at('TblBodyRowRuling/text()')) col_x = node.at('TblXColumnNum/text()') if node.at('TblXColumnRuling/text()') col_x_border = clean(node.at('TblXColumnRuling/text()')) end @format_info.merge!({ "#{current_tag}" => { "border_top" => "#{border_top}", "border_left" => "#{border_left}", "border_bottom" => "#{border_bottom}", "border_right" => "#{border_right}", "hf_separator" => "#{hf_separator}", "col_border" => "#{col_border}", "row_border" => "#{row_border}", "col_x" => "#{col_x}", "col_x_border" => "#{col_x_border}" }}) end def handle_id node @current_table_id = node.at('text()').to_s end def handle_tag node, tables tag = clean(node) @table_tag = tag if tag != 'Table' && tag != 'RepealContinue' && tag != 'RepealsSchedules' do_break = true else css_class = get_table_css_class(node) xml_tag = start_tag('TableData', node) unless css_class.empty? if xml_tag.include?('class=') xml_tag.gsub!('">', %Q| #{css_class}">|) else xml_tag.gsub!('>', %Q| class="#{css_class}">|) end end tables[@current_table_id] = [xml_tag] do_break = false end do_break end def handle_row node, tables @cell_count = 0 if @in_row if @in_heading tables[@current_table_id] << "</CellH></Row>" else tables[@current_table_id] << "</Cell></Row>" end @in_row = false @in_cell = false end row_id = node.at('Element/Unique/text()').to_s @in_row = true css_class = "" if !@format_info[@table_tag]["hf_separator"].empty? && @in_heading css_class = %Q| class="bottomborder"| end tables[@current_table_id] << %Q|<Row id="#{row_id}"#{css_class}>| end def handle_cell node, tables if @colspan_target > 0 if @colspan_count < @colspan_target @colspan_count += 1 @cell_count += 1 return else @colspan_target = 0 end end colspan = 1 if node.at('CellColumns/text()') colspan = node.at('CellColumns/text()').to_s colspan = colspan.to_i end first = ' class="first"' if @in_cell first = "" if @in_heading tables[@current_table_id] << "</CellH>" else tables[@current_table_id] << "</Cell>" end end cell_id = node.at('Element/Unique/text()').to_s @in_cell = true css_class = "" unless @format_info[@table_tag]["col_x_border"].empty? if (@format_info[@table_tag]["col_x"] == @cell_count.to_s && !@in_heading) || (@format_info[@table_tag]["col_x"].to_i == @cell_count.to_i + (colspan-1) && !@in_heading) if first == "" css_class = %Q| class="leftborder"| if @no_of_cols.to_i+-1 != @cell_count.to_i+(colspan-1) css_class = %Q| class="leftborder rightborder"| end else if @no_of_cols.to_i-1 != @cell_count+(colspan-1) css_class = %Q| class="rightborder"| end end end end unless @format_info[@table_tag]["col_border"].empty? if first == "" css_class = %Q| class="leftborder"| if @no_of_cols.to_i+-1 != @cell_count.to_i+(colspan-1) css_class = %Q| class="leftborder rightborder"| end else if @no_of_cols.to_i-1 != @cell_count+(colspan-1) css_class = %Q| class="rightborder"| end end end #assumes that if a Ruling node is used in this position then it is set to a valid value if node.at('CellTRuling/text()') && node.at('CellRRuling/text()') && node.at('CellBRuling/text()') && node.at('CellLRuling/text()') css_class = %Q| class="allborders"| else if node.at('CellTRuling/text()') css_class.gsub!('class="', 'class="topborder ') unless css_class.include?('topborder') end if node.at('CellRRuling/text()') css_class.gsub!('class="', 'class="rightborder ') unless css_class.include?('rightborder') end if node.at('CellBRuling/text()') css_class.gsub!('class="', 'class="bottomborder ') unless css_class.include?('bottomborder') end if node.at('CellLRuling/text()') css_class.gsub!('class="', 'class="leftborder ') unless css_class.include?('leftborder') end end if first != "" && css_class != "" first = "" css_class.gsub!('class="', 'class="first ') end if @in_heading tables[@current_table_id] << %Q|<CellH id="#{cell_id}"#{first}#{css_class}>| else tables[@current_table_id] << %Q|<Cell id="#{cell_id}"#{first}#{css_class}>| end @cell_count += 1 end def handle_cell_columns node, tables colspan = node.at('text()').to_s cell = tables[@current_table_id].pop cell = cell.gsub(">", %Q| colspan="#{colspan}">|) tables[@current_table_id] << cell @colspan_target = colspan.to_i @colspan_count = 1 end def handle_attribute node, tables if clean(node.at('AttrName')) == 'Align' attr_value = clean(node.at('AttrValue')) alignment = '' case attr_value when 'Center' alignment = 'centered' when 'Right' alignment = 'right' end cell_start = tables[@current_table_id].pop if cell_start.include?('class=') cell_start.gsub!('">', %Q| #{alignment}">|) else cell_start.gsub!('>', %Q| class="#{alignment}">|) end tables[@current_table_id] << cell_start end end def handle_body tables tables[@current_table_id] << '</CellH></Row>' if @in_heading @in_row = false @in_cell = false @in_heading = false end def add_text text, tables tables[@current_table_id] << text end def handle_node node, tables do_break = false case node.name when 'TblID' handle_id node when 'TblTag' do_break = handle_tag(node, tables) when 'Row' handle_row node, tables when 'Cell' handle_cell node, tables when 'Attribute' handle_attribute node, tables when 'CellColumns' handle_cell_columns node, tables when 'TblH' @in_heading = true when 'TblBody' handle_body tables when 'String' add_text clean(node), tables when 'Char' add_text get_char(node), tables end do_break end def get_table_css_class node css_class = "" if !@format_info[@table_tag]["border_top"].empty? && !@format_info[@table_tag]["border_right"].empty? && !@format_info[@table_tag]["border_bottom"].empty? && !@format_info[@table_tag]["border_left"].empty? css_class = "allborders" else unless @format_info[@table_tag]["border_top"].empty? css_class += " topborder " end unless @format_info[@table_tag]["border_right"].empty? css_class += " rightborder" end unless @format_info[@table_tag]["border_bottom"].empty? css_class += " bottomborder" end unless @format_info[@table_tag]["border_left"].empty? css_class += " leftborder" end if node.parent.at('TblFormat/TblTRuling/text()') && node.parent.at('TblFormat/TblLRuling/text()') && node.parent.at('TblFormat/TblBRuling/text()') && node.parent.at('TblFormat/TblRRuling/text()') css_class = "allborders" else if node.parent.at('TblFormat/TblTRuling/text()') css_class += " topborder" unless css_class.include?("topborder") end if node.parent.at('TblFormat/TblRRuling/text()') css_class += " rightborder" unless css_class.include?("rightborder") end if node.parent.at('TblFormat/TblBRuling/text()') css_class += " bottomborder" unless css_class.include?("bottomborder") end if node.parent.at('TblFormat/TblLRuling/text()') css_class += " leftborder" unless css_class.include?("leftborder") end end end css_class.strip end def handle_table table_xml, tables @current_table_id = nil @in_heading = false @in_row = false @in_cell= false @colspan_count = 0 @colspan_target = 0 @table_tag = "" table_count = tables.size @no_of_cols = table_xml.at('TblNumColumns/text()').to_s table_xml.traverse_element do |node| do_break = handle_node node, tables break if do_break end if tables.size > table_count if @in_heading add_text "</CellH></Row></TableData>", tables else add_text "</Cell></Row></TableData>", tables end end tables end end
# frozen_string_literal: true class User < ApplicationRecord devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :omniauthable with_options presence: true do validates :nickname validates :email, uniqueness: { case_sensitive: true } validates :password, format: { with: /\A(?=.*?[a-z])(?=.*?[\d])[a-z\d]+\z/i }, confirmation: true end has_many :performances has_one_attached :image has_many :likes def self.from_omniauth(auth) user = User.where(provider: auth.provider, uid: auth.uid).first unless user user = User.new( provider: auth.provider, uid: auth.uid, nickname: auth.info.name, name: auth.info.name, email: User.dummy_email(auth), password: Devise.friendly_token[0, 20] ) user.save(validate: false) end user end private def self.dummy_email(auth) "#{auth.uid}-#{auth.provider}@example.com" end end
class AddIndexToForeignKeys < ActiveRecord::Migration def change add_index :availabilities, :participant_id add_index :availabilities, :event_date_id add_index :event_dates, :event_id add_index :participants, :event_id end end
namespace :submission do task :creation => :environment do writer = Writer.first create_description(create_submission(writer.id)) end def create_submission(writer_id) submission = submission.create(:writer_id => writer_id, :name =>'Something you love', :genre => 'Horror') return submission.id end def create_description(submission_id) description = Description.new(:submission_id => submission_id, :summary => 'Something useful', :story => 'A pretty interesting story', :status => :unassigned) if description.save puts 'submission created successfully' else puts "#{description.errors}" end end end
require 'PushRadar/version' require 'PushRadar/Targeting' require 'net/http' require 'json' require 'openssl' module PushRadar # A client that interacts with PushRadar's API class APIClient # Creates a new instance of the PushRadar API client with the specified API secret def initialize(api_secret) # Set the API secret api_secret.strip! @api_secret = api_secret # Set the API endpoint @api_endpoint = 'https://api.pushradar.com/v2' end # Performs a POST request to the API destination specified def post(destination, data) # Add in the fields that should be sent with each request data['apiSecret'] = @api_secret data['clientPlatform'] = 'ruby' data['timestamp'] = Time.now.to_i # Make sure the destination does not contain the base URL or forward slash characters destination = destination.gsub('/', '') destination.sub! @api_endpoint, '' # Construct the actual URL to POST the data to url = @api_endpoint + '/' + destination # Send a POST request to the server uri = URI.parse(url) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true req = Net::HTTP::Post.new(url) req.content_type = 'application/x-www-form-urlencoded' data = URI.encode_www_form(data) req.body = data http.request(req) end end end
# The purpose of this scope is mainly to prevent # (call foo) in an escaped s-expression from being # rewritten to (callm self foo) when inside a class # definition - this rewrite is ok for non-escaped # code, but for embedded s-expressions the purpose # is to have explicit control over the low level # constructs class SexpScope < Scope def initialize(next_scope) @next = next_scope end def method @next ? @next.method : nil end def rest? @next.rest? end def lvaroffset 0 end def get_arg(a) arg = @next.get_arg(a) if arg[0] == :possible_callm arg[0] = :addr end arg end end
def roll_call_dwarves (dwarves) dwarves.each_with_index {|dwarf, i| puts "#{i+1} #{dwarf}"} end def summon_captain_planet (planeteer_calls) planeteer_calls = planeteer_calls.collect { | planeteer_calls | planeteer_calls.capitalize + "!" } end def long_planeteer_calls(calls) calls.any? { |calls| calls.length > 4} end def find_the_cheese(array) cheese_types = ["cheddar", "gouda", "camembert"] array.find do |word| cheese_types.include?(word) end end
require 'sidekiq' class RecurringWaiverPicksWorker include Sidekiq::Worker sidekiq_options retry: 2 def perform round = Round.current_round return if WaiverPick.pending.where(round_id: round.id).empty? waiver_cutoff = round.deadline_time - 1.day return if Time.now.to_date != (waiver_cutoff).to_date ::ProcessWaiverPicksWorker.perform_at(waiver_cutoff) end end
class Hotel < ActiveRecord::Base belongs_to(:user) validates_presence_of(:name, :description, :user_id, :address) validates_uniqueness_of(:name) def admin_or_belongs_to?(person, place) person.try(:admin?) || person.hotels.ids.include?(place) end def admin_check(person) person.try(:admin?) end has_attached_file(:image, styles: {thumbnail: '100x100>', full: '300X300>'}) validates_attachment_content_type(:image, content_type: /\Aimage\/.*\z/) geocoded_by(:address) after_validation(:geocode) end
=begin Написать методы, расширяющие встроенный в Ruby класс Array Все методы должны вызываться на объектах класса Array, т,е массивах. Метод square - должен возводить каждый элемент массива в квадрат и возвращать новый массив. Метод average - должен вернуть среднее арифметическое значение элементов массива (если метод вызывается на массиве строк - должен вернуть 0). Метод even_odd - должен вернуть разницу количества четных и нечетных чисел в массиве. Метод reverse_strings - должен вызываться на массиве строк и "переворачивать" все строки, возвращая новый массив. (Пример: ['string'].reverse_strings => ['gnirts']) Подсказка: чтобы вызывать все методы на объектах класса Array, достаточно просто объявить в программе класс Array и внутри него написать вышеописанные методы. Примечание: методы не должны менять те массивы, на которых они вызываются. Они только должны возвращать новые массивы. =end class Array def square squared_array = self.map { |num| num ** 2 } puts "Новый массив чисел, возведенных в квадрат: #{squared_array}" end def average return 0 if self.map { |elem| elem.is_a? String }.include?(true) average_value = (self.reduce(:+).to_f / self.size) puts "Cреднее арифметическое значение элементов массива: #{average_value}" end def even_odd even = self.select { |num| num.even? }.size odd = self.select { |num| num.odd? }.size puts "Разница четных и нечетных чисел в массиве: #{even - odd}" end def reverse_strings reversed = self.map { |string| string.reverse } puts "Массив с перевернутыми строками: #{reversed}" end end puts "Введите массив чисел" num_input = gets.chomp.to_s numbers = num_input.split.map { |input| input.to_i } puts "Введите массив строк" str_input = gets.chomp.to_s strings = str_input.split.map { |input| input.to_s } numbers.square numbers.average numbers.even_odd strings.reverse_strings
require 'rails' module Treasury class Engine < ::Rails::Engine config.autoload_paths += Dir["#{config.root}/lib"] initializer 'treasury', before: :load_init_rb do |app| app.config.paths['db/migrate'].concat(config.paths['db/migrate'].expanded) ActiveRecord::Base.extend(Treasury::Pgq) if defined?(ActiveRecord) require 'treasury/backwards' end initializer 'treasury-factories', after: 'factory_girl.set_factory_paths' do |_| if defined?(FactoryGirl) FactoryGirl.definition_file_paths.unshift root.join('spec', 'factories') end end end end
# -*- coding: utf-8 -*- =begin rdoc Model用のmoduleで、これをincludeするとUserに要求されるいくつかのメソッドが定義される。 =end module Diva::Model::UserMixin def user self end def icon Plugin.collect(:photo_filter, profile_image_url, Pluggaloid::COLLECT).map { |photo| Plugin.filtering(:miracle_icon_filter, photo)[0] }.first end def icon_large Plugin.collect(:photo_filter, profile_image_url_large, Pluggaloid::COLLECT).lazy.map { |photo| truth = Plugin.filtering(:miracle_icon_filter, photo)[0] if photo == truth truth else icon end }.first end def profile_image_url_large profile_image_url end def verified? false end def protected? false end end
require File.dirname(__FILE__) + '/../../lib/gna_xml' describe GNA_XML do describe 'GNA_XML::data_source_xml' do #TODO: add specs for wrong xml files as well. before(:each) do @data_source_xml = File.dirname(__FILE__) + "/../fixtures/feeds/index_fungorum_data_source.xml" @res = GNA_XML::data_source_xml(@data_source_xml) end it "should return hash" do @res.should be_an_instance_of(Hash) end it 'result should have metadata_url, data_url, title' do @res[:metadata_url].should == @data_source_xml @res[:title].should == "Index Fungorum" @res[:data_url].should == "http://example.com/url_to_data.xml" @res[:data_zip_compressed].should == true end it 'result might have description, logo_url' do @res[:description].should be_an_instance_of(String) @res[:logo_url].should be_an_instance_of(String) end end end
class WorksController < ApplicationController before_action :find_work, only: [:show, :edit, :update, :destroy] def home @top_albums = Work.top_works("album") @top_movies = Work.top_works("movie") @top_books = Work.top_works("book") @spotlight = Work.first end def index @albums = Work.all_works("album") @movies = Work.all_works("movie") @books = Work.all_works("book") end def show if @work @creation = "Created by: #{@work.creator}" @publish = "Published: #{@work.publication_year}" @describe = @work.description else flash[:fail] = "Unable to find work" redirect_to root_path end end def edit end def update if !@work.nil? if @work.update(work_params) redirect_to work_path(@work.id) else #Flash or render :edit end else redirect_to works_path end end def new @work = Work.new end def create @work = Work.new(work_params) if @work.save flash[:success] = "Successfully created #{@work.category} #{@work.id}" redirect_to root_path else # this feels wrong, I am unsure of the @work.error flash.now[:alert] = "A problem occurred: Could not create #{@work.category} #{@work.errors}" render :new end end def destroy if @work @work.destroy flash[:success] = "Sucessfully destroyed #{@work.category} #{@work.id}" end redirect_to root_path end private def work_params return params.require(:work).permit(:category, :title, :creator, :publication_year, :description, :id, :votes) end def find_work @work = Work.find_by(id: params[:id]) end end
class Employee < ApplicationRecord belongs_to :dog def to_s "#{self.first_name} #{self.last_name}" end # def set_dog # if self.dog.class == String # new_dog = Dog.find_by(name: self.dog) # self.dog = new_dog # end # end end
# Documentation: https://docs.brew.sh/Formula-Cookbook # https://rubydoc.brew.sh/Formula # PLEASE REMOVE ALL GENERATED COMMENTS BEFORE SUBMITTING YOUR PULL REQUEST! class CocoapodsCacheProxyServer < Formula desc "CocoaPods 缓存" homepage "https://github.com/0x1306a94/homebrew-apps" url "https://raw.githubusercontent.com/0x1306a94/homebrew-apps/master/cocoapods-cache-proxy-server.zip" sha256 "f4d12523994fae1e781ad1a2df25b9f05c1b31bc32c8cdca783b107a4f6c4f92" version "master" # depends_on "cmake" => :build def datadir prefix/"cocoapods-cache-proxy-server" end def install bin.install "cocoapods-cache-proxy-server" (datadir).mkpath (datadir/"conf.yaml").write <<~EOS --- user: admin password: 123456dd port: 9898 cacheDir: #{datadir} verbose: true EOS puts <<~EOS How to use? config file path: #{datadir}/conf.yaml cache dir: #{datadir} # start brew services start cocoapods-cache-proxy-server # stop brew services stop cocoapods-cache-proxy-server # restart brew services restart cocoapods-cache-proxy-server EOS end plist_options :manual => "cocoapods-cache-proxy-server" def plist; <<~EOS <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>KeepAlive</key> <true/> <key>Label</key> <string>#{plist_name}</string> <key>ProgramArguments</key> <array> <string>#{opt_bin}/cocoapods-cache-proxy-server</string> <string>-conf</string> <string>#{datadir}/conf.yaml</string> </array> <key>WorkingDirectory</key> <string>#{datadir}</string> <key>StandardErrorPath</key> <string>#{datadir}/error.log</string> <key>StandardOutPath</key> <string>#{datadir}/out.log</string> <key>RunAtLoad</key> <true/> </dict> </plist> EOS end test do # `test do` will create, run in and delete a temporary directory. # # This test will fail and we won't accept that! For Homebrew/homebrew-core # this will need to be a test that verifies the functionality of the # software. Run the test with `brew test ytoo`. Options passed # to `brew install` such as `--HEAD` also need to be provided to `brew test`. # # The installed folder is not in the path, so use the entire path to any # executables being tested: `system "#{bin}/program", "do", "something"`. system "false" end end
class DatabasesController < ApplicationController respond_to :json def index respond_with(server.database_names) end def show respond_with(database.collection_names) end end
#!/usr/bin/ruby # Simple Tomboy Server version 0.1.2 # THE AUTHOR OF THIS SOFTWARE IS NOT RELATED TO THE AUTHORS OF TOMBOY SOFTWARE # Copyright (c) 2011-2018 Marcio Frayze David (mfdavid@gmail.com) # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. require 'gserver' class TomBoyServer < GServer # This is the default directory for tomboy note files # If you are using an old version of tomboy, you may need to change this to "/.tomboy/" @@BASE_DIR = ENV['HOME'] + '/.local/share/tomboy/' # Getting and parsing the user command to get the name of the note the user wants to access def parse_note_name_from_request(io) parameters = io.gets note_name = parameters[5,parameters.length-16].strip end # Main method used by gserver, called when a new http request is received def serve(io) note_name = parse_note_name_from_request(io) return '' if note_name == 'favicon.ico' # Ignore request if it is for favicon.ico log "Received request for note: #{note_name}" # logs request into console # Sending back to the user some basic http header response io.puts(basic_http_response_header) # Processing and generating the actual user response user_response = html_head_code user_response += simple_top_menu if is_note_name_valid?(note_name) # Includes a simple top menu if not in the listing page user_response += page_content(note_name) # Includes the note content or list of notes user_response += css_code # Inject some css user_response += html_tail_code # HTML tail code user_response = optimize_html_code(user_response) # Optimizing the final html code # Sending page back to the user io.puts(user_response) log "Done processing request" end def page_content(note_name) page_body = '<body>' # Checking if user is accessing a page. If so, read the file and print it to the output # If no page was requested (or the page requested was not found), # create a menu with links to all the notes if is_note_name_valid?(note_name) log "Returning content from note: #{note_name}" page_body += load_note(note_name) else log 'Returning menu...' page_body += create_menu end page_body += '</body>' return page_body end # Strip out blank lines and useless tags def optimize_html_code(html_code) html_code = html_code.strip.gsub(/\n/,'') # Strip out blank lines html_code.gsub!(/(<br \/>){3,}/, '<br /><br />') # Avoid repetitive break lines html_code.gsub!(/<\/h1>(<br \/>){2,}/, '</h1><br />') # Avoid repetitive break lines again return html_code end # Load (and parse to html) a note - this code is very messy, should be refactored def load_note(note_name) lines = IO.readlines(@@BASE_DIR + '/' + note_name + '.note') lines = delete_non_relevant_lines(lines) user_response = '' # Reading note lines lines.each { |line| # Translating the links (get the title of the page and then recover the name of the file to create the link) start_link_index = line.index('<link:internal>') final_link_index = line.index('</link:internal>') while(start_link_index != nil and final_link_index != nil) # While there is still links to convert start_link_index = line.index('<link:internal>') + 15 title = line[start_link_index, final_link_index-start_link_index] # Parsing the title of the link page = get_page_with_title(title) if page != 'Not_Found' page = page[@@BASE_DIR.length, 36] line.sub!('<link:internal>', '<a href=' + page + '>') line.sub!('</link:internal>', '</a>') else # There is a link, but it's not valid! So we ignore it. line.sub!('<link:internal>', '') line.sub!('</link:internal>', '') end final_link_index = line.index('</link:internal>') # Checking if there is still more links in this line end user_response += convert_tomboy_to_html(line + '<br />') } return user_response end # Creates the default menu listing all the notes def create_menu menu = '<h1>Listing all notes</h1>' tomboy_notes = list_all_tomboy_notes tomboy_notes.each { | note | # Get the name of the note lines = IO.read(note) title_index = lines.index('<title>') + 7 title_end_index = lines.index('</title>') note = note[@@BASE_DIR.length, 36] menu += "<a href=#{note}>" menu += convert_tomboy_to_html(lines[title_index, title_end_index-title_index]) + '</a><br />' } return menu end # Ignore non-relevant lines (is there a better way to do this?) def delete_non_relevant_lines(lines) lines[0] = '' lines[3] = '' lines[-1] = '' lines[-2] = '' lines[-3] = '' lines[-4] = '' lines[-5] = '' lines[-6] = '' lines[-7] = '' lines[-8] = '' lines[-9] = '' lines[-10] = '' lines[-11] = '' return lines end # Converting tomboy xml code to html # I know, this code is very very ugly... but it works :) fell free to refactor it. def convert_tomboy_to_html(tomboy_code) tomboy_code.gsub!('<title>', '<h1>') tomboy_code.gsub!('</title>', '</h1>') tomboy_code.gsub!('<bold>', '<b>') tomboy_code.gsub!('</bold>', '</b>') tomboy_code.gsub!('<italic>', '<i>') tomboy_code.gsub!('</italic>', '</i>') tomboy_code.gsub!('<size:small>', '<font size=-1>') tomboy_code.gsub!('<size:large>', '<font size=+2>') tomboy_code.gsub!('<size:huge>', '<font size=+4>') tomboy_code.gsub!(/<\/size:[^>]+>/, '</font>') # Erasing all others useless xml tags tomboy_code.gsub!(/<?xml version=[^>]+>/, '') tomboy_code.gsub!(/<note version=[^>]+>/, '') tomboy_code.gsub!(/<text xml:space=\"preserve\"><note-content version=[^>]+>/, '') tomboy_code.gsub!('<title>', '<h1>') tomboy_code.gsub!('</title>', '</h1>') tomboy_code.gsub!('</note-content></text>', '') tomboy_code.gsub!('<link:internal>', '') # it should be replaced already, just in case tomboy_code.gsub!('</link:internal>', '') # it should be replaced already, just in case return tomboy_code.to_s end # Return the name of all tomboy notes files def list_all_tomboy_notes return Dir.glob(@@BASE_DIR + '*.note') end # Checks if the name of a note is valid (constains 36 standard chars and exists) def is_note_name_valid?(note_name) return false if note_name.size != 36 note_name.each_byte { |c| return false if not 'qwertyuiopasdfghjklzxcvbnm-1234567890'.include?(c.chr) } # Checking if file exists return File.exist?(@@BASE_DIR + note_name + '.note') end # Given a title, returns the respective note file name def get_page_with_title(title) tomboy_notes = list_all_tomboy_notes tomboy_notes.each { | note | # Get the name of the note lines = IO.read(note) title_index = lines.index('<title>') + 7 title_end_index = lines.index('</title>') current_title = lines[title_index, title_end_index-title_index] if current_title == title return note end } return 'Not_Found' end def html_head_code '<html><title>Simple Tomboy Server - ' + ENV['USER'] + '</title></head>' end def basic_http_response_header "HTTP/1.1 200/OK\r\nContent-type:text/html ; charset=UTF-8\r\n\r\n" end # Just some final html code closing tags, etc. def html_tail_code '<br /><hr>Powered by <a href="https://github.com/mfdavid/Simple-Tomboy-Server">Simple Tomboy Server</a></body></html>' end # Some CSS code that will be injected in the page to try and make it look less terrible def css_code '<style>body { background-color: #F0F0F0; margin:5% 15%; padding:0px; } a { text-decoration: none; color: #0000FF } a:hover { color: #0066CC; }</style>' end # Just a very simple top menu def simple_top_menu '<a href = "javascript:history.back()"><< Back to previous page</a> | <a href=.>Main menu</a>' end # For now, just logging the messages on console def log(message) puts Time.now.to_s + ' ' + message.to_s end end # Starts the server :-) server = TomBoyServer.new(10002, nil) server.start puts "Server started." server.join
class ChangeNumberToBeFloatInCalories < ActiveRecord::Migration[5.2] def change change_column :calories, :number, :float end end
# frozen_string_literal: true class AddCounterToFullSimulation < ActiveRecord::Migration[5.2] def change add_column :full_simulations, :counter, :integer, default: 0, null: false end end
class AddSlugToEvent < ActiveRecord::Migration def change add_column :events, :day_slug, :string end end
require 'rails_helper' RSpec.describe 'admin - new card account page' do include_context 'logged in as admin' let(:account) { create_account(:onboarded) } let(:person) { account.owner } let!(:product) { create(:card_product) } before { visit new_admin_person_card_account_path(person) } example 'creating an open card account' do expect(page).to have_field :card_card_product_id expect(page).to have_field :card_opened_on_1i expect(page).to have_field :card_opened_on_2i expect(page).to have_field :card_closed expect do click_button 'Save' end.to change { person.cards.count }.by(1) card_account = person.cards.last expect(card_account).to be_opened expect(current_path).to eq admin_person_path(person) end example 'creating a closed card account' do check :card_closed expect do click_button 'Save' end.to change { person.cards.count }.by(1) expect(person.cards.last).to be_closed expect(current_path).to eq admin_person_path(person) end example 'invalid card creation', :js do check :card_closed # closed before opened: select (Date.today.year - 1).to_s, from: :card_closed_on_1i expect do click_button 'Save' end.not_to change { person.cards.count } # still shows form, including with the 'closed' inputs visible: expect(page).to have_field :card_card_product_id expect(page).to have_field :card_opened_on_1i expect(page).to have_field :card_opened_on_2i expect(page).to have_field :card_closed, checked: true expect(page).to have_field :card_closed_on_1i expect(page).to have_field :card_closed_on_2i end end
# frozen_string_literal: true class Email < ApplicationRecord belongs_to :person validates :person_id, presence: true validates :addr, presence: true end
require 'rails_helper' RSpec.describe ApplicationHelper, :type => :helper do subject do Location.new({ location_name: "Boston, MA" }) end it "should have a name attribute" do expect(subject.location_name).to include("Boston, MA") end describe location do it { should have_many(:units)} end end
# frozen_string_literal: true # rubocop:disable Metrics/CyclomaticComplexity # rubocop:disable Metrics/PerceivedComplexity # rubocop:disable Metrics/ModuleLength module Enumerable def my_each arr = to_a return arr.to_enum unless block_given? n = 0 while arr.length > n yield(arr[n]) n += 1 end end def my_each_with_index arr = to_a return arr.to_enum unless block_given? n = 0 while arr.length > n yield(arr[n], n) n += 1 end end def my_select return to_enum unless block_given? res = [] my_each do |v| res << v if yield(v) == true end res end def my_all?(*args) check = true if block_given? if args.empty? my_each { |i| check = false unless yield(i) } elsif args[0].is_a?(Class) my_each { |i| check = false unless yield(i).class == args[0] } elsif args[0].is_a?(Regexp) my_each { |i| check = false unless (args[0]).match(yield(i)) } else my_each { |i| check = false unless yield(i) == args[0] } end return check elsif args.empty? my_all? { |obj| obj } else my_all?(args[0]) { |obj| obj } end end def my_any?(*args) check = false if block_given? if args.empty? my_each { |i| check = true if yield(i) } elsif args[0].is_a?(Class) my_each { |i| check = true if yield(i).class == args[0] } elsif args[0].is_a?(Regexp) my_each { |i| check = true if yield(i).match(args[0]) } else my_each { |i| check = true if yield(i) == args[0] } end return check elsif args.empty? my_any? { |obj| obj } else my_any?(args[0]) { |obj| obj } end end def my_none?(*args) check = true if block_given? if args.empty? my_each { |i| check = false if yield(i) } elsif args[0].is_a?(Class) my_each { |i| check = false if yield(i).class == args[0] } elsif args[0].is_a?(Regexp) my_each { |i| check = false if yield(i).match(args[0]) } else my_each { |i| check = false if yield(i) == args[0] } end return check elsif args.empty? my_none? { |obj| obj } else my_none?(args[0]) { |obj| obj } end end def my_count(*args) count = 0 if block_given? if args.empty? my_each { |i| count += 1 if yield(i) } else my_each { |i| count += 1 if yield(i) == args[0] } end return count elsif args.empty? my_count { |i| i } else my_count { |i| args[0] == i } end end def my_map(&proc) arr = to_a return arr.to_enum unless block_given? result = [] my_each { |i| result << proc.call(i) } result end def my_inject(*args) arr = to_a acc = args[0].is_a?(Integer) ? args[0] : first if block_given? if args.empty? my_each_with_index { |val, i| acc = yield(acc, val) if i.positive? } else my_each_with_index { |val, _| acc = yield(acc, val) } end elsif args[0].is_a?(Integer) && args[1].is_a?(Symbol) acc = args[0] my_each_with_index { |_, i| acc = args[1].to_proc.call(acc, arr[i]) } elsif args[0].is_a?(Symbol) my_each_with_index { |_, i| acc = args[0].to_proc.call(acc, arr[i]) if i.positive? } end acc end end # rubocop:enable Metrics/CyclomaticComplexity # rubocop:enable Metrics/PerceivedComplexity # rubocop:enable Metrics/ModuleLength def multiply_els(arr) arr.my_inject { |i, j| i * j } end
require 'rubug/gdb/stackframe' require 'test/unit' class TestStackframe < Test::Unit::TestCase def test_constructor_valid assert_nothing_raised { Rubug::Gdb::Stackframe.new( :addr => true, :args => true, :file => true, :from => true, :fullname => true, :func => true, :level => true, :line => true) } end def test_constructor_invalid assert_raise(ArgumentError) { Rubug::Gdb::Stackframe.new(:invalid => true) } end end
# frozen_string_literal: true FactoryBot.define do factory :store do name { FFaker::Company.name } owner_name { FFaker::NameBR.name } end end
class ApplicationController < ActionController::API include Knock::Authenticable protected # Method for checking if current_user is admin or not. def authorize_as_admin return_unauthorized unless !current_user.nil? && current_user.is_admin? end end
#!/usr/bin/env ruby require 'test/unit' # Test of Columnize module class TestColumnize < Test::Unit::TestCase # Ruby 1.8 form of require_relative TOP_SRC_DIR = File.join(File.expand_path(File.dirname(__FILE__)), '..', 'lib') require File.join(TOP_SRC_DIR, 'columnize.rb') # test columnize def test_basic assert_equal("1, 2, 3", Columnize::columnize([1, 2, 3], 10, ', ')) assert_equal("", Columnize::columnize(5)) assert_equal("1 3\n2 4", Columnize::columnize(['1', '2', '3', '4'], 4)) assert_equal("1 2\n3 4", Columnize::columnize(['1', '2', '3', '4'], 4, ' ', false)) assert_equal("<empty>\n", Columnize::columnize([])) assert_equal("oneitem", Columnize::columnize(["oneitem"])) data = (0..54).map{|i| i.to_s} assert_equal( "0, 6, 12, 18, 24, 30, 36, 42, 48, 54\n" + "1, 7, 13, 19, 25, 31, 37, 43, 49\n" + "2, 8, 14, 20, 26, 32, 38, 44, 50\n" + "3, 9, 15, 21, 27, 33, 39, 45, 51\n" + "4, 10, 16, 22, 28, 34, 40, 46, 52\n" + "5, 11, 17, 23, 29, 35, 41, 47, 53", Columnize::columnize(data, 39, ', ', true, false)) assert_equal( " 0, 1, 2, 3, 4, 5, 6, 7, 8, 9\n" + "10, 11, 12, 13, 14, 15, 16, 17, 18, 19\n" + "20, 21, 22, 23, 24, 25, 26, 27, 28, 29\n" + "30, 31, 32, 33, 34, 35, 36, 37, 38, 39\n" + "40, 41, 42, 43, 44, 45, 46, 47, 48, 49\n" + "50, 51, 52, 53, 54", Columnize::columnize(data, 39, ', ', false, false)) assert_equal( " 0, 1, 2, 3, 4, 5, 6, 7, 8\n" + " 9, 10, 11, 12, 13, 14, 15, 16, 17\n" + " 18, 19, 20, 21, 22, 23, 24, 25, 26\n" + " 27, 28, 29, 30, 31, 32, 33, 34, 35\n" + " 36, 37, 38, 39, 40, 41, 42, 43, 44\n" + " 45, 46, 47, 48, 49, 50, 51, 52, 53\n" + " 54", Columnize::columnize(data, 39, ', ', false, false, ' ')) data = ["one", "two", "three", "for", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eightteen", "nineteen", "twenty", "twentyone", "twentytwo", "twentythree", "twentyfour", "twentyfive","twentysix", "twentyseven"] assert_equal( "one two three for five six \n" + "seven eight nine ten eleven twelve \n" + "thirteen fourteen fifteen sixteen seventeen eightteen \n" + "nineteen twenty twentyone twentytwo twentythree twentyfour\n" + "twentyfive twentysix twentyseven", Columnize::columnize(data, 80, ' ', false)) assert_equal( "one five nine thirteen seventeen twentyone twentyfive \n" + "two six ten fourteen eightteen twentytwo twentysix \n" + "three seven eleven fifteen nineteen twentythree twentyseven\n" + "for eight twelve sixteen twenty twentyfour ", Columnize::columnize(data, 80)) end end
class CreateUserTrees < ActiveRecord::Migration[5.2] def change create_table :user_trees do |t| t.integer :cost t.integer :age t.integer :user_id t.integer :tree_id end end end
class ChangeColumnType < ActiveRecord::Migration[5.1] def change change_column :tasks, :start_date, :string end end
# coding : UTF-8 require 'ruby2d' set width: 640, height: 400, title: "Snake", diagnostics: true, fps_cap: 20 , background: 'navy' GRID_SIZE = 20 GRID_WIDTH = Window.width / GRID_SIZE GRID_HEIGHT = Window.height / GRID_SIZE class Snake attr_writer :direction def initialize @positions = [[0,Window.height/40], [1,Window.height/40], [2, Window.height/40], [3, Window.height/40]] @direction = 'right' @growing = false end def draw @positions.each do |i| Square.new(x: i[0] * GRID_SIZE, y: i[1] * GRID_SIZE, size:GRID_SIZE - 1, color: 'yellow' ) end end def move #groving snake unless @growing @positions.shift end #moving snake case @direction when 'down' @positions.push(new_coords(head[0], head[1] +1 )) when 'up' @positions.push(new_coords(head[0], head[1] -1 )) when 'left' @positions.push(new_coords(head[0] -1, head[1] )) when 'right' @positions.push(new_coords(head[0] +1, head[1] )) end @growing = false end def new_coords(x,y) [x % GRID_WIDTH,y % GRID_HEIGHT] end def can_change_direction_to?(new_direction) case @direction when 'up' then new_direction != 'down' when 'down' then new_direction != 'up' when 'left' then new_direction != 'right' when 'right' then new_direction != 'left' end end def grow @growing = true end # x coordinate of snake's head def x head[0] end # y coordinate of snake's head def y head[1] end # head coordinates of snake def head @positions.last end def hit_itself? @positions.size != @positions.uniq.size end end class Game def initialize @points = 0 @finished = false @food_X = rand(GRID_WIDTH) @food_Y = rand(GRID_HEIGHT) end def draw unless @finished Square.new(x: @food_X * GRID_SIZE, y: @food_Y * GRID_SIZE, size: GRID_SIZE, color: 'red') end Text.new(game_text, x: 10, y: 10) end def snake_eat_food?(x,y) @food_X == x && @food_Y == y end def record_hit @points += 1 @food_X = rand(GRID_WIDTH) @food_Y = rand(GRID_HEIGHT) end def game_text() if is_finish? @game_text = "Game over. Your score is : #{@points} Press 'R' to restart, 'Q' to quit" else @game_text = "Score : #{@points}" end end def is_finish? @finished end def finish @finished = true end end snake = Snake.new game = Game.new update do clear unless game.is_finish? snake.move end snake.draw game.draw if game.snake_eat_food?(snake.x, snake.y) game.record_hit snake.grow end if snake.hit_itself? game.finish end end on :key_down do |event| if ['down', 'up', 'left', 'right'].include?(event.key) if snake.can_change_direction_to?(event.key) snake.direction = event.key end end if game.is_finish? if event.key.downcase == 'r' snake = Snake.new game = Game.new elsif event.key.downcase == 'q' exit end end end show
class Log < ApplicationRecord belongs_to :member validates :total_time, presence: true validates :status, presence: true attribute :total_time, :integer, default: -> { 0 } enum status: Member.statuses end
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- # stub: sequel_migration_builder 0.4.3 ruby lib Gem::Specification.new do |s| s.name = "sequel_migration_builder" s.version = "0.4.3" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.require_paths = ["lib"] s.authors = ["Roland Swingler"] s.date = "2014-09-08" s.description = "Build Sequel Migrations based on the differences between two schemas" s.email = "roland.swingler@gmail.com" s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] s.files = [ ".document", ".rspec", "CHANGELOG", "LICENSE", "README.rdoc", "Rakefile", "VERSION", "lib/sequel/migration_builder.rb", "lib/sequel/schema/alter_table_operations.rb", "lib/sequel/schema/db_column.rb", "lib/sequel/schema/db_index.rb", "lib/sequel/schema/db_schema_parser.rb", "sequel_migration_builder.gemspec", "spec/alter_table_operations_spec.rb", "spec/db_column_spec.rb", "spec/db_index_spec.rb", "spec/db_schema_parser_spec.rb", "spec/migration_builder_spec.rb", "spec/spec_helper.rb" ] s.homepage = "http://github.com/knaveofdiamonds/sequel_migration_builder" s.rubygems_version = "2.2.1" s.summary = "Build Sequel Migrations based on the differences between two schemas" if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<sequel>, [">= 3.20.0"]) s.add_development_dependency(%q<rspec>, [">= 1.2.9"]) else s.add_dependency(%q<sequel>, [">= 3.20.0"]) s.add_dependency(%q<rspec>, [">= 1.2.9"]) end else s.add_dependency(%q<sequel>, [">= 3.20.0"]) s.add_dependency(%q<rspec>, [">= 1.2.9"]) end end
class ApplicationController < ActionController::API def secret_key # THIS IS A PLACEHOLDER, I NEED TO MOVE THIS INTO # ENVIROMENT VARIABLES BEFORE PRODUCTION "secret" end def encode(payload) JWT.encode(payload, secret_key, "HS256") end def decode(token) JWT.decode(token, secret_key, true, {algorithm: "HS256"})[0] end def tournament_points(tournament_id) current_winner = { name: "", points: 0 } tournament_users = User.all.map do |user| user_points = 0; user.tasks.each do |task| if task.tournament_id == tournament_id user_points += task.points end end if user_points > current_winner[:points] current_winner = { name: user.username, points: user_points } end end return current_winner end end
Rails.application.routes.draw do # get 'welcome/index' get "/" => "welcome#index" get "/about" => "welcome#about" end
module Rails module Generators module Migration module ClassMethods # The changes here differ from the original rails source code only in # swapping the order of the search pattern from <timestamp>_<filename> # to <filename>_<timestamp>. No need to annotate them since the methods # are only 1 line each. def migration_exists?(dirname, file_name) #:nodoc: migration_lookup_at(dirname).grep(/#{file_name}_\d+.rb$/).first end def migration_lookup_at(dirname) #:nodoc: Dir.glob("#{dirname}/*_[0-9]*.rb") end end end end end