text
stringlengths
10
2.61M
Rails.application.routes.draw do root "home#index" get :login, to: "sessions#new", as: :login post :login, to: "sessions#create" delete :logout, to: "sessions#destroy", as: :logout get :register, to: "users#new", as: :register post :register, to: "users#create" resources :users, only: %i(new create) resources :user_csvs, only: %i(index new create show destroy) end
require 'spec_helper' describe Player do describe '#initialize' do it 'creates a player object with a readable name and a readable array for holding cards' do my_player = Player.new(name: "John") expect(my_player.name).to eq "John" expect(my_player.cards).to eq [] end it 'defaults to Anonymous if no name is given' do my_player = Player.new() expect(my_player.name).to eq "Anonymous" end end context 'player with a full deck' do let(:player) do deck = Deck.new(type: 'regular') deck.shuffle player = Player.new(name: "Magic Mark") deck.cards.each { |card| player.add_card(card) } player end describe '#play_next_card' do it 'returns the players top card' do card_expected = player.cards[0] card_played = player.play_next_card expect(card_played).to eq card_expected end it 'removes the card from the players cards' do count = player.count_cards player.play_next_card expect(player.count_cards).to eq count - 1 end it 'does nothing if the player is out of cards' do player.play_next_card until player.out_of_cards? expect(player.play_next_card).to eq nil end end describe '#collect_winnings' do it 'collects all the winnings from a particular play and adds the cards to the players cards' do cards_played = [] 10.times { cards_played << player.play_next_card } cards_in_hand = player.count_cards player.collect_winnings(cards_played) expect(player.count_cards).to eq cards_in_hand + 10 end end describe '#add_card' do it 'adds a card to the players cards at the bottom' do card = Card.new(rank: "ace", suit: "spades") player.add_card(card) added_card = player.cards.last expect(added_card).to eq card end end describe '#count_cards' do it 'returns the number of cards a player has' do expect(player.count_cards).to eq 52 player.play_next_card expect(player.count_cards).to eq 51 51.times { player.play_next_card } expect(player.count_cards).to eq 0 end end describe '#out_of_cards?' do it 'returns false when the player still has cards' do expect(player.out_of_cards?).to be false end it 'returns true when the player has no more cards' do player.play_next_card until player.count_cards == 0 expect(player.out_of_cards?).to be true end end end end describe NullPlayer do let(:nullplayer) { NullPlayer.new } it 'returns nil when its name is called' do expect(nullplayer.name).to eq nil end it 'returns an empty array when its cards are called' do expect(nullplayer.cards).to eq [] end it 'does not raise an exception when the regular player methods are called' do expect { nullplayer.play_next_card }.to_not raise_exception expect { nullplayer.collect_winnings }.to_not raise_exception expect { nullplayer.add_card }.to_not raise_exception end it 'returns 0 when its cards are counted' do expect(nullplayer.count_cards).to eq 0 end it 'returns true when asked if it is out of cards' do expect(nullplayer.out_of_cards?).to be true end it 'calls all nullplayer objects equal if comparing two nullplayers' do expect(NullPlayer.new == NullPlayer.new).to be true end it 'returns false if comparing the equality of a nullplayer with a player' do expect(NullPlayer.new == Player.new).to be false end end
#encoding: utf-8 # Copyright (c) 2013-2014, Sylvain LAPERCHE # All rights reserved. # License: BSD 3-Clause (http://opensource.org/licenses/BSD-3-Clause) require 'test/unit' require 'netcdf' include NetCDF class TestDataset < Test::Unit::TestCase #--------------# # Dataset::new # #--------------# def test_nonexistent assert_raise NetCDFError do Dataset.new('fairy_file.nc') end end def test_not_NetCDF assert_raise NetCDFError do Dataset.new(__FILE__) end end def test_read_only nc = Dataset.new('test/data/simple.nc') assert_raise NetCDFError do nc.define_mode() end nc.close() end def test_ID nc1 = Dataset.new('test/data/simple.nc') nc2 = Dataset.new('test/data/simple.nc') assert_not_equal(nc1.id, nc2.id) nc1.close() nc2.close() end def test_noclobber nc1 = Dataset.new('test/data/scratch.nc', mode:'w', clobber:false) assert_raise NetCDFError do nc2 = Dataset.new('test/data/scratch.nc', mode:'w', clobber:false) end nc1.close() File.delete('test/data/scratch.nc') end # TODO: Add more tests later (need nc_inq) #---------------------# # Dataset#define_mode # #---------------------# def test_redef_closed nc = Dataset.new('test/data/simple.nc') nc.close() assert_raise NetCDFError do nc.define_mode() end end def test_redef_read_only nc = Dataset.new('test/data/simple.nc') assert_raise NetCDFError do nc.define_mode() end nc.close() end def test_redef_in_define_mode nc = Dataset.new('test/data/scratch.nc', mode:'w', clobber:false) assert_raise NetCDFError do nc.define_mode() end nc.close() File.delete('test/data/scratch.nc') end # TODO: Add more tests later (need functions to add dim & var) #-------------------# # Dataset#data_mode # #-------------------# def test_enddef_closed nc = Dataset.new('test/data/simple.nc') nc.close() assert_raise NetCDFError do nc.data_mode() end end def test_enddef_in_data_mode nc = Dataset.new('test/data/simple.nc') assert_raise NetCDFError do nc.data_mode() end nc.close() end # TODO: Add more tests later (need functions to add dim & var) #---------------# # Dataset#close # #---------------# def test_close_twice nc = Dataset.new('test/data/simple.nc') nc.close() assert_raise NetCDFError do nc.close() end end def test_close_define_mode nc = Dataset.new('test/data/scratch.nc', mode:'w', clobber:false) nc.close() File.delete('test/data/scratch.nc') end def test_close_data_mode nc = Dataset.new('test/data/simple.nc') nc.close() end #--------------# # Dataset#sync # #--------------# def test_sync_closed nc = Dataset.new('test/data/simple.nc') nc.close() assert_raise NetCDFError do nc.sync() end end def test_sync_define_mode nc = Dataset.new('test/data/scratch.nc', mode:'w', clobber:false) assert_raise NetCDFError do nc.sync() end nc.close() File.delete('test/data/scratch.nc') end # TODO: Add more tests later (need functions to add dim & var) #----------------------# # Dataset#define_mode? # #----------------------# def test_on_open nc = Dataset.new('test/data/simple.nc') assert_equal(false, nc.define_mode?) nc.close() end def test_on_create nc = Dataset.new('test/data/scratch.nc', mode:'w', clobber:false) assert_equal(true, nc.define_mode?) nc.close() File.delete('test/data/scratch.nc') end def test_after_redef nc = Dataset.new('test/data/simple.nc', mode:'r+') assert_equal(false, nc.define_mode?) nc.define_mode() assert_equal(true, nc.define_mode?) nc.close() end def test_after_enddef nc = Dataset.new('test/data/scratch.nc', mode:'w', clobber:false) assert_equal(true, nc.define_mode?) nc.data_mode() assert_equal(false, nc.define_mode?) nc.close() File.delete('test/data/scratch.nc') end end
require 'rails_helper' RSpec.describe SqueaksController, type: :controller do describe 'get#index' do it 'renders the squeaks index' do allow(subject).to receive(:logged_in?).and_return(true) # this line mimicks a logged in user get :index # type of request, then action to hit expect(response).to render_template(:index) end end describe 'get#new' do it 'renders form to make a new squeak' do allow(subject).to receive(:logged_in?).and_return(true) get :new expect(response).to render_template(:new) end end describe 'delete#destroy' do let!(:test_squeak) { create :squeak } before :each do allow(subject).to receive(:current_user).and_return(test_squeak.author) # assigns test_squeak author as current_user delete :destroy, params: { id: test_squeak.id } end it 'destroys the squeak' do expect(Squeak.exists?(test_squeak.id)).to be false end it 'redirects to squeaks_url' do expect(response).to have_http_status(302) expect(response).to redirect_to(squeaks_url) end end describe 'post#create' do before :each do create :user allow(subject).to receive(:current_user).and_return(User.last) end let(:valid_params) { { squeak: { body: 'whatever we want', author_id: User.last.id } } } let(:invalid_params) { { squeak: { not_body: 'this is a bad squeak', author_id: User.last.id } } } context 'with valid params' do it 'creates the squeak' do post :create, params: valid_params # sends a post request to create a new squeak using the valid params we defined expect(Squeak.exists?(Squeak.last.id)).to be true end it 'redirects to the squeak show page' do post :create, params: valid_params expect(response).to redirect_to(squeak_url(Squeak.last.id)) end end context 'with invalid params' do before :each do post :create, params: invalid_params end it 'redirects to new_squeak_url' do expect(response).to have_http_status(422) expect(response).to render_template(:new) end it 'adds errors to flash' do expect(flash[:errors]).to be_present end end end end
class ChangeApplicationsToCandidacies < ActiveRecord::Migration[5.2] def change rename_table :applications, :candidacies end end
class CreateStudyListItems < ActiveRecord::Migration def change create_table :study_list_items do |t| t.integer :study_list_id, null: false t.string :front t.string :back t.string :images t.boolean :pav, default: false t.boolean :kav, default: false t.timestamps end end end
require 'rails_helper' describe Report do describe 'workaround parsing bug in Rack or Rails for multi-select box' do it "should handle ['3','4','5']" do Report.list_of_ints_from_multiselect( ['3','4','5'] ).should == [3,4,5] end it "should handle ['3,4,5']" do Report.list_of_ints_from_multiselect( ['3,4,5'] ).should == [3,4,5] end it "should handle ['3']" do Report.list_of_ints_from_multiselect( ['3'] ).should == [3] end it "should handle empty array" do Report.list_of_ints_from_multiselect([]).should == [] end it "should handle nil" do Report.list_of_ints_from_multiselect(nil).should == [] end it "should omit zeros" do Report.list_of_ints_from_multiselect(['3,0,4,5']).should == [3,4,5] end end shared_examples "a valid SQL query" do it "should be valid SQL" do lambda { @r.execute_query }.should_not raise_error end it "should be an array plus bind variables" do @r.query.should be_an(Array) end end describe "SQL query for constraint" do describe "with no constraints" do it_should_behave_like "a valid SQL query" before(:each) do ; @r = Report.new ; end it "should have no bind slots" do @r.query.size.should == 1 end it "should dump the whole customers table" do @r.query.first.should match(/where\s+1\b/i) end end end describe "with output options" do describe "filtering by a single Zip code" do before(:each) do @r = Report.new(:filter_by_zip => "1", :zip_glob => "945") end it_should_behave_like "a valid SQL query" it "should generate a single LIKE constraint" do @r.query.first.should match(/like/i) @r.query.first.should_not match(/like.*like/i) end it "should generate an array with one bind slot" do @r.query.size.should == 2 end it "should fill the single bind slot correctly" do @r.query[1].should match(/945%/) end end describe "specifying zip code but not opting to use it" do it "should not apply the zip code filter" do @r = Report.new(:zip_glob => "945") @r.query.first.should_not match(/945%/) end end describe "filtering by multiple Zip codes" do before(:each) do @r = Report.new(:filter_by_zip => "1", :zip_glob => "945,92") end it_should_behave_like "a valid SQL query" it "should generate two bind slots" do @r.query.size.should == 3 end it "should fill in the bind slots correctly" do @r.query[1].should match(/945%/) @r.query[2].should match(/92%/) end end describe "setting exclude_blacklist" do before(:each) do ; @r = Report.new ; end it_should_behave_like "a valid SQL query" it "to true should specify e_blacklist = 0" do @r.output_options[:exclude_e_blacklist] = true @r.query.first.should match(/e_blacklist\s*=\s*0\b/i) end it "to false should specify e_blacklist = 1" do @r.output_options[:exclude_e_blacklist] = nil @r.query.first.should match(/e_blacklist\s*=\s*1\b/i) end it "if omitted should not try to match on e_blacklist" do @r.query.first.should_not match(/e_blacklist/i) end end describe "setting a nonexistent output option" do it "should be silently ignored" do @r = Report.new(:nonexistent_option => 1) lambda { @r.execute_query }.should_not raise_error end end end end
CitizenshipApp::Application.routes.draw do resources :questions resources :users resources :sessions, only: [:new, :create, :destroy] root 'static_pages#home' match '/signup', to: 'users#new', via: 'get' match '/signin', to: 'sessions#new', via: 'get' match '/signout', to: 'sessions#destroy', via: 'delete' match '/about', to: 'static_pages#about', via: 'get' match '/contact', to: 'static_pages#contact', via: 'get' match "/quizzes", to: 'quizzes#create', via: 'get' match "/quizzes/show/:id", to: 'quizzes#show', via: 'get' match "/quizzes/update/", to: 'quizzes#update', via: 'post' match "/quizzes/results/:id", to: 'quizzes#results', via: 'get' end
require 'couchrest' class Copier def initialize src_db, dst_db @src_db, @dst_db = src_db, dst_db end # copy src_doc and all attachments, dst_doc is the current doc in the dst_db def copy src, old_dst = nil # get source doc if src is a string (key) src_doc = src.is_a?(String) ? @src_db.get(src) : (src.is_a?(Hash) ? CouchRest::Document.new(src) : src) src_doc.database = @src_db # in case it's a hash, not a CouchRest::Document raise "document not found '#{src}'" if src_doc.nil? new_dst = src_doc.clone attachments_changed = false # if src has attachments, check whether they have changed or not if src_doc['_attachments'] if (old_dst.nil? || old_dst["_attachments"] != src_doc['_attachments']) # attachments have changed attachments_changed = true # remove attachments from dst_doc - they are added back later new_dst.delete "_attachments" end end # set the rev to the previous rev or remove it if new old_dst ? (new_dst["_rev"] = old_dst["_rev"]) : (new_dst.delete "_rev") if attachments_changed begin # saving the doc removes all old attachments (if any) # using regular save @dst_db.save_doc(new_dst) # copy attachments one by one src_doc['_attachments'].keys.each {|file| copy_attachment(src_doc, new_dst, file)} # attachment order might not be retained - reload doc again to make sure reloaded_doc = @dst_db.get new_dst['_id'] if (reloaded_doc['_attachments'].keys != src_doc['_attachments'].keys) puts "correcting attachment order..." ordered_attachments = src_doc['_attachments'].keys.inject({}) do |memo, key| memo[key] = reloaded_doc['_attachments'][key] memo end reloaded_doc['_attachments'] = ordered_attachments @dst_db.save_doc(reloaded_doc) end rescue RestClient::Conflict puts "ERROR: document version conflict, skipping..." return end else # use bulk save if attachments have not changed @dst_db.bulk_save_doc(new_dst) end end private def copy_attachment src_doc, dst_doc, filename size = src_doc['_attachments'][filename]['length'].to_i # puts " reading attachment '#{filename}' (#{format_size size}) ..." data = src_doc.fetch_attachment filename # puts " writing attachment '#{filename}' (#{format_size size}) ...'" content_type = src_doc['_attachments'][filename]['content_type'] dst_doc.put_attachment filename, data, { :raw => true, :content_type => content_type, "Content-Encoding" => "gzip", "Accept-Encoding" => "gzip" } end def format_size size_int units = %w{B KB MB GB TB} e = (Math.log(size_int)/Math.log(1024)).floor s = "%.1f" % (size_int.to_f / 1024**e) s.sub(/\.?0*$/, units[e]) end end
# # Testing rufus-verbs # # jmettraux@gmail.com # # Sun Jan 13 12:33:03 JST 2008 # require File.dirname(__FILE__) + '/base.rb' class ItemConditionalTest < Test::Unit::TestCase include TestBaseMixin include Rufus::Verbs def test_0 require 'open-uri' f = open "http://localhost:7777/items" d = f.read f.close assert_equal "{}", d.strip end def test_1 res = get :uri => "http://localhost:7777/items" assert_equal 200, res.code.to_i assert_equal "{}", res.body.strip p res['Etag'] #p res['Last-Modified'] assert res['Etag'].length > 0 assert res['Last-Modified'].length > 0 end def test_2 res = get "http://localhost:7777/items" assert_equal 200, res.code.to_i lm = res['Last-Modified'] etag = res['Etag'] res = get( "http://localhost:7777/items", :headers => { 'If-Modified-Since' => lm }) assert_equal 304, res.code.to_i res = get( "http://localhost:7777/items", :h => { 'If-None-Match' => etag }) assert_equal 304, res.code.to_i res = get( "http://localhost:7777/items", :h => { 'If-Modified-Since' => lm, 'If-None-Match' => etag }) assert_equal 304, res.code.to_i end end
require 'spec_helper' require 'timecop' RSpec.describe Raven::ClientState do let(:state) { Raven::ClientState.new } it 'should try when online' do expect(state.should_try?).to eq(true) end it 'should not try with a new error' do state.failure expect(state.should_try?).to eq(false) end it 'should try again after time passes' do Timecop.freeze(-10) { state.failure } expect(state.should_try?).to eq(true) end it 'should try again after success' do state.failure state.success expect(state.should_try?).to eq(true) end it 'should try again after retry_after' do Timecop.freeze(-2) { state.failure(1) } expect(state.should_try?).to eq(true) end it 'should exponentially backoff' do Timecop.freeze do state.failure Timecop.travel(2) expect(state.should_try?).to eq(true) state.failure Timecop.travel(3) expect(state.should_try?).to eq(false) Timecop.travel(2) expect(state.should_try?).to eq(true) state.failure Timecop.travel(8) expect(state.should_try?).to eq(false) Timecop.travel(2) expect(state.should_try?).to eq(true) end end end
module SMSFuHelper # Returns a collection of carriers to be used in your own select tag # e.g., <%= f.select :mobile_carrier, carrier_collection %> def carrier_collection SMSFu.carriers.sort.collect{ |carrier| [carrier[1]["name"], carrier[0]] } end # Returns a formatted select box filled with carriers # e.g., <%= carrier_select %> # - name => name of the method in which you want to store the carrier name # - phrase => default selected blank option in select box def carrier_select(name = :mobile_carrier, phrase = "Select a Carrier") select_tag name, options_for_select([phrase,nil]+carrier_collection, phrase) end end
class UsersController < ApplicationController skip_before_filter :login_required, only: [:new, :create] # GET /users # GET /users.json def index @users = User.all respond_to do |format| format.html # index.html.erb format.json { render json: @users } end end # GET /users/1 # GET /users/1.json def show @user = User.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @user } end end # GET /user/1/account def account @user = User.find(params[:id]) redirect_to root_path unless logged_in_user === @user # get additional data @games = @user.games.order(:title) @loans = @user.loans.where(status: Loan::STATUS_ONLOAN) @holds = @user.loans.where(status: Loan::STATUS_ONHOLD) @requests = @user.games.collect { |game| game.loans.held.first if game.loans.out.none? }.compact @games_out = @user.games.collect { |game| game.loans.out }.flatten end # GET /users/new # GET /users/new.json def new @user = User.new respond_to do |format| format.html # new.html.erb format.json { render json: @user } end end # GET /users/1/edit def edit @user = User.find(params[:id]) end # POST /users # POST /users.json def create @user = User.new( username: params[:user][:username], name: params[:user][:name], email: params[:user][:email], ) @user.password = params[:user][:password] @user.password_confirmation = params[:user][:password_confirmation] respond_to do |format| if @user.save format.html do session[:user_id] = @user.id redirect_to root_path, notice: "Welcome #{@user.name}" end format.json { render json: @user, status: :created, location: @user } else format.html { render action: "new" } format.json { render json: @user.errors, status: :unprocessable_entity } end end end # PUT /users/1 # PUT /users/1.json def update @user = User.find(params[:id]) respond_to do |format| if @user.update_attributes(params[:user]) format.html { redirect_to @user, notice: 'User was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @user.errors, status: :unprocessable_entity } end end end # DELETE /users/1 # DELETE /users/1.json def destroy @user = User.find(params[:id]) @user.destroy respond_to do |format| format.html { redirect_to users_url } format.json { head :no_content } end end end
class Alert < ApplicationRecord self.inheritance_column = :alert_type enum status: { active: 'active', archived: 'archived', errored: 'errored' } belongs_to :user before_create :generate_uuid scope :search, -> { where(alert_type: 'Alert::Search') } scope :bill, -> { where(alert_type: 'Alert::Bill') } scope :recent, -> { order(created_at: 'desc') } scope :by_name, -> { order('LOWER(name)') } attr_accessor :payload_string def self.humanize_query(query) clauses = [] query.each do |k, v| next unless v.present? label = k == 'q' ? '' : k op = k == 'q' ? '' : ':' clauses << "#{label}#{op}#{v}" end clauses.join(' AND ') end def self.prune_query(query) query.slice(:q, :state).reject { |k,v| v.blank? } end def url_name 'alerts/' end def public_url "#{Rails.application.routes.url_helpers.root_url}#{url_name}#{url_query}" end def url_query uuid end def to_param uuid end def generate_uuid self.uuid ||= SecureRandom.uuid end def pretty_query query end def has_query?(possible_query) self.class.prune_query(parsed_query).to_json == possible_query.to_json end def parsed_query JSON.parse(query, symbolize_names: true) rescue # if alert was hand-edited it may not be valid JSON anymore { q: query.to_s } end def mark_as_sent update_columns(last_sent_at: Time.zone.now) end def os_checksum(os_payload) self.payload_string = os_payload.to_json checksum = Digest::SHA256.hexdigest self.payload_string Rails.cache.write("alert-#{id}-#{checksum}", self.payload_string) checksum end def checksum_short (checksum || 'nocheck')[0..7] end private def write_payload_diff(sum) old_key = "alert-#{id}-#{checksum}" new_key = "alert-#{id}-#{sum}" old_payload = Rails.cache.fetch(old_key) { "{}" } # empty hash if not found new_payload = self.payload_string diff = Hashdiff.diff(JSON.parse(old_payload), JSON.parse(new_payload)) Rails.cache.write("alert-#{id}-#{sum}-diff", diff) end def update_as_run(sum) write_payload_diff(sum) update!(last_run_at: Time.zone.now, checksum: sum) end end
module CollinsNotify class CommandRunner def run args app = CollinsNotify::Application.new begin app.configure! args get_contact_and_asset app, true # throws exception if not configured properly rescue SystemExit => e exit e.status rescue CollinsNotify::ConfigurationError => e app.logger.fatal "Error with input option - #{e}" exit 1 rescue StandardError => e app.logger.fatal "Error parsing CLI options - #{e}" $stdout.puts CollinsNotify::Options.get_instance(app.config) exit 2 end # This is legacy behavior app.config.type = :email if app.config.type.nil? unless app.valid? then $stdout.puts CollinsNotify::Options.get_instance(app.config) exit 3 end app.logger.trace "Configuration -> #{app.config.to_hash.inspect}" begin contact, asset = get_contact_and_asset app if !app.notify!(asset, contact) then raise Exception.new "failed" end rescue Timeout::Error => e app.logger.fatal "TIMEOUT sending notification via #{app.type}" exit 4 rescue Exception => e app.logger.fatal "ERROR sending notification via #{app.type} - #{e}" exit 5 end app.logger.info "Successfully sent #{app.type} notification" exit 0 end protected def get_contact_and_asset app, test_only = false return [nil, OpenStruct.new] unless app.selector and !app.selector.empty? ccfg = app.config.collins if ccfg.nil? or ccfg.empty? then raise CollinsNotify::ConfigurationError.new "No collins configuration but selector specified" end collins = Collins::Client.new ccfg.merge(:logger => app.logger) return if test_only asset = nil if app.selector[:tag] then app.logger.info "Finding collins asset using asset tag #{app.selector[:tag]}" asset = collins.get app.selector[:tag] else app.logger.info "Finding collins asset using asset selector #{app.selector.inspect}" assets = collins.find(app.selector) app.logger.debug "Found #{assets.size} assets in collins using selector, only using first" asset = assets.first end if asset.nil? then raise CollinsNotify::ConfigurationError.new "No asset found using #{app.selector.inspect}" end [asset.contact, asset] end end end
class CatRentalRequest < ApplicationRecord validates: :status, inclusion: %w(PENDING APPROVED DENIED) validates: :cat_id, :start_date, :end_date, :status, presence: true belongs_to :cat, foreign_key: :cat_id, class_name: :Cat end
# encoding: utf-8 module Antelope module Ace class Scanner # Scans the third part. Everything after the content # boundry is copied directly into the output. module Third # Scans the third part. It should start with a content # boundry; raises an error if it does not. It then scans # until the end of the file. # # @raise [SyntaxError] if somehow there is no content # boundry. # @return [void] def scan_third_part @scanner.scan(CONTENT_BOUNDRY) or error! tokens << [:third] tokens << [:copy, @scanner.scan(/[\s\S]+/m) || ""] end end end end end
class CreateAttributes < ActiveRecord::Migration def self.up create_table :attributes do |t| t.string :name, :limit => 20, :null => false t.timestamps end end end
#!/usr/bin/env ruby require "date" require "fileutils" require File.expand_path("../../storm_data/storm_events.rb", __FILE__) require File.expand_path("../forecast.rb", __FILE__) FROM_ARCHIVE = ARGV.include?("--from-archive") DRY_RUN = ARGV.include?("--dry-run") DELETE_UNNEEDED = ARGV.include?("--delete-unneeded") # Delete files in time range not associated with storm events. # Runs through 2018-10 are stored on HRRR_1 # Runs 2018-11 onward are stored on HRRR_2 # Google archive only has up to f15 until 2016-8-25...and the Utah archive got rid of their 2016 data for some reason. # 2016-8-24 is where the 250mb winds, lightning, and surface RH appear, which our models assume. # If we use the older data, we'll have to disregard those # For training: # --from-archive flag implies storm event hours±1 only (HALF_WINDOW_SIZE below) # Don't have enough disk space to store them all at once :( # Download next set after one set has loaded and is training. # FORECAST_HOURS=2,6,11,12,13,18 ruby get_hrrr.rb --from-archive --delete-unneeded # FORECAST_HOURS=1,2,3,6,12,18 ruby get_hrrr.rb --from-archive --delete-unneeded # THREAD_COUNT=2 FORECAST_HOURS=2,5,6,7,12,18 ruby get_hrrr.rb --from-archive --delete-unneeded # FORECAST_HOURS=2,6,12,16,17,18 ruby get_hrrr.rb --from-archive --delete-unneeded # THREAD_COUNT=3 FORECAST_HOURS=11,12,13,16,17,18 ruby get_hrrr.rb --from-archive --delete-unneeded # THREAD_COUNT=3 FORECAST_HOURS=5,6,7,11,12,13 ruby get_hrrr.rb --from-archive --delete-unneeded # THREAD_COUNT=3 FORECAST_HOURS=1,2,3,5,6,7 ruby get_hrrr.rb --from-archive --delete-unneeded # THREAD_COUNT=3 FORECAST_HOURS="" VALIDATION_RUN_HOURS=8,9,10,12,13,14 ruby get_hrrr.rb --from-archive --delete-unneeded # THREAD_COUNT=3 FORECAST_HOURS="" VALIDATION_RUN_HOURS=8,9,10,12,13,14 TEST_RUN_HOURS=8,9,10,12,13,14 ruby get_hrrr.rb --from-archive --delete-unneeded # Forecaster runs these: # RUN_HOURS=8,9,10 FORECAST_HOURS=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18 ruby get_hrrr.rb # RUN_HOURS=12,13,14 FORECAST_HOURS=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18 ruby get_hrrr.rb # Want three hour windows. Don't have storage yet for all, so we'll start with +11,+12,+13 and build from there. RUN_HOURS = ENV["RUN_HOURS"]&.split(",")&.map(&:to_i) || (0..23).to_a FORECAST_HOURS = ENV["FORECAST_HOURS"]&.split(",")&.map(&:to_i) || [2, 6, 11, 12, 13, 18] VALIDATION_RUN_HOURS = ENV["VALIDATION_RUN_HOURS"]&.split(",")&.map(&:to_i) || [] TEST_RUN_HOURS = ENV["TEST_RUN_HOURS"]&.split(",")&.map(&:to_i) || [] MIN_FILE_BYTES = 80_000_000 THREAD_COUNT = Integer((DRY_RUN && "1") || ENV["THREAD_COUNT"] || (FROM_ARCHIVE ? "2" : "8")) HALF_WINDOW_SIZE = 90*MINUTE # Grab forecasts valid within this many minutes of a geocoded storm event loop { break if Dir.exists?("/Volumes/HRRR_1/"); puts "Waiting for HRRR_1 to mount..."; sleep 4 } loop { break if Dir.exists?("/Volumes/HRRR_2/"); puts "Waiting for HRRR_2 to mount..."; sleep 4 } class HRRRForecast < Forecast # def year_month_day # "%04d%02d%02d" % [run_date.year, run_date.month, run_date.day] # end # # def year_month # "%04d%02d" % [run_date.year, run_date.month] # end # # def run_hour_str # "%02d" % [run_hour] # end # # def forecast_hour_str # "%02d" % [forecast_hour] # end # # def valid_time # Time.utc(run_date.year, run_date.month, run_date.day, run_hour) + forecast_hour*HOUR # end def file_name "hrrr_conus_sfc_#{year_month_day}_t#{run_hour_str}z_f#{forecast_hour_str}.grib2" end def archive_url "https://storage.googleapis.com/high-resolution-rapid-refresh/hrrr.#{year_month_day}/conus/hrrr.t#{run_hour_str}z.wrfsfcf#{forecast_hour_str}.grib2" end def alt_archive_url "https://pando-rgw01.chpc.utah.edu/hrrr/sfc/#{year_month_day}/hrrr.t#{run_hour_str}z.wrfsfcf#{forecast_hour_str}.grib2" end def ncep_url "https://ftp.ncep.noaa.gov/data/nccf/com/hrrr/prod/hrrr.#{year_month_day}/conus/hrrr.t#{run_hour_str}z.wrfsfcf#{forecast_hour_str}.grib2" end def base_directory if ([run_date.year, run_date.month] <=> [2018, 10]) <= 0 "/Volumes/HRRR_1/hrrr" else "/Volumes/HRRR_2/hrrr" end end # def directory # "#{base_directory}/#{year_month}/#{year_month_day}" # end # def path # "#{directory}/#{file_name}" # end def alt_directory # directory.sub(/^\/Volumes\/HRRR_1\//, "/Volumes/HRRR_2/") raise "no alt directory for HRRR: the online archive serves as the backup" end def alt_path nil end # # def make_directories! # return if DRY_RUN # system("mkdir -p #{directory} 2> /dev/null") # if alt_path # system("mkdir -p #{alt_directory} 2> /dev/null") # end # end def min_file_bytes MIN_FILE_BYTES end # def downloaded? # (File.size(path) rescue 0) >= min_file_bytes # end # # def ensure_downloaded!(from_archive: false) # url_to_get = from_archive ? archive_url : ncep_url # make_directories! # unless downloaded? # puts "#{url_to_get} -> #{path}" # return if DRY_RUN # data = `curl -f -s --show-error #{url_to_get}` # if $?.success? && data.size >= min_file_bytes # File.write(path, data) # if alt_path # File.write(alt_path, data) if Dir.exists?(alt_directory) && (File.size(alt_path) rescue 0) < min_file_bytes # end # end # end # end # # def remove! # if File.exists?(path) # puts "REMOVE #{path}" # FileUtils.rm(path) unless DRY_RUN # end # if alt_path && File.exists?(alt_path) # puts "REMOVE #{alt_path}" # FileUtils.rm(alt_path) unless DRY_RUN # end # end end if FROM_ARCHIVE # Storm event hours only, for now. Would be 12TB for all +2 +6 +12 +18 forecasts. start_date_parts = ENV["START_DATE"]&.split("-")&.map(&:to_i) || [2016,8,24] # https://pando-rgw01.chpc.utah.edu/hrrr/sfc/20180101/hrrr.t00z.wrfsfcf00.grib2 DATES = (Date.new(*start_date_parts)..Date.today).to_a SATURDAYS = DATES.select(&:saturday?) SUNDAYS = DATES.select(&:sunday?) storm_event_times = conus_event_hours_set(STORM_EVENTS, HALF_WINDOW_SIZE) forecasts_in_range = DATES.product(RUN_HOURS, (0..18).to_a).map do |date, run_hour, forecast_hour| HRRRForecast.new(date, run_hour, forecast_hour) end forecasts_to_get = forecasts_in_range.select do |forecast| FORECAST_HOURS.include?(forecast.forecast_hour) && (storm_event_times.include?(forecast.valid_time) || storm_event_times.include?(forecast.valid_time + HOUR) || storm_event_times.include?(forecast.valid_time - HOUR)) end validation_forecasts_to_get = SATURDAYS.product(VALIDATION_RUN_HOURS, (1..18).to_a).map do |date, run_hour, forecast_hour| HRRRForecast.new(date, run_hour, forecast_hour) end test_forecasts_to_get = SUNDAYS.product(TEST_RUN_HOURS, (1..18).to_a).map do |date, run_hour, forecast_hour| HRRRForecast.new(date, run_hour, forecast_hour) end forecasts_to_get = (forecasts_to_get + validation_forecasts_to_get + test_forecasts_to_get).uniq forecasts_to_remove = DELETE_UNNEEDED ? (forecasts_in_range - forecasts_to_get) : [] forecasts_to_remove.each(&:remove!) else # https://ftp.ncep.noaa.gov/data/nccf/com/hrrr/prod/hrrr.20190220/conus/hrrr.t02z.wrfsfcf18.grib2 ymds = ENV["FORECAST_DATE"] ? [ENV["FORECAST_DATE"].gsub("-","")] : `curl -s https://ftp.ncep.noaa.gov/data/nccf/com/hrrr/prod/`.scan(/hrrr\.(\d{8})\//).flatten.uniq forecasts_to_get = ymds.product(RUN_HOURS, FORECAST_HOURS).map { |ymd, run_hour, forecast_hour| HRRRForecast.new(ymd_to_date(ymd), run_hour, forecast_hour) } end # hrrr.t02z.wrfsfcf18.grib2 threads = THREAD_COUNT.times.map do Thread.new do while forecast_to_get = forecasts_to_get.shift forecast_to_get.ensure_downloaded!(from_archive: FROM_ARCHIVE) end end end threads.each(&:join)
class MonstersController < ApiController before_action :require_login, except: [:index, :show] def index monsters=Monster.all render json:{monsters: monsters} end def show monster=Monster.find(params[:id]) monster_user=monster.user render json:{monster: monster} end def create monster=Monster.new(monster_params) monster.user_id=current_user.id if monster.save render json:{message: 'ok', monster: monster} else render json:{message: 'Could not create monster !'} end end private def monster_params params.require(:monster).permit(:name, :description) end end
class ServicesController < ApplicationController def index @title = "Services" @services = Service.all end end
require 'account' require 'date' RSpec.describe Account do subject(:account) { described_class.new } # account = Account.new # date = DateFormat.new let(:amt) { 1000 } let(:date) { '09/09/2020' } let(:type) { ' ' } # describe '#date' do # hashtag means you're testing a method # it 'shows the date' do # expect(account.date).to eq date_format # end # end describe '#deposit' do it 'increases the balance' do account.deposit(amt) expect(account.balance).to eq(amt) end end describe '#withdrawal' do it 'decreases the balance' do account.deposit(amt) account.withdrawal(amt) expect(account.balance).to eq(0) end end context 'when making a deposit or withdrawal' do # context when you're testing different outputs it 'stores the date, credit, amount and balance for a deposit' do account.deposit(amt) expect(account.transactions).to eq([[date, amt, type, account.balance]]) end it 'stores the date, credit, amount and balance for a withdrawal' do account.deposit(amt) account.withdrawal(500) expect(account.transactions[1]).to eq([date, type, 500, account.balance]) end end end
class Vanagon module Utilities module ExtraFilesSigner class << self def commands(project, mktemp, source_dir) # rubocop:disable Metrics/AbcSize tempdir = nil commands = [] # Skip signing extra files if logging into the signing_host fails # This enables things like CI being able to sign the additional files, # but locally triggered builds by developers who don't have access to # the signing host just print a message and skip the signing. Vanagon::Utilities.retry_with_timeout(3, 5) do tempdir = Vanagon::Utilities::remote_ssh_command("#{project.signing_username}@#{project.signing_hostname}", "#{mktemp} 2>/dev/null", return_command_output: true) end remote_host = "#{project.signing_username}@#{project.signing_hostname}" remote_destination_directory = "#{remote_host}:#{tempdir}" remote_signing_script_path = File.join(tempdir, File.basename('sign_extra_file')) extra_flags = '' extra_flags = '--extended-attributes' if project.platform.is_macos? project.extra_files_to_sign.each do |file| remote_file_to_sign_path = File.join(tempdir, File.basename(file)) local_source_path = File.join('$(tempdir)', source_dir, file) remote_source_path = "#{remote_host}:#{remote_file_to_sign_path}" local_destination_path = local_source_path commands += [ "#{Vanagon::Utilities.ssh_command} #{remote_host} \"echo '#{project.signing_command} #{remote_file_to_sign_path}' > #{remote_signing_script_path}\"", "rsync -e '#{Vanagon::Utilities.ssh_command}' --verbose --recursive --hard-links --links --no-perms --no-owner --no-group #{extra_flags} #{local_source_path} #{remote_destination_directory}", "#{Vanagon::Utilities.ssh_command} #{remote_host} /bin/bash #{remote_signing_script_path}", "rsync -e '#{Vanagon::Utilities.ssh_command}' --verbose --recursive --hard-links --links --no-perms --no-owner --no-group #{extra_flags} #{remote_source_path} #{local_destination_path}" ] end commands rescue RuntimeError require 'vanagon/logger' VanagonLogger.error "Unable to connect to #{project.signing_username}@#{project.signing_hostname}, skipping signing extra files: #{project.extra_files_to_sign.join(',')}" raise if ENV['VANAGON_FORCE_SIGNING'] [] end end end end end
$: << File.expand_path('../lib', __FILE__) require 'rack-emstream' class Sender def initialize @times = 100 @data = "data" end def each @times.times { |i| yield @data } end def length @times * @data.length end end require 'logger' use Rack::EMStream run lambda { |env| sender = Sender.new [ 200, { 'Content-Length' => sender.length.to_s }, sender ] }
require 'spec_helper' describe ExamRoom::Practice::Exam do before :each do setup_for_models end describe "scopes" do it "completed" do practice_exam = TestSupport::ExamRoom.generate_practice_sba_exam! ExamRoom::Practice::Exam.completed.count.should == 0 practice_exam.questions.size.times do |i| practice_question = ExamRoom::Practice::Question.find(practice_exam.questions[i].id) practice_question.attempt!(practice_question.question.correct_answer_id) end ExamRoom::Practice::Exam.completed.count.should == 1 end it "incomplete" do practice_exam = TestSupport::ExamRoom.generate_practice_sba_exam! ExamRoom::Practice::Exam.incomplete.count.should == 1 practice_exam.questions.size.times do |i| practice_question = ExamRoom::Practice::Question.find(practice_exam.questions[i].id) practice_question.attempt!(practice_question.question.correct_answer_id) ExamRoom::Practice::Exam.incomplete.count.should == 1 if i < 2 end ExamRoom::Practice::Exam.completed.count.should == 1 end end it "is must have an user_id" do practice_exam = ExamRoom::Practice::Exam.new practice_exam.valid? practice_exam.errors.to_hash.should have_key(:user_id) end it "is must have an exam_id" do practice_exam = ExamRoom::Practice::Exam.new practice_exam.valid? practice_exam.errors.to_hash.should have_key(:exam_id) end it "is must save its number of questions" do practice_exam = ExamRoom::Practice::Exam.new practice_exam.valid? practice_exam.errors.to_hash.should have_key(:num_questions) end it "has score_percentage" do practice_exam = TestSupport::ExamRoom.generate_practice_sba_exam! practice_exam.score_percentage.should == 0 practice_question = ExamRoom::Practice::Question.find(practice_exam.questions.first.id) practice_question.attempt!(practice_question.question.answers.first.id) practice_exam.score_percentage == 100 practice_question = ExamRoom::Practice::Question.find(practice_exam.questions.first.id) practice_question.attempt!(practice_question.question.answers.last.id) practice_exam.score_percentage == 50 practice_exam.num_correct_answers = 5 practice_exam.num_incorrect_answers = 20 practice_exam.score_percentage.should == 20 practice_exam.num_correct_answers = 0 practice_exam.num_incorrect_answers = 25 practice_exam.score_percentage.should == 0 practice_exam.num_correct_answers = 0 practice_exam.num_incorrect_answers = 0 practice_exam.score_percentage.should == 0 end it "has progress_percentage", :progress => true do practice_exam = TestSupport::ExamRoom.generate_practice_sba_exam! practice_exam.progress_percentage.should == 0 practice_question = ExamRoom::Practice::Question.find(practice_exam.questions.first.id) practice_question.attempt!(practice_question.question.answers.first.id) practice_exam.progress_percentage == 5 end it "should update its score correctly" do practice_exam = TestSupport::ExamRoom.generate_practice_sba_exam! practice_exam.num_correct_answers.should == 0 final_score = 0 practice_exam.questions.each_with_index do |practice_question, index| practice_question = ExamRoom::Practice::Question.find(practice_question.id) final_score += 1 if index.even? old_score = practice_exam.score # Get it correct if true if index.even? practice_question.attempt!(practice_question.question.correct_answer_id) else practice_question.attempt!(practice_question.question.answers.where("id != ?", practice_question.question.correct_answer_id).first.id) end practice_exam.reload practice_exam.score.should == old_score + (index.even?? 1 : 0) end practice_exam.score.should == final_score end it "should update its attempts counters correctly" do practice_exam = TestSupport::ExamRoom.generate_practice_sba_exam! practice_exam.num_correct_answers.should == 0 practice_exam.num_incorrect_answers.should == 0 practice_exam.num_skipped_answers.should == 0 final_num_correct_answers = 0 final_num_incorrect_answers = 0 final_num_skipped_answers = 0 practice_exam.questions.each_with_index do |practice_question, index| practice_question = ExamRoom::Practice::Question.find(practice_question.id) old_num_correct_answers = practice_exam.num_correct_answers old_num_incorrect_answers = practice_exam.num_incorrect_answers old_num_skipped_answers = practice_exam.num_skipped_answers # Get it correct if true case index % 3 when 0 practice_question.attempt!(practice_question.question.correct_answer_id) final_num_correct_answers += 1 practice_exam.reload practice_exam.num_correct_answers.should == old_num_correct_answers + 1 when 1 practice_question.attempt!(practice_question.question.answers.where("id != ?", practice_question.question.correct_answer_id).first.id) final_num_incorrect_answers += 1 practice_exam.reload practice_exam.num_incorrect_answers.should == old_num_incorrect_answers + 1 when 2 practice_question.attempt!(nil) final_num_skipped_answers += 1 practice_exam.reload practice_exam.num_skipped_answers.should == old_num_skipped_answers + 1 end end practice_exam.num_correct_answers.should == final_num_correct_answers practice_exam.num_incorrect_answers.should == final_num_incorrect_answers practice_exam.num_skipped_answers.should == final_num_skipped_answers end it "should update its possible score correctly" do practice_exam = TestSupport::ExamRoom.generate_practice_sba_exam! practice_exam.possible_score.should == 0 final_possible_score = 0 practice_exam.questions.each_with_index do |practice_question, index| practice_question = ExamRoom::Practice::Question.find(practice_question.id) final_possible_score += 1 old_possible_score = practice_exam.possible_score # Get it correct if true if index.even? practice_question.attempt!(practice_question.question.correct_answer_id) else practice_question.attempt!(practice_question.question.answers.where("id != ?", practice_question.question.correct_answer_id).first.id) end practice_exam.reload practice_exam.possible_score.should == old_possible_score + 1 end practice_exam.possible_score.should == final_possible_score end it "should update number of questions taken" do practice_exam = TestSupport::ExamRoom.generate_practice_sba_exam! practice_exam.num_questions_attempted.should == 0 (0..4).each do |i| practice_question = ExamRoom::Practice::Question.find(practice_exam.questions[i].id) practice_question.attempt!(practice_question.question.correct_answer_id) practice_exam.reload practice_exam.num_questions_attempted.should == i + 1 end practice_exam.num_questions_attempted.should == 5 end it "should update its time_taken correctly" do practice_exam = TestSupport::ExamRoom.generate_practice_sba_exam! practice_exam.score.should == 0 (0..2).each do |i| practice_question = ExamRoom::Practice::Question.find(practice_exam.questions[i].id) practice_question.started! sleep(2) practice_question.attempt!(practice_question.question.correct_answer_id) practice_exam.reload practice_exam.time_taken.should be_within(2).of((i + 1) * 2) end practice_exam.time_taken.should be_within(2).of(6) end it "should updated its status throughout the exam" do practice_exam = TestSupport::ExamRoom.generate_practice_sba_exam! practice_exam.is_started?.should == false practice_exam.is_completed?.should == false total_questions = practice_exam.questions.size practice_exam.questions.each_with_index do |practice_question, index| practice_question = ExamRoom::Practice::Question.find(practice_question.id) practice_question.attempt!(practice_question.question.correct_answer_id) practice_exam.reload practice_exam.is_started?.should == true practice_exam.is_completed?.should == false unless index == (total_questions - 1) end practice_exam.reload practice_exam.is_completed?.should == true practice_exam.is_started?.should == true end it "should only take questions from the specified exam" do exam = TestSupport::ExamRoom.create_exam! user = TestSupport::General.create_user! # Create two exams exam = nil 2.times do exam = TestSupport::ExamRoom.create_exam! 10.times{exam.questions << TestSupport::ExamRoom.create_mcq!} end # Test that only half of the exam questions are being generated # and that they are all from the correct exam practice_exam = ExamRoom::Practice::Exam.generate!(user, exam.id) practice_exam.questions.count.should == 10 practice_exam.questions.each do |question| question.question.exam_ids.should include(exam.id) end end end
module SessionsHelper #Logs in the given user def log_in(user) session[:user_id] = user.id # creates a temp cookie and encrypt user.id end #return the current login user def current_user @current_user ||= User.find_by(id: session[:user_id]) end #Return true if user is logged in, else false def log_in? #debugger !current_user.nil? end # Log out the current user def log_out session.delete(:user_id) # session[:user_id] = null @current_user = nil end end
class PositionsController < ApplicationController before_filter :authenticate_user! before_action :set_position, only: [:show, :edit, :update, :destroy] after_action :verify_authorized, :except => [:index, :new] before_action :set_authorize_check, :except => [:index, :new] # This always follows the verify_authorized layout :resolve_layout def index @positions = current_user.positions end def show authorize @position @requests = resolve_scope(params[:type]) end def new @position = Position.new end def edit end def create @position = Position.new(position_params) @position.user_id = current_user.id if @position.save redirect_to @position, notice: 'Position was successfully created.' else render :new end end def update if @position.update(position_params) redirect_to @position, notice: 'Position was successfully updated.' else render :edit end end def destroy @position.destroy redirect_to positions_url, notice: 'Position was successfully destroyed.' end private # Use callbacks to share common setup or constraints between actions. def set_position @position = Position.find(params[:id]) end # Only allow a trusted parameter "white list" through. def position_params params.require(:position).permit(:title, :description, :fields_attributes).tap do |whitelisted| whitelisted[:fields] = params[:position][:fields] end end def set_authorize_check authorize @position end def resolve_layout %w(new).include?(action_name) ? "application" : "dashboard" end def resolve_scope(type) case type when "process" @position.position_requests.processed.sort_by{|i| i.created_at}.reverse! when "rejected" @position.position_requests.rejected.sort_by{|i| i.created_at}.reverse! when "accepted" @position.position_requests.accepted.sort_by{|i| i.created_at}.reverse! when "archived" @position.position_requests.archived.sort_by{|i| i.created_at}.reverse! else @position.position_requests.pending.sort_by{|i| i.created_at}.reverse! end end end
describe Limbo::Rails::Request do describe "#url" do context "URL with a standard port" do it "returns a formatted URL without port" do rails_request = Limbo::Rails::Request.new(request(port: 80)) rails_request.url.should == "http://example.com/blog" end end context "URL with non-standard port" do it "returns a formatted URL with the port included" do rails_request = Limbo::Rails::Request.new(request(port: 1337)) rails_request.url.should == "http://example.com:1337/blog" end end end end
class JavascriptSweeper < ActionController::Caching::Sweeper observe Javascript def after_update(asset) expire_cache_for asset if asset.type == 'Javascript' end def after_destroy(asset) expire_cache_for asset if asset.type == 'Javascript' end private def expire_cache_for(record) expire_page :controller => '/javascripts', :action => 'show', :id => "#{record.attributes['title']}.js" end end
# # Be sure to run `pod lib lint MideaSmartCommon.podspec' to ensure this is a # valid spec before submitting. # # Any lines starting with a # are optional, but their use is encouraged # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'MideaSmartCommon' s.version = '0.1.1' s.summary = '美的智慧的一些公用组建' s.description = '美的智慧的一些公用组建,提高项目开发效率及项目质量' s.homepage = 'https://github.com/midea-smart' s.screenshots = 'http://www.lgstatic.com/thumbnail_300x300/image1/M00/21/E6/CgYXBlU--F2AcMEOAABoYyINKNk984.png' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'denglibing' => 'libing.deng@midea.com' } s.source = { :git => 'https://github.com/midea-smart/MideaSmartCommon.git', :tag => s.version.to_s } s.ios.deployment_target = '8.0' s.subspec 'MSTableViewCommon' do |mstvc| mstvc.source_files = 'MideaSmartCommon/MideaSmartUI/MSTableViewCommon/*.{h,m}' end # s.resource_bundles = { # 'MideaSmartCommon' => ['MideaSmartCommon/Assets/*.png'] # } # s.public_header_files = 'Pod/Classes/**/*.h' # s.frameworks = 'UIKit', 'MapKit' # s.dependency 'AFNetworking', '~> 2.3' end
require 'matrix' require_relative 'print' # @param [Matrix] _a # @param [Array] _b def gauss(_a, _b) a, b = _a.dup, _b.dup size = a.row_size (0...size - 1).each do |i| (i + 1...size).each do |j| ratio = a[j, i] / a[i, i] b[j] -= ratio * b[i] (0...size).each do |k| a[j, k] -= ratio * a[i, k] end end end res = Array.new(size, 0) (0...size).reverse_each do |i| res[i] = b[i] (i + 1...size).each do |j| res[i] -= a[i, j] * res[j] end res[i] /= a[i, i] end res end puts "Input n:" n = gets.to_i a = Matrix.build(n, n) { |x, y| x == y ? 2.0 : 15.0 } b = [] (0...n).each do |i| b.push(i.to_f) end Print.matrix(a, b) s = gauss(a, b) printf("\nSolutions = ["+ "%0.2f, " * (s.size - 1) + "%0.2f]\n", *s)
require "pathname" require "fileutils" module Snapit class Storage attr_reader :path def initialize(root_path) @path = root_path.join("snapit_captures") FileUtils.mkdir_p(path) unless Dir.exists?(path) end def set_script_name!(name) @script_name = name @script_name = @script_name.gsub(/[^0-9a-z ]/i, '').gsub(/ /i, '_') end def script_name @script_name || "default" end def output_path p = path.join(script_name) FileUtils.mkdir_p(p) unless Dir.exists?(p) p end end end
TeamUserType = GraphqlCrudOperations.define_default_type do name 'TeamUser' description 'TeamUser type' interfaces [NodeIdentification.interface] field :dbid, types.Int field :user_id, types.Int field :team_id, types.Int field :status, types.String field :role, types.String field :permissions, types.String field :team do type TeamType resolve -> (team_user, _args, _ctx) { team_user.team } end field :user do type UserType resolve -> (team_user, _args, _ctx) { team_user.user } end end
class DefectsController < ApplicationController before_filter :set_project before_action :set_defect, only: [:show, :edit, :update, :destroy] before_action :set_breadcrumbs # GET /defects # GET /defects.json def index @defects = @project.defects @defect = Defect.new end # GET /defects/1 # GET /defects/1.json def show end # GET /defects/new def new @defect = @project.defects.new add_breadcrumb 'New' end # GET /defects/1/edit def edit end # POST /defects # POST /defects.json def create @defect = Defect.new(defect_params) @defect.project = @project respond_to do |format| if @defect.save format.html { redirect_to project_defects_url(@project), notice: 'Defect was successfully created.' } format.json { render :index, status: :created, location: @defect } else format.html { render :index } format.json { render json: @defect.errors, status: :unprocessable_entity } end end end # PATCH/PUT /defects/1 # PATCH/PUT /defects/1.json def update respond_to do |format| if @defect.update(defect_params) format.html { redirect_to project_defects_url(@project) } format.json { render :show, status: :ok, location: @defect } else format.html { render :edit } format.json { render json: @defect.errors, status: :unprocessable_entity } end end end # DELETE /defects/1 # DELETE /defects/1.json def destroy @defect.destroy respond_to do |format| format.html { redirect_to project_defects_url(@project), notice: 'Defect was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_breadcrumbs add_breadcrumb "Projects", :authenticated_root_path add_breadcrumb @project.name, edit_project_path(@project) add_breadcrumb 'Defects', project_defects_path(@project) end def set_defect @defect = @project.defects.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def defect_params params.require(:defect).permit(:project_id, :defect_type_id,:name, :description, :date, :phase_type_id, :type, :fix_count, :fixed, :fix_time) end end
# this is a sample model for testing purpose class Event #:nodoc: include Mongoid::Document field :name, type: String field :date, type: Date field :published, type: Mongoid::Boolean, default: false default_scope ->{ where(published: true) } end
Convention over Configuration(CoC) Less code to write Some code Rails will automatically generate Often, there is no need to code Database Abstraction Layer No need to deal with low-level DB details No need for SQL Important to understand the SQL generated! **ORM: Object-Relational Mapping: mapping db to Ruby classes Agile-friendly, cross-platform, open source SQLite for database by default Self-contained, serverless, zero-config, transactional, relational SQL database engine Most widely deployed SQL engine in the world MVC: Model View Controller 1979, software pattern Model: represents data the app is working with(and maybe business logic) View: visual representation of data(html, JSON, XML...) Controller: interaction between model and view MVC cycle: 1. Request sent 2. Controller <-> model 3. Controller invokes view 4. View render data Summary Rapid prototyping "Think less, do more" ### Creating your first application 1. rails new appname(my_first_app) #first command Version control your rails app Rails automatically generates .gitignore cd appname -> git init -> git add . -> git commit -m "aaa" #this is for Heroku This is a directory with auto-generated structure and some code Rails also provides built-in web server 2. Open another terminal window, go into my_first_app, run rails server (or rails s) Directory structure convention App: controllers, views, models (and helpers) Configuration files: which DB? DB: files related to your db and migration "scripts" public: static files (like HTML) Server looks into public directory before looking anywhere else If we want to add completely static webpage to app, we can add it to public directory Gemdile: dependencies managed by Bundler If all your pages are going to be static, don't use rails ' <Summary> Rails new creates new app Rails s runs the app (needs to be inside generated directory) Static pages live inside public directory ###Controller and View Generating a Controller Controllers contain actions(Ruby methods) and orchestrate web requests Rails can quickly generate controller and 0 or more actions with associated views rails generate(g) controller controller_name [action1 action2] ex: rails g controller greeter hello No DOCTYPE, head, or body ERB: looks like HTML file, but has erb extension ERB is a templating library that lets you embed Ruby into HTML Tag Patterns <% ruby code... %> - evaluate ruby code <%= ... ruby code ...%> - output evaluated Ruby code <Summary> Controllers contain actions(methods) ERB allows you to either evaluate expression or output one ###Routes Routes: before the controller can orchestrate where the web request goes, the web request needs to get routed to the Controller All routes need to be specified (either generated by rails generators or manually) in the config/routes.rb file Rake: Ruby's build language ' Rake = Ruby Make No XML - written entirely in Ruby Rails uses rake to automate app-related tasks ex) Database, running tests, etc List of rake tasks: rake --tasks Zero-in on indiv rake task and what it does with a --describe tag rake --describe task_name Rake routes: explains your currently defined routes <Summary> Router directs request to right controller rake routes lets you see which routes are currently defined
# frozen_string_literal: true require 'spec_helper' describe ImageBatchesDownloadService do let(:target_folder) { Dir.mktmpdir } let(:fixtures_path) { "#{File.dirname(__FILE__)}/fixtures/" } let(:images) do { 'airplane.png' => 'https://homepages.cae.wisc.edu/~ece533/images/airplane.png', 'arctichare.png' => 'https://homepages.cae.wisc.edu/~ece533/images/arctichare.png' } end describe '#call' do subject { described_class.new(images.values, target_folder).call } context 'when there are no errors' do before do images.each { |image_name, image_url| stub_request(:get, image_url).to_return(status: 200, body: image_name) } end it 'downloads images into the target folder' do expect(subject).to eq([]) downloaded_images = Dir["#{target_folder}/*.png"].map(&File.method(:basename)) expect(downloaded_images).to match_array(images.keys) downloaded_images.each do |image_path| donwloaded_file = "#{target_folder}/#{image_path}" expect(File.read(donwloaded_file).strip).to eq(image_path) end end end context 'when an exception is occurred' do before { images.each_value { |image_url| stub_request(:get, image_url).and_raise(exception_class) } } shared_examples "returns errors and doesn't download images " do it do expect(subject.map(&:keys).flatten).to match_array(images.values.map { |url| URI.parse(url) }) expect(subject.map(&:values).flatten).to match_array(Array.new(2) { a_kind_of(exception_class) }) expect(Dir["#{target_folder}/*.png"].map(&File.method(:basename))).to be_empty end end context 'when Timeout Error is occurred' do let(:exception_class) { Timeout::Error } it_behaves_like "returns errors and doesn't download images " end context 'when Socket Error is occurred' do let(:exception_class) { SocketError } it_behaves_like "returns errors and doesn't download images " end context 'when URI Invalid Error is occurred' do let(:exception_class) { URI::InvalidURIError } it_behaves_like "returns errors and doesn't download images " end end end end
class AddUserIdToTsubuyakies < ActiveRecord::Migration def change add_column :tsubuyakies, :user_id, :integer end end
def vendor_build_env # Each of the following environment variables should be set, # preferably by an automated tool like Qt::Commander::Creator::Toolchain#env [ 'ANDROID_NDK_ROOT', # eg. "/home/user/android/android-ndk-r9d" 'TOOLCHAIN_PATH', # eg. "/home/user/android/android-ndk-r9d/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/bin" 'TOOLCHAIN_NAME', # eg. "arm-linux-androideabi-4.8" 'TOOLCHAIN_HOST', # eg. "arm-linux-androideabi" 'TOOLCHAIN_ARCH', # eg. "arm" ].each { |x| raise "Please set the #{x} environment variable" unless ENV[x] } host = ENV['TOOLCHAIN_HOST'] arch = ENV['TOOLCHAIN_ARCH'] ndk_root = ENV['ANDROID_NDK_ROOT'] toolpath = ENV['TOOLCHAIN_PATH'] sysroot = "#{ndk_root}/platforms/android-9/arch-#{arch}" prefix_dir = File.join(File.dirname(__FILE__),'prefix/'+ENV['TOOLCHAIN_NAME']) system "mkdir -p #{prefix_dir}" _CPP = "#{host}-cpp" _CC = "#{host}-gcc" _CXX = "#{host}-g++" _LD = "#{host}-ld" _AS = "#{host}-as" _AR = "#{host}-ar" _RANLIB = "#{host}-ranlib" _CFLAGS = "--sysroot=#{sysroot}" _CPPFLAGS = "--sysroot=#{sysroot}" _CXXFLAGS = "--sysroot=#{sysroot}" _LDFLAGS = "" _LIBS = "-lc -lgcc -ldl" # Construct load flags from global variables and library-specific option hash define_method :configure_flags do |opts| opts ||= {} case opts[:APP_STL] when :stlport_static case arch when 'arm' (opts[:LDFLAGS] ||= "") << " -L#{ndk_root}/sources/cxx-stl/stlport/libs/armeabi" when 'x86' (opts[:LDFLAGS] ||= "") << " -L#{ndk_root}/sources/cxx-stl/stlport/libs/x86" when 'mips' (opts[:LDFLAGS] ||= "") << " -L#{ndk_root}/sources/cxx-stl/stlport/libs/mips" end (opts[:CFLAGS] ||= "") << " -I#{ndk_root}/sources/cxx-stl/stlport/stlport" (opts[:CPPFLAGS] ||= "") << " -I#{ndk_root}/sources/cxx-stl/stlport/stlport" (opts[:CXXFLAGS] ||= "") << " -I#{ndk_root}/sources/cxx-stl/stlport/stlport" (opts[:LIBS] ||= "") << " -lstlport_static" end [ "CPP=#{_CPP}", "CC=#{_CC}", "CXX=#{_CXX}", "LD=#{_LD}", "AS=#{_AS}", "AR=#{_AR}", "RANLIB=#{_RANLIB}", "CFLAGS='#{_CFLAGS} #{opts[:CFLAGS]} -I#{prefix_dir}/include'", "CPPFLAGS='#{_CPPFLAGS} #{opts[:CPPFLAGS]} -I#{prefix_dir}/include'", "CXXFLAGS='#{_CXXFLAGS} #{opts[:CXXFLAGS]} -I#{prefix_dir}/include'", "LDFLAGS='#{_LDFLAGS} #{opts[:LDFLAGS]} -L#{prefix_dir}/lib'", "LIBS='#{_LIBS} #{opts[:LIBS]}'", " --host=#{host}", " --prefix=#{prefix_dir}", opts.fetch(:other, ''), ].join(' ') end end
# -*- coding : utf-8 -*- module Mushikago module Hanamgri class SaveDictionaryRequest < Mushikago::Http::PutRequest def path; "/1/hanamgri/dictionary" end request_parameter :domain_name request_parameter :description def initialize domain_name, options={} super(options) self.domain_name = domain_name self.description = options[:description] if options.has_key?(:description) end end end end
describe NOAA do it { should respond_to :forecast } it { should respond_to :current_conditions } it { should respond_to :current_conditions_at_station } end
class CreateConsultantSkills < ActiveRecord::Migration def change create_table :consultant_skills do |t| t.references :consultant, index: true, null: false t.references :skill, index: true, null: false t.timestamps end end end
class CreateSales < ActiveRecord::Migration def change create_table :sales do |t| t.string :customer_name t.date :delvery_note_date t.integer :delvery_note_number t.date :tax_invoice_date t.integer :tax_invoice_number t.string :particuars t.string :quantity t.string :unit_price t.string :value t.string :ppn t.string :tatal_amount t.date :payment_term_days t.date :payment_term_due_date t.date :cheque_date t.integer :cheque_no t.string :cheque_cleared t.string :status t.string :days t.string :interest t.string :remarks t.references :user, index: true t.timestamps null: false end add_foreign_key :sales, :users end end
# frozen_string_literal: true class JobsClientSelectComponent < ViewComponent::Base def initialize(selected: nil) clients = Client.all @clients_for_select = clients.map {|c| [c.name, c.id]} @clients_for_select.push(['Add new...', -1]) @selected = selected&.id end end
class RepoWorker include Sidekiq::Worker def perform base_url = "https://atom.io" page_path = "/packages/list" page_url = base_url + page_path # FIXME: Maybe timeout home = Nokogiri::HTML(Typhoeus.get(page_url).body) page_total = home.css('.pagination a:not(.next_page)').last.content list_links = ("1"..page_total).map { |p| "#{page_url}?page=#{p}" } # Find the atom home url for each package links = list_links.inject([]) do |memo, page| current = Nokogiri::HTML(Typhoeus.get(page).body) memo.concat(current.css('.package-name a').map do |l| { :atom_url => URI.escape(base_url + l['href']) } end) end # Find all the responsing repo url(github) links = links.map do |link| begin l = link[:atom_url] pkg_page = Nokogiri::HTML(Typhoeus.get(l).body) link[:url] = pkg_page.css('.package-meta > a'). map { |l| l['href'] }. # make sure it's a right github url select { |url| url =~ /^https?:\/\/github.com\/[\.\w-]+\/[\.\w-]+$/ }.first link rescue StandardError => e Rails.logger.fatal "ERROR in finding github link, #{e}" Rails.logger.debug "Package atom link: #{l}" end end insert_repos(links) end def insert_repos(links) links.each do |link| url = link[:url] if Repo.where({url: url}).count == 0 owner, name = link[:url].split('/').last(2) repo = Octokit.repo(owner + '/' + name) attrs = [:id, :name, :full_name, :forks_count, :created_at, :updated_at, :pushed_at].inject({}) do |memo, key| memo[key] = repo[key] memo end attrs[:atom_url] = link[:atom_url] attrs[:url] = url attrs[:owner_login] = repo.owner.login attrs[:stars_count] = repo.stargazers_count Repo.create(attrs) end end end def self.start perform_async end end
module Light module Decorator module Concerns module Associations module CollectionProxy extend ActiveSupport::Concern # Decorate ActiveRecord::Model associations # # @param [Hash] options (optional) # @return [ActiveRecord::Associations::CollectionProxy] def decorate(options = {}) @decorated = true override_scope(options) override_load_target(options) self end # Check current association is decorated or not # # @return [Bool] def decorated? !@decorated.nil? end private def override_scope(options) @association.define_singleton_method :scope do super().decorate(options) end end def override_load_target(options) @association.define_singleton_method :load_target do super().map { |target| target.decorate(options) } end end end end end end end
module Hayaku::WebSockets class ListenerManager def initialize @listeners = [] end # initialize def register(listener) if listener.is_a?(Hayaku::WebSockets::Listener) @listeners << listener end end def for(connection, event) connection = connection.to_s event = event.to_s @listeners.select{ |l| l.name == connection && l.event == event } end end # ListenerManager end
class AddSecretTokenToGsParameter < ActiveRecord::Migration def up require 'securerandom' GsParameter.create(:name => 'SECRET_TOKEN', :section => 'Cookies', :value => SecureRandom.hex(64), :class_type => 'String') end def down GsParameter.where(:name => 'SECRET_TOKEN').destroy_all end end
class UsersController < ApplicationController before_action :authenticate_user! #before_action :require_admin def index @users=User.all end def show end def new @user=User.new end def create @user = User.new(user_params) respond_to do |format| if @user.save format.html { redirect_to @unit, notice: 'User was successfully created.' } format.json { render action: 'show', status: :created, location: @user } else format.html { render action: 'new' } format.json { render json: @user.errors, status: :unprocessable_entity } end end end def edit end def update if current_user.update_attributes(user_params) flash[:notice] = "User information updated" redirect_to edit_user_registration_path else flash[:error] = "Invalid user information" redirect_to edit_user_registration_path end end private def user_params params.require(:user).permit(:name, :email, :password ) end end
json.array!(@words) do |word| json.extract! word, :id, :name, :definition, :example json.url word_url(word, format: :json) end
#!/usr/bin/env jruby require 'jrubyfx' class LineChart < JRubyFX::Application def start(stage) months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] values = [[23, 14, 15, 24, 34, 36, 22, 45, 43, 17, 29, 25], [33, 34, 25, 44, 39, 16, 55, 54, 48, 27, 37, 29], [44, 35, 36, 33, 31, 26, 22, 25, 43, 44, 45, 44]] with(stage, title: "Line Chart Sample") do stage.layout_scene(800, 600) do line_chart(category_axis, number_axis(label: :Month), title: :Stocks) do values.length.times do |j| xy_chart_series(name: "Portfolio #{j+1}") do months.length.times { |i| xy_chart_data(months[i], values[j][i]) } end end end end stage.show end end end LineChart.launch
# -*- mode:ruby; coding:utf-8 -*- require 'www/enbujyo/helper' module WWW class Enbujyo class Movie include WWW::Enbujyo::Utils STATES = [:none, :accepted, :encoding, :completed, :downloaded, :unavailable] RESULT = [:win, :draw, :lose] # needed attr_reader :title, :date, :result, :status # maybe nil attr_reader :encoded_at, :requested_at, :bought_at, :published_at attr_reader :download_limit, :download_left attr_reader :thumbnail attr_reader :url, :delete_url attr_reader :id attr_reader :game attr_reader :yours def initialize(agent, info, game, max_download = 5) @agent = agent @game = game @title = info[:title] or warn 'Movie: title not found' @date = info[:date] or warn 'Movie: date not found' @result = info[:result] @result = case info[:result] when /勝利/ : :win when /敗北/ : :lose when /分/ : :draw else warn 'Movie: result not found' end @status = case info[:encode_status] when /受付中/ : :accepted when /エンコード中/ : :encoding else if info[:yours] :yours elsif info[:download_left].nil? :completed elsif info[:download_left] > 0 :downloaded else :unavailable end end @encoded_at = info[:encoded_at] @requested_at = info[:requested_at] @bought_at = info[:bought_at] @published_at = info[:published_at] @download_limit = info[:download_limit] @download_left = info[:download_left] @thumbnails = info[:thumbnails] @url = info[:url] || info[:purchase_url] @id = Movie.url_to_id(@url) if @url @delete_url = info[:delete_url] end def download unless @url warn "Can't download this movie yet." return false end case @status when :completed download_completed(@url) when :downloaded if /download-conf.html/ =~ @url download_completed(@url) else download_downloaded(@url) end else warn "Can't download this movie." return false end end def downloadable? [:downloaded, :completed].include? @status end def self.url_to_id(url) url.scan(/u=(.*)/).to_s end private def download_completed(url) page = @agent.auth_get url # XXX: 動画券がないときの処理. link = page.links.find{|l| /download-ok\.html/ =~ l.href } if link download_downloaded(page.uri + link.href) else warn "Download link is not found in #{page.uri}" false end end def download_downloaded(url) page = @agent.auth_get url link = page.links.find{|l| /download.cgi/ =~ l.href } if link download_movie(@agent, page.uri + link.href) else warn "Download link is not found in #{page.uri}" false end end def self.movietype_query(movietype) case movietype when 0, '0', :normal_normal, :nn '0' when 1, '1', :normal_reverse, :nr '1' when 2, '2', :fixed_normal, :fn '2' when 3, '3', :fixed_reverse, :fr '3' when 's', :small 's' else raise ArgumentError, "MovieType #{movietype} is not valid." end end end end end
class JoinTableBoxContract < ApplicationRecord belongs_to :box_simulation belongs_to :box_contract end
class CategoriesController < ApplicationController before_action :fetch_common_data def show @category = Category.find params[:id] @products = @category.products.onshelf.page(params[:page] || 1).per(params[:per_page] || 12).order(id: "desc").includes(:main_picture) end end
class AddCreateTimeToArticles < ActiveRecord::Migration def change add_column :articles, :create_time, :date, :null => false, :default => DateTime.now end end
require "rails_helper" RSpec.describe DayHelper, type: :helper do describe "#doy_to_date" do it "turns year and day to a date" do expect(doy_to_date(2018, 2)).to eq(Date.new(2018, 1, 2)) end it "respects strings as input as well" do expect(doy_to_date("2019", "5")).to eq(Date.new(2019, 1, 5)) end end end
class AgendasController < ApplicationController before_action :find_agenda, except: [:index, :new, :create] def index @agendas = current_user.agendas.all end def new @agenda = current_user.agendas.build end def create @agenda = current_user.agendas.build(agenda_params) if @agenda.save flash[:notice] = "New agenda saved!" redirect_to @agenda else flash[:notice] = "Something went wrong" render :new end end def edit end def update @agenda.update(agenda_params) redirect_to agendas_path end def destroy @agenda.destroy flash[:notice] = "Agenda deleted" redirect_to my_agendas_path end private def find_agenda @agenda = Agenda.find(params[:id]) end def agenda_params params.require(:agenda).permit(:title, :body, :tags) end end
# @param {Integer[]} nums # @return {Integer} def num_identical_pairs(nums) good_pairs_count = 0 0.upto(nums.length - 1) do |i| 1.upto(nums.length - 1) do |j| if nums[i] == nums[j] && i < j good_pairs_count += 1 end end end return good_pairs_count end
class Cellnum attr_accessor :owner attr_reader :code @@Size=48 def initialize(x) if x.is_a? Cellnum @val=x.val @code=x.code else @code=nil @val=Cellnum.to_bin_range(x.to_i,@@Size); end end def val @val end def val=(v) @val=v @code=nil end def +(x) Cellnum.new(@val+x.to_i) end def -(x) Cellnum.new(@val-x.to_i) end def *(x) Cellnum.new(@val*x.to_i) end def /(x) Cellnum.new(@val/x.to_i) end def %(x) Cellnum.new(@val % x.to_i) end def &(x) Cellnum.new(@val & x.to_i) end def |(x) Cellnum.new(@val | x.to_i) end def ^(x) Cellnum.new(@val ^ x.to_i) end def not Cellnum.new( to_bin.tr("01","10").rjust(@@Size,"1").to_i(2)) end def ==(x) @val==x.to_i end def <=(x) @val<=x.to_i end def >=(x) @val>=x.to_i end def >(x) @val>x.to_i end def <(x) @val<x.to_i end def to_i return @val end def to_s return "#"+@val.to_s end def to_bin #Cellnum.to_bin(@val,@@Size) Cellnum.to_bin_48(@val) end def Cellnum.to_bin_48(x) y=to_bin_range_48(x); (y>=0)? format("%b",x).rjust(48,"0") : format("%b",x)[3..-1].rjust(48,"1"); end def Cellnum.to_bin_range_48(x); x+=(140737488355328); x%=281474976710656; x-(140737488355328); end def Cellnum.to_bin(x,bits) y=to_bin_range(x,bits); (y>=0)? format("%b",x).rjust(bits,"0") : format("%b",x)[3..-1].rjust(bits,"1"); end def Cellnum.to_bin_range(x,bits); p=2**bits; x+=(p>>1); x%=p; x-(p>>1); end def Cellnum.from_bin(x) if x[0..0]=="1" then return -(x.tr("01","10").to_i(2))-1 else return x.to_i(2) end end def Cellnum.to_16_bit(x) to_bin(x,16) end def Cellnum.from_16_bit(x) from_bin(x) end def to_code() return @code if @code @code=Disassembler.bin_to_code(to_bin) return @code end end
require 'rspec' require 'pry' require 'colorize' puts "\nBANKING CODE CHALLENGE".yellow puts "XXXXXXXXXXXXXXXXXXXXXX".yellow puts "\nPART 1".magenta puts "\nCreate the models and their relationships to accurately reflect banks, accounts and transfers.".green bank1 = BankingCodeChallenge::Bank.new("Bank1") account_1_1 = BankingCodeChallenge::Account.new(1111,bank1,50500, "Jim") account_1_2 = BankingCodeChallenge::Account.new(1122,bank1,2000) bank1.addAccount(account_1_1) bank1.addAccount(account_1_2) puts "\nFirst bank name: " + bank1.name puts "\nFirst bank accounts: " bank1.accounts.map{|a| puts "account number: " + a.number.to_s + " balance: €" + a.balance.to_s } bank2 = BankingCodeChallenge::Bank.new("Bank2") account_2_1 = BankingCodeChallenge::Account.new(2211,bank2,3000, "Emma") account_2_2 = BankingCodeChallenge::Account.new(2222,bank2,4000) bank2.addAccount(account_2_1) bank2.addAccount(account_2_2) puts "\nSecond bank name: " + bank2.name puts "\nSecond bank accounts: " bank2.accounts.map{|a| puts "account number: " + a.number.to_s + " balance: €" + a.balance.to_s } puts "\nTransfer €500 by INTRA-BANK transfer".green puts "\nBEFORE transfer".green puts bank1.name puts "account number: " + account_1_1.number.to_s + " balance: €" + account_1_1.balance.to_s puts "account number: " + account_1_2.number.to_s + " balance: €" + account_1_2.balance.to_s puts "history of the transfers: " + bank1.transfers.count.to_s intraBank = BankingCodeChallenge::IntraBank.new(account_1_1, account_1_2, 500) intraBank.deliver puts "\nTransfering...".cyan puts "\nAFTER transfer".green puts bank1.name puts "Transfer status: " + intraBank.status puts "account number: " + account_1_1.number.to_s + " balance: €" + account_1_1.balance.to_s puts "account number: " + account_1_2.number.to_s + " balance: €" + account_1_2.balance.to_s puts "history of the transfers: " + bank1.transfers.count.to_s puts "\nTransfer €500 by INTER-BANK transfer".green puts "\nBEFORE transfer".green puts bank1.name puts "account number: " + account_1_1.number.to_s + " balance: €" + account_1_1.balance.to_s puts "history of the transfers: " + bank1.transfers.count.to_s puts bank2.name puts "account number: " + account_2_1.number.to_s + " balance: €" + account_2_1.balance.to_s puts "history of the transfers: " + bank2.transfers.count.to_s interBank = BankingCodeChallenge::InterBank.new(account_1_1, account_2_1, 500) interBank.deliver puts "\nTransfering...".cyan puts "\nAFTER transfer".green if interBank.status == "failed delivery" puts "Transfer status: Transfer failed by 30% chance of failure." else puts "Transfer status: " + interBank.status end puts bank1.name puts "account number: " + account_1_1.number.to_s + " balance: €" + account_1_1.balance.to_s puts "history of the transfers: " + bank1.transfers.count.to_s puts bank2.name puts "account number: " + account_2_1.number.to_s + " balance: €" + account_2_1.balance.to_s puts "history of the transfers: " + bank2.transfers.count.to_s puts "\nPART 2".magenta puts "\nJim has an account on the bank A and Emma has an account on the bank B." puts "Jim owes Emma 20000€. Emma is already a bit angry, because she did not get the money although Jim told her that he already sent it." puts "Help Jim send his money by developing a transfer​ ​agent​." agent = BankingCodeChallenge::Agent.new() puts "This agent assures that everybody gets their money." puts "When the agent receives an order to transfer money from account A to account B," puts "he issues transfers considering commissions,transfer limits and possibility of transfer failures." puts "\nTransfer €2000 by an Agent".green puts "\nBEFORE transfer" puts bank1.name puts account_1_1.holder + "´s account balance: €" + account_1_1.balance.to_s puts "history of the transfers: " + bank1.transfers.count.to_s puts bank2.name puts account_2_1.holder + "´s account balance: €" + account_2_1.balance.to_s puts "history of the transfers: " + bank2.transfers.count.to_s status = agent.makeTransfer(20000,account_1_1,account_2_1) puts "\nTransfering...".cyan puts "\nAFTER transfer" puts "Transfer status: " + status puts bank1.name puts account_1_1.holder + "´s account balance: €" + account_1_1.balance.to_s puts "history of the transfers: " + bank1.transfers.count.to_s puts bank2.name puts account_2_1.holder + "´s account balance: €" + account_2_1.balance.to_s puts "history of the transfers: " + bank2.transfers.count.to_s
#! /usr/bin/env ruby # # script used to start ocean visualization environment # loads the flat_fish.world # require 'vizkit' require 'rock/bundle' require 'rock/gazebo' require 'sdf' # # add model paths to GAZEBO_MODEL_PATH variable # ENV['GAZEBO_MODEL_PATH'] = "#{ENV['GAZEBO_MODEL_PATH']}:#{ENV['AUTOPROJ_CURRENT_ROOT']}/robots:#{Bundles.find_dirs('models', 'sdf', :all => true, :order => :specific_first).first}" Rock::Gazebo.initialize Bundles.initialize sdf = SDF::Root.load("scenes/flat_fish/flat_fish.world") sdf.each_model(recursive: true) do |model| begin task_name = "gazebo:#{model.full_name.gsub('::', ':')}" task = Bundles.get(task_name) rescue Exception => e puts e.message next end task_proxy = task.to_async #set the property here begin Orocos.conf.apply(task, [model.name]) rescue warn "unable to apply config to #{model.name}" end task.to_async.on_reachable do begin if task_proxy.rtt_state == :PRE_OPERATIONAL task_proxy.configure end if task_proxy.rtt_state == :STOPPED task_proxy.start end state = task_proxy.rtt_state if state != :RUNNING STDERR.puts "could not start #{task_name} (currently in state #{state})" end rescue Exception => e STDERR.puts "failed to start #{task_name}: #{e}" end end end # # call the script rock-gazebo-viz # rock-gazebo-viz 'sdf world file name', --env=plugin_name # exec("rock-gazebo-viz", "scenes/flat_fish/flat_fish.world", "--env=Ocean")
require_relative 'kii_api' require_relative 'kii_object' class KiiBucket include KiiAPI include KiiObjectPersistance def initialize name, context, path @name = name @context = context @path = path end def new_object data KiiObject.new data, @context, "#{@path}/buckets/#{@name}/objects" end def get_objects headers = { content_type: "application/vnd.kii.QueryRequest+json" } data = { bucketQuery: { clause: { type: :all } } } @context.request :post, "#{@path}/buckets/#{@name}/query", data.to_json, headers end end
module Kademy module Locale LOCALE_SUBDOMAINS = { "en" => 'www', "es" => 'es-es', "de" => 'de', "fr" => 'fr', "pt" => 'pt' } def self.get_locale_subdomain(locale = nil) check(locale) LOCALE_SUBDOMAINS[locale] end def self.check(locale=nil) raise UnsupportedLocaleError, "The locale #{locale} is not supported" unless LOCALE_SUBDOMAINS[locale] end end end
RSpec.describe Dashing::DashboardsController do before do @routes = Dashing::Engine.routes end describe 'GET "index"' do def action get :index end it 'responds success' do action expect(response).to be_success end end describe 'GET "show"' do def action(params = {}) get :show, params end context 'when template exists' do it 'responds success' do action(name: 'foo') expect(response).to be_success end end context 'when template does not exist' do it { expect { action }.to raise_error } it { expect { action(name: 'bar') }.to raise_error } end end end
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "celly/version" Gem::Specification.new do |s| s.name = "celly" s.version = Celly::VERSION s.authors = ["Jared Pace"] s.email = ["jared@codeword.io"] s.homepage = "" s.summary = %q{Sends a reimbursement form for your ATT cell phone bill} s.description = %q{Automate sending reimbursement forms for your cell phone account, if your company does that sort of thing} s.rubyforge_project = "celly" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] # specify any dependencies here; for example: # s.add_development_dependency "rspec" s.add_runtime_dependency 'capybara' s.add_runtime_dependency 'capybara-webkit' s.add_runtime_dependency 'pdfkit' s.add_runtime_dependency 'pony' end
class AddSeveralAttrToEpisodes < ActiveRecord::Migration[5.0] def change change_table :episodes do |t| t.boolean "favorite" t.boolean "seen" t.integer "rating" end change_column_default :episodes, :favorite, false change_column_default :episodes, :seen, false change_column_default :episodes, :favorite, nil end end
# frozen_string_literal: true module HelpScout class API class Client attr_reader :authorize def initialize(authorize: true) @authorize = authorize end def connection @_connection ||= build_connection.tap do |conn| if authorize? HelpScout::API::AccessToken.refresh! conn.authorization(:Bearer, access_token) if access_token end end end private def access_token HelpScout.access_token&.value end def authorize? authorize end def build_connection Faraday.new(url: BASE_URL) do |conn| conn.request :json conn.response(:json, content_type: /\bjson$/) conn.adapter(Faraday.default_adapter) end end end end end
class CreateStatuses < ActiveRecord::Migration def change create_table :statuses do |t| t.integer :user_id t.string :title t.text :content t.timestamps null: false end end end
module MTMD module FamilyCookBook class Pagination PAGE_SIZE = 20 PAGE_NUMBER = 1 attr_reader :page_size, :page_number attr_accessor :errors_array, :total def initialize(options = {}) options = options.symbolize_keys @errors_array = [] @total = options.fetch(:total, nil) @page_size = options.fetch(:limit, PAGE_SIZE).to_i @page_number = options.fetch(:page, PAGE_NUMBER).to_i end def valid? if page_size.to_i > PAGE_SIZE errors_array << "Page can have only #{PAGE_SIZE} items." return false end true end def previous return nil if page_number == 1 page_number-1 end def next page_number+1 end def last return nil unless total total_pages end def first 1 end def offset return 0 if page_number == 1 page_number * page_size end def limit page_size end def errors errors_array end def total_pages value = total.to_f / page_size.to_f return value.ceil if value < 1.0 value.to_i end end end end
# ### `Recipe` # Build the following methods on the Recipe class class Recipe @@all = [] def initialize(name) @name = name @@all << self end # - `Recipe.all` # should return all of the recipe instances def self.all @@all end # - `Recipe.most_popular` # should return the recipe instance with the highest number of users (the recipe that has the most recipe cards) # - `Recipe#users` # should return the user instances who have recipe cards with this recipe def get_users RecipeCard.all.select do |recipe_card| recipe_card.recipe == self end end def users get_users.collect do |recipe_card| recipe_card.user end end # - `Recipe#ingredients` # should return all of the ingredients in this recipe def get_ingredients RecipeIngredient.all.select do |stuff| stuff.recipe == self end end def ingredients get_ingredients.collect do |double_stuff| double_stuff.ingredient end end # - `Recipe#allergens` # should return all of the ingredients in this recipe that are allergens # - `Recipe#add_ingredients` # should take an array of ingredient instances as an argument, and associate each of those ingredients with this recipe end
FactoryGirl.define do sequence(:random_string) {|n| SecureRandom.hex} sequence(:user_email) {|n| "somebody#{n}@test.com"} factory :user do email {generate(:user_email)} password {generate(:random_string)} factory :admin do admin true end factory :provider_admin do association :provider, factory: :provider provider_admin true end factory :provider_user do association :provider, factory: :provider end end end
Rails.application.routes.draw do get 'listings/index' get 'listings/new' get 'listings/show' get 'listings/edit' get 'categories/new' get 'categories/show' devise_for :users resources :listings root'listings#index' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
require File.dirname(__FILE__) + '/../../test_helper' class UserRoutingTest < ActionController::TestCase tests UserController test 'route to :show' do assert_routing '/user', { :controller => 'user', :action => 'show' } end test 'route to :new' do assert_routing '/user/new', { :controller => 'user', :action => 'new' } end test 'route to :create' do assert_routing({ :path => '/user', :method => :post }, { :controller => 'user', :action => 'create' }) end test 'route to :edit' do assert_routing '/user/edit', { :controller => 'user', :action => 'edit' } end test 'route to :update' do assert_routing({ :path => '/user', :method => :put }, { :controller => 'user', :action => 'update' }) end test 'route to :destroy' do assert_routing({ :path => '/user', :method => :delete }, { :controller => 'user', :action => 'destroy' }) end test 'helper to :show' do assert_equal '/user', user_path end test 'helper to :new' do assert_equal '/user/new', new_user_path end end
module Peek module Views class AltRoutes < View attr_reader :name # A view that allows for quick toggling of alternative routes. # # name - Text that will be displayed in the peek bar. The name # of the feature or pages that will be toggled. # # Returns Peek::Views::AltRoutes def initialize(options = {}) @name = options.fetch(:name, 'Alternate Routes') end end end end
require 'spec_helper' describe FacebookDialog::OptionSerialization do subject do FacebookDialog::OptionSerialization.new({ response_type: [:code, :token], scope: [:offline_access, :email] }) end it "breaks an array of response types into a comma delimited list" do subject.serialized_hash[:response_type].should eql("code,token") end it "breaks an array of scopes into a comma delimited list" do subject.serialized_hash[:scope].should eql("offline_access,email") end end
require 'ci/common' def mysql_version ENV['FLAVOR_VERSION'] || 'latest' end def mysql_flavor ENV['MYSQL_FLAVOR'] || 'mysql' end def mysql_repo if mysql_flavor == 'mysql' if mysql_version == '5.5' 'jfullaondo/mysql-replication' else 'bergerx/mysql-replication' end elsif mysql_flavor == 'mariadb' 'bitnami/mariadb' end end def mysql_rootdir "#{ENV['INTEGRATIONS_DIR']}/mysql_#{mysql_version}" end container_name = 'dd-test-mysql' container_port = 13_306 slave_container_port = 13_307 namespace :ci do namespace :mysql do |flavor| task before_install: ['ci:common:before_install'] do `docker kill $(docker ps -q --filter name=#{container_name}_slave) || true` `docker rm $(docker ps -aq --filter name=#{container_name}_slave) || true` `docker kill $(docker ps -q --filter name=#{container_name}_master) || true` `docker rm $(docker ps -aq --filter name=#{container_name}_master) || true` end task :install do Rake::Task['ci:common:install'].invoke('mysql') if mysql_flavor == 'mariadb' sh %(docker run -p #{container_port}:3306 --name #{container_name}_master \ -e MARIADB_ROOT_PASSWORD=master_root_password \ -e MARIADB_REPLICATION_MODE=master \ -e MARIADB_REPLICATION_USER=my_repl_user \ -e MARIADB_REPLICATION_PASSWORD=my_repl_password \ -e MARIADB_USER=my_user \ -e MARIADB_PASSWORD=my_password \ -e MARIADB_DATABASE=my_database -d #{mysql_repo}:#{mysql_version}) else sh %(docker run -p #{container_port}:3306 --name #{container_name}_master \ -e MYSQL_ALLOW_EMPTY_PASSWORD=1 -d #{mysql_repo}:#{mysql_version}) end end task before_script: ['ci:common:before_script'] do Wait.for container_port count = 0 logs = `docker logs #{container_name}_master 2>&1` puts 'Waiting for MySQL to come up' if mysql_flavor == 'mariadb' expect_log = 'mariadb successfully initialized' expect_log_up = 'Starting mysqld daemon with databases' else expect_log = 'MySQL init process done. Ready for start up' expect_log_up = 'MySQL init process done. Ready for start up' end until count == 20 || logs.include?(expect_log) sleep_for 2 logs = `docker logs #{container_name}_master 2>&1` count += 1 end raise 'Master not up in time. Failing...' unless logs.include? expect_log_up puts 'MySQL is up!' if mysql_flavor == 'mariadb' sh %(docker run -p #{slave_container_port}:3306 --name #{container_name}_slave \ -e MYSQL_ALLOW_EMPTY_PASSWORD=1 --link #{container_name}_master:master \ -e MARIADB_REPLICATION_MODE=slave \ -e MARIADB_REPLICATION_USER=my_repl_user \ -e MARIADB_REPLICATION_PASSWORD=my_repl_password \ -e MARIADB_MASTER_HOST=master \ -e MARIADB_MASTER_ROOT_PASSWORD=master_root_password -d #{mysql_repo}:#{mysql_version}) else sh %(docker run -p #{slave_container_port}:3306 --name #{container_name}_slave \ -e MYSQL_ALLOW_EMPTY_PASSWORD=1 --link #{container_name}_master:master \ -d #{mysql_repo}:#{mysql_version}) end Wait.for slave_container_port count = 0 logs = `docker logs #{container_name}_slave 2>&1` puts 'Waiting for MySQL to come up' until count == 20 || logs.include?(expect_log) sleep_for 2 logs = `docker logs #{container_name}_slave 2>&1` count += 1 end raise 'Slave not up in time. Failing...' unless logs.include? expect_log_up puts 'MySQL is up!' opts = '' cli_version = mysql_version if mysql_flavor == 'mariadb' opts = '--password=master_root_password' cli_version = 'latest' end sh %(docker run -it --link #{container_name}_master:mysql --rm mysql:#{cli_version} \ sh -c 'exec mysql -h\"$MYSQL_PORT_3306_TCP_ADDR\" -P\"MYSQL_PORT_3306_TCP_PORT\" -uroot \ #{opts} -e \"create user \\"dog\\"@\\"%\\" identified by \\"dog\\"; \ GRANT PROCESS, REPLICATION CLIENT ON *.* TO \\"dog\\"@\\"%\\" WITH MAX_USER_CONNECTIONS 5; \ CREATE DATABASE testdb; \ CREATE TABLE testdb.users (name VARCHAR(20), age INT); \ GRANT SELECT ON testdb.users TO \\"dog\\"@\\"%\\"; \ INSERT INTO testdb.users (name,age) VALUES(\\"Alice\\",25); \ INSERT INTO testdb.users (name,age) VALUES(\\"Bob\\",20); \ GRANT SELECT ON performance_schema.* TO \\"dog\\"@\\"%\\"; \ USE testdb; \ SELECT * FROM users ORDER BY name; "') end task script: ['ci:common:script'] do this_provides = [ 'mysql' ] Rake::Task['ci:common:run_tests'].invoke(this_provides) end task before_cache: ['ci:common:before_cache'] task cleanup: ['ci:common:cleanup'] do `docker kill $(docker ps -q --filter name=#{container_name}_slave) || true` `docker rm $(docker ps -aq --filter name=#{container_name}_slave) || true` `docker kill $(docker ps -q --filter name=#{container_name}_master) || true` `docker rm $(docker ps -aq --filter name=#{container_name}_master) || true` end task :execute do exception = nil begin %w(before_install install before_script).each do |u| Rake::Task["#{flavor.scope.path}:#{u}"].invoke end if !ENV['SKIP_TEST'] Rake::Task["#{flavor.scope.path}:script"].invoke else puts 'Skipping tests'.yellow end Rake::Task["#{flavor.scope.path}:before_cache"].invoke rescue => e exception = e puts "Failed task: #{e.class} #{e.message}".red end if ENV['SKIP_CLEANUP'] puts 'Skipping cleanup, disposable environments are great'.yellow else puts 'Cleaning up' Rake::Task["#{flavor.scope.path}:cleanup"].invoke end raise exception if exception end end end
module FunnelsHelper def funnel_data(params = {}) # format input start_date = Date.today.beginning_of_week end_date = Date.today.end_of_week if params.has_key? :start_date start_date = params[:start_date].to_date.beginning_of_week end if params.has_key? :end_date end_date = params[:end_date].to_date.end_of_week end # get all ranges date_ranges = funnel_date_ranges(start_date, end_date) query_result = run_query sql_query(date_ranges, start_date, end_date) # merge data return merge_date query_result.as_json end def run_query(query) ActiveRecord::Base.connection.execute query end def sql_query(date_ranges, start_date, end_date) " SELECT #{case_generater(date_ranges)} as date_range, workflow_state, COUNT(*) as count FROM applicants WHERE created_at >= '#{format_date start_date}' AND created_at <= '#{format_date end_date}' GROUP BY workflow_state, #{case_generater(date_ranges)} " end def merge_date(sql_result) funnel_json = Hash.new { |h, k| h[k] = Hash.new } sql_result.each do |row| funnel_json[row[0]][row[1]] = row[2] end return funnel_json end def case_generater(date_ranges) query_case = [] date_ranges.each do |range| start_date, end_date = format_date(range[0]), format_date(range[1]) name = "#{start_date}-#{end_date}" query_case << "WHEN created_at >= '#{start_date}' AND created_at <= '#{end_date}' THEN '#{name}'" end return "CASE #{query_case.join(" ")} END" end def funnel_date_ranges(start_date, end_date) ranges = [] (start_date..end_date).step(7).each do |date| ranges << [date.beginning_of_week, date.end_of_week] end return ranges end def format_date(date) date.strftime "%Y-%m-%d" end end
# frozen_string_literal: true # Indexes resources loaded into Fedora from CITI. class CitiIndexer < ActiveFedora::IndexingService def generate_solr_document super.tap do |solr_doc| solr_doc["read_access_group_ssim"] = ["group", "registered"] solr_doc[Solrizer.solr_name("aic_type", :facetable)] = object.class.to_s solr_doc[Solrizer.solr_name("status", :symbol)] = [object.status.pref_label] if object.status solr_doc[Solrizer.solr_name("documents", :symbol)] = object.documents.map(&:uid) solr_doc[Solrizer.solr_name("representations", :symbol)] = object.representations.map(&:uid) solr_doc[Solrizer.solr_name("preferred_representation", :symbol)] = [object.preferred_representation.uid] if object.preferred_representation end end end
class Api::V1::TweetsController < ApplicationController module TwitterAuthentication def client Twitter::REST::Client.new do |config| config.consumer_key = ENV.fetch('TWITTER_CONSUMER_KEY') config.consumer_secret = ENV.fetch('TWITTER_CONSUMER_SECRET') config.access_token = ENV.fetch('TWITTER_ACCESS_TOKEN') config.access_token_secret = ENV.fetch('TWITTER_ACCESS_SECRET') end end end def show topic = Topic.find_by_querytext(params[:topic]) unless topic head :no_content and return end render json: Tweet.eager_load(:topic).where(:topic => topic).order(posted_on: :desc).limit(10) end def post unless params[:body] head :bad_request and return end client.update(params[:body]) end include TwitterAuthentication end
class TagTimeRange < ActiveRecord::Base # Attributes # ---------- belongs_to :time_range belongs_to :tag end
class ChangeOrderCloumnName < ActiveRecord::Migration[5.1] def change rename_column :orders, :status, :order_status end end
# frozen_string_literal: true module TimeClusterHelper STATUS_INDICATORS = {bad: %w([* *]), questionable: %w([ ])}.with_indifferent_access def time_cluster_display_data(cluster, display_style, options = {}) with_status = options[:with_status] formatted_times = time_cluster_data(cluster, display_style).map { |time| cluster_display_formatted_time(time, cluster, display_style) } time_array = if with_status formatted_times.zip(cluster.time_data_statuses).map do |formatted_time, status| brackets = STATUS_INDICATORS.fetch(status, ['', '']) formatted_time ? "#{brackets.first}#{formatted_time}#{brackets.last}" : '--:--:--' end else formatted_times end stop_indicator = cluster.show_stop_indicator? ? fa_icon('hand-paper', style: 'color: Tomato') : '' content_tag(:div) do concat time_array.join(' / ') concat ' ' concat stop_indicator end end def time_cluster_export_data(cluster, display_style) time_cluster_data(cluster, display_style) .map { |time| cluster_export_formatted_time(time, cluster, display_style) } end def time_cluster_data(cluster, display_style) case display_style.to_sym when :segment cluster.aid_time_recordable? ? [cluster.segment_time, cluster.time_in_aid] : [cluster.segment_time] when :ampm cluster.absolute_times_local when :military cluster.absolute_times_local when :early_estimate cluster.absolute_estimates_early_local when :late_estimate cluster.absolute_estimates_late_local else cluster.times_from_start end end def cluster_display_formatted_time(time, cluster, display_style) case display_style.to_sym when :segment cluster.finish? ? time_format_xxhyymzzs(time) : time_format_xxhyym(time) when :ampm cluster.finish? ? day_time_format_hhmmss(time) : day_time_format(time) when :military cluster.finish? ? day_time_military_format_hhmmss(time) : day_time_military_format(time) when :early_estimate cluster.finish? ? day_time_format_hhmmss(time) : day_time_format(time) when :late_estimate cluster.finish? ? day_time_format_hhmmss(time) : day_time_format(time) else cluster.finish? ? time_format_hhmmss(time) : time_format_hhmm(time) end end def cluster_export_formatted_time(time, cluster, display_style) case display_style.to_sym when :segment time ? time_format_hhmmss(time) : '' when :ampm time ? day_time_format_hhmmss(time) : '' when :military time ? day_time_military_format_hhmmss(time) : '' else time ? time_format_hhmmss(time) : '' end end end
desc 'Enables default actions for all existing projects' task enable_default_actions: [:environment] do Project.all.each do |project| if project.actions.blank? project.actions = GithubAction::DEFAULT_ACTIONS project.save! end end end
## #* Order database model #* generated by scaffold class Order < ActiveRecord::Base attr_accessible :address, :email, :name, :pay_type ## # the following relations are described in project.rdoc has_many :line_items , :dependent => :destroy ## # the two common payment types PAYMENT_TYPES = [ "Direct pay after delivery" , "Credit card" ] ## #* validators check the form to have the correct values #* any problems with the form is shown to him , after he tries to place the order validates :name, :address, :email, :pay_type, :presence => true validates :pay_type, :inclusion => PAYMENT_TYPES def add_line_items_from_cart(cart) ## # the line_items are moved into the order cart.line_items.each do |item| item.cart_id = nil line_items << item end end end
# $Id$ require 'attr_encrypted' class BackupSource < ActiveRecord::Base belongs_to :member, :foreign_key => 'user_id' belongs_to :backup_site has_many :backup_source_days has_many :backup_photo_albums has_many :backup_source_jobs @@max_consecutive_failed_backups = 25 # Should be about 1 day's worth @@max_notification_alerts = 3 # Max number of error emails to send cattr_reader :max_consecutive_failed_backups cattr_reader :max_notification_alerts #after_create :cb_after_create_init_backup # The new hotness # TODO: migrate unencrypted values to these columns, then rename columns & drop these attr_encrypted :auth_login2, :auth_password2, :key => 'peek a choo moo', :prefix => '', :suffix => '_enc' named_scope :by_site, lambda {|name| { :joins => :backup_site, :conditions => {'backup_sites.name' => name} } } named_scope :twitter, lambda { { :joins => :backup_site, :conditions => {'backup_sites.name' => BackupSite::Twitter} } } named_scope :facebook, lambda { { :joins => :backup_site, :conditions => {'backup_sites.name' => BackupSite::Facebook} } } named_scope :blog, lambda { { :joins => :backup_site, :conditions => {'backup_sites.name' => BackupSite::Blog} } } named_scope :gmail, lambda { { :joins => :backup_site, :conditions => {'backup_sites.name' => BackupSite::Gmail} } } named_scope :picasa, lambda { { :joins => :backup_site, :conditions => {'backup_sites.name' => BackupSite::Picasa} } } named_scope :linkedin, lambda { { :joins => :backup_site, :conditions => {'backup_sites.name' => BackupSite::Linkedin} } } named_scope :active, :conditions => { :auth_confirmed => true, :backup_state => [:pending, :backed_up], :deleted_at => nil } named_scope :needs_scan, :conditions => {:needs_initial_scan => true} named_scope :photo_album, lambda {|id| { :joins => :backup_photo_albums, :conditions => {'backup_photo_albums.source_album_id' => id} } } acts_as_state_machine :initial => :pending, :column => 'backup_state' state :pending state :backed_up, :enter => :do_backed_up state :disabled event :backup_complete do transitions :from => [:pending, :disabled], :to => :backed_up end event :backup_error_max_reached do transitions :from => [:pending, :backed_up], :to => :disabled end # Returns most recent BackupSourceJob def latest_backup backup_source_jobs.newest end # Returns backup data type sets associated with this site def backup_data_sets EternosBackup::SiteData.site_data_sets(backup_site) end # Uses searchlogic association named_scope to find all photos # def photos # backup_photo_albums.backup_photos_id_not_null.map(&:backup_photos) # end def login_failed!(error) update_attributes(:last_login_attempt_at => Time.now.utc, :auth_error => error) end def logged_in! t = Time.now update_attributes(:last_login_attempt_at => t, :last_login_at => t, :auth_error => nil) end def auth_required? true end def confirmed? !!auth_confirmed end def confirmed! unless confirmed? update_attribute(:auth_confirmed, true) # Initiate backup on auth confirmation reload.backup end end def active? !self.disabled? && !self.deleted_at end # add this backup source to backup queue # TODO: CAN'T DO THIS UNLESS WE CAN CONNECT TO REMOTE RABBITMQ def backup #EternosBackup::BackupJobPublisher.add_source(self) end def next_backup_at EternosBackup::BackupScheduler.next_source_backup_at(self) end # Counts how many times most recent backup jobs have failed in a row, # Stopping after 1st successful backup def consecutive_failed_backup_jobs count = 0 backup_source_jobs.descend_by_created_at.each do |job| break if job.successful? count += 1 end count end # Helper to determine if this source has backup problems that should be reported def requires_error_alert? active? && (self.error_notifications_sent < max_notification_alerts) && backup_broken? end def backup_broken? consecutive_failed_backup_jobs >= self.max_consecutive_failed_backups end def sent_error_alert increment!(:error_notifications_sent) end def update_last_backup_times update_attributes(:last_backup_at => Time.now.utc, :latest_day_backed_up => Date.today) save(false) end # Delegates backup completion info to the source owner def on_backup_complete(info={}) unless info[:errors] # Reset error notification count after succesful backups update_attributes(:error_notifications_sent => 0, :auth_error => nil) end update_last_backup_times member.backup_finished!(info) end # TODO: MOVE TO MIX-IN MODULE # These photo methods should not be here def photo_album(id) backup_photo_albums.find_by_source_album_id(id) end def photos backup_photo_albums.map(&:backup_photos).flatten end def photos_between_dates(s, e) BackupPhoto.find backup_photo_albums.photos_between_dates(s, e).map(&:id) end # ABSTRACT CLASS - BACKUP SOURCES SHOULD IMPLEMENT # STORAGE METRIC METHODS def num_items backup_photo_albums.size end def bytes_backed_up 0 end # Descriptive title for source def description returning String.new do |d| d << backup_site.name.capitalize if title && !title.blank? d << " - " << title elsif respond_to?(:name) && !name.blank? d << " - " << name end end end # Returns string description of current backup status def backup_status_desc status = if !confirmed? 'Authentication Required' elsif active? if lb = latest_backup lb.successful? ? 'OK' : 'Failed' else 'OK' end else 'Inactive' end if (status == 'Failed') && backup_broken? status = EternosBackup::BackupSourceError.new(self).short_error end status end def last_backup_date last_backup_date = if dt = (latest_backup ? latest_backup.finished_at : last_backup_at) dt.to_date else 'None' end end protected # Called by state machine entering :backed_up # Updates source backup related attributes def do_backed_up self.update_attributes(:needs_initial_scan => false) update_last_backup_times end end
class RenameOnlineToState < ActiveRecord::Migration class Instance < ActiveRecord::Base; end def up add_column :gpdb_instances, :state, :string, :default => 'online' GpdbInstance.reset_column_information GpdbInstance.update_all(:state => 'online') GpdbInstance.where("online = false").update_all(:state => 'offline') remove_column :gpdb_instances, :online end def down add_column :gpdb_instances, :online, :boolean, :default => true GpdbInstance.reset_column_information GpdbInstance.where("state <> 'online'").update_all(:online => false) remove_column :gpdb_instances, :state end end
namespace :count_models do desc 'Count all of the Models.' task :models => :environment do puts ' ' puts 'Current Movies = ' + Movie.count.to_s puts ' ' puts 'Current Theaters = ' + Theater.count.to_s puts ' ' puts 'Current Users = ' + User.count.to_s puts ' ' puts 'Current Viewers = ' + Viewer.count.to_s end end
require_relative 'spec_helper' require_relative '../lib/friend_entries_fetcher' describe FriendEntriesFetcher do let(:lj_driver) { double(:lj_driver) } let(:rss_items_extractor) { double(:rss_items_extractor) } let(:friend_entries_fetcher) { FriendEntriesFetcher.new lj_driver, rss_items_extractor } it 'fetches user entries' do entry1, entry2 = build(:entry), build(:entry) lj_driver.stub(:user_rss).with('artemave').and_return('xml') rss_items_extractor.stub(:extract_items).with('xml').and_return([entry1, entry2]) entries = friend_entries_fetcher.fetch 'artemave' entries.should == [entry1, entry2] end it 'returns empty list as entries for wrong usernames' do lj_driver.stub(:user_rss).with('_artem').and_raise(LjDriver::BadUserName) entries = friend_entries_fetcher.fetch '_artem' entries.should == [] end end
class Microinjection < ActiveRecord::Base #Note that Andreas should be able to create one of these records with almost nothing for a clone validates_presence_of :status, :clone_name, :mgi_accession_id #WHEN an id is stamped on, it should be unique across all records validates_uniqueness_of :production_centre_mi_id, :allow_nil => true validates_inclusion_of :status, :in => %w(Unassigned, MicroinjectionInProgress, GenotypeConfirmed, AvailableForDistribution), :message => "status {{value} invalid - must be one of Unassigned, MicroinjectionInProgress, GenotypeConfirmed, AvailableForDistribution" validates_inclusion_of :production_centre_name, :in => %w(HAR ICS CNR SNG or HMGU), :message => "{{value}} must be one of HAR ICS CNR SNG or HMGU}" validates_numericality_of :chimeras_with_het_offspring, :number_het_offspring, :num_blasts, :num_transferred, :number_born, :number_male_chimeras, :number_female_chimeras, :number_male_100_percent, :number_male_gt_80_percent, :number_male_40_80_percent, :number_male_lt_40_percent, :number_chimera_mated, :number_chimera_mating_success, :chimeras_with_glt_from_genotyping, :het_rate_lt_10_percent, :het_rate_btw_10_50_percent, :het_rate_gt_50_percent, :het_rate_gt_50_percent, :number_het_offspring, :number_live_glt_offspring # validate :uninjected_clone_must_be_unassigned # def uninjected_clone_must_be_unassigned # if(microinjection_date.nil? && !(status == "Unassigned")){ # errors.add(:status, " status must actually be Unassigned if MI has no microinjection date") # } # end end
class Post < ActiveRecord::Base acts_as_taggable_on :post_tags has_attached_file :image, :storage => :s3, :s3_credentials => "#{Rails.root.to_s}/config/s3.yml", :path => ":rails_root/public/ckeditor_assets/pictures/:id/:style_:basename.:extension", :styles => { :medium => "300x300>",:small=> "200x200", :thumb => "100x100>"}, :default_url => "http://placehold.it/300x300" validates_attachment_content_type :image, :content_type => %w(image/jpeg image/jpg image/png) end
def is_valid(s) hash = { '(' => ')', '{' => '}', '[' => ']' } arr = Array.new (0...s.size).each do |index| if arr.empty? or hash[arr.last] != s[index] arr.push(s[index]) else arr.pop end end return arr.empty? end puts is_valid "()" puts is_valid "()[]{}" puts is_valid "(]" puts is_valid "([)]" puts is_valid "{[]}"
class ApplicationController < ActionController::API def encode_token(payload) JWT.encode(payload, hmac_secret, 'HS256') end def user_payload(user) {user_id: user.id} end def hmac_secret ENV['JWT_SECRET_KEY'] end def token request.headers['Authorization'] end def decoded_token JWT.decode(token, hmac_secret, true, {algorithm: "HS256"}) end def logged_in_user User.find(decoded_token[0]['user_id']) end end
#!/usr/local/bin/ruby -w # This program demonstrates a bug in the Sqlite DBD: DBH#do should # return the row processed count, but it returns nil # When run with dbi-0.0.23 this program gives: # Oops! count1=nil require 'dbi' File.delete('foo') if FileTest.exists?('foo') db = DBI.connect('dbi:sqlite:foo') db['AutoCommit'] = true db.do('create table foo(bar varchar(200))') count1 = db.do('insert into foo (bar) values (?)','abc') STDERR.puts "Oops! count1=#{count1.inspect}" if count1 != 1 # workaround count2 = nil db.execute('insert into foo (bar) values (?)','def') do |sth| count2 = sth.rows end STDERR.puts "Oops! count2=#{count2.inspect}" if count2 != 1
class DrugStock < ApplicationRecord belongs_to :facility, optional: true belongs_to :region belongs_to :user belongs_to :protocol_drug validates :in_stock, numericality: true, allow_nil: true validates :received, numericality: true, allow_nil: true validates :for_end_of_month, presence: true scope :with_region_information, -> { select("block_regions.name AS block_region_name, block_regions.id AS block_region_id, drug_stocks.*") .joins("INNER JOIN regions AS facility_regions ON drug_stocks.facility_id = facility_regions.source_id INNER JOIN regions AS block_regions ON block_regions.path = subpath(facility_regions.path, 0, - 1)") } def self.latest_for_facilities_grouped_by_protocol_drug(facilities, end_of_month) drug_stock_list = latest_for_facilities(facilities, end_of_month) || [] drug_stock_list.each_with_object({}) { |drug_stock, acc| acc[drug_stock.protocol_drug.id] = drug_stock } end def self.latest_for_regions_grouped_by_protocol_drug(region, end_of_month) drug_stock_list = latest_for_regions(region, end_of_month) || [] drug_stock_list.each_with_object({}) { |drug_stock, acc| acc[drug_stock.protocol_drug.id] = drug_stock } end def self.latest_for_regions(regions, for_end_of_month) select("DISTINCT ON (region_id, protocol_drug_id) *") .includes(:protocol_drug) .where(region_id: regions, for_end_of_month: for_end_of_month) .order(:region_id, :protocol_drug_id, created_at: :desc) end def self.latest_for_facilities(facilities, for_end_of_month) select("DISTINCT ON (facility_id, protocol_drug_id) *") .includes(:protocol_drug) .where(facility_id: facilities, for_end_of_month: for_end_of_month) .order(:facility_id, :protocol_drug_id, created_at: :desc) end def self.latest_for_facilities_cte(facilities, for_end_of_month) # This is needed to do GROUP queries which do not compose with DISTINCT ON from(latest_for_facilities(facilities, for_end_of_month), table_name) .includes(:protocol_drug) end def self.latest_for_regions_cte(regions, for_end_of_month) # This is needed to do GROUP queries which do not compose with DISTINCT ON from(latest_for_regions(regions, for_end_of_month), table_name) .includes(:protocol_drug) end end
require 'rails_helper' RSpec.describe "locales/edit", type: :view do before(:each) do @locale = assign(:locale, Locale.create!( :name => "MyString", :municipality => nil )) end it "renders the edit locale form" do render assert_select "form[action=?][method=?]", locale_path(@locale), "post" do assert_select "input#locale_name[name=?]" assert_select "input#locale_municipality_id[name=?]" end end end
module API class Entrance < Grape::API # Api logger def self.logger Logger.new("#{Rails.root}/log/api.log") end # 404 rescue_from ActiveRecord::RecordNotFound do rack_response({message: '404 Not found'}.to_json, 404) end # 400 rescue_from Grape::Exceptions::ValidationErrors do |e| rack_response({ status: e.status, message: e.message, errors: e.errors }.to_json, e.status) end # 500 rescue_from :all do |exception| # lifted from https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb#L60 # why is this not wrapped in something reusable? trace = exception.backtrace message = "\n#{exception.class} (#{exception.message}):\n" message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code) message << " " << trace.join("\n ") API::Entrance.logger.add Logger::FATAL, message rack_response({message: '500 Internal Server Error'}.to_json, 500) end before do header 'Content-Type', 'text/json;charset=utf-8' end format :xml default_format :xml helpers API::Helpers mount API::App::Root mount API::Weixin::Root end end
class PdfStatement < Prawn::Document # { "category"=>"M", # "customer"=>{ "birth_date"=>"1953-11-27", # "given_names"=>"Krzysztof", # "id"=>"74975", "name"=>"Ziętara"}, # "date_of_issue"=>"2018-07-13", # "division"=>{ "english_name"=>"VHF radiotelephone operator's certificate", # "id"=>"15", # "name"=>"świadectwo operatora radiotelefonisty VHF", # "number_prefix"=>"MA-", # "short_name"=>"VHF"}, # "id"=>"81115", # "number"=>"MA-05998", # "valid_thru"=>""} # info: # Author – who created the document # CreationDate – the date and time when the document was originally created # Creator – the originating application or library # Producer – the product that created the PDF. In the early days of PDF people would use a Creator application like Microsoft Word to write a document, print it to a PostScript file and then the Producer would be Acrobat Distiller, the application that converted the PostScript file to a PDF. Nowadays Creator and Producer are often the same or one field is left blank. # Subject – what is the document about # Title – the title of the document # Keywords – keywords can be comma separated # ModDate -the latest modification date and time def initialize(certificate_data, view, author, title) super(:page_size => "A4", :page_layout => :portrait, :info => { :Title => title, :Author => author, :Subject => "", :CreationDate => Time.now, } ) @view = view font_families.update("DejaVu Sans" => { :normal => "#{Rails.root}/app/assets/fonts/DejaVuSans.ttf", :bold => "#{Rails.root}/app/assets/fonts/DejaVuSans-Bold.ttf", :italic => "#{Rails.root}/app/assets/fonts/DejaVuSans-Oblique.ttf", :bold_italic => "#{Rails.root}/app/assets/fonts/DejaVuSans-BoldOblique.ttf" }) font "DejaVu Sans", size: 11 logo # header_left_corner header_right_corner qrcode(certificate_data) data(certificate_data) footer end def logo image "#{Rails.root}/app/assets/images/logo_uke_en_do_lewej.png", :at => [0, 780], :height => 25 stroke_line [0,735], [525,735], self.line_width = 0.1 end def qrcode(cert) qrcode_content = "#{Rails.application.secrets[:search_url]}" + "?number_prefix=#{cert[:division][:number_prefix]}&number=#{cert[:number].last(5)}&date_of_issue=#{cert[:date_of_issue]}&valid_thru=#{cert[:valid_thru]}" + "&name=#{cert[:customer][:name]}&given_names=#{cert[:customer][:given_names]}&birth_date=#{cert[:customer][:birth_date]}" print_qr_code(qrcode_content, pos: [390, 170], extent: 144, stroke: false, level: :m) # text_box "#{qrcode_content}", size: 10, # :at => [0, 615], # :width => 500, # :height => 100 end def header_right_corner draw_text "Gdynia, " + Time.now.strftime('%Y-%m-%d'), :at => [400, 710], size: 11 end def data(cert) #move_down 80 #current_row = 525 valid_thru = cert[:valid_thru].present? ? "#{cert[:valid_thru]}" : "---------- (without expiry date)" draw_text "Confirmation #{cert[:division][:short_name]}", :at => [0, 610], size: 14 draw_text "Office of Electronic Communications informs that the certificate:", :at => [0, 560], size: 11 draw_text "Type:", :at => [70, 520], size: 11 draw_text "#{cert[:division][:english_name]} (#{cert[:division][:short_name]})", :at => [150, 520], size: 11 draw_text "No.:", :at => [70, 500], size: 11 draw_text "#{cert[:number]}", :at => [150, 500], size: 11 draw_text "Date of issue:", :at => [70, 480], size: 11 draw_text "#{cert[:date_of_issue]}", :at => [150, 480], size: 11 draw_text "Valid till:", :at => [70, 460], size: 11 draw_text "#{valid_thru}", :at => [150, 460], size: 11 draw_text "has been issued for #{cert[:customer][:name]} #{cert[:customer][:given_names]} (date of birth #{cert[:customer][:birth_date]}).", :at => [0, 420], size: 11 text_box "The above certificate has been issued according to ITU Radio Regulations and the IMO STCW Convention by the " + "President of the Office of Electronic Communications.", size: 11, :align => :justify, :at => [0, 380], :width => 525, :height => 300 # date_start = DateTime.parse('2020/03/01') # date_end = DateTime.parse('2020/08/31') # if cert[:valid_thru].present? # if (date_start...date_end).include?(cert[:valid_thru]) # draw_text "Attention!", :at => [0, 270], size: 12, :style => :bold # text_box "In view of the increasing spread of Coronavirus COVID-19 and the government measures taken to minimise its impact, " + # "the validity of the certificates, which expire after 1 March 2020, is extended until 1 September 2020.", size: 11, :align => :justify, # :at => [0, 260], # :width => 525, # :height => 300, :style => :italic # end # end end def footer stroke_color "BECC25" stroke_line [0, 10], [525,10], self.line_width = 2.0 text "generated from https://confirmation.uke.gov.pl, e-mail: ske.gdynia@uke.gov.pl, © 2018 UKE", size: 6, :style => :italic, :align => :right, :valign => :bottom end end
require 'rails_helper' feature 'message board only shows current day' do context 'as an authorized user' do let(:user) { FactoryGirl.create(:user) } before :each do sign_in_as user end scenario 'I just see messages for today' do family = FactoryGirl.create(:family_membership, user: user).family FactoryGirl.create(:family_message, message: 'This should show for today', family: family, user: user) FactoryGirl.create(:family_message, message: 'This should not be visible', family: family, user: user, created_at: 1.day.ago) visit family_family_messages_path(family.id) expect(page).to have_content 'This should show for today' expect(page).to_not have_content 'This should not be visible' end scenario 'I can see yesterdays messages' do family = FactoryGirl.create(:family_membership, user: user).family FactoryGirl.create(:family_message, message: 'This should show for today', family: family, user: user) FactoryGirl.create(:family_message, message: 'This should not be visible', family: family, user: user, created_at: 1.day.ago) visit family_family_messages_path(family.id) expect(page).to have_content 'This should show for today' expect(page).to_not have_content 'This should not be visible' find(:css, '#prev-day').click expect(page).to_not have_content 'This should show for today' expect(page).to have_content 'This should not be visible' end end context 'as a visitor' do scenario 'I get redirected' do family = FactoryGirl.create(:family) visit family_family_messages_path(family) expect(page).to have_content('sign in') end end end
class MoviesController < ApplicationController def show # show more details about... id = params[:id] || session[:id] # retrieve movie ID from URI route @movie = Movie.find(id) # look up movie by unique ID # will render app/views/movies/show.<extension> by default end def index @movies = Movie.all @all_ratings = Movie.all_ratings # tell index.html.erb which boxes to show if not params.has_key? (:ratings) and not params.has_key? (:column) if session.has_key? (:ratings) redirect_to movies_path(:ratings => session[:ratings]) and return # params[:ratings] = session[:ratings] else # params has no :ratings AND session has no :ratings # nothing to do in this case end if session.has_key? (:column) redirect_to movies_path(:column => session[:column]) and return # params[:column] = session[:column] end end if params.has_key? (:ratings) session[:ratings] = params[:ratings] # added @ratings_to_show = params[:ratings].keys.uniq else # @ratings_to_show = [] @ratings_to_show = @all_ratings end @movies = Movie.with_ratings(@ratings_to_show) if params.has_key? (:column) # to indicate the column we sort on column = params[:column] session[:column] = params[:column] # added @selection_criterion = params[:column] if column == "Title" @movies = @movies.order(:title) else @movies = @movies.order(:release_date) end end @movies end def new # default: render 'new' template end def create @movie = Movie.create!(movie_params) flash[:notice] = "#{@movie.title} was successfully created." redirect_to movies_path end def edit @movie = Movie.find params[:id] end def update @movie = Movie.find params[:id] @movie.update_attributes!(movie_params) flash[:notice] = "#{@movie.title} was successfully updated." redirect_to movie_path(@movie) end def destroy @movie = Movie.find(params[:id]) @movie.destroy flash[:notice] = "Movie '#{@movie.title}' deleted." redirect_to movies_path end private # Making "internal" methods private is not required, but is a common practice. # This helps make clear which methods respond to requests, and which ones do not. def movie_params params.require(:movie).permit(:title, :rating, :description, :release_date) end end
class Card FACE_CARDS_RANKED = [ "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A" ] def initialize(card_str) raise EmptyCardError if card_str.nil? || card_str.empty? @card_str = card_str end def face @card_str[0] end def suit @card_str[1] end class EmptyCardError < StandardError; end end