text
stringlengths
10
2.61M
module Ricer::Plugins::Convert class Gunzip < Ricer::Plugin trigger_is :gunzip has_usage '<..text..>' def execute(text) begin text.force_encoding('binary') z = Zlib::Inflate.new reply = zstream.inflate(text) ensure z.finish z.close end end end end
class MessagesController < ApplicationController before_filter :require_user def new @message = Message.new end def create @message = Message.new(message_params) @message.account = @current_user.account addressee_account = find_existing_account(params[:message][:addressees_attributes][0][:url]) unless addressee_account addressee_account = Factories::AccountFactory.from_activitystreams2_url(params[:message][:addressees_attributes][0][:url]) end @message.addressees.build(account: addressee_account, target_type: params[:message][:addressees_attributes][0][:target_type]) if @message.save flash[:notice] = "Message sent!" redirect_to home_path else render action: :new end end def message_params params.require(:message).permit( :content ) end def find_existing_account(url) account_url = URI(url) base_url = URI(request.base_url) if account_url.host == base_url.host && account_url.port == base_url.port route = Rails.application.routes.recognize_path(account_url.path) if route[:controller] == 'accounts' && route[:action] == 'show' return Account.find_by(username: route[:id]) || Account.find(route[:id]) end end Account.find_by activitystreams2_url: url end end
#!/usr/bin/env ruby # Copyright (c) 2013 Holger Amann <holger@sauspiel.de> # # MIT License # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. require 'optparse' require 'rbarman' include RBarman def nagios_return_value(value, w, c) ret_val = 0 if value >= c.to_i ret_val = 2 elsif value >= w.to_i ret_val = 1 else ret_val = 0 end ret_val end def latest_backup_id(server) Backups.all(server).latest.id end def check_ssh(server) return_code = 0 ssh_ok = Server.by_name(server).ssh_check_ok if ssh_ok puts "SSH connection ok" else puts "SSH connection failed!" return_code = 2 end return_code end def check_pg(server) return_code = 0 pg_ok = Server.by_name(server).pg_conn_ok if pg_ok puts "PG connection ok" else puts "PG connection failed!" return_code = 2 end return_code end def check_backups_available(server, warning, critical) return_code = 0 count = Backups.all(server).count if count == 0 p "No backups available!" return_code = 2 else p "#{count} backups available" return_code = nagios_return_value(count, warning, critical) end return_code end def check_last_wal_received(server, warning, critical) latest = Backup.by_id(server, latest_backup_id(server), { :with_wal_files => true }) if latest.nil? p "No backups available" return 0 end if latest.status == :started p 'New backup started' return 0 else last = latest.wal_files.last diff = (Time.now - last.created).to_i p "Last wal was received #{diff} seconds ago (#{last})" nagios_return_value(diff, warning, critical) end end def check_failed_backups(server, warning, critical) backups = Backups.all(server) count = 0 backups.each do |backup| count = count + 1 if backup.status == :failed end p "#{count} backup(s) failed" nagios_return_value(count, warning, critical) end def check_missing_wals(server, limit = nil) latest = Backup.by_id(server, latest_backup_id(server), { :with_wal_files => true }) if latest.nil? p "No backups available!" return 0 end if latest.status == :started p 'New backup started' return 0 end if limit && latest.wal_files.count > limit wal_files = latest.wal_files.reverse[0..limit].reverse latest.wal_files = wal_files latest.begin_wal = wal_files.first end missing = latest.missing_wal_files if missing.count == 0 puts "There are no missing wal files in the latest backup" return 0 else lines = Array.new missing.each { |m| lines << m.to_s } puts "There are #{missing.count} missing wal files in the latest backup:\n #{ lines.join("\n") }" return 2 end end def validate_params(params) params.each do |k,v| if v.nil? raise OptionParser::MissingArgument.new("\'#{k.upcase}\' must be defined!") end end end options = {} optparse = OptionParser.new do |opts| opts.banner = "Usage check-barman.rb [options]" options[:action] = nil opts.on('-a', '--action ACTION', [ :ssh, :pg, :backups_available, :last_wal_received, :failed_backups, :missing_wals ] ,'The name of the check to be executed') do |action| options[:action] = action end options[:missing_wals_check_limit] = nil opts.on('-m', '--missing-wals-check-limit NUMBER', Integer, 'Check only the last n wal files (reduces execution time)') do |limit| options[:missing_wals_check_limit] = limit end options[:server] = nil opts.on('-s', '--server SERVER ', String, 'The \'server\' in barman terms') do |server| options[:server] = server end options[:warning] = nil opts.on('-w', '--warning WARNING', 'The warning level') do |warn| options[:warning] = warn end options[:critical] = nil opts.on('-c', '--critical CRITICAL', 'The critical level') do |critical| options[:critical] = critical end options[:barman_home] = "/var/lib/barman" opts.on('-h', '--barman-home PATH', String, "path to barman's Home directory, default /var/lib/barman") do |h| options[:barman_home] = h end options[:barman_binary] = "/usr/bin/barman" opts.on('-b', '--barman-binary PATH', String, "path to barman binary, default /usr/bin/barman") do |b| options[:barman_binary] = b end options[:version] opts.on('-v', '--version', "Show version information") do puts "check-barman v0.2.1" puts "rbarman v#{::RBarman::VERSION}" exit end end if ARGV.count == 0 puts optparse exit 1 end begin optparse.parse! rescue OptionParser::InvalidArgument puts $!.to_s puts optparse exit 1 end server = options[:server] warning = options[:warning] critical = options[:critical] action = options[:action] return_code = 1 Configuration.instance.binary = options[:barman_binary] Configuration.instance.barman_home = options[:barman_home] begin return_code = case action when :ssh validate_params({:server => server}) check_ssh(server) when :pg validate_params({:server => server}) check_pg(server) when :backups_available validate_params({:server => server, :warning => warning, :critical => critical}) check_backups_available(server, warning, critical) when :last_wal_received validate_params({:server => server, :warning => warning, :critical => critical}) check_last_wal_received(server, warning, critical) when :failed_backups validate_params({:server => server, :warning => warning, :critical => critical}) check_failed_backups(server, warning, critical) when :missing_wals validate_params({:server => server}) check_missing_wals(server, options[:missing_wals_check_limit]) end rescue OptionParser::MissingArgument puts $!.to_s puts optparse exit 1 end exit return_code
namespace :check do desc "Send a primary email for socail login users to reset their passwors based on new signup feature" task send_signup_notifications: :environment do subject = '“Important - your email login in Check”' User.where.not(email: '').find_each do |u| unless u.encrypted_password? print '.' SecurityMailer.delay.custom_notification(u, subject) end end end end
class Conf attr_reader :name, :tickets, :flights attr_accessor :popularity def initialize(name, tickets, flights) @name = name.downcase @tickets = tickets @flights = flights @popularity = 0 end def tickets? tickets > 0 end def flights? flights > 0 end def attend(app) raise("#{app} is trying to attend #{name}, but there are no tickets left.") unless tickets? @tickets -= 1 if flights? app.flight = true @flights -= 1 end end def to_row [popularity, name, tickets, flights] end def <=> (other) name <=> other.name end end
class AdminController < ApplicationController before_action :authorized? def index # Static links end private def authorized? redirect_to root_path unless admin? end end
class FixColumnName < ActiveRecord::Migration def change rename_column :comments, :blog_id, :post_id end end
class Tag < ApplicationRecord validates :name, presence: true, length: { maximum: 100 } has_many :tag_post, dependent: :destroy has_many :post, through: :tag_post end
# == Schema Information # # Table name: subreleases # # id :integer not null, primary key # release_id :integer indexed, indexed => [subrelease_id] # subrelease_id :integer indexed => [release_id], indexed # created_at :datetime not null # updated_at :datetime not null # # Indexes # # index_subreleases_on_release_id (release_id) # index_subreleases_on_release_id_and_subrelease_id (release_id,subrelease_id) UNIQUE # index_subreleases_on_subrelease_id (subrelease_id) # class Subrelease < ActiveRecord::Base belongs_to :release belongs_to :subrelease, class_name: 'Release' end
Vagrant.configure("2") do |config| config.vm.box = "centos/7" config.vbguest.auto_update = false config.vm.box_check_update = false config.vm.synced_folder ".", "/vagrant", disabled: true # Gitea gitea config.vm.define "gitea" do |gitea| gitea.vm.network "private_network", ip: "192.168.4.11" gitea.vm.hostname = "gitea.tp4.b2" gitea.vm.provider "virtualbox" do |v| v.memory = 512 v.name = "gitea.tp4.b2" gitea.vm.provision "shell", path: "scripts/install-gitea.sh" end end # MariaDB db config.vm.define "db" do |db| db.vm.network "private_network", ip: "192.168.4.12" db.vm.hostname = "db.tp4.b2" db.vm.provider "virtualbox" do |v| v.memory = 512 v.name = "db.tp4.b2" end end # NGINX nginx config.vm.define "nginx" do |nginx| nginx.vm.network "private_network", ip: "192.168.4.13" nginx.vm.hostname = "nginx.tp4.b2" nginx.vm.provider "virtualbox" do |v| v.memory = 512 v.name = "nginx.tp4.b2" nginx.vm.provision "file", source: "conf/nginx.conf", destination: "/tmp/nginx.conf" nginx.vm.provision "shell", inline: "cp /tmp/nginx.conf /etc/nginx/nginx.conf" end end # NFS nfs config.vm.define "nfs" do |nfs| nfs.vm.network "private_network", ip: "192.168.4.14" nfs.vm.hostname = "nfs.tp4.b2" nfs.vm.provider "virtualbox" do |v| v.memory = 512 v.name = "nfs.tp4.b2" end end # Backup #gitea.vm.provision "file", # source: "scripts/backup.sh", # destination: "/tmp/backup.sh" end
class RemoveStartAtFromOrderItems < ActiveRecord::Migration def change remove_column :order_items, :start_at end end
class PortfolioCoinsController < BaseController attr_reader :portfolio_coin before_action :authenticated? before_action :set_portfolio_coin, only: [:update, :destroy] def index refresh_market_coins(portfolio_coins) render json: portfolio_coins, each_serializer: PortfolioCoinSerializer end def create if already_present?(portfolio_coin_params[:market_coin_id]) throw_error "Market coin already inserted" return end unless portfolio_coin = create_portfolio_coin throw_error "#{user_market_coin.errors.full_messages.join(', ')}" return end render json: portfolio_coin end def update unless portfolio_coin.update(portfolio_coin_params) throw_error "#{user_portfolio.errors.full_messages.join(', ')}" return end render json: portfolio_coin end def destroy unless portfolio_coin.destroy throw_error "#{user_portfolio.errors.full_messages.join(', ')}" return end render json: {} end private def refresh_market_coins(portfolio_coins) MarketCoinHandler.new(coin_ids: portfolio_coins.pluck(:market_coin_id)).refresh_and_fetch end def create_portfolio_coin PortfolioCoin.create(portfolio_coin_params.merge(user_portfolio: user_portfolio)) end def already_present?(market_coin) user_portfolio.portfolio_coins.where(market_coin: market_coin).count > 0 end def portfolio_coins @portfolio_coins ||= user_portfolio.portfolio_coins.order(created_at: :asc) end def set_portfolio_coin @portfolio_coin ||= user_portfolio.portfolio_coins.where(id: params[:id]).first end def user_portfolio user_portfolio_handler.find end def portfolio_coin_params params[:portfolio_coin].permit! end def user_portfolio_handler @user_portfolio_handler ||= UserPortfolioHandler.new(user: current_user) end end
class ChangeShowsTable < ActiveRecord::Migration def change remove_column :shows, :latest_episode remove_column :shows, :next_episode add_column :shows, :last_title, :string add_column :shows, :last_airdate, :date add_column :shows, :last_episode, :string add_column :shows, :next_title, :string add_column :shows, :next_airdate, :date add_column :shows, :next_episode, :string add_column :shows, :airtime, :string end end
require "rails_helper" RSpec.describe Category, type: :model do context "associations" do it {is_expected.to have_many(:news_leases)} it {is_expected.to have_many(:news_need_rents)} end end
require 'rails_helper' describe Slugable do let(:dummy_metaclass) { Class.new { include Slugable } } let(:instance) { dummy_metaclass.new } it "returns correctly slugified text" do text = "This is a rails 5 text" expect(instance.slugify(text)).to eq "this-is-a-rails-5-text" end it "returns correctly slugified text with multiple whitespace" do text = "Title WIth whitespace" expect(instance.slugify(text)).to eq "title-with-whitespace" end it "correctly transliterates diacritics" do text = "Ivan Lučev" expect(instance.slugify(text)).to eq "ivan-lucev" end it "returns correctly slugified text with outer whitespace " do text = " Someone copy pasted weirdly " expect(instance.slugify(text)).to eq "someone-copy-pasted-weirdly" end end
# Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. require File.expand_path('../config/application', __FILE__) require 'rake' require 'rsolr' Lovelyromcoms::Application.load_tasks desc "start mongo and solr" task :start_mongo do if RUBY_PLATFORM.include? "darwin" exec "vendor/extras/mongodb/mongodb-osx-x86_64-2.0.2/bin/mongod &" elsif RUBY_PLATFORM.include? "linux" exec "vendor/extras/mongodb/mongodb-linux-x86_64-2.0.2/bin/mongod &" end end task :start_solr do exec "cd vendor/extras/apache-solr-3.5.0/example/;java -jar start.jar &" end task :reset_solr_index do solr = RSolr.connect :url => 'http://localhost:8983/solr/collection1/' solr.delete_by_query('*:*') solr.update :data => '<commit/>' end
# encoding: utf-8 # copyright: 2016, @username-is-already-taken2 # copyright: 2016, @cdbeard2016 # license: All rights reserved title 'Example Controls to test windows_task resource' describe windows_task('\Microsoft\Windows\AppID\PolicyConverter') do its('logon_mode') { should eq 'Interactive/Background' } its('last_result') { should eq '1' } its('task_to_run') { should cmp '%Windir%\system32\appidpolicyconverter.exe' } its('run_as_user') { should eq 'LOCAL SERVICE' } end describe windows_task('\Microsoft\Windows\Time Synchronization\SynchronizeTime') do it { should be_enabled } end describe windows_task('\Microsoft\Windows\AppID\PolicyConverter') do it { should be_disabled } end describe windows_task('\Microsoft\Windows\Defrag\ScheduledDefrag') do it { should exist } end describe windows_task('\I\made\this\up') do it { should_not exist } end
# require_relative "../../spec/spec_helper" # # RSpec.describe 'Check Yahoo Page' do # # before(:example) do # browser_setup(browser_version) # end # # after(:example) do |example| # capture_screenshot_on_failure(example) # end # # it "Check Yahoo text - True" do |example| # log_start_test("#{example.description}") # open_url("http://www.yahoo.com") # expect(is_text_present('404 - File or directory not found')).to eq(true) # log_complete_test("#{example.description}") # end # # it "Check Yahoo text - False" do |example| # log_start_test("#{example.description}") # open_url("http://www.yahoo.com") # expect(is_text_present('Yahoo')).to eq(true) # log_complete_test("#{example.description}") # end # end
# frozen_string_literal: true # inventory class Inventory < ApplicationRecord belongs_to :ingredient belongs_to :ingredient_type scope :from_year, ->(date) { where(datetime: date.beginning_of_year..date.end_of_year).order(price: :desc) } scope :from_last_three_months, ->(date) { where(datetime: 2.months.ago.beginning_of_month..date.end_of_month).order(price: :desc) } scope :by_type, lambda { |type_id| if type_id.present? where(ingredient_type_id: type_id) else all end } scope :by_id, lambda { |_id| if _id.present? where(ingredient_id: _id) else all end } before_create :set_default_date, :adjust_total enum adjust_symbol: { add: 'add', minus: 'minus', equal: 'equal' } def set_default_date self.datetime = DateTime.now if datetime.nil? end def adjust_total self.price_after_adjust = case adjust_symbol when 'add' (price * number) + adjust_price when 'minus' (price * number) - adjust_price else price * number end end end
class People < ApplicationRecord def self.all page = 0, per_page = 25 url = ENV['SALESLOFT_BASE_URL'] + '/v2/people.json' headers = { 'Authorization' => "Bearer #{ENV['SALESLOFT_API_KEY']}" } query_params = { 'per_page' => per_page, 'include_paging_counts' => true, 'page' => page } response = HTTParty.get(url, :headers => headers, :query => query_params) @people = response['data'] return @people end def self.findById id url = ENV['SALESLOFT_BASE_URL'] + '/v2/people.json' headers = { 'Authorization' => "Bearer #{ENV['SALESLOFT_API_KEY']}" } query_params = { 'include_paging_counts' => true, 'ids' => id } response = HTTParty.get(url, :headers => headers, :query => query_params) @person = response['data'] return @person end end
class InstitutionsController < ApplicationController before_action :authenticate_user! def index @submission = Submission.find_by_user_id(current_user.id) if @submission @institutions = Institution.where(:submission_id => @submission.id) else redirect_to dashboard_home_path, :notice => "Please complete scholarship application first." end end end
require 'spec_helper' # This spec was generated by rspec-rails when you ran the scaffold generator. # It demonstrates how one might use RSpec to specify the controller code that # was generated by Rails when you ran the scaffold generator. # # It assumes that the implementation code is generated by the rails scaffold # generator. If you are using any extension libraries to generate different # controller code, this generated spec may or may not pass. # # It only uses APIs available in rails and/or rspec-rails. There are a number # of tools you can use to make these specs even more expressive, but we're # sticking to rails and rspec-rails APIs to keep things simple and stable. # # Compared to earlier versions of this generator, there is very limited use of # stubs and message expectations in this spec. Stubs are only used when there # is no simpler way to get a handle on the object needed for the example. # Message expectations are only used when there is no simpler way to specify # that an instance is receiving a specific message. describe EventRequestsController do before :each do request.accept = 'application/json' end describe 'with event request' do before :each do @event_request = FactoryGirl.create :event_request end describe "GET index" do it "assigns all eventRequest as @eventRequest" do sign_in @event_request.event.customer get :index, {event_id: @event_request.event.id} assigns(:event_requests).should eq([@event_request]) end it 'photographer can not see list of requests' do sign_in @event_request.photographer expect {get :index, {event_id: @event_request.event.id}}.to raise_error(CanCan::AccessDenied) end end describe "GET show" do it "assigns the requested event_request as @event_request" do sign_in @event_request.photographer get :show, {event_id: @event_request.event.id, :id => @event_request.to_param} assigns(:event_request).should eq(@event_request) end end describe "DELETE destroy" do it "destroys the requested event_request" do sign_in @event_request.photographer expect { delete :destroy, {event_id: @event_request.event.id, :id => @event_request.to_param} }.to change(EventRequest, :count).by(-1) end end end describe "POST create" do describe "with valid params" do it "creates a new EventRequest" do sign_in FactoryGirl.create :photographer expect { post :create, {event_id: FactoryGirl.create(:event).id} }.to change(EventRequest, :count).by(1) end it "assigns a newly created event_request as @event_request" do user = FactoryGirl.create :photographer event = FactoryGirl.create :event sign_in user post :create, {event_id: event.id} assigns(:event_request).should be_a(EventRequest) assigns(:event_request).should be_persisted assigns(:event_request).event.should eq(event) assigns(:event_request).photographer.should eq(user) end end end end
require 'test_helper' class ControlpnyntsControllerTest < ActionDispatch::IntegrationTest setup do @controlpnynt = controlpnynts(:one) end test "should get index" do get controlpnynts_url assert_response :success end test "should get new" do get new_controlpnynt_url assert_response :success end test "should create controlpnynt" do assert_difference('Controlpnynt.count') do post controlpnynts_url, params: { controlpnynt: { limite: @controlpnynt.limite, n1: @controlpnynt.n1, n2: @controlpnynt.n2, siglas: @controlpnynt.siglas, vendida: @controlpnynt.vendida } } end assert_redirected_to controlpnynt_url(Controlpnynt.last) end test "should show controlpnynt" do get controlpnynt_url(@controlpnynt) assert_response :success end test "should get edit" do get edit_controlpnynt_url(@controlpnynt) assert_response :success end test "should update controlpnynt" do patch controlpnynt_url(@controlpnynt), params: { controlpnynt: { limite: @controlpnynt.limite, n1: @controlpnynt.n1, n2: @controlpnynt.n2, siglas: @controlpnynt.siglas, vendida: @controlpnynt.vendida } } assert_redirected_to controlpnynt_url(@controlpnynt) end test "should destroy controlpnynt" do assert_difference('Controlpnynt.count', -1) do delete controlpnynt_url(@controlpnynt) end assert_redirected_to controlpnynts_url end end
FactoryGirl.define do factory :course do name description subscribe_state :allowed end end
FactoryGirl.define do factory(:image) do description 'A picture' photo Rack::Test::UploadedFile.new("#{Rails.root}/spec/fixtures/images/wolv.jpg", "image/jpg") # photo_file_name {'spicoli.jpg'} # photo_content_type {'spicoli.jpg'} # photo_file_size {1024} end end
require "spec_helper" describe Paperclip::Storage::Ftp::Server do let(:server) { Paperclip::Storage::Ftp::Server.new } context "initialize" do it "accepts options to initialize attributes" do options = { :host => "ftp.example.com", :user => "user", :password => "password", :port => 2121 } server = Paperclip::Storage::Ftp::Server.new(options) server.host.should == options[:host] server.user.should == options[:user] server.password.should == options[:password] server.port.should == options[:port] end it "sets a default port" do server = Paperclip::Storage::Ftp::Server.new server.port.should == Net::FTP::FTP_PORT end end context "#file_exists?" do it "returns true if the file exists on the server" do server.connection = double("connection") server.connection.should_receive(:nlst).with("/files/original").and_return(["foo.jpg"]) server.file_exists?("/files/original/foo.jpg").should be_true end it "returns false if the file does not exist on the server" do server.connection = double("connection") server.connection.should_receive(:nlst).with("/files/original").and_return([]) server.file_exists?("/files/original/foo.jpg").should be_false end end context "#get_file" do it "returns the file object" do server.connection = double("connection") server.connection.should_receive(:getbinaryfile).with("/files/original.jpg", "/tmp/original.jpg") server.get_file("/files/original.jpg", "/tmp/original.jpg") end end context "#put_file" do it "stores the file on the server" do server.connection = double("connection") server.should_receive(:mkdir_p).with("/files") server.connection.should_receive(:putbinaryfile).with("/tmp/original.jpg", "/files/original.jpg") server.put_file("/tmp/original.jpg", "/files/original.jpg") end end context "#delete_file" do it "deletes the file on the server" do server.connection = double("connection") server.connection.should_receive(:delete).with("/files/original.jpg") server.delete_file("/files/original.jpg") end end context "#connection" do it "returns a memoized ftp connection to the given server" do server.host = "ftp.example.com" server.user = "user" server.password = "password" connection = double("connection") Net::FTP.should_receive(:new).once.and_return(connection) connection.should_receive(:connect).once.with(server.host, server.port) connection.should_receive(:login).once.with(server.user, server.password) 2.times { server.connection.should == connection } end end context "mkdir_p" do it "creates the directory and all its parent directories" do server.connection = double("connection") server.connection.should_receive(:mkdir).with("/").ordered server.connection.should_receive(:mkdir).with("/files").ordered server.connection.should_receive(:mkdir).with("/files/foo").ordered server.connection.should_receive(:mkdir).with("/files/foo/bar").ordered server.mkdir_p("/files/foo/bar") end it "does not stop on Net::FTPPermError" do server.connection = double("connection") server.connection.should_receive(:mkdir).with("/").and_raise(Net::FTPPermError) server.connection.should_receive(:mkdir).with("/files") server.mkdir_p("/files") end end end
FactoryBot.define do factory :pessoa do nome { FFaker::NameBR.first_name } sobrenome { FFaker::NameBR.last_name } documento { FFaker::IdentificationBR.cpf } email { FFaker::Internet.email } data_nascimento { FFaker::Time.date-FFaker::Random.rand(18..90).year } end end
require_relative("./db/sql_runner") require_relative("./star") require_relative("./casting") class Movie attr_reader :id attr_accessor :title, :genre, :rating def initialize(new_movie) @id = new_movie['id'].to_i if new_movie['id'] @title = new_movie['title'] @genre = new_movie['genre'] @rating = new_movie['rating'].to_i end def save() sql = "INSERT INTO movies (title, genre, rating) VALUES ($1, $2, $3) RETURNING id" values = [@title, @genre, @rating] movie = SqlRunner.run(sql, values).first @id = movie['id'].to_i end def self.all() sql = "SELECT * FROM movies" values = [] movies = SqlRunner.run(sql, values) result = movies.map { |movie| Movie.new(movie) } return result end def update() sql = "UPDATE movies SET (title, genre, rating) = ($1, $2, $3) WHERE id = $4" values = [@title, @genre, @rating, @id] SqlRunner.run(sql, values) end def self.delete_all() sql = "DELETE FROM movies" values = [] SqlRunner.run(sql, values) end def self.map_items(movies_data) result = movies_data.map { |movie| Movie.new(movie) } return result end def stars_in_the_movie() sql = "SELECT stars.* FROM stars INNER JOIN castings ON castings.star_id = stars.id WHERE movie_id = $1" values = [@id] stars_data = SqlRunner.run(sql, values) return Star.map_items(stars_data) end end
class LoginotesController < ApplicationController # before_action :logged_in_user, only: [:create] def new end def create @truck = Truck.find(params[:loginote][:truck_id]) @loginote = @truck.loginotes.build(loginote_params) if @loginote.save flash[:success] = "Loginote created" redirect_to karte_path(@truck.id) else render 'loginotes/form' end end private def loginote_params params.require(:loginote).permit(:content) end end
# # Cookbook Name:: IBM-IHS # Recipe:: default # # Copyright 2015, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute # # ibm_ihs1 = node['ibm-ihs']['package1'] ibm_ihs2 = node['ibm-ihs']['package2'] ibm_ihs3 = node['ibm-ihs']['package3'] ibm_ihs_extract = node['ibm-ihs']['extract-dir'] ibm_ihs_bin = node['ibm-ihs']['bin'] ibm_im_path = node['ibm-im']['path'] #ibm_ihs_path = node['ibm-ihs']['path'] ibm_ihs_start = node['ibm-ihs']['start'] package "unzip" package "apr-util" package "compat-expat1" directory "#{ibm_ihs_extract}" do action :create mode '755' user 'root' group 'root' end bash "unzip-ibm-ihs" do user 'root' code <<-EOH unzip #{ibm_ihs1} -d #{ibm_ihs_extract} unzip #{ibm_ihs2} -d #{ibm_ihs_extract} unzip #{ibm_ihs3} -d #{ibm_ihs_extract} EOH not_if { ::File.exists?("#{ibm_ihs_extract}/repository.config")} # not_if {Dir ["#(ibm_ihs_extract)"]} end execute "install-ibm-ihs" do command "#{ibm_im_path}/imcl install com.ibm.websphere.IHS.v85 -repositories #{ibm_ihs_extract} -installationDirectory /opt/IBM/HTTPServer -acceptLicense -properties 'user.ihs.httpPort=80,user.ihs.allowNonRootSilentInstall=true' -log /tmp/ihs_install.xml" not_if { ::File.exists?("#{ibm_ihs_bin}")} # not_if {Dir ["#(ibm_ihs_path)"]} end execute "start-ibm-ihs" do command "#{ibm_ihs_start}/apachectl -k start" end
# frozen_string_literal: true RSpec.describe JwtAuth do describe '.auth_credentials' do context 'when token' do it 'should add user details to headers' do user = User.find_by_email ENV['ADMIN_EMAIL'] scopes = attributes_for(:permission, role: 'admin')[:permissions] token = attributes_for(:auth, user: user)[:token] env = { 'HTTP_AUTHORIZATION' => "Bearer #{token}" } fullname = "#{user[:fname]} #{user[:lname]}" user_cred = { 'id' => user[:id], 'email' => user[:email], 'fullname' => fullname } described_class.new(app).auth_credentials env expect(env[:scopes]).to eq scopes expect(env[:user]).to eq user_cred end end end end
class AddRatesToReview < ActiveRecord::Migration def change add_column :reviews, :rate_1, :integer, default: 0 add_column :reviews, :rate_2, :integer, default: 0 add_column :reviews, :rate_3, :integer, default: 0 add_column :reviews, :rate_4, :integer, default: 0 add_column :reviews, :total_rating, :float end end
class CreateRecords < ActiveRecord::Migration def change create_table :records do |t| t.date :exam_date t.references :physician, index: true, foreign_key: true t.references :patient, index: true, foreign_key: true t.float :height t.float :weight t.integer :pulse t.integer :blood_pressure_sys t.integer :blood_pressure_dia t.string :reason_code t.text :symptom_list t.text :prescription t.text :notes t.timestamps null: false end end end
namespace :heroku do desc 'restarts all the heroku dynos so we can control when they restart' task :restart do Heroku::API.new(username: ENV['HEROKU_USERNAME'], password: ENV['HEROKU_PASSWORD']).post_ps_restart(ENV['HEROKU_APP_NAME']) end end
module Events class NoteOnWorkspaceDataset < Note has_targets :dataset, :workspace has_activities :actor, :dataset, :workspace include_shared_search_fields(:dataset) end end
class CreateBrokerInfos < ActiveRecord::Migration def up create_table :broker_infos do |t| t.references :user, index: true t.float :lead_rate, default: 1 t.float :discount, default: 0 t.datetime :updated_at end end end
#!/usr/bin/env ruby lib_dir = File.expand_path('../../lib', __FILE__) $LOAD_PATH << lib_dir unless $LOAD_PATH.include?(lib_dir) require 'ept' require 'optparse' def usage $stderr.puts "USAGE: #{$0} verify FILENAME" exit 1 end command = ARGV.shift case command when "verify" options = {silent: false} OptionParser.new do |o| o.on '-s', '--silent' do |v| options[:silent] = true end end.parse! file = ARGV.shift usage unless ARGV.empty? && file begin Ept.read_file(file) rescue Errno::ENOENT puts "File #{file} not found or not readable" unless options[:silent] exit 2 rescue Ept::SyntaxError puts "File #{file} is not syntactically valid" unless options[:silent] exit 3 else puts "File #{file} is valid" unless options[:silent] exit 0 end when "help" usage end
Rails.application.routes.draw do mount GithubOnRails::Engine => "/github_on_rails" end
require_relative '../test_helper' class CommentTest < TestCase def setup 3.times.each do |i| Factory(:user) end User.first.boards.create!(name: "stop", active: true, description: "nothing") User.first.boards.create!(name: "start", active: true, description: "nothing") User.first.posts.create!(title: "post", content: "nothing", board: Board.first) end def test_karma_with_reply Comment.create!(content: "comment", user: User.last, post: Post.last) assert_equal 1, User.last.karma Comment.first.destroy assert_equal 0, User.last.karma end def test_reply_post Comment.create!(content: "comment", user: User.last, post: Post.last) assert_equal 1, User.first.mentions.to_a.size assert_equal "post", User.first.mentions.to_a.first.type end def test_reply_merge_mention Comment.create!(content: "comment", user: User.last, post: Post.last) Comment.create!(content: "comment", user: User.all[User.all.size/2], post: Post.last) assert_equal 1, User.first.mentions.to_a.size assert_equal 2, User.first.mentions.first.triggers.size end def test_reply_by_himself Comment.create!(content: "comment", user: User.first, post: Post.last) assert_equal 0, User.first.mentions.to_a.size end def test_reply_mention_from_other_user Comment.create!(content: "comment", user: User.last, post: Post.last) assert_equal 0, User.last.messages.to_a.size Comment.create!(content: "comment", user: User.all[User.all.size/2], post: Post.last) assert_equal 2, Comment.all.size assert_equal 1, User.last.mentions.to_a.size assert_equal User.all[User.all.size/2].nick, User.last.mentions.to_a.first.triggers.first assert_equal "reply", User.last.mentions.to_a.first.type end end
# frozen_string_literal: true require 'gtk2' require_relative '../utils' require 'mui/gtk_extension' require 'mui/gtk_contextmenu' # CRUDなリストビューを簡単に実現するためのクラス class Gtk::CompatListView < Gtk::TreeView extend Memoist attr_accessor :dialog_title type_register def initialize super() initialize_model set_columns end private def initialize_model set_model(Gtk::ListStore.new(*column_schemer.flatten.map{|x| x[:type]})) end def set_columns column_schemer.inject(0){ |index, scheme| if scheme.is_a? Array col = Gtk::TreeViewColumn.new(scheme.first[:label]) col.resizable = scheme.first[:resizable] scheme.each{ |cell| if cell[:kind] cell_renderer = get_render_by(cell, index) col.pack_start(cell_renderer, cell[:expand]) col.add_attribute(cell_renderer, cell[:kind], index) end index += 1 } append_column(col) else if(scheme[:label] and scheme[:kind]) col = Gtk::TreeViewColumn.new(scheme[:label], get_render_by(scheme, index), scheme[:kind] => index) col.resizable = scheme[:resizable] append_column(col) end index += 1 end index } end def get_render_by(scheme, index) kind = scheme[:kind] renderer = scheme[:renderer] case when renderer if renderer.is_a?(Proc) renderer.call(scheme, index) else renderer.new end when kind == :text Gtk::CellRendererText.new when kind == :pixbuf Gtk::CellRendererPixbuf.new end end def column_schemer raise 'Override this method!' end end
require_relative '../../../src/conta.rb' # Pre-condition Given(/^I have an origin account$/) do |table| @saldo_inicial_joao = table.rows_hash['balance'].to_i @valor_transf = table.rows_hash['transfer_value'].to_i @conta_joao = Conta.new('JoaoOrigin') @conta_joao.deposita(@saldo_inicial_joao) end Given(/^I have a destiny account$/) do |table| @saldo_inicial_maria = table.rows_hash['balance'].to_i @conta_maria = Conta.new('MariaDestiny') @conta_maria.deposita(@saldo_inicial_maria) end # Actions When(/^I make de transference$/) do @conta_joao.transfere(@valor_transf, @conta_maria) end # Expected Results Then(/^I see a message$/) do |success_message| success_message = success_message.gsub('ORIGEM', @conta_joao.nome) success_message = success_message.gsub('VALOR', @valor_transf.to_s) success_message = success_message.gsub('DESTINO', @conta_maria.nome) expect(@conta_joao.output.to_s).to eq success_message end Then(/^account balances are updated$/) do @saldo_final_joao = @saldo_inicial_joao - @valor_transf @saldo_final_maria = @saldo_inicial_maria + @valor_transf #expect(@conta_joao.saldo).to eq @saldo_final_joao expect(@conta_maria.saldo).to eq @saldo_final_maria end
require File.join(File.dirname(__FILE__), '..', '..', 'spec_helper') describe QuotientCube::Tree::Base do describe "with the store, product, season data set" do before(:each) do @table = Table.new( :column_names => [ 'store', 'product', 'season', 'sales' ], :data => [ ['S1', 'P1', 's', 6], ['S1', 'P2', 's', 12], ['S2', 'P1', 'f', 9] ] ) @dimensions = ['store', 'product', 'season'] @measures = ['sales[sum]', 'sales[avg]'] @cube = QuotientCube::Base.build( @table, @dimensions, @measures ) do |table, pointers| sum = 0 pointers.each do |pointer| sum += table[pointer]['sales'] end [sum, sum / pointers.length.to_f] end @tempfile = Tempfile.new('database') @database = KyotoCabinet::DB.new @database.open(@tempfile.path, KyotoCabinet::DB::OWRITER | KyotoCabinet::DB::OCREATE) @tree = QuotientCube::Tree::Builder.build(@database, @cube, :prefix => 'prefix') end after(:each) do @database.close end it "should get a list of dimensions" do @tree.dimensions.should == ['store', 'product', 'season'] end it "should get a list of measures" do @tree.measures.should == ['sales[sum]', 'sales[avg]'] end it "should get a list of values" do @tree.values('store').should == ['S1', 'S2'] @tree.values('product').should == ['P1', 'P2'] @tree.values('season').should == ['f', 's'] end it "should answer point and range queries" do @tree.find(:all).should == {'sales[sum]' => 27.0, 'sales[avg]' => 9.0} @tree.find('sales[avg]', :conditions => {'product' => 'P1'}).should == {'product' => 'P1', 'sales[avg]' => 7.5} @tree.find('sales[avg]', 'sales[sum]').should == \ {'sales[sum]' => 27.0, 'sales[avg]' => 9.0} @tree.find('sales[avg]', :conditions => {'product' => 'P1', 'season' => 'f'}).should == \ {'product' => 'P1', 'season' => 'f', 'sales[avg]' => 9.0} @tree.find('sales[avg]', :conditions => {'product' => ['P1', 'P2', 'P3']}).should == [ {'product' => 'P1', 'sales[avg]' => 7.5}, {'product' => 'P2', 'sales[avg]' => 12.0} ] @tree.find(:all, :conditions => {'product' => :all}).should == [ {'product' => 'P1', 'sales[avg]' => 7.5, 'sales[sum]' => 15.0}, {'product' => 'P2', 'sales[avg]' => 12.0, 'sales[sum]' => 12.0} ] end end describe "with the signup source data set" do before(:each) do @table = Table.new( :column_names => [ 'hour', 'user[source]', 'user[age]', 'event[name]', 'user[id]' ], :data => [ ['340023', 'blog', 'NULL', 'signup', '1'], ['340023', 'blog', 'NULL', 'signup', '2'], ['340023', 'twitter', '14', 'signup', '3'] ] ) @dimensions = ['hour', 'user[source]', 'user[age]', 'event[name]'] @measures = ['events[count]', 'events[percentage]', 'users[count]', 'users[percentage]'] total_events = @table.length total_users = @table.distinct('user[id]').length @cube = QuotientCube::Base.build( @table, @dimensions, @measures ) do |table, pointers| events_count = pointers.length events_percentage = (events_count / total_events.to_f) * 100 users = Set.new pointers.each do |pointer| users << @table[pointer]['user[id]'] end users_count = users.length users_percentage = (users_count / total_users.to_f) * 100 [events_count, events_percentage, users_count, users_percentage] end @tempfile = Tempfile.new('database') @database = KyotoCabinet::DB.new @database.open(@tempfile.path, KyotoCabinet::DB::OWRITER | KyotoCabinet::DB::OCREATE) @tree = QuotientCube::Tree::Builder.build(@database, @cube) end after(:each) do @database.close end it "should have the correct meta data" do @tree.dimensions.should == ['hour', 'user[source]', 'user[age]', 'event[name]'] @tree.measures.should == ['events[count]', 'events[percentage]', 'users[count]', 'users[percentage]'] @tree.values('hour').should == ['340023'] @tree.values('user[source]').should == ['blog', 'twitter'] @tree.values('user[age]').should == ['14', 'NULL'] @tree.values('event[name]').should == ['signup'] end it "should answer various queries" do @tree.find(:all, :conditions => {'hour' => ['3400231']}).should == [] @tree.find(:all, :conditions => {'hour' => '3400231'}).should == nil @tree.find(:all, :conditions => {'event[name]' => 'fake'}).should == nil @tree.find(:all, :conditions => {'event[name]' => ['fake1', 'fake2']}).should == [] @tree.find(:all, :conditions => {'hour' => '340023'}).should == { 'hour' => '340023', 'events[count]' => 3, 'events[percentage]' => 100.0, 'users[count]' => 3, 'users[percentage]' => 100.0 } @tree.find(:all, :conditions => \ {'hour' => ['340023']}).should == [{ 'hour' => '340023','events[count]' => 3, 'events[percentage]' => 100.0,'users[count]' => 3, 'users[percentage]' => 100.0 }] @tree.find(:all, :conditions => \ {'event[name]' => 'signup'}).should == { 'event[name]' => 'signup', 'events[count]' => 3, 'events[percentage]' => 100.0, 'users[count]' => 3, 'users[percentage]' => 100.0 } @tree.find(:all, :conditions => \ {'event[name]' => ['signup']}).should == [{ 'event[name]' => 'signup', 'events[count]' => 3, 'events[percentage]' => 100.0, 'users[count]' => 3, 'users[percentage]' => 100.0 }] @tree.find(:all, :conditions => \ {'hour' => :all}).should == [{ 'hour' => '340023', 'events[count]' => 3, 'events[percentage]' => 100.0, 'users[count]' => 3, 'users[percentage]' => 100.0 }] @tree.find(:all, :conditions => \ {'event[name]' => :all}).should == [{ 'event[name]' => 'signup', 'events[count]' => 3, 'events[percentage]' => 100.0, 'users[count]' => 3, 'users[percentage]' => 100.0 }] @tree.find('events[count]', :conditions => { 'user[age]' => '14', 'event[name]' => 'signup' }).should == {'user[age]' => '14', 'event[name]' => 'signup', 'events[count]' => 1.0} @tree.find('events[count]', :conditions => { 'user[age]' => '14', 'event[name]' => 'fake' }).should == nil @tree.find(:all).should == { 'events[count]' => 3, 'events[percentage]' => 100.0, 'users[count]' => 3, 'users[percentage]' => 100.0 } value = @tree.find('events[percentage]', :conditions => {'user[source]' => 'twitter'}) value.key?('events[percentage]').should == true (value['events[percentage]'] * 100).to_i.should == 3333 @tree.find('users[count]', :conditions => {'user[age]' => 'NULL'}).should == \ {'user[age]' => 'NULL', 'users[count]' => 2.0} @tree.find('users[count]', :conditions => {'user[age]' => :all}).should == [ {'user[age]' => '14', 'users[count]' => 1.0}, {'user[age]' => 'NULL', 'users[count]' => 2.0} ] end end describe "with only one row" do before(:each) do @table = Table.new( :column_names => [ 'hour', 'user[source]', 'user[age]', 'event[name]', 'user[id]' ], :data => [ ['340023', 'blog', 'NULL', 'signup', '1'], ] ) @dimensions = ['hour', 'user[source]', 'user[age]', 'event[name]'] @measures = ['events[count]', 'events[percentage]', 'users[count]', 'users[percentage]'] total_events = @table.length total_users = @table.distinct('user[id]').length @cube = QuotientCube::Base.build( @table, @dimensions, @measures ) do |table, pointers| events_count = pointers.length events_percentage = (events_count / total_events.to_f) * 100 users = Set.new pointers.each do |pointer| users << @table[pointer]['user[id]'] end users_count = users.length users_percentage = (users_count / total_users.to_f) * 100 [events_count, events_percentage, users_count, users_percentage] end @tempfile = Tempfile.new('database') @database = KyotoCabinet::DB.new @database.open(@tempfile.path, KyotoCabinet::DB::OWRITER | KyotoCabinet::DB::OCREATE) @tree = QuotientCube::Tree::Builder.build(@database, @cube, :prefix => 'prefix') end after(:each) do @database.close end it "should answer a variety of queries" do @tree.find(:all).should == { 'events[count]' => 1, 'events[percentage]' => 100.0, 'users[count]' => 1, 'users[percentage]' => 100.0 } @tree.find('events[count]', :conditions => \ {'hour' => :all}).should == [{'hour' => '340023', 'events[count]' => 1.0}] @tree.find('events[count]', :conditions => {'hour' => 'fake'}).should == nil end end describe "with the tiny hourly events data set" do before(:each) do base_table = load_fixture('tiny_hourly_events') @dimensions = ['day', 'hour', 'event[name]'] @measures = ['events[count]'] @cube = QuotientCube::Base.build(base_table, @dimensions, @measures) do |table, pointers| [pointers.length] end @tempfile = Tempfile.new('database') @database = KyotoCabinet::DB.new @database.open(@tempfile.path, KyotoCabinet::DB::OWRITER | KyotoCabinet::DB::OCREATE) @tree = QuotientCube::Tree::Builder.build(@database, @cube) end it "should answer various queries" do @tree.find(:all, :conditions => \ {'event[name]' => 'signup', 'hour' => :all}).should == \ [{"hour"=>"349205", "event[name]"=>"signup", "events[count]"=>2.0}, {"hour"=>"349206", "event[name]"=>"signup", "events[count]"=>1.0}] end end describe "with fixed values at dimensions greater than the first" do before(:each) do @table = Table.new( :column_names => [ 'day', 'hour', 'event', 'source' ], :data => [ ['1', '1', 'home', 'direct'], ['2', '3', 'home', 'NULL'], ['2', '4', 'time', 'NULL'] ] ) @dimensions = ['day', 'hour', 'event', 'source'] @measures = ['events[count]'] @cube = QuotientCube::Base.build(@table, @dimensions, @measures) do |table, pointers| [pointers.length] end @tempfile = Tempfile.new('database') @database = KyotoCabinet::DB.new @database.open(@tempfile.path, KyotoCabinet::DB::OWRITER | KyotoCabinet::DB::OCREATE) @tree = QuotientCube::Tree::Builder.build(@database, @cube) end after(:each) do @database.close end it "should do some queries" do @tree.find(:all, :conditions => \ {'event' => 'time', 'day' => :all}).should == \ [{"day"=>"2", "event"=>"time", "events[count]"=>1.0}] @tree.find(:all, :conditions => \ {'event' => 'home', 'day' => :all}).should == \ [{"day" => "1", "event" => "home", "events[count]" => 1.0}, {"day" => "2", "event" => "home", "events[count]" => 1.0}] end end describe "The hardest bug to find ever" do before(:each) do @table = Table.new( :column_names => [ 'day', 'hour', 'event', 'source' ], :data => [ ['day2', 'hour3', 'home', 'NULL'], ['day2', 'hour4', 'home', 'NULL'], ['day2', 'hour4', 'time', 'NULL'] ] ) @dimensions = ['day', 'hour', 'event', 'source'] @measures = ['events[count]'] @cube = QuotientCube::Base.build(@table, @dimensions, @measures) do |table, pointers| [pointers.length] end @tempfile = Tempfile.new('database') @database = KyotoCabinet::DB.new @database.open(@tempfile.path, KyotoCabinet::DB::OWRITER | KyotoCabinet::DB::OCREATE) @tree = QuotientCube::Tree::Builder.build(@database, @cube) end it "should answer the one query that matters" do @tree.find(:all, :conditions => \ {'event' => 'time', 'day' => :all}).should == \ [{"day"=>"day2", "event"=>"time", "events[count]"=>1.0}] end it "should answer this other hard range query" do @tree.find(:all, :conditions => \ {'event' => ['home', 'time']}).should == \ [{'event' => 'home', 'events[count]' => 2.0}, {'event' => 'time', 'events[count]' => 1.0}] end end end
require File.dirname(__FILE__) + '/../../spec_helper' require File.dirname(__FILE__) + '/fixtures/classes' class DefineMethodSpecClass end describe "Module#define_method when given an UnboundMethod" do it "correctly passes given arguments to the new method" do klass = Class.new do def test_method(arg1, arg2) [arg1, arg2] end define_method(:another_test_method, instance_method(:test_method)) end klass.new.another_test_method(1, 2).should == [1, 2] end it "adds the new method to the methods list" do klass = Class.new do def test_method(arg1, arg2) [arg1, arg2] end define_method(:another_test_method, instance_method(:test_method)) end klass.new.should have_method(:another_test_method) end it "can add an initializer" do klass = Class.new do attr_reader :args define_method(:initialize) do |*args| @args = args end end klass.new(1,2,3).args.should == [1,2,3] end ruby_bug "redmine:2117", "1.8.7" do it "works for singleton classes too" do klass = Class.new class << klass def test_method :foo end end child = Class.new(klass) sc = class << child; self; end sc.send :define_method, :another_test_method, klass.method(:test_method).unbind child.another_test_method.should == :foo end end end describe "Module#define_method" do it "defines the given method as an instance method with the given name in self" do class DefineMethodSpecClass def test1 "test" end define_method(:another_test, instance_method(:test1)) end o = DefineMethodSpecClass.new o.test1.should == o.another_test end it "defines a new method with the given name and the given block as body in self" do class DefineMethodSpecClass define_method(:block_test1) { self } define_method(:block_test2, &lambda { self }) end o = DefineMethodSpecClass.new o.block_test1.should == o o.block_test2.should == o end it "raises a TypeError when the given method is no Method/Proc" do lambda { Class.new { define_method(:test, "self") } }.should raise_error(TypeError) lambda { Class.new { define_method(:test, 1234) } }.should raise_error(TypeError) end it "accepts a Method (still bound)" do class DefineMethodSpecClass attr_accessor :data def inspect_data "data is #{@data}" end end o = DefineMethodSpecClass.new o.data = :foo m = o.method(:inspect_data) m.should be_an_instance_of(Method) klass = Class.new(DefineMethodSpecClass) klass.send(:define_method,:other_inspect, m) c = klass.new c.data = :bar c.other_inspect.should == "data is bar" lambda{o.other_inspect}.should raise_error(NoMethodError) end it "maintains the Proc's scope" do class DefineMethodByProcClass in_scope = true method_proc = proc { in_scope } define_method(:proc_test, &method_proc) end o = DefineMethodByProcClass.new o.proc_test.should be_true end end
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2014-2020 MongoDB Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'mongo/index/view' module Mongo # Contains constants for indexing purposes. # # @since 2.0.0 module Index # Wildcard constant for all. # # @since 2.1.0 ALL = '*'.freeze # Specify ascending order for an index. # # @since 2.0.0 ASCENDING = 1 # Specify descending order for an index. # # @since 2.0.0 DESCENDING = -1 # Specify a 2d Geo index. # # @since 2.0.0 GEO2D = '2d'.freeze # Specify a 2d sphere Geo index. # # @since 2.0.0 GEO2DSPHERE = '2dsphere'.freeze # Specify a geoHaystack index. # # @since 2.0.0 # @deprecated GEOHAYSTACK = 'geoHaystack'.freeze # Encodes a text index. # # @since 2.0.0 TEXT = 'text'.freeze # Specify a hashed index. # # @since 2.0.0 HASHED = 'hashed'.freeze # Constant for the indexes collection. # # @since 2.0.0 COLLECTION = 'system.indexes'.freeze end end
class Marker < ApplicationRecord belongs_to :user belongs_to :post scope :bookmarks, -> { where(type_of_maker: "BOOKMARK") } scope :reported, -> { where(type_of_maker: "REPORTED") } validates :user_id, uniqueness: { scope: [:post_id]} end
#!/run/nodectl/nodectl script # Can be used to process transactions for a given node. All transactions are # considered as NoOp and thus always succeed. Can be used to temporarily bypass # offline node, however with consequences -- since the transactions are not # executed, the state of the database will not correspond with the node. # require 'nodectld/standalone' NODE_ID = 170 db = NodeCtld::Db.new log = File.open('executed-transactions.txt', 'a') loop do rows = db.union do |u| # Transactions for execution u.query( "SELECT * FROM ( (SELECT t1.*, 1 AS depencency_success, ch1.state AS chain_state, ch1.progress AS chain_progress, ch1.size AS chain_size FROM transactions t1 INNER JOIN transaction_chains ch1 ON ch1.id = t1.transaction_chain_id WHERE done = 0 AND node_id = #{NODE_ID} AND ch1.state = 1 AND depends_on_id IS NULL GROUP BY transaction_chain_id, priority, t1.id) UNION ALL (SELECT t2.*, d.status AS dependency_success, ch2.state AS chain_state, ch2.progress AS chain_progress, ch2.size AS chain_size FROM transactions t2 INNER JOIN transactions d ON t2.depends_on_id = d.id INNER JOIN transaction_chains ch2 ON ch2.id = t2.transaction_chain_id WHERE t2.done = 0 AND d.done = 1 AND t2.node_id = #{NODE_ID} AND ch2.state = 1 GROUP BY transaction_chain_id, priority, id) ORDER BY priority DESC, id ASC ) tmp GROUP BY transaction_chain_id, priority ORDER BY priority DESC, id ASC LIMIT 1" ) # Transactions for rollback. # It is the same query, only transactions are in reverse order. u.query( "SELECT * FROM ( (SELECT d.*, ch2.state AS chain_state, ch2.progress AS chain_progress, ch2.size AS chain_size, ch2.urgent_rollback AS chain_urgent_rollback FROM transactions t2 INNER JOIN transactions d ON t2.depends_on_id = d.id INNER JOIN transaction_chains ch2 ON ch2.id = t2.transaction_chain_id WHERE t2.done = 2 AND d.status IN (1,2) AND d.done = 1 AND d.node_id = #{NODE_ID} AND ch2.state = 3) ORDER BY priority DESC, id DESC ) tmp GROUP BY transaction_chain_id, priority ORDER BY priority DESC, id DESC LIMIT 1" ) end rows.each do |row| puts "Executing transaction #{row['id']}" # Make it into a noop row['handle'] = 10001 log.puts(row['id']) log.flush c = NodeCtld::Command.new(row) c.execute c.save(db) end sleep(1) end log.close
require 'rails_helper' RSpec.describe 'お気に入り登録機能', type: :request do let(:user) { create(:user) } let!(:tweet) { create(:tweet, user: user) } context 'お気に入り登録処理' do context 'ログインしている場合' do before do sign_in user end it 'Tweetのお気に入り登録ができること' do expect { post "/api/tweets/#{tweet.id}/like" }.to change(user.likes, :count).by(1) end it 'Tweetのお気に入り解除ができること' do tweet.likes.create(user_id: user.id) expect { delete "/api/tweets/#{tweet.id}/like" }.to change(user.likes, :count).by(-1) end end context 'ログインしていない場合' do it 'お気に入り登録は実行できず、エラーメッセージ' do expect { post "/api/tweets/#{tweet.id}/like" }.not_to change(Like, :count) expect(response).to have_http_status(401) end it 'お気に入り解除は実行できず、エラーメッセージ' do expect { delete "/api/tweets/#{tweet.id}/like" }.not_to change(Like, :count) expect(response).to have_http_status(401) end end end context 'お気に入り一覧ページの表示' do context 'ログインしている場合' do before do sign_in user end it 'レスポンスが正常に表示されること' do get favorites_path expect(response).to have_http_status(200) expect(response).to render_template('favorites/index') end end context 'ログインしていない場合' do it 'ログイン画面にリダイレクトすること' do get favorites_path expect(response).to have_http_status(302) expect(response).to redirect_to new_user_session_path end end end end
class StudentRepprovedCourseSubject < ActiveRecord::Base self.table_name = "student_repproved_course_subject" belongs_to :course_subject_student has_many :student_examination_repproved_subjects end
class Book < ActiveFedora::Base has_metadata name: "properties", type: ActiveFedora::SimpleDatastream do |m| m.field('title') end end
json.array!(@mailing_lists) do |mailing_list| json.extract! mailing_list, :id, :name json.url mailing_list_url(mailing_list, format: :json) end
class AddBeerStyleReference < ActiveRecord::Migration[5.2] def change add_reference :beers, :styles, index: true reversible do Style.all.each do |style| Beer.where(old_style: style.name).each do |beer| beer.styles_id = style.id beer.save! end end end end end
shared_examples 'total count pagination param' do it 'responds with the total_count passed to render_paginated, overwrites the real total_count' do expect(response_body(response)['total_count']).to( be Constants::DEFAULT_TOTAL_COUNT[:total_count] ) expect(response_body(response)['total_count']).not_to be DummyModel.count end end
=begin rdoc -------------------------------------------------------------------------------- Run rapper against all eligible files in a directory tree, compiling a list of the syntax errors in the files. -------------------------------------------------------------------------------- Usage: ld4l_scan_directory_tree <directory> <error_file> [[regexp] input_format] [REPLACE] -------------------------------------------------------------------------------- =end module Ld4lIngesting class ScanDirectoryTree USAGE_TEXT = 'Usage is ld4l_scan_directory_tree <directory> <error_file> [[regexp] input_format] [REPLACE]' DEFAULT_MATCHER = /.+\.(rdf|owl|nt|ttl)$/ def initialize @bad_files_count = 0 @error_count = 0 end def process_arguments(args) replace_output = args.delete('REPLACE') raise UserInputError.new(USAGE_TEXT) unless args && (2..4).include?(args.size) raise UserInputError.new("#{args[0]} is not a directory") unless Dir.exist?(args[0]) @top_dir = File.expand_path(args[0]) raise UserInputError.new("#{args[1]} already exists -- specify REPLACE") if File.exist?(args[1]) unless replace_output raise UserInputError.new("Can't create #{args[1]}: no parent directory.") unless Dir.exist?(File.dirname(args[1])) @error_file_path = File.expand_path(args[1]) if args[2] @filename_matcher = Regexp.new(args[2]) else @filename_matcher = DEFAULT_MATCHER end if args[3] @input_format = args[3] else @input_format = 'ntriples' end end def traverse_the_directory Dir.chdir(@top_dir) do Find.find('.') do |path| if File.file?(path) && path =~ @filename_matcher scan_file_and_record_errors(path) end end end end def scan_file_and_record_errors(path) `rapper -i #{@input_format} #{path} - > /dev/null 2> #{@tempfile_path}` error_lines = File.readlines(@tempfile_path).each.select {|l| l.index('Error')} unless error_lines.empty? @bad_files_count += 1 @error_count += error_lines.size @error_file.write(error_lines.join) end puts "-- found #{error_lines.size} errors in #{path}" end def report puts ">>>>>>> bad files #{@bad_files_count}, errors #{@error_count}" end def run() begin process_arguments(ARGV) begin @error_file = File.open(@error_file_path, 'w') begin tempfile = Tempfile.new('ld4l_scan') @tempfile_path = tempfile.path traverse_the_directory() report ensure tempfile.close! if tempfile end ensure @error_file.close if @error_file end rescue UserInputError puts puts "ERROR: #{$!}" puts end end end end
require 'rails_helper' RSpec.describe Comment, type: :model do context 'a comment belongs to a user' do it {should belong_to(:user)} end context 'a comment belongs to a post' do it {should belong_to(:post)} end end
class RemoveSeenIdFromMovie < ActiveRecord::Migration[5.1] def change remove_column :movies, :seen_id end end
class AddHealthToDeploymentTargetsMetadata < ActiveRecord::Migration def change add_column :deployment_target_metadata, :adapter_is_healthy, :boolean end end
FactoryBot.define do factory :item do name { Faker::Food.fruits } price { rand(0..99_999_999) } count { rand(0..99) } association :shop end end
class BlogsController < ApplicationController def index @blogs = Blog.all end def new @blog = Blog.new end def create blog = Blog.new(blog_params) blog.user_id = current_user.id if blog.save redirect_to "/" else render "blogs/new" end end def show @blog = Blog.find(params[:id]) @users = User.all # current_blog end def edit @blog = Blog.find(params[:id]) end def update @current_blog = Blog.find(params[:id]) if @current_blog.update(blog_params) redirect_to "/blogs/#{current_blog.id}" end end def destroy blog = Blog.find(params[:id]) if blog.destroy redirect_to "/" end end private def blog_params params.require(:blog).permit(:title, :content, :user_id) end end
class Meow < ActiveRecord::Base def sound_type if self.cat "cat" else "human" end end end
# == Schema Information # # Table name: pages # # id :integer not null, primary key # slug :string(255) not null # title :string(255) not null # body :text # account_id :integer # parent_id :integer # created_at :datetime not null # updated_at :datetime not null # sidebar_id :decimal(, ) # class Page < ActiveRecord::Base attr_accessible :body, :slug, :title, :sidebar_id belongs_to :account belongs_to :parent, :class_name => 'Page' belongs_to :sidebar has_many :children, :class_name => 'Page', :foreign_key => 'parent_id' validates_uniqueness_of :slug, :scope => :account_id def self.by_id_or_slug(slug_or_id, account_id) @page = Page.where('account_id = ? AND (slug = ? OR id = ?)', account_id, slug_or_id, slug_or_id).first end end
## # Simple class to hold a collection of search result data. # class GoogleCustomSearch::ResultSet include Kaminari::ConfigurationMethods::ClassMethods attr_reader :time, :total, :pages, :suggestion, :labels attr_internal_accessor :limit_value, :offset_value alias :total_count :total def self.create(xml_hash, offset, per_page) self.new(xml_hash['TM'].to_f, xml_hash['RES']['M'].to_i, parse_results(xml_hash['RES']['R']), spelling = xml_hash['SPELLING'] ? spelling['SUGGESTION'] : nil, parse_labels(xml_hash), offset, per_page) end def self.create_empty self.new(0.0, 0, [], nil, {}) end def self.parse_results(res_r) GoogleCustomSearch::Result.parse(res_r) end def self.parse_labels(xml_hash) return {} unless context = xml_hash['Context'] and facets = context['Facet'] facets.map do |f| (fi = f['FacetItem']).is_a?(Array) ? fi : [fi] end.inject({}) do |h, facet_item| facet_item.each do |element| h[element['label']] = element['anchor_text'] end h end end def initialize(time, total, pages, suggestion, labels, offset = 0, limit = 20) @time, @total, @pages, @suggestion, @labels = time, total, pages, suggestion, labels @_limit_value, @_offset_value = (limit || default_per_page).to_i, offset.to_i class << self include Kaminari::PageScopeMethods end end end
# A triangle is classified as follows: # right One angle of the triangle is a right angle (90 degrees) # acute All 3 angles of the triangle are less than 90 degrees # obtuse One angle is greater than 90 degrees. # To be a valid triangle, the sum of the angles must be exactly 180 degrees, # and all angles must be greater than 0: if either of these conditions is not # satisfied, the triangle is invalid. # Write a method that takes the 3 angles of a triangle as arguments, and returns # a symbol :right, :acute, :obtuse, or :invalid depending on whether the # triangle is a right, acute, obtuse, or invalid triangle. # You may assume integer valued angles so you don't have to worry about floating # point errors. You may also assume that the arguments are specified in degrees. def is_valid_triangle(angle1, angle2, angle3) angles = [angle1, angle2, angle3] if angles.reduce(:+) == 180 && angle1 != 0 && angle2 != 0 && angle3 != 0 true else false end end def triangle(angle1, angle2, angle3) if is_valid_triangle(angle1, angle2, angle3) if angle1 == 90 || angle2 == 90 || angle3 == 90 p :right elsif angle1 < 90 && angle2 < 90 && angle3 < 90 p :acute elsif angle1 > 90 || angle2 > 90 || angle3 > 90 p :obtuse end else p :invalid end end p triangle(60, 70, 50) == :acute p triangle(30, 90, 60) == :right p triangle(120, 50, 10) == :obtuse p triangle(0, 90, 90) == :invalid p triangle(50, 50, 50) == :invalid
class Board attr_accessor :x, :y, :parent, :children def initialize(x, y, parent=nil) @x = x @y = y @parent = parent @children = [] end def possible_children candidates = [] candidates << [@x+1,@y+2] candidates << [@x+1,@y-2] candidates << [@x-1,@y+2] candidates << [@x-1,@y-2] candidates << [@x+2,@y+1] candidates << [@x+2,@y-1] candidates << [@x-2,@y+1] candidates << [@x-2,@y+1] children = candidates.select { |pos| pos[0] >= 0 && pos[1] >= 0 && pos[0] <= 7 && pos[1] <= 7} children = children.map {|child_coords| Board.new(child_coords[0], child_coords[1], self)} @children = children end end def get_search_obj(search_obj, root_obj) queue = [] queue << root_obj loop do current = queue.shift return current if current.x == search_obj.x && current.y == search_obj.y current.possible_children.each {|child| queue << child } end end def knight_moves(start_arr, finish_arr) search_obj = Board.new(finish_arr[0], finish_arr[1]) root_obj = Board.new(start_arr[0], start_arr[1]) result = get_search_obj(search_obj, root_obj) route = [] route.unshift([search_obj.x, search_obj.y]) current = result.parent while current route.unshift([current.x, current.y]) current = current.parent end puts "Shortest path achieved in #{route.length - 1} steps. Here's the route:" route.each {|square| square.to_s } end p knight_moves([0,0],[1,2]) p knight_moves([0,0],[3,3]) p knight_moves([3,3],[0,0])
class MovesController < ApplicationController before_action :set_move, only: [:show, :edit, :update, :destroy] # GET /moves/1 # GET /moves/1.json def show end def update respond_to do |format| if @move.update(move_params) format.html { redirect_to root_path, notice: 'move was successfully updated.' } format.json { render :show, status: :ok, location: @move } else format.html { render :edit } format.json { render json: @move.errors, status: :unprocessable_entity } end end end private # Use callbacks to share common setup or constraints between actions. def set_move @move = Move.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def move_params params.require(:move).permit(:priority) end end
Rails.application.routes.draw do get 'password_resets/new' get 'password_resets/edit' get '/signup', to:'users#new' post '/signup', to:'users#create' get '/login', to:'sessions#new' post '/login', to:'sessions#create' # 画像データの取得 get '/show_image', to: 'application#show_image' delete '/logout', to:'sessions#destroy' get 'skillsheets/index' get 'skillsheets/download' get 'skillsheets/update_skillsheet' get 'skillsheets/search'#追記 resources :users do member do get 'get_image' get 'get_skillsheet' end end resources :pdca_posts resources :defect_forms resources :qiita_posts resources :interview_posts resources :account_activations, only: [:edit] resources :feedbacks, only: [:create, :update, :destroy] resources :comments, only: [:create, :destroy] resources :password_resets, only: [:new, :create, :edit, :update] resources :blogs resources :faq resources :movies do get 'sort', on: :collection end resources :movie_categories do get 'sort', on: :collection end resources :skillsheets get '/get_skillsheet', to: 'skillsheets#get_skillsheet' get '/index', to: 'skillsheets#index' patch '/update_business_status', to: 'skillsheets#update_business_status' resources :terms do collection do get 'ajax_search' end end resources :users do member do get 'get_image' get 'get_skillsheet' end end post '/category_create', to: 'faq#category_create' patch '/category_update/:id', to: 'faq#category_update' delete '/category_destroy/:id', to: 'faq#category_destroy' post '/tag_new', to: 'users#tag_new' delete '/tag_delete', to: 'users#tag_delete' # patch '/post_course', to:'users#update_course' patch '/post_pic', to:'users#update_picture' patch '/tag_edit', to:'users#tag_edit' #追加 patch '/tag_show', to:'users#tag_show' #追加 sugi delete '/delete_tag', to: 'users#tag_delete' #temp post⇨deleteに変更しshow.htmlと統一 patch '/post_skillsheet', to: 'skillsheets#update_skillsheet' patch '/register_status', to: 'users#register_status' root 'top#index' get '/information', to: 'information#show' post '/information', to: 'information#create', as: 'create_information' patch '/information', to: 'information#update' delete '/information', to: 'information#destroy' get '/basic_programming', to: 'static_pages#progate' # progate代替えとして代用修正 post '/basic_programming', to: 'static_pages#progate' # progate代替えとして代用修正 get '/attendance_system', to: 'static_pages#railstutorial' # Railsチュートリアルの代替えとして追加 get '/portfolio', to: 'portfolio_comments#portfolio' post '/comments/create', to: 'portfolio_comments#create' post '/comments/:id/destroy', to: 'portfolio_comments#destroy' get '/qa', to: 'static_pages#qa' get '/portfolio_mv', to: 'static_pages#portfolio_mv' post '/defect_forms/notify_to_slack', to: 'defect_forms#notify_to_slack' patch '/html_css_status', to: 'html_css_statuses#update' patch '/html_css_status_schedule', to: 'html_css_statuses#update_schedule', as: 'html_css_schedule' patch '/html_css_status_completion', to: 'html_css_statuses#update_completion', as: 'html_css_completion' patch '/javascript_status', to: 'javascript_statuses#update' patch '/javascript_status_schedule', to: 'javascript_statuses#update_schedule', as: 'javascript_schedule' patch '/javascript_status_completion', to: 'javascript_statuses#update_completion', as: 'javascript_completion' patch '/ruby_status', to: 'ruby_statuses#update' patch '/ruby_status_schedule', to: 'ruby_statuses#update_schedule', as: 'ruby_schedule' patch '/ruby_status_completion', to: 'ruby_statuses#update_completion', as: 'ruby_completion' patch '/bootstrap_status', to: 'bootstrap_statuses#update' patch '/bootstrap_status_schedule', to: 'bootstrap_statuses#update_schedule', as: 'bootstrap_schedule' patch '/bootstrap_status_completion', to: 'bootstrap_statuses#update_completion', as: 'bootstrap_completion' patch '/rubyonrails_status', to: 'rubyonrails_statuses#update' patch '/rubyonrails_status_schedule', to: 'rubyonrails_statuses#update_schedule', as: 'rubyonrails_schedule' patch '/rubyonrails_status_completion', to: 'rubyonrails_statuses#update_completion', as: 'rubyonrails_completion' patch '/railstutorial_status', to: 'railstutorial_statuses#update' patch '/railstutorial_status_schedule', to: 'railstutorial_statuses#update_schedule', as: 'railstutorial_schedule' patch '/user_movie_status', to: 'user_movie_statuses#update' patch '/user_movie_status_schedule', to: 'user_movie_statuses#update_schedule', as: 'user_movie_schedule' 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/>. # require 'set' module ActiveSupport #:nodoc: module CoreExtensions #:nodoc: module Hash #:nodoc: # Return a hash that includes everything but the given keys. This is useful for # limiting a set of parameters to everything but a few known toggles: # # @person.update_attributes(params[:person].except(:admin)) module Except # Returns a new hash without the given keys. def except(*keys) dup.except!(*keys) end # Replaces the hash without the given keys. def except!(*keys) keys.map! { |key| convert_key(key) } if respond_to?(:convert_key) keys.each { |key| delete(key) } self end end end end end
# coding: utf-8 require 'taggable' class Content include Mongoid::Document include Mongoid::Timestamps include Mongoid::Commentable # include Mongoid::TaggableWithContext # include Mongoid::TaggableWithContext::AggregationStrategy::MapReduce # include Mongoid::TaggableWithContext::AggregationStrategy::RealTime include Mongoid::Likeable include Mongoid::Search include Mongoid::Taggable paginates_per 8 field :title, type: String field :body, type: String field :category, type: String field :locked, type: Boolean, :default => false field :impressions_count, type: Integer, :default => 0 embeds_many :model_tags # impressionist gem is_impressionable :column_name => :impressions_count, :unique => :session_hash, :counter_cache => true validates :title, :presence => true validates :category, :inclusion => {:in => %w(健康知识 就医指南 治疗交流 护理园地 用药常识), :message => "%{value} is not a valid category" }, :allow_nil => true search_in :title, :body accepts_nested_attributes_for :comments, :reject_if => lambda { |a| a[:body].blank? }, :allow_destroy => true # accepts_nested_attributes_for :model_tags, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true belongs_to :user scope :newest, desc(:created_at) scope :most_liked, desc(:likers_count) scope :most_commented, desc(:comments_count) scope :with_tag, ->(phrase){where('model_tags.name' => phrase)} def presenter_klass klass = "#{self.class.to_s}Presenter" klass.constantize end def content_type case self.class.to_s when "Article" out = "文章" when "Blog" out = "日记" when "Topic" out = "话题" when "Question" out = "问题" when "Video" out = "视频" when "Poll" out = "投票" else out = "content" end return out end end
class EssayStyleDetail include RailsHelpers def self.build(controller) issue = IssueQuery.find(controller.params.require(:issue_id)) essay_style = EssayStyleQuery.find(controller.params.require(:id)) self.new(issue, essay_style) end delegate :friendly_id, :title, to: :essay_style delegate :year, to: :issue_detail attr_accessor :issue, :essay_style def initialize(issue, essay_style) @essay_style = essay_style @issue = issue @issue_detail = IssueDetail.new(issue) end def body MarkdownDetail.new(essay_style.body).markdown end def style_id essay_style.id end def link_to_show() LinkToRouteWithImage.call(routes.issue_essay_style_path(issue_detail.friendly_id, friendly_id), title, essay_style.cover_image.url(:small), 211, 75) end def short_link_to_show(css = "") helpers.link_to(essay_style.title, routes.issue_essay_style_path(@issue.friendly_id, @essay_style), class: css) end def link_to_issue issue_detail.link_to_show end def link_to_essay(essay) EssayLink.render(essay, false) end def essays @essays ||= EssayQuery.published_essays_for_issue_and_essay_style(issue, essay_style) end def has_essays? (essays.size > 0) end def render_highlighted_essay if highlighted_essay.present? render_to_string "essay_styles/highlighted_essay", highlighted_essay_detail: highlighted_essay else nil end end def render_issue_header IssueHeader.render(issue, true) end def highlighted_essay @highlighted_essay ||= HighlightedEssayDetail.new(issue, essay_style) end private def issue_detail @issue_detail end end
require_relative '../../../puppet_x/century_link/clc' require_relative '../../../puppet_x/century_link/prefetch_error' Puppet::Type.type(:clc_group).provide(:v2, parent: PuppetX::CenturyLink::Clc) do mk_resource_methods read_only(:id, :servers_count) IGNORE_GROUP_NAMES = ['Archive', 'Templates'] def self.instances begin groups = client.list_groups groups.map { |group| new(group_to_hash(group)) } rescue Timeout::Error, StandardError => e raise PuppetX::CenturyLink::PrefetchError.new(self.resource_type.name.to_s, e) end end def self.prefetch(resources) instances.each do |prov| if !IGNORE_GROUP_NAMES.include?(prov.name) && resource = resources[prov.name] resource.provider = prov end end end def self.group_to_hash(group) { id: group['id'], name: group['name'], description: group['description'], custom_fields: group['customFields'], servers_count: group['serversCount'], datacenter: group['locationId'], ensure: :present, } end def exists? Puppet.info("Checking if group #{name} exists") @property_hash[:ensure] == :present end def create Puppet.info("Creating group #{name}") params = { 'name' => name, 'description' => resource[:description], 'parentGroupId' => find_parent_group(resource), 'customFields' => resource[:custom_fields], } group = client.create_group(params) @property_hash[:id] = group['id'] @property_hash[:ensure] = :present if resource[:defaults] begin default_params = remove_null_values(group_defaults(resource[:defaults])) client.set_group_defaults(group['id'], default_params) rescue client.delete_group(group['id']) @property_hash[:ensure] = :absent end end if resource[:scheduled_activities] begin scheduled_activities_params = remove_null_values(group_scheduled_activities(resource[:scheduled_activities])) client.set_group_scheduled_activities(group['id'], scheduled_activities_params) rescue client.delete_group(group['id']) @property_hash[:ensure] = :absent end end true end def destroy Puppet.info("Deleting group #{name}") client.delete_group(id) @property_hash[:ensure] = :absent end private def find_parent_group(params) if params[:parent_group_id] params[:parent_group_id] elsif params[:datacenter] group = client.show_hw_group_for_datacenter(params[:datacenter]) group['id'] elsif params[:parent_group] group = find_group_by_name(params[:parent_group]) group['id'] end end def group_defaults(params) { 'cpu' => params['cpu'], 'memoryGb' => params['memory'], 'networkId' => params['network_id'], 'primaryDns' => params['primary_dns'], 'secondaryDns' => params['secondary_dns'], 'templateName' => params['template_name'], } end def group_scheduled_activities(params) { 'status' => params['status'], 'type' => params['type'], 'beginDateUTC' => params['begin_date'], 'repeat' => params['repeat'], 'customWeeklyDays' => params['custom_weekly_days'], 'expire' => params['expire'], 'expireCount' => params['expire_count'], 'expireDateUTC' => params['expire_date'], 'timeZoneOffset' => params['time_zone_offset'] } end end
class Service < ApplicationRecord belongs_to :branch has_one :company, through: :branch has_one :region, through: :branch validates :branch, :name, :price_cents, :duration_minutes, presence: true validates :price_cents, :duration_minutes, numericality: true validates :name, uniqueness: { scope: :branch } def disable! update! disabled: true end end
class SvnRepo < ActiveRecord::Base inherits_from :repo, methods: true belongs_to :project, class_name: SvnProject end
require_relative 'image' class Menu attr_reader :image def show_menu system('clear') loop do print '> ' process(STDIN.gets.chomp) end end def process(input) begin case input when /^I\s+\d+\s+\d+$/ new_image(*parse(input)) when /^C$/ @image.clear when /^L\s+\d+\s+\d+\s+[A-Z]$/ colour_pixel(*parse(input)) when /^V\s+\d+\s+\d+\s+\d+\s+[A-Z]$/ vertical_segment(*parse(input)) when /^H\s+\d+\s+\d+\s+\d+\s+[A-Z]$/ horizontal_segment(*parse(input)) when /^F\s+\d+\s+\d+\s+[A-Z]$/ fill(*parse(input)) when /^S$/ # nil#to_s exists, so need to manually raise raise NoMethodError unless @image puts @image.to_s when /^X$/ exit else puts 'Unrecognised command' end rescue ArgumentError => e # pass argument errors up from image.rb puts e.message rescue NoMethodError puts 'No image exists' end end private def new_image(cols, rows) @image = Image.new(columns: cols, rows: rows) end def fill(column, row, colour) # All operations in image.rb are zero-indexed, so need to convert @image.fill(column: column - 1, row: row - 1, colour: colour) end def horizontal_segment(startcolumn, endcolumn, row, colour) @image.horizontal_segment(startcolumn: startcolumn - 1, endcolumn: endcolumn - 1, row: row - 1, colour: colour) end def vertical_segment(column, startrow, endrow, colour) @image.vertical_segment(column: column - 1, startrow: startrow - 1, endrow: endrow - 1, colour: colour) end def colour_pixel(column, row, colour) @image.colour_pixel(column: column - 1, row: row - 1, colour: colour) end def parse(input) params = input.split[1..-1] case params.length when 2 params.map(&:to_i) when 3 params[0..1].map(&:to_i) + [params[2].to_sym] when 4 params[0..2].map(&:to_i) + [params[3].to_sym] end end end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_filter :init before_filter :handle_cookies def handle_cookies # Do whatever it is you want to do with your cookies #@barcode = cookies[:barcode] @barcode = request.cookies['barcode'] #@barcode = 'HelloMiffy' end private def init if (request.env['HTTP_USER_AGENT'].include?('6040')) @viewport = 'user-scalable=0, initial-scale=1, target-densitydpi=283' else @viewport = 'user-scalable=0, initial-scale=1, target-densitydpi=285' end I18n.locale = params[:locale] || I18n.default_locale end end
#Questions #1. How do I construct proper password confirmation and validation? #2. How to create proper views/errors for when a signup field is left blank or a password is incorrect class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception helper_method :current_user helper_method :page helper_method :navigation def current_user if session[:user_id] User.find_by(id: session[:user_id]) rescue nil end end def login_required unless current_user flash[:error] = "You must be logged in to do that!" session[:redirect] = request.url redirect_to login_path end end def page @page || '' end def navigation @navigation || 'layouts/navigation' end end
def no_dupes?(arr) singles = [] until arr.empty? ele = arr.shift if arr.include?(ele) arr.delete(ele) else singles << ele end end singles end # Write a method no_dupes?(arr) that accepts an array as an arg and returns an new array containing the elements that were not repeated in the array. # Examples # p no_dupes?([1, 1, 2, 1, 3, 2, 4]) == [3, 4] # p no_dupes?(['x', 'x', 'y', 'z', 'z']) == ['y'] # p no_dupes?([true, true, true]) == [] def no_consecutive_repeats?(arr) (0...(arr.length - 1)).none? do |idx| arr[idx] == arr[idx + 1] end end # Write a method no_consecutive_repeats?(arr) that accepts an array as an arg. The method should return true if an element never appears consecutively in the array; it should return false otherwise. # # Examples # p no_consecutive_repeats?(['cat', 'dog', 'mouse', 'dog']) == true # p no_consecutive_repeats?(['cat', 'dog', 'dog', 'mouse']) == false # p no_consecutive_repeats?([10, 42, 3, 7, 10, 3]) == true # p no_consecutive_repeats?([10, 42, 3, 3, 10, 3]) == false # p no_consecutive_repeats?(['x']) == true def char_indices(str) char_idx_hash = Hash.new { |hash, key| hash[key] = [] } str.chars.each_with_index { |char, idx| char_idx_hash[char] << idx } char_idx_hash end # Write a method char_indices(str) that takes in a string as an arg. The method should return a hash containing characters as keys. The value associated with each key should be an array containing the indices where that character is found. # # Examples # p char_indices('mississippi') == {"m"=>[0], "i"=>[1, 4, 7, 10], "s"=>[2, 3, 5, 6], "p"=>[8, 9]} # p char_indices('classroom') == {"c"=>[0], "l"=>[1], "a"=>[2], "s"=>[3, 4], "r"=>[5], "o"=>[6, 7], "m"=>[8]} def longest_streak(str) counter_hash = Hash.new { |hash, key| hash[key] = 0 } str.chars { |char| counter_hash[char] += 1 } longest = counter_hash.sort { |a, b| a[1] <=> b[1] }.last longest[0] * longest[1] end # Write a method longest_streak(str) that accepts a string as an arg. The method should return the longest streak of consecutive characters in the string. If there are any ties, return the streak that occurs later in the string. # # Examples # p longest_streak('a') == 'a' # p longest_streak('accccbbb') == 'cccc' # p longest_streak('aaaxyyyyyzz') == 'yyyyy' # p longest_streak('aaabbb') == 'bbb' # p longest_streak('abc') == 'c' def bi_prime?(num) (2...num).any? do |int1| (2...num).any? do |int2| both_prime?(int1, int2) && (int1 * int2 == num) end end end def both_prime?(num1, num2) return false if num1 < 2 || num2 < 2 (2...num1).none? { |factor| num1 % factor == 0 } && (2...num2).none? { |factor| num2 % factor == 0 } end # Write a method bi_prime?(num) that accepts a number as an arg and returns a boolean indicating whether or p not the number is a bi-prime. A bi-prime is a positive integer that can be obtained by multiplying two prime numbers. # # Examples # p bi_prime?(14) == true # p bi_prime?(22) == true # p bi_prime?(25) == true # p bi_prime?(94) == true # p bi_prime?(24) == false # p bi_prime?(64) == false # p both_prime?(2, 2) == true # p both_prime?(3, 4) == false # p both_prime?(9, 7) == false # p both_prime?(31, 47) == true def vigenere_cipher(str, arr) alpha = ("a".."z").to_a str.chars.each_with_index do |char, idx| key = arr[idx % arr.length] alpha_idx = alpha.index(char) new_char = alpha[(alpha_idx + key) % 26] str[idx] = new_char end str end # Write a method vigenere_cipher(message, keys) that accepts a string and a key-sequence as args, returning the encrypted message. Assume that the message consists of only lowercase alphabetic characters. # Examples # p vigenere_cipher("toerrishuman", [1]) == "upfssjtivnbo" # p vigenere_cipher("toerrishuman", [1, 2]) == "uqftsktjvobp" # p vigenere_cipher("toerrishuman", [1, 2, 3]) == "uqhstltjxncq" # p vigenere_cipher("zebra", [3, 0]) == "ceerd" # p vigenere_cipher("yawn", [5, 1]) == "dbbo" def vowel_rotate(str) last_vowel = str[str.rindex(/[aeiou]/)] str.chars.each_with_index do |char, idx| if 'aeiou'.include?(char) str[idx] = last_vowel last_vowel = char end end str end # Write a method vowel_rotate(str) that accepts a string as an arg and returns the string where every vowel is replaced with the vowel the appears before it sequentially in the original string. The first vowel of the string should be replaced with the last vowel. # # Examples # p vowel_rotate('computer') == "cempotur" # p vowel_rotate('oranges') == "erongas" # p vowel_rotate('headphones') == "heedphanos" # p vowel_rotate('bootcamp') == "baotcomp" # p vowel_rotate('awesome') == "ewasemo"
class ReportsController < ApplicationController def viewofficers if session[:logged_in].nil? redirect_to home_404_path return end @OFFICERS = Officer.order(Order: :asc) reports = Report.order(Officer_ID: :asc) statuses = Status.all @REPORTS = [] for i in reports for j in @OFFICERS if i.Officer_ID == j.id @REPORTS += [statuses[i.Status].Type] break end end end end def reviewreport if session[:logged_in].nil? redirect_to home_404_path return end report = Report.find_by(officer: params[:officer]).text @who = params[:officer] n = report.length ofc = Report.find_by(officer: @who) if report[n-1] == '*' || report[n-1] == '#' || report[n-2] == '*' || report[n-2] == '#' || report[n-3] == '#' || report[n-3] == '*' @report = "Error: the last 3 characters of your report can't be * or #. Please go back and change that." report += "\nPlease make the last 3 characters not * or #" ofc.text = report elsif report.include?("****") || report.include?("####") report.gsub("****", '') report.gsub("####", '') ofc.text = report @report = "Error: I found \"****\" or \"####\" in your report. Please go back and change that." else ofc.text = report f = Format.new @report = f.format(report) end ofc.save end def minutes #Get people with no reports @noReportOfficers = Report.where(noreport: true) #Get people with reports and segregate by h officer or not. f = Format.new @formattedHReports = [] @hasReportHOfficers = [] unformattedHReports = Report.where(noreport: false, h_officer: true) for i in unformattedHReports @formattedHReports << f.format(i.text) @hasReportHOfficers << i.officer end @formattedNonHReports = [] @hasReportNonHOfficers = [] unformattedNonHReports = Report.where(noreport: false, h_officer: false) for i in unformattedNonHReports @formattedNonHReports << f.format(i.text) @hasReportNonHOfficers << i.officer end @newbusiness = f.format(Business.find_by(id: 1).text) @oldbusiness = f.format(Business.find_by(id: 2).text) end def edit if session[:logged_in].nil? redirect_to home_404_path return else @officer = Officer.find_by(Name: params[:officer]) @report = Report.find_by(Officer_ID: @officer.id) end def new if session[:logged_in].nil? redirect_to home_404_path end end def save if session[:logged_in].nil? redirect_to home_404_path end r = Report.find_by(officer: params[:officer]) r.text = params[:currentReport] reportStatus = params[:noreport] #For some reason, the noreport button is nil when false. So this works. if reportStatus.nil? r.noreport = false else r.noreport = true end r.save redirect_to reports_minutes_path end def help if session[:logged_in].nil? redirect_to home_404_path end end def edit_business @new_business = Business.find_by(id: 1) end def save_business x = Business.find_by(id: 1) x.text = params[:new_business] x.save redirect_to reports_viewofficers_path end def increment_week Report.update_all(noreport: false) newBusiness = Business.find_by(id: 1) oldBusiness = Business.find_by(id: 2) oldBusiness.text = newBusiness.text newBusiness.text = "" oldBusiness.save newBusiness.save redirect_to root_path end end end
#!/usr/bin/env ruby require 'test/unit' require 'fileutils' require 'rake' require 'test/filecreation' require 'test/capture_stdout' ###################################################################### class TestTask < Test::Unit::TestCase include CaptureStdout include Rake def setup Task.clear end def test_create arg = nil t = intern(:name).enhance { |task| arg = task; 1234 } assert_equal "name", t.name assert_equal [], t.prerequisites assert t.prerequisites.is_a?(FileList) assert t.needed? t.execute assert_equal t, arg assert_nil t.source assert_equal [], t.sources end def test_invoke runlist = [] t1 = intern(:t1).enhance([:t2, :t3]) { |t| runlist << t.name; 3321 } t2 = intern(:t2).enhance { |t| runlist << t.name } t3 = intern(:t3).enhance { |t| runlist << t.name } assert_equal [:t2, :t3], t1.prerequisites t1.invoke assert_equal ["t2", "t3", "t1"], runlist end def test_dry_run_prevents_actions Rake.application.options.dryrun = true runlist = [] t1 = intern(:t1).enhance { |t| runlist << t.name; 3321 } out = capture_stdout { t1.invoke } assert_match(/execute .*t1/i, out) assert_match(/dry run/i, out) assert_no_match(/invoke/i, out) assert_equal [], runlist ensure Rake.application.options.dryrun = false end def test_tasks_can_be_traced Rake.application.options.trace = true t1 = intern(:t1) { |t| runlist << t.name; 3321 } out = capture_stdout { t1.invoke } assert_match(/invoke t1/i, out) assert_match(/execute t1/i, out) ensure Rake.application.options.trace = false end def test_no_double_invoke runlist = [] t1 = intern(:t1).enhance([:t2, :t3]) { |t| runlist << t.name; 3321 } t2 = intern(:t2).enhance([:t3]) { |t| runlist << t.name } t3 = intern(:t3).enhance { |t| runlist << t.name } t1.invoke assert_equal ["t3", "t2", "t1"], runlist end def test_find task :tfind assert_equal "tfind", Task[:tfind].name ex = assert_raises(RuntimeError) { Task[:leaves] } assert_equal "Don't know how to build task 'leaves'", ex.message end def test_defined assert ! Task.task_defined?(:a) task :a assert Task.task_defined?(:a) end def test_multi_invocations runs = [] p = proc do |t| runs << t.name end task({:t1=>[:t2,:t3]}, &p) task({:t2=>[:t3]}, &p) task(:t3, &p) Task[:t1].invoke assert_equal ["t1", "t2", "t3"], runs.sort end def test_task_list task :t2 task :t1 => [:t2] assert_equal ["t1", "t2"], Task.tasks.collect {|t| t.name} end def test_task_gives_name_on_to_s task :abc assert_equal "abc", Task[:abc].to_s end def test_symbols_can_be_prerequisites task :a => :b assert_equal ["b"], Task[:a].prerequisites end def test_strings_can_be_prerequisites task :a => "b" assert_equal ["b"], Task[:a].prerequisites end def test_arrays_can_be_prerequisites task :a => ["b", "c"] assert_equal ["b", "c"], Task[:a].prerequisites end def test_filelists_can_be_prerequisites task :a => FileList.new.include("b", "c") assert_equal ["b", "c"], Task[:a].prerequisites end def test_investigation_output t1 = intern(:t1).enhance([:t2, :t3]) { |t| runlist << t.name; 3321 } intern(:t2) intern(:t3) out = t1.investigation assert_match(/class:\s*Rake::Task/, out) assert_match(/needed:\s*true/, out) assert_match(/pre-requisites:\s*--t2/, out) end private def intern(name) Rake.application.define_task(Rake::Task,name) end end
require 'spec_helper' module UniqueSequence describe Generator do let(:generator) { Generator.new } describe "#get_next" do it "should return an array" do generator.get_next.class.should == Array end it "should return [1] as the first sequence" do sequence = generator.get_next sequence.should == [1] end context "last digit not repeated" do it "should return with the last element repeated" do sequence = generator.get_next([1]) sequence.should == [1,1] end it "should return with the second last element incremented and cut the trailing if the last digit is 9" do sequence = generator.get_next([1,9]) sequence.should == [2] end end context "last digit repeated" do it "should return with the last element incremented by 1 appended" do sequence = generator.get_next([1,1]) sequence.should == [1,1,2] end end it "should increment the second last element by 1 and cut the trailing if the digit if the sum is greater than @@SUM" do sequence = generator.get_next([1,1,2,2,3,3]) sequence.should == [1,1,2,2,3,4] end it "should be nil if the sequence is [9]" do sequence = generator.get_next([9]) sequence.should be_nil end end describe "get_all_valid" do it "should return 38 sequences" do sequences = generator.get_all_valid sequences.should have(38).sequences end end end end
class ChangeGoalToBeFloatInUsers < ActiveRecord::Migration[5.2] def change change_column :users, :goal, :float, :null => false, :default => 0 end end
#!/usr/bin/env ruby Server = Struct.new(:index, :size, :value, :row, :col, :group) Row = Struct.new(:index, :size, :free, :cols) Group = Struct.new(:index, :capacity, :servers) class DataCenter attr_reader :lines, :rows, :cols, :occupied, :group_count attr_reader :grid attr_reader :servers attr_reader :groups def initialize(lines) @lines = lines @grid = [] @servers = [] parse_header parse_occupied parse_servers end def parse_header @rows, @cols, @occupied, @group_count, _ = lines[0].split.map(&:to_i) @grid = Array.new(rows) { |i| Row.new(i, cols, cols, Array.new(cols)) } @groups = Array.new(@group_count) { |i| Group.new(i, 0, []) } end def parse_occupied lines[1..occupied].each do |line| r, c = line.split.map(&:to_i) grid[r].cols[c] = :x grid[r].free -= 1 end end def parse_servers lines[(occupied + 1)..lines.size].each_with_index do |line, idx| servers << Server.new(idx, *line.split.map(&:to_i)) end end def magic servers.sort_by! { |s| [-1.0 * s.value / s.size, s.size] } servers.each do |server| place_server server end distribute_servers output end def place_server(server) grid.sort_by(&:free).each do |row| (row.size - server.size + 1).times do |i| can_be_placed = true server.size.times do |j| can_be_placed &&= row.cols[i+j] == nil end if can_be_placed server.size.times do |j| row.cols[i+j] = server.index end server.row = row.index server.col = i row.free -= server.size return row.index end end end end def placed_servers servers.select { |s| s.row && s.col } end def distribute_servers placed_servers.sort_by { |s| [-s.value, s.size] }.each do |server| group = groups.min_by do |g| c = g.servers.select { |s| s.row == server.row }.inject(0) { |a,s| a + s.value } g.capacity + c end server.group = group.index group.servers << server compute_capacity group end end def compute_capacity(group) group.capacity = rows.times.map do |i| servs = group.servers.select { |s| s.row != i } servs.inject(0) { |a,s| a + s.value } end.max end def output score = groups.map do |g| rows.times.map do |i| g.servers.select { |s| s.row != i }.inject(0) { |a,s| a + s.value } end.min end.min $stderr.puts "Score: #{score}" servers.sort_by(&:index).each do |server| if server.group puts "#{server.row} #{server.col} #{server.group}" else puts "x" end end end end DataCenter.new(ARGF.read.split("\n")).magic
# Based on code from https://github.com/cmaclell/Basic-Tweet-Sentiment-Analyzer ############################################################################# # Copyright: Christopher MacLellan 2010 # Description: This code adds functions to the string class for calculating # the sentivalue of strings. It is not called directly by the # tweet-search-sentiment.rb program but is included for possible # future use. # # 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, see <http://www.gnu.org/licenses/>. ############################################################################# # # In an initializer, you can initialize some global defaults: # # Sentimental.load_defaults # Sentimental.threshold = 0.1 # # Then create an instance for usage: # # analyzer = Sentimental.new # analyzer.get_sentiment('I love your service') # => :positive # # You can make new analyzers with individual thresholds: # # analyzer = Sentimental.new(0.9) # analyzer.get_sentiment('I love your service') # => :positive # analyzer.get_sentiment('I like your service') # => :neutral # class Sentimental @@sentihash = Hash.new(0.0) @@threshold = 0.0 def initialize(threshold = nil) @threshold = threshold || @@threshold end ##################################################################### # Function that returns the sentiment value for a given string. # This value is the sum of the sentiment values of each of the words. # Stop words are NOT removed. # # return:float -- sentiment value of the current string ##################################################################### def get_score(string) sentiment_total = 0.0 # tokenize the string, also throw away some punctuation tokens = string.to_s.downcase.split(/\W*\s+\W*|^\W+|\W+$/) tokens.each do |token| sentiment_total += @@sentihash[token] end sentiment_total end def get_sentiment(string) score = get_score(string) # if less then the negative threshold classify negative if score < (-1 * @threshold) :negative # if greater then the positive threshold classify positive elsif score > @threshold :positive else :neutral end end # Loads the default sentiment files def self.load_defaults load_senti_file(File.dirname(__FILE__) + '/sentiwords.txt') load_senti_file(File.dirname(__FILE__) + '/sentislang.txt') end ##################################################################### # load the specified sentiment file into a hash # # filename:string -- name of file to load # sentihash:hash -- hash to load data into # return:hash -- hash with data loaded ##################################################################### def self.load_senti_file(filename) # load the word file file = File.new(filename) while (line = file.gets) parsedline = line.chomp.split(/\s/) sentiscore = parsedline[0] text = parsedline[1] @@sentihash[text] = sentiscore.to_f end file.close end def self.threshold=(threshold) @@threshold = threshold end end
class AddTotalPriceToTransactions < ActiveRecord::Migration[6.0] def change add_column :transactions, :total_price, :float end end
require 'test_helper' class ApplicationHelperTest < ActionView::TestCase test "full title helper" do assert_equal full_title, "LinksIn" assert_equal full_title("Help"), "Help | LinksIn" end end
class AddWebPageViewableToCustomers < ActiveRecord::Migration def change add_column :customers, :web_page_viewable, :boolean, default: false; end end
class CreateDeprecatedNotebooks < ActiveRecord::Migration[4.2] def change create_table :deprecated_notebooks do |t| t.integer :notebook_id t.integer :deprecater_user_id t.boolean :disable_usage t.string :reasoning t.text :alternate_notebook_ids, array: true t.timestamps null: false end end end
class CitiesController < ApplicationController skip_before_action :authenticate_user!, only: [:show, :index, :search] def index if params[:query].present? @city = City.where("name ILIKE ?", "%#{params[:query]}%").first if @city return redirect_to city_path(@city) else flash[:alert] = "Impossible de trouver ta ville" return redirect_to root_path end end @price_range = params[:price_range] @activity = params[:activity] @weather = params[:weather] @environment = params[:environment] query_select = <<~SQL *, CASE WHEN price_range = #{@price_range} THEN 10 ELSE 0 END + CASE WHEN activity = '#{@activity}' THEN 1 ELSE 0 END + CASE WHEN weather = '#{@weather}' THEN 1 ELSE 0 END + CASE WHEN environment = '#{@environment}' THEN 10 ELSE 0 END AS score SQL @cities = City.select(query_select).order('score DESC').limit(3) end def show @city = City.find(params[:id]) @pois = @city.pois if user_signed_in? @favorite_city = current_user.favorite_cities.find_by(city_id: @city.id) end end def search # if params[:query].present? # @cities = City.where("name ILIKE ?", "%#{params[:query]}%") # else @cities = City.all # end end end
# ハッシュとはキーと値の組み合わせでデータを管理するオブジェクトのこと # 配列とは複数のデータをまとめて格納できるオブジェクトのこと # ハッシュは {}で囲われていて、配列は[]で囲われている ## 具体例 a = {'japan' => 'yen', 'us' => 'dollar'} puts a #⇛ {"japan"=>"yen", "us"=>"dollar"} ### japanがキーにあたり、yenが値となる。 ## 要素の追加、変更、取得 ## 追加 ### ハッシュ[キー] = 値 で追加可能 ### ハッシュaにitalyというキーでeuroという値を追加する処理 a['italy'] = 'euro' puts a #⇛{"japan"=>"yen", "us"=>"dollar", "italy"=>"euro"} ### すでに要素が存在している場合は上書きされる a['japan'] = '円' puts a #⇛{"japan"=>"円", "us"=>"dollar", "italy"=>"euro"} ## 取得 ### ハッシュ[キー] で値の取得可能 a['japan'] puts a['japan'] #⇛円 ## ハッシュを使った繰り返し処理 ### eachメソッドを使うと、キーと値の組み合わせを順に取り出せる a = {'japan' => 'yen', 'us' => 'dollar', 'italy' => 'euro'} a.each do |key, value| puts "#{key}:#{value}" end #⇛ japan:yen #⇛ us:dollar #⇛ italy:euro ## ハッシュの同値比較、要素数の取得、要素の削除 ## ハッシュの同値比較 ### == でハッシュ同士を比較できる a = {'x' => 1, 'y' => 2, 'z' => 3} b = {'x' => 1, 'y' => 2, 'z' => 3} c = {'y' => 2, 'z' => 3, 'x' => 1} d = {'x' => 10, 'y' => 20, 'z' => 30} # キーも値も同じであるためtrueが返る puts a == b #⇛ true # 順番は違うけれどキーも値も同じであるためtrueが返る puts a == c #⇛ false # キーと値が異なるためfalseが返る puts a == d #⇛ true ## 要素数の取得 ### sizeメソッド(lengthメソッド)を使えばハッシュの要素の個数を調べられる puts a.size #⇛3 puts a.length #⇛3 ## 要素の削除 ### deleteメソッドで指定したキーに対応する要素を削除できる a.delete('x') puts a #⇛{"y"=>2, "z"=>3} # シンボル ## シンボルは、ソース上では文字列のように見え、内部では整数として扱われる、両者を仲立ちするような存在です。(リファレンスより) ### 特徴として、内部で整数として扱われるため処理が文字列よりも高速 ### 同じシンボルであれば、全く同じオブジェクトであると判別するためメモリの使用効率がよくなる # 確認 puts :apple.object_id #⇛899868 puts :apple.object_id #⇛899868 puts :apple.object_id #⇛899868 puts "apple".object_id #⇛70126019934900 puts "apple".object_id #⇛70126019934840 puts "apple".object_id #⇛70126019934780 ### シンボルはいイミュータブルであるため、破壊的な変更はできない、つまり何か勝手に変更されるリスクがない。 a = "apple" puts a.upcase! #⇛APPLE 文字列だと変更される a = :apple #puts a.upcase! #⇛undefined method `upcase!' シンボルだとエラーになる ## ハッシュのキーにシンボルを使う ### その際は シンボル:値 という記法になる事に注意! a = {japan:'yen', us:'dollar'} #⇛{:japan=>:yen, :us=>:dollar} ### キーも値もシンボルである場合は以下のようになる a = {japan: :yen, us: :dollar} #⇛{:japan=>:yen, :us=>:dollar} # %記法でシンボルやシンボルの配列を作成する a = :apple puts a ## 上記は以下のように書き換えられる ## !は区切り文字につかう puts %s!apple! ## シンボルの配列を作成するときは %i を使うことが可能、この時空白文字が要素の区切りになる puts %i(apple orange grape) #⇛[:apple, :orange, :grape] ### deviseなどで独自のカラムを追加する時などに使える。 ## devise_parameter_sanitizer.permit(:sign_up, keys: [:hoge, :hoge])は以下のようになる ## devise_parameter_sanitizer.permit(:sign_up, keys: %i(hoge hoge))
# This class stores information about drawing class Drawing def self.give_me_a_circle Circle.new end # The class of line class Line end # The class circle class Circle # Create title circle def what_am_i "This is a circle" end end end a = Drawing.give_me_a_circle puts a.what_am_i a = Drawing::Circle.new puts a.what_am_i Pi = 3.141592 class OtherPlanet Pi = 4.5 def self.circumference_of_circle(radius) radius * 2 * Pi end end puts OtherPlanet.circumference_of_circle(10) puts OtherPlanet::Pi puts Pi
class UsersController < ApplicationController before_filter :authenticate_user! def index authorize! :index, @user, :message => 'Not authorized as an administrator.' @users = User.all end def show end def update authorize! :update, @user, :message => 'Not authorized as an administrator.' @user = User.find(params[:id]) if @user.update_attributes(params[:user], :as => :admin) redirect_to users_path, :notice => "User updated." else redirect_to users_path, :alert => "Unable to update user." end end def destroy authorize! :destroy, @user, :message => 'Not authorized as an administrator.' user = User.find(params[:id]) unless user == current_user user.destroy redirect_to users_path, :notice => "User deleted." else redirect_to users_path, :notice => "Can't delete yourself." end end def finish_signup if request.patch? && params[:user] #&& params[:user][:email] if current_user.update(user_params) sign_in(current_user, :bypass => true) # Notifier.send_signup_email(@user).deliver redirect_to root_path, notice: 'Your profile was successfully updated.' else @show_errors = true end end end private def set_user @user = User.find(params[:id]) end def user_params accessible = [ :name, :email ] # extend with your own params accessible << [ :password, :password_confirmation ] unless params[:user][:password].blank? params.require(:user).permit(accessible) end end
class Image < ActiveRecord::Base require 'open-uri' # OpenURI::Buffer::StringMax = 10240 OpenURI::Buffer::StringMax = 0 belongs_to :gallery after_save :create_dimensioned after_destroy :delete_image validate :check_format def file= (f) self.original_filename = f.original_filename @file = f end def file return @file end def self.unaltered_file return 'original' end def check_format errors.add_on_empty 'name' if !(self.file.kind_of? ActionDispatch::Http::UploadedFile) errors.add :base, 'No file selected.' return end meta = `#{IMAGE_MAGICK_PATH}/identify -format %m,%w,%h #{self.file.path} 2>&1` meta_strs = meta.split(',') self.width = meta_strs[1].to_i self.height = meta_strs[2].to_i if !meta_strs || !(meta_strs[0] == 'JPEG' || meta_strs[0] == 'PNG') || self.height <= 0 || self.width <= 0 errors.add :base, 'Data contains errors or is not a supported format.' end end def create_dimensioned gallery = Gallery.find(self.gallery_id) temp_path = self.file.path base_path = "#{Gallery.absolute_path}/#{gallery.holder}/#{gallery.id.to_s}/#{self.id.to_s}" FileUtils.mkdir_p(base_path) # keep original copy original_path = "#{base_path}/#{Image.unaltered_file}.jpg" FileUtils.cp(temp_path, original_path) dims = gallery.dimensions dims.each do |dim| self.create_with_dimension(dim) end end def delete_image base_path = "#{Gallery.absolute_path}/#{gallery.holder}/#{gallery.id.to_s}/#{self.id.to_s}" FileUtils.remove_entry_secure(base_path) end def create_with_dimension(dimension) gallery = Gallery.find(self.gallery_id) base_path = "#{Gallery.absolute_path}/#{gallery.holder}/#{gallery.id.to_s}/#{self.id.to_s}" dim_name = dimension.name.gsub(/[\s]/,"_").gsub(/[\W]/,"").downcase dest_path = "#{base_path}/#{dim_name}.jpg" src_path = "#{base_path}/#{Image.unaltered_file}.jpg" FileUtils.cp(src_path, dest_path) base_command = "#{IMAGE_MAGICK_PATH}/convert \"#{dest_path}\"" if dimension.crop? if dimension.resize? if dimension.aspect aspect_ratio = dimension.aspect elsif dimension.height && dimension.width aspect_ratio = (dimension.width.to_f / dimension.height.to_f) end crop_width = (self.height * aspect_ratio).round crop_height = (self.width * (1/aspect_ratio)).round else if dimension.aspect crop_width = (self.height * dimension.aspect).round crop_height = (self.width * (1/dimension.aspect)).round else if dimension.width && !dimension.height crop_width = dimension.width crop_height = self.height elsif !dimension.width && dimension.height crop_width = self.width crop_height = dimension.height elsif dimension.width && dimension.height crop_width = dimension.width crop_height = dimension.height end end end y_offset = 0 x_offset = 0 if self.height > crop_height y_offset = ((self.height - crop_height)/2).round elsif self.width > crop_width x_offset = ((self.width - crop_width)/2).round end `#{base_command} -crop #{crop_width}x#{crop_height}+#{x_offset}+#{y_offset} "#{dest_path}"` end if dimension.resize? if dimension.width && !dimension.height `#{base_command} -resize #{dimension.width} -quality 100 "#{dest_path}"` elsif !dimension.width && dimension.height `#{base_command} -resize x#{dimension.height} -quality 100 "#{dest_path}"` elsif dimension.width && dimension.height `#{base_command} -resize #{dimension.width}x#{dimension.height}> -quality 100 "#{dest_path}"` end end end def destroy_with_dimension(dimension) gallery = Gallery.find(self.gallery_id) base_path = "#{Gallery.absolute_path}/#{gallery.holder}/#{gallery.id.to_s}/#{self.id.to_s}" dim_name = dimension.name.gsub(/[\s]/,"_").gsub(/[\W]/,"").downcase dest_path = "#{base_path}/#{dim_name}.jpg" FileUtils.rm(dest_path) end def rename_with_dimension(old, new) gallery = Gallery.find(self.gallery_id) base_path = "#{Gallery.absolute_path}/#{gallery.holder}/#{gallery.id.to_s}/#{self.id.to_s}" old_name = old.name.gsub(/[\s]/,"_").gsub(/[\W]/,"").downcase new_name = new.name.gsub(/[\s]/,"_").gsub(/[\W]/,"").downcase old_path = "#{base_path}/#{old_name}.jpg" new_path = "#{base_path}/#{new_name}.jpg" FileUtils.mv(old_path, new_path) end def tag(dim_name = Image.unaltered_file, options = {}) gallery = Gallery.find(self.gallery_id) image_path = self.src(dim_name, gallery) return "<img src=\"#{image_path}\" alt=\"#{self.name}\" />" end def src(dim_name = Image.unaltered_file, gallery = nil) if !gallery gallery = Gallery.find(self.gallery_id) end if (dim_name.downcase <=> Image.unaltered_file) == 0 image_name = Image.unaltered_file else image_name = dim_name.gsub(/[\s]/,"_").gsub(/[\W]/,"").downcase end return "#{Gallery.relative_path}/#{gallery.holder}/#{gallery.id.to_s}/#{self.id.to_s}/#{image_name}.jpg" end def holder(gallery = nil) if !gallery gallery = Gallery.find(self.gallery_id) end return gallery.holder_type.pluralize.downcase end end
class CreateMessageAttachmentOverlays < ActiveRecord::Migration def change create_table :message_attachment_overlays do |t| t.string :one_to_one_id t.column :message_id, 'CHAR(10)', null: false t.string :overlay, :uuid, null: false t.integer :file_size, null: false t.timestamps t.index :one_to_one_id t.index :message_id end end end
class Picture < ApplicationRecord belongs_to :item has_attached_file :image, styles: { high: "1260x900#", medium: "560x400#", thumb: "200x200#" }, default_url: ":style/missing_item_image.jpg" validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/ end
require 'test_helper' class Finance::Provider::InvoicesControllerTest < ActionDispatch::IntegrationTest setup do @cinstance = FactoryBot.create(:cinstance) @buyer = @cinstance.buyer_account @provider_account = @cinstance.provider_account @provider_account.create_billing_strategy @provider_account.settings.allow_finance! # @provider_account.settings.allow_finance # @provider_account.settings.show_finance login_provider @provider_account end context 'InvoicesController' do should 'list all invoices' do get admin_finance_account_invoices_path @buyer assert_response :success assert_template 'finance/provider/invoices/index' assert_not_nil assigns(:invoices) assert_active_menus({main_menu: :audience, submenu: :finance, sidebar: :invoices, topmenu: :dashboard}) end should 'list invoices by month' do get admin_finance_invoices_path @buyer, month: '2009-11' assert_response :success assert_template 'finance/provider/invoices/index' end context 'with existing Invoice' do setup do @invoice = FactoryBot.create(:invoice, :buyer_account => @cinstance.buyer_account, :provider_account => @cinstance.provider_account) Invoice.any_instance.stubs(:find).returns(@invoice) end should 'show' do get admin_finance_invoice_path @invoice assert_response :success assert_equal @invoice, assigns(:invoice) assert_active_menus({main_menu: :audience, submenu: :finance, sidebar: :invoices, topmenu: :dashboard}) end should 'show without buyer_account' do # Invoice should be settled before destroying buyer account @invoice.issue_and_pay_if_free! @invoice.buyer_account.destroy! get admin_finance_invoice_path @invoice assert_response :success assert_active_menus({main_menu: :audience, submenu: :finance, sidebar: :invoices, topmenu: :dashboard}) end should 'edit' do get edit_admin_finance_invoice_path @invoice assert_response :success assert_equal @invoice, assigns(:invoice) assert_active_menus({main_menu: :audience, submenu: :finance, sidebar: :invoices, topmenu: :dashboard}) end should 'update' do put admin_finance_invoice_path @invoice assert_response :redirect assert_equal @invoice, assigns(:invoice) end [ :cancel, :pay, :generate_pdf, :charge ].each do |action| should "respond to AJAX action #{action}" do Invoice.any_instance.stubs("transition_allowed?").returns(true) Invoice.any_instance.stubs("#{action}!").returns(true) put url_for([action, :admin, :finance, @invoice]), :format => 'js' assert_response :success end should "handle '#{action}' action failure" do Invoice.any_instance.stubs("transition_allowed?").returns(true) Invoice.any_instance.stubs("#{action}!").returns(false) put url_for([action, :admin, :finance, @invoice]), :format => 'js' assert_response :success # TODO: update error messages end end context 'with line items' do setup do @line_item = FactoryBot.create(:line_item, :invoice => @invoice, cost: 2000) end should 'show with current invoice renders link to add custom line item' do Invoice.any_instance.stubs(:current?).returns(true) get admin_finance_invoice_path @invoice assert_response :success end should 'show with past invoice does not render link to add custom line item' do Invoice.any_instance.stubs(:editable?).returns(false) get admin_finance_invoice_path @invoice assert_response :success end should 'show with past invoice does not render button to delete custom line item' do Invoice.any_instance.stubs(:editable?).returns(false) get admin_finance_invoice_path @invoice assert_response :success end should 'show with open invoice renders button to delete custom line item' do Invoice.any_instance.stubs(:editable?).returns(true) get admin_finance_invoice_path @invoice assert_response :success end end end end test '#charge does not invoke invoice automatic charging' do invoice = FactoryBot.create(:invoice, buyer_account: @buyer, provider_account: @provider_account) Invoice.any_instance.stubs('transition_allowed?').returns(true) Invoice.any_instance.expects(:charge!).with(false).returns(true) put charge_admin_finance_invoice_path invoice, format: :js assert_response :success end end
require 'spec_helper' describe Sinatra::Hal do def app Sinatra.new do helpers Sinatra::Hal get "/" do hal_links do link :self, "/" link :people, "/people" end end get("/people/1") do hal Person.new end get("/people") do hal [ Person.new ] end end end def response_should_eq(expected) begin JSON.parse(last_response.body).should eq(expected) rescue JSON::ParserError fail "Invalid JSON response: #{last_response.body}" end last_response.content_type.should eq "application/hal+json" end describe "#hal" do describe "when is an object" do let(:expected_json) do { "name" => "Some Name", "age" => 20, "_links" => { "self" => { "href" => "/person/1" } } } end it "returns an application/hal+json response" do get "/people/1" response_should_eq expected_json end end describe "when is object respond_to :each method" do let(:expected_json) do [ { "name" => "Some Name", "age" => 20, "_links" => { "self" => { "href" => "/person/1" } } } ] end it "returns an array as application/hal+json response" do get "/people" response_should_eq expected_json end end end describe "hal_links" do let(:expected_hash) do { "_links" => { "self" => { "href" => "/" }, "people" => { "href" => "/people" } } } end it "returns a json with links" do get "/" response_should_eq expected_hash end end end
class SessionsController < ApplicationController def new redirect_to '/desk' and return if is_logged? @session = Session.new end def create redirect_to users_path and return if is_logged? @session = Session.new(session_params) if antiflood if @session.valid? user = User.find_by_id!(@session.id) unless user.activated flash[:warning] = t('sessions.create.activation') render 'new' return end if user.blocked flash[:alert] = t('sessions.create.block') render 'new' return end session[:user] = Hash.new session[:user][:id] = user.id session[:user][:nickname] = user.nickname session[:user][:level] = user.level flash[:success] = t('sessions.create.success') redirect_to '/desk' else flash.now[:alert] = t('sessions.create.fail') render 'new' end else render 'new' end end def destroy redirect_to '/desk' and return unless is_logged? session[:user] = false flash[:info] = t('sessions.destroy.success') redirect_to action: 'new' end private def session_params params.require(:session).permit(:nickname, :password) end end
# Methods for DB-Handling # Communication with DB get '/collections/?' do content_type :json settings.mongo_db.database.collection_names.to_json end # Finding Records # list all Doc in the test collection get '/documents/?' do content_type :json settings.mongo_db.find.to_a.to_json end #find a document by its ID get '/document/:id/?' do content_type :json document_by_id(params[:id]) end # insert a new document from request parameters, # then return the full doc post '/new_document/?' do content_type :json db = settings.mongo_db result = db.insert_one params db.find(:_id => result.inserted_id).to_a.first.to_json end # update the doc specified by :id, setting just its # name attribute to params[:name], then return the full # doc put '/update_name/:id/?' do content_type :json id = object_id(params[:id]) name = params[:name] settings.mongo_db.find(:_id => id).find_one_and_update('$set' => {:name => name}) document_by_id(id) end # delete specified doc and return success delete '/remove/:id' do content_type :json db = settings.mongo_db id = object_id(params[:id]) documents = db.find(:_id => id) if !documents.to_a.first.nil? documents.find_one_and_delete {:success => true}.to_json else {:success => false}.to_json end end
module KeyConcern extend ActiveSupport::Concern included do after_initialize :add_key def add_key self.key ||= SecureRandom.hex end end end
class DatePicker < SimpleForm::Inputs::DatePicker def input(wrapper_options) template.content_tag(:div, super) end end
class Oystercard attr_reader :balance, :entry_station, :journey_history DEFAULT_BALANCE = 0 MINIMUM_AMOUNT = 1 MAX_CAPACITY = 90 def initialize(balance = DEFAULT_BALANCE) @balance = balance @in_use = false @journey_history = [] end def top_up(amount) raise "amount more than 90" if @balance >= MAX_CAPACITY @balance += amount end def touch_in(entry_station) raise "not enough amount on card" if @balance < MINIMUM_AMOUNT @entry_station = entry_station "Welcome to #{entry_station}" end def touch_out(exit) deduct(MINIMUM_AMOUNT) @entry_station = nil @journey_history << {entry: @entry_station, exit: exit} "touching out" end def in_journey? @entry_station != nil ? true : false end private def deduct(amount) @balance -= amount "money deducted" end end
# frozen_string_literal: true class AuthenticationService < BaseService private attr_reader :headers def initialize(headers) @headers = headers @user = nil end def payload return unless token_present? @data = user if user end def user @user ||= User.find_by(id: user_id) @user || errors.add(:token, I18n.t('decode_authentication_command.token_invalid')) && nil end def token_present? token.present? && token_payload.present? end def token return auth_header.split(' ').last if auth_header.present? errors.add(:token, I18n.t('decode_authentication_command.token_missing')) nil end def auth_header headers['Authorization'] end def token_payload @token_payload ||= begin decoded = Api::JwtTokenGenerator.decode(token) errors.add(:token, I18n.t('decode_authentication_command.token_expired')) unless decoded decoded end end def user_id token_payload['user_id'] end end