text
stringlengths
10
2.61M
class GuessingGameRound def initialize(round_number = 1) @won = false @answer = rand(1..10) @round_number = round_number @guesses_used = 0 @guesses_allowed = 3 end def play puts "===Round #{@round_number}===" @guesses_allowed.times do make_guess if @won break end end print_result end def won? @won end def guesses_used @guesses_used end private def make_guess print "Guess a number 1-10 (hint: #{@answer}): " guess = gets.to_i if guess == @answer @won = true else puts "Incorrect." end @guesses_used += 1 end def print_result if @won puts "Correct!" else puts "The answer was #{@answer}." end puts end end class GuessingGame def initialize @rounds = 5 @rounds_won = 0 @total_guesses = 0 end def play @rounds.times do |current_round| round = GuessingGameRound.new(current_round + 1) round.play gather_statistics(round) end print_result end private def gather_statistics(round) if round.won? @rounds_won += 1 end @total_guesses += round.guesses_used end def print_result puts "You won #{@rounds_won} out of #{@rounds} rounds." puts "You made an average of #{@total_guesses / @rounds} guesses each round." end end guessing_game = GuessingGame.new guessing_game.play
class ApplicationController < ActionController::API def authenticate_request auth_token = request.headers['Authorization'] if auth_token token = JsonWebToken.decode(auth_token) @employee = Employee.find_by(id: token[:employee_id]) render json: {error: "could not validate the auth token"}, status: :unauthorized if @employee.nil? else render json: {eroor: "auth token is missing"}, status: :forbidden end end protected def payload(employee) return nil unless employee and employee.id auth_token = generate_jwt_token(employee) { auth_token: auth_token, employee: { id: employee.id, name: employee.name, email: employee.email, unique_id: employee.unique_id, created_at: employee.created_at, updated_at: employee.updated_at } } end def generate_jwt_token employee JsonWebToken.encode({employee_id: employee.id, exp: Time.now.to_i + 2592000}) end end
class CreateOuts < ActiveRecord::Migration[5.2] def change create_table :outs do |t| t.integer :slave_id, index: true t.integer :trader_id, index: true t.timestamps end end end
class PasswordValidationValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) if value.blank? record.errors.add(attribute, 'パスワードを入力してください。') elsif value.length < 8 record.errors.add(attribute, 'パスワードは8文字以上で入力してください。') elsif value.length > 128 record.errors.add(attribute, 'パスワードは128文字以内で入力してください。') end end end
class AddTrialFieldsToUsers < ActiveRecord::Migration[5.2] def change add_column :users, :trial, :boolean add_column :users, :trial_started, :datetime end end
module ThreeScale module Backend class ServiceUserManagementUseCase def initialize(service, username = nil) @service = service @username = username end def add storage.sadd(@service.storage_key("user_set"), @username) end def exists? storage.sismember @service.storage_key("user_set"), @username end def delete storage.srem @service.storage_key("user_set"), @username end private def storage Service.storage end end end end
Gem::Specification.new do |spec| spec.name = "rack-builtwith" spec.version = "1.0.0.alpha" spec.author = "Samuel Cochran" spec.email = "sj26@sj26.com" spec.summary = %q{Remove your site from builtwith.com} spec.homepage = "https://github.com/sj26/rack-builtwith" spec.license = "MIT" spec.metadata["homepage_uri"] = spec.homepage spec.metadata["source_code_uri"] = "https://github.com/sj26/rack-builtwith" spec.files = Dir["README.md", "LICENSE", "lib/**/*"] spec.add_dependency "rack" spec.add_development_dependency "bundler", "~> 2.0" spec.add_development_dependency "rake", "~> 12.3" spec.add_development_dependency "rspec", "~> 3.0" end
require 'rails_helper' RSpec.describe Arena, type: :model do describe "validation of uniqueness" do it "is valid if the names differ" do create :arena arena1 = build :arena expect(arena1).to be_valid end it "is not valid if they are the same" do arena = create :arena arena1 = build(:arena, arena_name: arena.arena_name) expect( arena1 ).not_to be_valid end end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) COLORS = ["calico", "black", "white", "tuxedo", "leopard", "tabby"] 20.times do Cat.create!(birth_date: Faker::Date.backward(5475), color: COLORS.sample, name: Faker::Name.first_name, sex: ["M", "F"].sample, description: Faker::Hacker.say_something_smart) end
#encoding: utf-8 class LabTest < ActiveRecord::Base include Dynamisable # Constants # Put here constants for LabTest # Relations belongs_to :work_order belongs_to :test_status belongs_to :test_type belongs_to :test_type_version belongs_to :specimen belongs_to :tested_by, class_name: 'User', foreign_key: 'tested_by_id' has_many :pictures, dependent: :destroy # Nested attributes accepts_nested_attributes_for :pictures, allow_destroy: true, reject_if: lambda { |picture| picture[:image].blank? } # Callbacks # Put here custom callback methods for LabTest before_save :set_test_type # Validations # validates :started_at, <validations> # validates :ended_at, <validations> # validates :work_order, <validations> validates :test_status, presence: true # validates :test_type, <validations> validates :test_type_version, presence: true validates :specimen, presence: true validates :tested_by, presence: true # validates :data, <validations> validates :test_type_id, uniqueness: { scope: :specimen_id } # Scopes (used for search form) # Put here custom queries for LabTest scope :by_name, ->(name) { where("name ILIKE ?", "%#{name}%") } # Scope for search def self.to_xls(work_order) # samples = Sample.where(work_order: work_order).includes(:specimens, {lab_tests: :test_type_version}) specimens = Specimen.where(sample_id: work_order.samples.pluck(:'samples.id')).includes({sample: :sample_type_version}, :specimen_type_version, {lab_tests: [:test_type_version, :tested_by, :test_status]}) h = specimens.group_by {|s| "#{s.sample.sample_type_version.name}_ #{s.specimen_type_version.name}" } h = Hash[h.map {|k, specimens| [k, { sample_fields: specimens.first.sample.sample_type_version.data["fields"], specimen_fields: specimens.first.specimen_type_version.data["fields"], test_type_versions: specimens.map{|s| s.lab_tests}.flatten.map{|lt| lt.test_type_version}.uniq, specimens: specimens }]}] end # Instance methods # Override to_s method def to_s self.test_type end private def set_test_type if self.test_type_version self.test_type = self.test_type_version.test_type end end end
class StatementsPage include PageObject include FooterPanel include HeaderPanel include DataMagic include ValidationHelper include Canada_FooterPanel include WaitingMethods PAGE_HEADING = "Statements & Documents" page_url FigNewton.cos_url_prefix + '/accounts/statements' select_list(:cardsdropdown, :id => 'account_name') p(:not_entitled_message, :id => 'not_entitled_message') spans(:date, :xpath => '/div[@class="statement_list"]/span[2]') links(:view_print, :text => 'View/Print') select_list(:yeardropdown, :id => 'statements_year') select_list(:accountname, :id =>'account_name') h1(:page_heading, :class => 'page_title') table(:statements_table, :class => 'statements_table') div(:tab_description, :class => 'divwrap') h1(:feature_unavailable_page_title, :id => 'error_page_title') p(:reference_code, :id => 'errorMessage') link(:adobe_link, :id => 'download_adobe_reader') link(:view_print, :id => 'monthly_view_print_1') link(:save_to_pdf, :id => 'monthly_save_to_pdf_1') link(:view_pdf_with_screenreader, :id => 'monthly_view_with_screen_reader_1') link(:monthly_tab, :text => 'Monthly') link(:year_end_tab, :text => 'Year-End Summary') link(:year_end_tab_id, :id => 'yearend_tab') link(:quarterly_tab, :text => 'Quarterly Summary') link(:quarterly_tab_id, :id => 'quarterly_tab') link(:documents_tab, :text => 'Documents') button(:go_paperless_button, :id => 'go_paperless_button') link(:paperless_related_link, :id => 'paperless') h2(:related_links, :id => 'related_links') image(:card_art_img, :id => 'card_art') #Canada Statements a(:yearly_summary_tab, :id => 'yearend_tab') link(:first_view_transaction, :id => 'view_transactions') h1(:transaction_details, :class => 'page_title') a(:third_account_alerts, :id => 'account_alerts') a(:fourth_account_summary, :id => 'account_summary') a(:second_download_transaction, :id => 'download_transactions') a(:set_account_alert, :id => 'account_alerts') ##############RAMPAGE French Canada p(:view_print_desc_save_stmt, :class => 'desc') div(:statement_monthly_description, :xpath => '//*[@id="monthly_aria_control"]/table/caption/span/div') link(:statement_documents_tab, :xpath => '//*[@id="documents_tab"]') div(:statement_documents_description, :xpath => '//*[@id="documents_aria_control"]/table/caption/span/div') ##############RAMPAGE French Canada def system_outage_message_visible paragraph_element(:id => 'global_system_message').visible? end def validate_tab_order(tabs_to_display, tab_status) tab_list = tabs_to_display.split(', ') tab_status_list = tab_status.split(', ') unordered_list_element(:id => 'document_type_tabs').each_with_index do |li, index| tab_list[index].should == li.text tab_status_list[index].should == li.class_name end end def heading PAGE_HEADING end def dropdown_defaults yeardropdown_element.selected_options end def dropdown_values_select yeardropdown_element.options.each do |list| yeardropdown_element.select(list) end end def page_content_section puts(section_element(:id => 'main_content').text) section_element(:id => 'main_content').when_visible.text end def statements_row_count quarterly_rows_set = statements_table_element.select{|tr| tr.class_name == 'statements_row'} quarterly_row_size = quarterly_rows_set.size end def quarterly_visible link_element(:id => 'quarterly') end def no_summaries_visible link_element(:text => 'View/Print').click end def wait_for_stmts_page_to_load wait_until do @browser.windows.last.url.include? "/statements" end end def wait_for_page_to_load wait_for_logo_to_load wait_for_footer_to_load wait_for_navigation_menu_to_load wait_for_stmts_page_to_load end def dynamic_year footer_element.paragraph_element.text end def quarterly_list list_item(:class => 'desktop_content') end def menu_items yeardropdown_element.options.collect { |option| option.text } end def year_end_summary_view link_element(:text => 'View/Print').click end def date_stmnts table_element(:class => 'statements_table')[4][1].text end def date_stmnts_canada table_element(:class => 'statements_table')[1][1].text end def goto_quarterly_tab link_element(:text => 'Quarterly Summary').click wait_until do @browser.windows.last.url.include? "/statements/quarterly" self.tab_description_element.text.include? "Quarterly Summary for" end end def quarterly_summary_view link_element(:text => 'View/Print').click end def monthly_hyperlink link_element(:text => 'view monthly statements').click end def legal_disclosures link_element(:text => 'Read additional important disclosures').click end def click_on_documents_tab_by_id link_element(:id => 'documents_tab').click wait_until do @browser.windows.last.url.include? "/statements/documents" end end def goto_documents_tab link_element(:text => 'Documents').click wait_until do @browser.windows.last.url.include? "/statements/documents" self.tab_description_element.text.include? "Documents for" end end def goto_monthly_tab link_element(:text => 'Monthly').click wait_until do @browser.windows.last.url.include? "/statements/monthly" self.tab_description_element.text.include? "Monthly Statement for" end end def documents_view link_element(:text => 'View/Print').click end def documents_screen_reader link_element(:text => 'View PDF with screen reader').click end def quarterly_screen_reader link_element(:text => 'View PDF with screen reader').click end def select_year(year) yeardropdown_element.select(year) wait_until do @browser.windows.last.url.include? year end end def documents_headers link_element(:text => 'View/Print').click end def popup_a_window popup_window attach_to_window(:url => success.html) end def goto_year_end_tab link_element(:text => 'Year-End Summary').click wait_until do @browser.windows.last.url.include? "/statements/yearend" self.tab_description_element.text.include? "Year-End Summary for" end end def click_year_end_tab link_element(:id => 'yearend_tab').click wait_until do @browser.windows.last.url.include? "/statements/yearend" end end def click_quarterly_tab link_element(:id => 'quarterly_tab').click wait_until do @browser.windows.last.url.include? "/statements/quarterly" end end def select_statement_year_option(option_txt) select_list_element(:id => 'statements_year').select(option_txt) wait_until do @browser.tr(:class => 'statements_row').visible? end end def extract_account_number(account_name) acctLastFour = account_name.match('\\.\\.\\.[0-9]{4}') # puts "Account last four: #{acctLastFour}, length: #{acctLastFour[0].length}." acctLastFour[0][-4..-1] end def special_account_number(account_name) acctLastFour = account_name.match('\\.\\.\\.[0-9]{4}.*$') # puts "Special account number: #{acctLastFour[0].lstrip}" acctLastFour[0].lstrip end def accountname card_name = select_list_element(:id => 'account_name').text card_name.split(/\./).first end #def cap_one_logo # link_element(:text => 'Capital One').click #end def monthly_statement_dates puts "date elements: #{date_elements}" date_elements.collect do |date| puts "actual date: #{date}" if date.text.strip =~ /^(\d+)\/(\d+)\/(\d{4})$/ Date.new $3.to_i, $1.to_i, $2.to_i else nil end end.compact end def statements_tabs_visible? monthly_tab_element.visible? and year_end_tab_element.visible? and documents_tab_element.visible? end def language_toggle div_element(:class=> 'lang_toggle').visible? end def language div_element(:class=> 'lang_toggle').link_element(:class => 'active').click end def langs_en link_element(:class => 'active').attribute_value('data-lang') end def langs_french link_element(:href => '#x').attribute_value('data-lang') end def globe_image span_element(:class=> 'globe').visible? end def hover_over_home_button list_item_element(:id => "home").when_present.hover ajax_wait end #########################To Handle FireFox Hover ##################### def select_sub_menu_item_for_firefox (menu, sub_menu_item) mouseover_over_menu_item_ff(menu) select_menu_item_ff(sub_menu_item) end def mouseover_over_menu_item_ff(menu) menu_id = "my_" + menu.downcase top_menu_element = list_item_element(:id => "#{menu_id}") @sub_menu = top_menu_element.div_element(:class => "sub") top_menu_element.when_present.fire_event 'onmouseover' ajax_wait end def select_menu_item_ff(sub_menu_item) # link_element(:text => sub_menu_item).when_visible.focus link_element(:text => sub_menu_item).when_visible.fire_event 'onclick' end end
class Notice < ActiveRecord::Base has_many :documents has_many :attachments belongs_to :project accepts_nested_attributes_for :attachments end
class CampRegistration < ActiveRecord::Base validates_presence_of :name, :if => :name_in_form? validates_presence_of :email, :if => :email_in_form? validates_presence_of :age, :if => :age_in_form? validates_presence_of :position, :if => :position_in_form? validates_presence_of :school, :if => :school_in_form? validates_presence_of :phone, :if => :phone_in_form? validates_presence_of :street_address, :if => :address_in_form? validates_presence_of :city, :if => :address_in_form? validates_presence_of :state, :if => :address_in_form? validates_presence_of :zip, :if => :address_in_form? validates_presence_of :grade, :if => :grade_in_form? validates_presence_of :yrs_of_exp, :if => :yrs_of_exp_in_form? validates_presence_of :finding_resolute, :if => :finding_resolute_in_form? validates_presence_of :registration_form_id validates_presence_of :shirt_size, :if => :shirt_size_in_form? validates_presence_of :gender, :if => :gender_in_form? validates_format_of :phone, :with => /^(\()?([0-9]{3})(\)|-|.\s)?([0-9]{3})(-)?([0-9]{4}|[0-9]{4})$/, :on => :create, :if => :phone_in_form? validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create, :if => :email_in_form? validates_format_of :zip, :with => /^\d{5}([\-]\d{4})?$/, :if => :address_in_form? validates_numericality_of :age, :less_than => 100, :if => :age_in_form? validates_numericality_of :grade, :less_than => 13, :greater_than => 0, :if => :grade_in_form? validates_numericality_of :yrs_of_exp, :if => :yrs_of_exp_in_form? has_one :camp, :through => :registration_form has_one :registration_form def to_param id end def registration_form @form ||= RegistrationForm.find_by_id(registration_form_id) end def self.format_for_save(object) return object if object[:position].nil? pos_string = "" object[:position].each_pair do |key, value| pos_string << "#{value}, " object[:position].delete(key) end object.merge({:position => pos_string}) end private def method_missing(symbol, &block) if symbol.to_s =~ /(.+)_in_form\?/ method_bool = $1 + "?" registration_form.send(method_bool, &block) else super end end end
module Currency CURRENCY_MAPPING = {'PHP' => 1, 'US$' => 40} LOCAL_CURRENCY = 'PHP' def self.all CURRENCY_MAPPING.keys end end
class SerializeChunkedUploadTask def initialize(chunked_upload_task) @chunked_upload_task = chunked_upload_task end def call { id: @chunked_upload_task.id, large_file: serialize_large_file } end private def serialize_large_file large_file = @chunked_upload_task.large_file { id: large_file.id, path: large_file.data.url } end end
class CreateReminderService < ApplicationService def initialize(params) @params = params end def call reminder = Reminder.create!( title: @params[:title], note: @params[:note], due_date: @params[:due_date], remind_interval: @params[:remind_interval], reminderable: @params[:reminderable] ) result(true, reminder) rescue StandardError => e result(false, e) end end
require 'rails_helper' RSpec.describe Song, type: :model do it 'has a title' do c1 = create(:category) song = build(:song) expect(song.title).to be_a(String) song.title = nil expect(song).to_not be_valid end it 'should have a category' do song = build(:song, categories: []) expect(song).to_not be_valid song.categories.build(attributes_for(:category)) expect(song).to be_valid end it 'has authors' do author = create(:author) author2 = create(:musician) song = create(:song) song.authors = [author, author2] expect(song.authors[0]).to be_a(Author) expect(song.authors.count).to eq(2) end it 'could be included in different playlists' do user = create(:user) song = create(:song) playlist1 = create(:playlist, user: user) playlist2 = create(:playlist2, user: user) playlist1.songs = [song] playlist2.songs = [song] expect(song.playlists.count).to eq(2) expect(playlist1.songs.last).to be(song) expect(playlist2.songs.last).to be(song) end it 'assostiated with user if included in playlist' do user = create(:user) playlist = create(:playlist, user: user) song = create(:song) user.playlists << playlist playlist.songs << song expect(song.users).to include(user) end end
class ReviewsController < ApplicationController helper_method :average_rating def index restaurant_name = params[:review][:restaurant] num_entries = params[:review][:num_entries].to_i scraper = ReviewScraper.new @reviews = scraper.search(restaurant_name, num_entries) respond_to do |format| format.html end end private def average_rating @reviews.sum(&:rating)/@reviews.length end end
# coding: utf-8 require 'spec_helper' describe Locomotive::ThemeAsset do describe 'attaching a file' do before(:each) do Locomotive::ThemeAsset.any_instance.stubs(:site_id).returns('test') @asset = FactoryGirl.build(:theme_asset) end describe 'file is a picture' do it 'should process picture' do @asset.source = FixturedAsset.open('5k.png') @asset.source.file.content_type.should_not be_nil @asset.image?.should be_true end it 'should get width and height from the image' do @asset.source = FixturedAsset.open('5k.png') @asset.width.should == 32 @asset.height.should == 32 end end describe 'local path and folder' do it 'should set the local path based on the content type' do @asset.source = FixturedAsset.open('5k.png') @asset.save @asset.local_path.should == 'images/5k.png' end it 'should set the local path based on the folder' do @asset.folder = 'trash' @asset.source = FixturedAsset.open('5k.png') @asset.save @asset.local_path.should == 'images/trash/5k.png' end it 'should set sanitize the local path' do @asset.folder = '/images/à la poubelle' @asset.source = FixturedAsset.open('5k.png') @asset.save @asset.local_path.should == 'images/a_la_poubelle/5k.png' end end describe '#validation' do it 'does not accept text file' do @asset.source = FixturedAsset.open('wrong.txt') @asset.valid?.should be_false @asset.errors[:source].should_not be_blank end it 'is not valid if another file with the same path exists' do @asset.source = FixturedAsset.open('5k.png') @asset.save! another_asset = FactoryGirl.build(:theme_asset, :site => @asset.site) another_asset.source = FixturedAsset.open('5k.png') another_asset.valid?.should be_false another_asset.errors[:local_path].should_not be_blank end end it 'should process stylesheet' do @asset.source = FixturedAsset.open('main.css') @asset.source.file.content_type.should_not be_nil @asset.stylesheet?.should be_true end it 'should compile scss stylesheet if compile is set' do @asset.compile = true asset = FixturedAsset.open('main.scss') Locomotive.config.assets_append_paths = [File.dirname(asset.path)] @asset.source = asset @asset.source.compiled.should_not be_nil @asset.source.compiled.path.should match(/compiled_main.scss$/) File.open(@asset.source.compiled.path).read.gsub(/\s+/,'').should match("body{color:#001122;}") @asset.source.store! @asset.source.compiled.path.should match(/compiled_main.css$/) end it 'should process javascript' do @asset.source = FixturedAsset.open('application.js') @asset.source.file.content_type.should_not be_nil @asset.javascript?.should be_true end it 'should compile coffescript if compile is set' do @asset.compile = true @asset.source = FixturedAsset.open('application.coffee') @asset.source.compiled.should_not be_nil @asset.source.compiled.path.should match(/compiled_application.coffee$/) File.open(@asset.source.compiled.path).read.gsub(/\s+/,'').should == "(function(){varsquare;square=function(x){returnx*x;};}).call(this);" @asset.source.store! @asset.source.compiled.path.should match(/compiled_application.js$/) end it 'should get size' do @asset.source = FixturedAsset.open('main.css') @asset.size.should == 25 end end describe 'creating from plain text' do before(:each) do Locomotive::ThemeAsset.any_instance.stubs(:site_id).returns('test') @asset = FactoryGirl.build(:theme_asset, { :site => FactoryGirl.build(:site), :plain_text_name => 'test', :plain_text => 'Lorem ipsum', :performing_plain_text => true }) end it 'should handle stylesheet' do @asset.plain_text_type = 'stylesheet' @asset.valid?.should be_true @asset.stylesheet?.should be_true @asset.source.should_not be_nil end it 'should handle javascript' do @asset.plain_text_type = 'javascript' @asset.valid?.should be_true @asset.javascript?.should be_true @asset.source.should_not be_nil end end end
class Setting < ApplicationRecord belongs_to :user # validates :name, presence : { message: :no_name} validates :country, length: { minimum: 2, message: :country } validates :language, length: { minimum: 2, message: :language } end
# frozen_string_literal: true module DX module Api module File # Clone a file, based on its id, from a source container (e.g. a source project) to a folder path in a destination container (e.g. a destination project) # https://documentation.dnanexus.com/developer/api/data-containers/cloning#api-method-class-xxxx-clone # # DX::Api::File.clone( # api_token: "API_TOKEN", # file_id: "file-1234", # source_id: "project-1234", # destination_id: "project-4567", # folder_path: "destination/folder/path", # ) # # @param api_token [String] Your api token # @param file_id [String] The id of the file to clone # @param source_id [String] The id of the source container # @param destination_id [String] The id of the destination container # @param folder_path [String] The folder path to copy the file to # @return [DX::Api::Response] A dx response whose body contains the ids of the source container, destination container, as well as an array of objects tha tcould not be cloned since they already exist in the container def self.clone(api_token:, file_id:, source_id:, destination_id:, folder_path:) DX::Api::Request.new( api_token: api_token, path: [source_id, 'clone'].join('/'), # e.g. project-1234/clone body: { project: destination_id, # the destination container objects: [file_id], destination: folder_path, parents: true } ).make.then(&DX::Api::Response.method(:from_http)) end end end end
class ApplicationController < ActionController::Base def admin_only authenticate_user! unless current_user.admin redirect_to user_path(current_user), notice: "Only an administrator may perform that function." end end end
class Team attr_accessor :name, :ranking def initialize(name, ranking) @name = name @ranking = ranking end end @teams = [] def menu puts "Choose From the Following:" puts "----------------------" puts "1. Enter Teams" puts "2. List Teams" puts "3. List Match-ups" puts "0. Exit Program" choice = gets.chomp.to_i case choice when 1 enter_teams when 2 list_teams when 3 matchup when 0 puts "Thanks for coming." else clear_screen puts "Not a valid selection. Try again." menu end end def clear_screen Gem.win_platform? ? (system "cls") : (system "clear") end def enter_teams finished = false puts "Enter team names and rankings. Type 'done' when done." while finished == false # while !finished print "Team Name: " name = gets.chomp if name == "done" finished = true else print "Ranking: " ranking = gets.chomp.to_i team = Team.new(name, ranking) @teams.push(team) puts "Team successfully created!" end end clear_screen menu end def list_teams @teams.each_with_index do |team, index| puts "#{index+1}. #{team.name}" end return_to_menu end def matchup puts "Matchups:" temp_arr = [] @teams.each do |team| temp_arr.push(team) end if @teams.length%2 != 0 puts "(#{temp_arr[0].ranking}) #{temp_arr.delete_at(0).name} has a bye" end while temp_arr.length > 0 puts "(#{temp_arr[0].ranking}) #{temp_arr.delete_at(0).name} versus (#{temp_arr[-1].ranking}) #{temp_arr.delete_at(-1).name}" end return_to_menu end def return_to_menu puts "Return to main menu? [y/n]" choice = gets.chomp.downcase if choice == "y" clear_screen menu else puts "Okay. Thanks for coming." end end puts "Welcome to the Tournament Program" menu
require 'spec_helper' describe Ginatra::Repo do let(:repo) { Ginatra::RepoList.find('test') } describe "repo" do it "returns name" do expect(repo.name).to eq("test") end it "returns param" do expect(repo.param).to eq("test") end it "returns description" do expect(repo.description).to eq("") end end describe "#commit" do it "returns commit by sha" do commit = repo.commit '095955b' expect(commit).to be_a_kind_of(Rugged::Commit) expect(commit.oid).to eq('095955b6402c30ef24520bafdb8a8687df0a98d3') end end describe "#commit_by_tag" do it "returns commit by tag" do commit = repo.commit_by_tag 'v0.0.3' expect(commit).to be_a_kind_of(Rugged::Commit) expect(commit.oid).to eq('0c386b293878fb5f69031a998d564ecb8c2fee4d') end end describe "#commits" do context "when branch exist" do it "returns an array of commits" do commits = repo.commits('master', 2) expect(commits).to be_a_kind_of(Array) expect(commits.size).to eq(2) expect(commits.first.oid).to eq('095955b6402c30ef24520bafdb8a8687df0a98d3') end end context "when branch not exist" do it "raises Ginatra::InvalidRef" do expect { repo.commits('404-branch') }.to raise_error(Ginatra::InvalidRef) end end end describe "#branches" do it "returns an array of branches" do branches = repo.branches expect(branches).to be_a_kind_of(Array) expect(branches.size).to eq(1) expect(branches.first.name).to eq('master') expect(branches.first.target.oid).to eq('095955b6402c30ef24520bafdb8a8687df0a98d3') end end describe "#branches_with" do it "returns an array of branches including commit" do branches = repo.branches_with('095955b6402c30ef24520bafdb8a8687df0a98d3') expect(branches).to be_a_kind_of(Array) expect(branches.size).to eq(1) expect(branches.first.name).to eq('master') end end describe "#branch_exists?" do it "checks existence of branch" do expect(repo.branch_exists?('master')).to be true expect(repo.branch_exists?('master-404')).to be false end end end
class ApplicationController < ActionController::Base protect_from_forgery def is_admin unless(session[:admin]) redirect_to admin_login_path end end def is_member unless(member_signed_in?) session["member_return_to"] = "#{request.fullpath}" redirect_to new_member_session_path end end def count_orders @countnew = Order.where(["status = ?", "new"]).count @countcheck = Order.where(["status = ?", "check"]).count @countprocessing = Order.where(["status = ?", "processing"]).count @countdeliver = Order.where(["status = ?", "deliver"]).count @countcancel = Order.where(["status = ?", "cancel"]).count end def count_cartitems if(cookies[:cart]) @cartitems = JSON.parse(cookies[:cart]) @cartitems_count = @cartitems.length else @cartitems_count = 0 end end def record_login_redirect_path session["member_return_to"] = "#{request.fullpath}" end def after_sign_in_path_for(resource) request.env['omniauth.origin'] || stored_location_for(resource) || root_path end def after_sign_out_path_for(resource_or_scope) (request.referrer == "#{request.protocol}#{request.host_with_port}"+check_orders_path) ? root_path : request.referrer end end
puts (0..1000).select {|n| n%3==0 || n%5==0}.inject(0) {|s,n| s+=n}
execute "replace frontend" do if /^(2.0|2.2)/ =~ node['zabbix']['server']['version'] command <<-CMD #{node['hyclops']['download_path']}/setup.py replace \ -d #{node['zabbix']['frontend_dir']} \ --zabbix-version=#{$&} CMD action :run else p "Not supported version.(Supported only 2.0 or 2.2)" end end
module Forums class Topic < ApplicationRecord include MarkdownRenderCaching has_ancestry cache_depth: true belongs_to :isolated_by, optional: true, class_name: 'Topic' belongs_to :created_by, class_name: 'User' has_many :threads, dependent: :destroy has_many :subscriptions, dependent: :destroy validates :name, presence: true, length: { in: 1..128 } validates :description, presence: true caches_markdown_render_for :description validates :locked, inclusion: { in: [true, false] } validates :pinned, inclusion: { in: [true, false] } validates :hidden, inclusion: { in: [true, false] } validates :isolated, inclusion: { in: [true, false] } validates :default_hidden, inclusion: { in: [true, false] } validates :default_locked, inclusion: { in: [true, false] } scope :locked, -> { where(locked: true) } scope :unlocked, -> { where(locked: false) } scope :pinned, -> { where(pinned: true) } scope :hidden, -> { where(hidden: true) } scope :visible, -> { where(hidden: false) } scope :isolated, -> { where(isolated: true) } after_initialize :set_defaults, unless: :persisted? before_save :update_isolated_by after_save :cascade_isolated_by! after_save :cascade_threads_depth! def not_isolated? isolated_by.nil? end private def set_defaults [:pinned, :isolated, :default_hidden].each do |attribute| self[attribute] = false if self[attribute].nil? end return unless parent self.locked = parent.locked if locked.nil? self.hidden = parent.hidden if hidden.nil? end def cascade_threads_depth! return unless saved_changes.key? 'ancestry' threads.update(depth: depth + 1) end def cascade_isolated_by! return if persisted? || !isolated_changed? || !children? descendants.where(isolated_by: isolated_by_was).update(isolated_by: self) end def update_isolated_by if isolated? self.isolated_by = self elsif persisted? || ancestry_changed? self.isolated_by = ancestors.where.not(isolated_by: nil).first end end end end
require 'rails_helper' describe Api::V1::IpController, type: :controller do let!(:api_key) { create(:api_key) } before { request.headers['Content-Type'] = 'application/json;charset=utf-8' request.headers['Authorization'] = "Bearer #{api_key.token}" } describe 'POST /api/v1/store' do context 'when data is valid' do let!(:ip) do { 'ip_list': [ '1.1.1.1: 1,2,3' ] }.as_json end it 'should be stored' do post :store, params: ip, format: :json expect(response).to have_http_status(:ok) expect(Ip.all.count).to eq(1) end end context 'when data is invalid' do let!(:ip) do { 'ip_list': [ '1.1.1: 1,2,3' ] }.as_json end it 'should raise InputMalformedError' do post :store, params: ip, format: :json expect(Ip.all.count).to eq(0) expect(response).to have_http_status(:bad_request) expect(json['error']).to eq('Malformed input.') end end end describe '/api/v1/compute' do context 'when it has ips stored' do let!(:ip) { create(:ip) } let!(:ip2) { create(:ip, values: [1, 5]) } let(:expected) { { data: { ip_code: { ip.address => '1,2,3,5' } } }.as_json } it 'should return computed data' do post :compute, format: :json expect(ComputeHistory.all.count).to eq(1) expect(Ip.all.count).to eq(0) expect(json).to eq(expected) end end context 'when it has no ips stored' do let(:expected) { { data: { ip_code: {} } }.as_json } it 'should return empty ip_code' do post :compute, format: :json expect(ComputeHistory.all.count).to eq(1) expect(json).to eq(expected) end end end describe '/api/v1/compute_histories' do context 'when requested' do let!(:history) { create(:compute_history) } let!(:expected) { { data: [ { ip_code: { '1.1.1.1' => '1,2,3' }, computed_at: history.computed_at } ] }.as_json } it 'should return all previous computed data' do get :compute_histories, format: :json expect(json).to eq(expected) end end end end
class QuestionTung < ActiveRecord::Base belongs_to :survey_tung has_many :answers, :dependent => :destroy accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true validates_presence_of :content, :question_type validate :proper_answers_number private def proper_answers_number if question_type && question_type != "Text" && answers.size < 2 errors.add("with #{question_type} type", ", there must be at least two answers") end end end
require "rails_helper" RSpec.describe WalterMessageNotificationJob, type: :job do describe "#perform" do it "does not send a request when no endpoint is set" do fake_http = spy(HTTP) message = create(:outgoing_message) expect(fake_http).not_to receive(:post) stub_const("HTTP", fake_http) described_class.perform_now message end it "sends a request with the outgoing message info to walter endpoint" do fake_http = spy(HTTP) message = create(:outgoing_message) expect(fake_http).to receive(:post).with(walter_endpoint, params: { contact_walter_id: message.contact.walter_id, first_name: message.contact.first_name, last_name: message.contact.last_name, to: message.to, body: message.body, user_walter_id: message.user.walter_id, type: message.type, }) stub_const("HTTP", fake_http) described_class.perform_now message end end def walter_endpoint Rails.application.config.walter_notification_endpoint = "http://fakewalterendpoint.com" end end
class AdminController < ApplicationController before_filter :login_required require_role :admin def index @current_item = "admin" end end
class Comment < ApplicationRecord belongs_to :user belongs_to :imageable, polymorphic: true validates_presence_of :content validates_length_of :content, :within => 1..100 end
class CommentsController < ApplicationController before_action :authenticate_user! before_action :set_comment, only: [:destroy] before_action :is_owner?, only: [:destroy] def create @comment = Comment.new(comment_params) if @comment.save flash[:notice] = "댓글을 작성하였습니다." redirect_to post_path(params[:post_id]) else flash[:danger] = "댓글을 입력하세요." redirect_to :back end end def destroy @comment.destroy redirect_to post_path(params[:post_id]) end private def set_comment @comment = Comment.find(params[:id]) end def comment_params params.require(:comment).permit(:content, :user_id, :post_id) end def is_owner? redirect_to root_path unless current_user == @comment.user end end
#encoding: utf-8 class BlogInfo < ActiveRecord::Base self.table_name = 'blog_info' validates :name, length: {minimum: 2, maximum: 20} validates :email, format: {with: /\A[a-zA-Z0-9\-]+@[a-zA-Z0-9-]+\.(org|com|cn|io|net|cc|me)\z/} end
class ConvertDeploymentsActiveFlagToADeactivationFlag < ActiveRecord::Migration def self.up rename_column :deployments, :is_active, :is_deactivated end def self.down rename_column :deployments, :is_deactivated, :is_active end end
class TeacherSchoolClassDiscipline < ActiveRecord::Base belongs_to :teacher belongs_to :school_class belongs_to :discipline belongs_to :period has_many :students, through: :school_class def school_class_discipline_name school_class.name + " - " + discipline.name end def teacher_discipline_name teacher.user.full_name + " - " + discipline.name end def school_class_teacher_name school_class.name + " - " + teacher.user.full_name end [Teacher, SchoolClass, Discipline, Period].each { |k| k.send(:alias_method, :tscd, :teacher_school_class_discipline) } validates_presence_of :teacher_id, :school_class_id, :discipline_id, :period_id validates_with TSCDValidator end
class UsersController < ApplicationController def show profile = Profile.find(params[:id]) user = User.find(params[:id]) end def edit @user = User.find(current_user) end def update if current_user.update(user_params) sign_in(current_user, bypass: true) redirect_to user_path, notice: "更新が完了しました" else redirect_to edit_user_registration_path(current_user), alert: "更新できませんでした" end end def destroy sign_out(current_user) end private def user_params params.require(:user).permit(:password, :nickname, :email) end end
require_relative '../../../puppet_x/century_link/clc' require_relative '../../../puppet_x/century_link/prefetch_error' Puppet::Type.type(:clc_server).provide(:v2, parent: PuppetX::CenturyLink::Clc) do mk_resource_methods read_only(:id, :os_type, :os, :location, :ip_addresses) def self.instances begin servers = client.list_servers servers.delete_if { |server| server['description'].nil? || server['description'] == '' } servers.map { |server| new(server_to_hash(server)) } rescue Timeout::Error, StandardError => e raise PuppetX::CenturyLink::PrefetchError.new(self.resource_type.name.to_s, e) end end def self.prefetch(resources) instances.each do |prov| if resource = resources[prov.name] resource.provider = prov end end end def self.server_to_hash(server) details = server['details'] || {} group = client.show_group(server['groupId']) hash = { id: server['id'], name: server['description'], type: server['type'], storage_type: server['storageType'], location: server['locationId'], os_type: server['osType'], os: server['os'], group_id: server['groupId'], cpu: details['cpu'], memory: details['memoryMB'] / 1024, public_ip_address: public_ip_address_hash(server['id'], details), ip_addresses: details['ipAddresses'], group: group['name'], ensure: details['powerState'].to_sym, } public_ip_hash = public_ip_address_hash(server['id'], details) hash[:public_ip_address] = public_ip_hash if public_ip_hash hash end def self.public_ip_address_hash(server_id, server_details) ip_addresses = server_details['ipAddresses'] public_ip = ip_addresses.find { |addr| !addr['public'].nil? } return 'absent' if public_ip.nil? ip_data = client.show_public_ip(server_id, public_ip['public']) { 'internal_ip' => ip_data['internalIPAddress'], 'ports' => ip_data['ports'], 'source_restrictions' => ip_data['sourceRestrictions'], } end def exists? Puppet.info("Checking if server #{name} exists") @property_hash[:ensure] != nil && @property_hash[:ensure] != :absent end def started? Puppet.info("Checking if server #{name} is started") [:present, :started].include?(@property_hash[:ensure]) end def stopped? Puppet.info("Checking if server #{name} is stopped") @property_hash[:ensure] == :stopped end def paused? Puppet.info("Checking if server #{name} is paused") @property_hash[:ensure] == :paused end def create Puppet.info("Starting server #{name}") fail("source_server_id can't be blank") if resource[:source_server_id].nil? config = { 'name' => name, 'description' => name, 'type' => resource[:type], 'sourceServerId' => resource[:source_server_id], 'cpu' => resource[:cpu], 'memoryGB' => resource[:memory], 'storageType' => resource[:storage_type], 'isManagedOS' => resource[:managed], 'isManagedBackup' => resource[:managed_backup], 'primaryDns' => resource[:primary_dns], 'secondaryDns' => resource[:secondary_dns], 'ipAddress' => resource[:ip_address], 'password' => resource[:password], 'sourceServerPassword' => resource[:source_server_password], 'customFields' => resource[:custom_fields], } config = config_with_group(config) config = config_with_network(config) config = config_with_disks(config) server = client.create_server(remove_null_values(config)) @property_hash[:id] = server['id'] @property_hash[:ensure] = :present if resource[:public_ip_address] begin params = public_ip_config(resource[:public_ip_address]) client.create_public_ip(@property_hash[:id], params) rescue client.delete_server(@property_hash[:id]) @property_hash[:ensure] = :absent end end true end def memory=(value) client.set_server_property(id, 'memory', value.to_s) @property_hash[:memory] = value end def cpu=(value) client.set_server_property(id, 'cpu', value.to_s) @property_hash[:cpu] = value end def public_ip_address=(value) if value == 'absent' ip_addresses.each do |ip_data| public_ip = ip_data['public'] if public_ip client.delete_public_ip(id, public_ip) end end else params = public_ip_config(resource[:public_ip_address]) client.create_public_ip(id, params) end end def destroy Puppet.info("Deleting server #{name}") client.delete_server(id) @property_hash[:ensure] = :absent true end def start Puppet.info("Starting server #{name}") client.power_on_server(id) @property_hash[:ensure] = :started end def stop Puppet.info("Stopping server #{name}") client.shutdown_server(id) @property_hash[:ensure] = :stopped end def pause Puppet.info("Pausing server #{name}") client.pause_server(id) @property_hash[:ensure] = :paused end private def public_ip_config(config) remove_null_values({ 'ports' => config[:ports] || config['ports'], 'sourceRestrictions' => config[:source_restrictions] || config['source_restrictions'], }) end def config_with_group(config) if resource[:group_id] config['groupId'] = resource[:group_id] elsif resource[:group] config['groupId'] = find_group_by_name(resource[:group])['id'] end config end def config_with_disks(config) if resource[:disks] config['additionalDisks'] = resource[:disks] end config end def config_with_network(config) if resource[:network_id] config['networkId'] = resource[:network_id] elsif resource[:network] config['networkId'] = find_network_by_name(resource[:network])['id'] end config end def find_network_by_name(name) networks = client.list_networks matching_networks = networks.select { |network| network['name'] == name } if matching_networks.empty? raise Puppet::Error, "Network '#{name}' not found" end if matching_networks.size > 1 raise Puppet::Error, "There are #{matching_networks.size} networks " \ "matching '#{name}'. Consider using network_id" end matching_networks.first end end
$:.push File.expand_path("../lib", __FILE__) require "spellbook/version" Gem::Specification.new do |s| s.name = "spellbook" s.version = SpellBook::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Yutaka HARA"] s.email = ["yutaka.hara.gmail.com"] s.homepage = "http://github.com/yhara/spellbook/" s.summary = %q{Launcher for browser-based desktop applications} s.description = s.summary 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"] s.add_dependency('activerecord', '>= 3.0') s.add_dependency('sinatra', '>= 1.2') s.add_dependency('sinatra-activerecord', '= 0.1.3') s.add_dependency('sqlite3') s.add_dependency('slim', '~> 1.0.3') s.add_dependency('slop') s.add_dependency('sass') s.add_dependency('rack-proxy') s.add_dependency('childprocess') s.add_development_dependency('capybara') s.add_development_dependency('thin') s.add_development_dependency('rack-test') s.add_development_dependency('rspec', '>= 2.0') s.add_development_dependency('sinatra-reloader') end
class Contentr::Admin::FilesController < Contentr::Admin::ApplicationController def index @files = Contentr::File.all end def new @file = Contentr::File.new end def create @file = Contentr::File.new(file_params) if @file.save flash[:success] = 'File created.' redirect_to contentr_admin_files_path(:root => @root_file) else render :action => :new end end def edit @file = Contentr::File.find(params[:id]) end def update @file = Contentr::File.find(params[:id]) if @file.update_attributes(file_params) flash[:success] = 'File updated.' redirect_to contentr_admin_files_path(:root => @root_file) else render :action => :edit end end def destroy file = Contentr::File.find(params[:id]) file.destroy redirect_to contentr_admin_files_path(:root => @root_file) end protected def file_params params.require(:file).permit(*Contentr::File.permitted_attributes) end end
Rails.application.routes.draw do root 'welcome#index' resources :upvotes resources :countries get '/users/:id', to: 'users#show', as: 'user' resources :divingsites do put "like" => "divingsites#upvote" end resources :reviews get '/signup', to: 'users#new', as: 'signup' post '/signup', to: 'users#create' # sessions management get '/login', to: 'sessions#new', as: 'login' post '/sessions', to: 'sessions#create', as: 'sessions' post '/logout', to: 'sessions#destroy', as: 'logout' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html resources :divingsites, :only => [:index, :show] do resources :reviews, :only => [:new, :create] do put "like" => "reviews#upvote" end end end
class ApplicationController < ActionController::Base protect_from_forgery with: :null_session def show_all klass = get_class klass.all end def find_random klass = get_class klass.all.sample end def find_resource klass = get_class search_param = get_search_param if params[:id] klass.find(params[:id]) elsif params[search_param].to_i == 0 klass.find_one(search_param, params[search_param]) else klass.find_by(search_param => params[search_param]) end end def find_resources klass = get_class search_param = get_search_param if params[search_param].to_i == 0 klass.find_all(search_param, params[search_param]) else klass.where(search_param => params[search_param]) end end private def get_class params[:controller].singularize.camelize.demodulize.constantize end def get_search_param params.symbolize_keys.keys.first end end
class RecipesController < ApplicationController before_action :set_recipe, only: [:show, :edit, :update, :destroy] def index @recipes = current_user.recipes.recent @completed = Recipe.new.completed(current_user) end def show end def new @recipe = current_user.recipes.new @recipe.ingredients.build end def edit end def create @recipe = current_user.recipes.new(recipe_params) ingredient_params = params[:recipe][:ingredients_attributes].permit!.to_hash @recipe.ingredients_attributes = ingredient_params.map do |key, value| @recipe.ingredients.new( name: value['name'], amount: value['amount'], quantity: value['quantity'], unit_id: value['unit_id'].to_i ) end if @recipe.save redirect_to @recipe, notice: "レシピ「#{@recipe.name}」を登録しました。" else render :new end end def fetch @recipe = current_user.recipes.new @recipe.fetch(params[:fetch_url]) if params[:new].present? render :new elsif params[:edit].present? render :edit end end def reset completed = params[:completed] if completed recipes = current_user.recipes.all recipes.each { |recipe| recipe.update!(cooked: false) } redirect_to recipes_path, notice: "レシピリストをリセットしました。" end end def update recipe = current_user.recipes.find(params[:id]) recipe.update!(recipe_params) redirect_to recipes_path, notice: "レシピ「#{recipe.name}」を更新しました。" end def destroy @recipe.destroy redirect_to recipes_path, notice: "レシピ「#{@recipe.name}」を削除しました。" end private def recipe_params params.require(:recipe).permit( :cooked, :name, :url, :cooking_recipe, :cooked_at, :how_many, ingredients_attributes: [ :name, :amount, :quantity, :unit_id ] ) end def set_recipe @recipe = current_user.recipes.find(params[:id]) end end
require 'bcrypt' class User include Mongoid::Document attr_accessor :password field :email, type: String field :name, type: String field :password_salt, type: String field :password_hash, type: String has_many :tools def authenticated?(pswd) BCrypt::Password.new(self.password_hash) == pswd end before_save :encrypt_password private def encrypt_password if password.present? self.password_salt = BCrypt::Engine.generate_salt self.password_hash = BCrypt::Engine.hash_secret(password, password_salt) self.password = nil end end end
require 'everyday_natsort_kernel' require 'rbe/data/data_store' require 'everyday_thor_util/builder' include EverydayThorUtil::Builder root_command[:var] = command(aliases: %w(variable v), short_desc: 'var SUBCOMMAND ARGS...', desc: 'configure stored variables') root_command[:var][:add] = command(short_desc: 'add VAR_NAME DEFAULT_VALUE', desc: 'add/modify a variable default value') { |name, value| Rbe::Data::DataStore.vars.save_local = options[:local] Rbe::Data::DataStore.vars[name] = value } root_command[:var][:add][:local] = flag(type: :boolean, desc: 'add/modify local variables') root_command[:var][:list_add] = command(short_desc: 'list-add VAR_NAME DEFAULT_VALUES...', desc: 'add/modify a variable default value list') { |name, *values| Rbe::Data::DataStore.vars.save_local = options[:local] Rbe::Data::DataStore.vars[name] = values } root_command[:var][:list_add][:local] = flag(type: :boolean, desc: 'add/modify local variable value lists') root_command[:var][:list_sort] = command(short_desc: 'list-sort VAR_NAME', desc: 'sort a variable default value list') { |name| Rbe::Data::DataStore.vars.save_local = options[:local] Rbe::Data::DataStore.vars.search_local = options[:local] arr = Rbe::Data::DataStore.vars[name] Rbe::Data::DataStore.vars[name] = arr.natural_sort if arr.is_a?(Array) } root_command[:var][:list_sort][:local] = flag(type: :boolean, desc: 'sort local variable value lists') root_command[:var][:var_sort] = command(short_desc: 'var-sort', desc: 'sort the variables in the vars.rbe.yaml file') { Rbe::Data::DataStore.vars.save_local = options[:local] Rbe::Data::DataStore.vars.search_local = options[:local] Rbe::Data::DataStore.vars.sort_list } root_command[:var][:var_sort][:local] = flag(type: :boolean, desc: 'sort the variables in the local vars.rbe.yaml file') root_command[:var][:list] = command(aliases: %w(ls), short_desc: 'list [var_name]', desc: 'list the variables with defaults, optionally filtering by variable name') { |var_name = nil| vars = Rbe::Data::DataStore.vars.keys vars = vars.grep(/.*#{var_name}.*/) if var_name vars.sort! if vars.nil? || vars.empty? puts "Did not find any variables matching #{var_name}" else longest_var = vars.map { |v| v.to_s.length }.max vars.each { |v| puts "#{v.to_s.ljust(longest_var)} => #{Rbe::Data::DataStore.vars[v].to_s}" } end } root_command[:var][:remove] = command(aliases: %w(rm delete), short_desc: 'remove var_name', desc: 'remove a variable default value') { |var_name| Rbe::Data::DataStore.vars.save_local = options[:local] Rbe::Data::DataStore.vars.delete(var_name) if Rbe::Data::DataStore.vars.has_key?(var_name) } root_command[:var][:remove][:local] = flag(type: :boolean, desc: 'remove local variables') root_command[:var][:rewrite] = command(aliases: %w(rw), short_desc: 'rewrite', desc: 'rewrite the variable storage files to fix formatting differences caused by manual editing') { Rbe::Data::DataStore.vars.write_vars puts 'Vars rewritten' }
require './spec/spec_helper' describe Result do let(:the_class) {Result} subject { Result.new(:label => "A result", :score => 1) } describe "Instance Methods" do it {should respond_to :id} it {should respond_to :klass} it {should respond_to :raw_data} it {should respond_to :score} it {should respond_to :value} end it 'takes a hash as its argument' do the_class.new({}).should be end it 'exposes a lot of passed arguments' do the_class.new({:id => 'this'}).id.should eq 'this' the_class.new({:klass => 'this'}).klass.should eq 'this' the_class.new({:score => 'this'}).score.should eq 'this' end it 'exposes hash[:label] as value, on purpose' do the_class.new({:label => 'this', :value => 'that'}).value.should eq 'this' the_class.new({:label => 'this', :value => 'that'}).label.should eq 'this' end it 'passes any other .something calls down to the raw_data' do the_class.new({:thumbnail => 'this'}).thumbnail.should eq 'this' end end
class PaginaPrincipalTaxistaController < ApplicationController before_action :authenticate_driver! def index @driver=current_driver end end
require 'binary_heap' class PriorityQueueHashMap include BinaryHeap def initialize max_heap=false @elements = [] @index = {} @is_min_heap = !max_heap end def pop min_or_max = @elements.shift.key @index[min_or_max] = nil min_or_max end def add (key, value) @elements << KeyValue.new(key, value) index = @elements.size - 1 @index[key] = index bubble_up @elements, index end def updateKey(key, newValue) index = @index[key] return if index.nil? return if index >= @elements.size return if index < 0 old = @elements[index].value @elements[index].update_value(newValue) if (is_min_heap?) if (newValue < old) bubble_up @elements, index else bubble_down @elements, index end end if (is_max_heap?) if (newValue > old) bubble_up @elements, index else bubble_down @elements, index end end end def getMin if is_min_heap? pop else size = @elements.size last_index = size - 1 smallest = last_index if @elements[size - 2] < @elements[last_index] smallest = size - 2 end if last_index == smallest @elements.pop @index[last_index] = nil else last_item = @elements.pop smallest_item = @elements.pop @elements << last_item @index[smallest] = nil smallest_item end end end def getMax if is_max_heap? pop else size = @elements.size last_index = size - 1 largest = last_index if @elements[size - 2] > @elements[last_index] largest = size - 2 end if last_index == largest @elements.pop @index[last_index] = nil else last_item = @elements.pop largest_item = @elements.pop @elements << last_item @index[largest] = nil largest_item end end end def empty? @elements.empty? end private attr_reader :elements, :is_min_heap def swap elements, i, j elements[i], elements[j] = elements[j], elements[i] @index[i], @index[j] = j, i end class KeyValue include Comparable attr_reader :key, :value def initialize key, value validate_value value @key = key @value = value end def update_value new_value validate_value new_value @value = new_value end def <=>(other) validate_other other @value <=> other.value end private def validate_other other unless other.is_a? KeyValue raise "Please provide KeyValue class" end end def validate_value value unless value.is_a?(Integer) || value.is_a?(Float) raise "Value must be a number" end end end end
# frozen_string_literal: true module Lox class Scanner attr_reader :input def initialize(input) @input = input end def each_char return enum_for(:each_char) unless block_given? input.each_line do |line| line.each_char do |character| yield(character) end end end end end
module Gaman module Clip # Internal: Parses a FIBS You Say CLIP message. This CLIP message confirms # that FIBS has processed your request to send a 'say' or 'tell'. Message # is in the format: # # name message # # name: name of the player that the message was sent to. # message: message sent by the user. class YouSay def initialize(text) @name, @message = text.split(' ', 2) end def update(state) state.message_sent(:message, @message, @name) end end end end
require File.expand_path('../../../spec_helper', __FILE__) describe "1.9", -> describe "Time#round", -> before do @time = R.Time.utc(2010, 3, 30, 5, 43, "25.123456789".to_r) @subclass = Class.new(Time).now it "defaults to rounding to 0 places", -> @time.round.should == R.Time.utc(2010, 3, 30, 5, 43, 25.to_r) it "rounds to 0 decimal places with an explicit argument", -> @time.round(0).should == R.Time.utc(2010, 3, 30, 5, 43, 25.to_r) it "rounds to 7 decimal places with an explicit argument", -> @time.round(7).should == R.Time.utc(2010, 3, 30, 5, 43, "25.1234568".to_r) it "returns an instance of Time, even if #round is called on a subclass", -> @subclass.round.should be_kind_of Time
module Merb::Cache::DatabaseStore::Sequel # Module that provides Sequel support for the database backend # The cache model class CacheModel < Sequel::Model(Merb::Controller._cache.config[:table_name].to_sym) set_schema do primary_key :id varchar :ckey, :index => true varchar :data timestamp :expire, :default => nil end # Fetch data from the database using the specified key # The entry is deleted if it has expired # # ==== Parameter # key<Sting>:: The key identifying the cache entry # # ==== Returns # data<String, NilClass>:: # nil is returned whether the entry expired or was not found def self.cache_get(key) if entry = self.filter(:ckey => key).single_record(:limit => 1) return entry.data if entry.expire.nil? || Time.now < entry.expire self.expire(key) end nil end # Store data to the database using the specified key # # ==== Parameters # key<Sting>:: The key identifying the cache entry # data<String>:: The data to be put in cache # expire<~minutes>:: # The number of minutes (from now) the cache should persist # get<Boolean>:: # used internally to behave like this # - when set to true, perform update_or_create on the cache entry # - when set to false, force creation of the cache entry def self.cache_set(key, data, expire = nil, get = true) attributes = {:ckey => key, :data => data, :expire => expire } if get entry = self.filter(:ckey => key).single_record(:limit => 1) entry.nil? ? self.create(attributes) : entry.set(attributes) else self.create(attributes) end true end # Expire the cache entry identified by the given key # # ==== Parameter # key<Sting>:: The key identifying the cache entry def self.expire(key) self.filter(:ckey => key).delete end # Expire the cache entries matching the given key # # ==== Parameter # key<Sting>:: The key matching the cache entries def self.expire_match(key) self.filter{:ckey.like key + "%"}.delete end # Expire all the cache entries def self.expire_all self.delete_all end # Perform auto-migration in case the table is unknown in the database def self.check_table self.create_table unless self.table_exists? end end end
module Sass::Script::Functions include Flatrack::AssetExtensions def sized_image(filename, width=nil, height=nil) raise ArgumentError, 'height or width must be provided' unless width || height # assert types assert_type filename, :String if width assert_type width, :Number width = width.to_s.chomp 'px' end if height assert_type height, :Number height = height.to_s.chomp 'px' end # compute size size = [width, :x, height].join # Build Name filename = unquote(filename).to_s extension = File.extname(filename) basename = File.basename(filename, extension) new_name = asset_path [basename, "_#{size}", extension].join # Finish Sass::Script::String.new(new_name) end declare :sized_image, :args => [:filename, :width, :height] end
class Player < ActiveRecord::Base self.per_page = 30 self.primary_key = 'account_id' include PlayersHelper include ApplicationHelper after_create :save_player has_many :playedgames, :dependent => :destroy has_many :games, :through => :playedgames has_many :participations, :class_name => "Participant" has_many :heroes, -> {uniq}, :through => :participations, :source => :hero has_many :matches, :through => :participations, :source => :match has_many :dota_stats, :class_name => "DotaStats" validates :account_id, presence: true, uniqueness: {case_sensitive:false} scope :by_achievement_count, -> { joins(:playedgames).order(PlayedGame.by_achievement_count) } scope :by_time_played, -> { order(:total_time_played) } def acc_id to_account_id(self.account_id) end def steam_id to_steam_id self.account_id end def to_acc_id self.account_id = acc_id puts acc_id end def total_time_played played_time = playedgames.sum(:playedtime) end def total_time_played_string played_time = total_time played_time_hours = (played_time / 60).round(2) played_time_days = (played_time_hours / 24).round(2) "#{played_time_hours.to_s} hrs (#{played_time_days.to_s} days)" end def game_ids games.map(&:game_id) end def player_games if Game.any? owned_games = Steam.owned_games(steamid: self.steam_id) owned_games.each do | game | begin puts game.id g = Game.find_by(appid: game.id) self.playedgames.create(game_id: g.id, playedtime: game.playtime_forever) unless game_ids.include?(g.id) update_time_played rescue "Not Found" end end unless owned_games.nil? end end def hero_matches(id) matches = self.participations.select { |p| p.hero_id == id} matches end def wins participations.select{ |x| x.side.downcase == x.match.winner && x.match.lobby_type != "Co-op with bots"} end def total_wins wins.count end def losses participations.select{ |x| x.side.downcase != x.match.winner && x.match.lobby_type != "Co-op with bots"} end def radiant_matches participations.select { |x| x.side.downcase == "radiant" } end def dire_matches participations.select { |x| x.side.downcase == "dire" } end def record "#{total_wins} - #{participations.count - total_wins}" end def get_profile profile = Steam.profile(self.steam_id) if name.nil? end def save_player(profile = nil) profile = get_profile if profile.nil? self.dota_stats.create if profile self.name = profile.person_name self.real_name = profile.real_name self.clan_id = profile.clan_id.to_s self.country_code = profile.country_code self.state_code = profile.state_code self.profile_created_at = profile.created_at self.access_state = profile.access_state self.configured = profile.configured? self.status = profile.status self.last_login = profile.last_login self.profile_url = profile.profile_url self.small_avatar = profile.small_avatar_url self.medium_avatar = profile.medium_avatar_url self.large_avatar = profile.big_avatar_url self.commentable = profile.commentable? self.current_game_id = profile.game_id self.current_game_title = profile.game_title self.current_game_server_ip = profile.game_server_ip end self.save player_games end def get_friends friends = Steam.friends(self.steam_id) unless friends.nil? friends.each do |f| if player = Player.find_by(:account_id => to_account_id(f.steam_id)) unless self.friends.find_by(:account_id => player.account_id) self.friendships.create(:friend_id => player.id) end else p = Player.create(:account_id => to_account_id(f.steam_id)) self.friendships.build(:friend_id => p.id) sleep(1) end end end end def update_time_played self.total_time = playedgames.sum(:playedtime) save end def has_friends? self.friends.any? end end
require "xmlrpc/server" require 'xmlrpc/client' require "./LindaDistributed" require "./ConverterModule" module XMLRPCLinda class Common @@Port = 8088 @@Host = "localhost" @@Path = "/" @@Namespace = "LindaDistributed" def self.Port @@Port end def self.Host @@Host end def self.Path @@Path end def self.Namespace @@Namespace end def self.getFullyNamedMethod(method) tag = LindaDistributed::Common.OperationLookup[method][:tag] "#{@@Namespace}.#{tag}" end end class Server @port = nil @server = nil @lindaUrl = nil @lindaClient = nil def initialize(port, lindaUrl) @port = port @lindaUrl = lindaUrl end def start() @server = XMLRPC::Server.new(@port) @lindaClient = LindaDistributed::Client.new(@lindaUrl) puts "Started At #{Time.now}" serverProcessThread = Thread.new{internalStart()} serverProcessThread.join puts "End at #{Time.now}" end def internalStart() addHandlers() @server.serve end def addHandlers() @server.add_handler(Common.getFullyNamedMethod(:take)) do |t| process(:take, t) end @server.add_handler(Common.getFullyNamedMethod(:read)) do |t| process(:read, t) end @server.add_handler(Common.getFullyNamedMethod(:write)) do |t| process(:write, t) end end def getMethodInfo(m) {:key => m.to_s, :val => m, m => Common.getFullyNamedMethod(m)} end def process(m, t) method = getMethodInfo(m) converted = ConverterModule::Converter.xmlRPCTupleToTuple(t) output = @lindaClient.send(method[:val], converted) if (!output.is_a?(Module.const_get('Array'))) output = output.to_s end { "status" => true, "context" => {"method" => method, "input" => t}, "output": output } end end class Client @host = nil @port = nil @proxy = nil def initialize(host, port) @host = host @port = port path = Common.Path @proxy = XMLRPC::Client.new(@host, path, @port) end def sendMessage(method, tuple) @proxy.call(method, tuple) end end end
class Parameter < ActiveRecord::Base has_many :payload_requests has_many :clients, through: :payload_requests validates :list, presence: true, uniqueness: true end
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2014-2020 MongoDB Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Mongo # Allows objects to easily log operations. # # @since 2.0.0 module Loggable # The standard MongoDB log prefix. # # @since 2.0.0 PREFIX = 'MONGODB'.freeze # Convenience method to log debug messages with the standard prefix. # # @example Log a debug message. # log_debug('Message') # # @param [ String ] message The message to log. # # @since 2.0.0 def log_debug(message) logger.debug(format_message(message)) if logger.debug? end # Convenience method to log error messages with the standard prefix. # # @example Log a error message. # log_error('Message') # # @param [ String ] message The message to log. # # @since 2.0.0 def log_error(message) logger.error(format_message(message)) if logger.error? end # Convenience method to log fatal messages with the standard prefix. # # @example Log a fatal message. # log_fatal('Message') # # @param [ String ] message The message to log. # # @since 2.0.0 def log_fatal(message) logger.fatal(format_message(message)) if logger.fatal? end # Convenience method to log info messages with the standard prefix. # # @example Log a info message. # log_info('Message') # # @param [ String ] message The message to log. # # @since 2.0.0 def log_info(message) logger.info(format_message(message)) if logger.info? end # Convenience method to log warn messages with the standard prefix. # # @example Log a warn message. # log_warn('Message') # # @param [ String ] message The message to log. # # @since 2.0.0 def log_warn(message) logger.warn(format_message(message)) if logger.warn? end # Get the logger instance. # # @example Get the logger instance. # loggable.logger # # @return [ Logger ] The logger. # # @since 2.1.0 def logger ((respond_to?(:options) && options && options[:logger]) || Logger.logger) end private def format_message(message) format("%s | %s".freeze, _mongo_log_prefix, message) end def _mongo_log_prefix (respond_to?(:options) && options && options[:log_prefix]) || PREFIX end end end
class CreateTypeWorkdaysWorkers < ActiveRecord::Migration def change if !table_exists? :type_workdays_workers create_table :type_workdays_workers do |t| t.integer :worker_id t.integer :type_workday_id end end end end
class JobTitle < ActiveRecord::Base include ReindexExpensesAfterSave validates :name, presence: true has_many :job_title_assignments has_many :expenses, through: :job_title_assignments end
require_relative "operations" require "rake" module Gaudi # This is the default directory layout: # src/platform # |-name/ - sources and local headers # |-inc/ - public headers # |-test/ - unit tests # # Code can be split in several source directories and by default we will look for the files in # source_directory/common/name and source_directory/platform/name for every source_directory module StandardPaths include Gaudi::PlatformOperations # Determine which directories correspond to the given name # # This method maps the repository directory structure to the component names def determine_directories(name, source_directories, system_config, platform) paths = source_directories.map { |source_dir| Rake::FileList["#{source_dir}/{#{platform},common}/#{name}"].existing }.inject(&:+) raise GaudiError, "Cannot find source directories for '#{name}' in #{source_directories.join(",")}" if paths.empty? return paths end def determine_sources(component_directories, system_config, platform) src = system_config.source_extensions(platform) Rake::FileList[*component_directories.pathmap("%p/**/*{#{src}}")].exclude(*determine_test_directories(component_directories).pathmap("%p/**/*")) end def determine_headers(component_directories, system_config, platform) hdr = system_config.header_extensions(platform) Rake::FileList[*component_directories.pathmap("%p/**/*{#{hdr}}")].exclude(*determine_test_directories(component_directories).pathmap("%p/**/*")) end def determine_test_directories(component_directories) Rake::FileList[*component_directories.pathmap("%p/test")].existing end def determine_interface_paths(component_directories) Rake::FileList[*component_directories.pathmap("%p/inc")].existing end # Returns the path to the executable file corresponding to the component def executable(component, system_config) _, _, ext_exe = *system_config.extensions(component.platform) File.join(system_config.out, component.platform, component.name, "#{component.name}#{ext_exe}") end # Returns the path to the library file corresponding to the component def library(component, system_config) _, ext_lib, ext_exe = *system_config.extensions(component.platform) File.join(system_config.out, component.platform, component.name, "#{component.name}#{ext_lib}") end # Returns the path to the object output file corresponding to src def object_file(src, component, system_config) ext_obj, _, _ = *system_config.extensions(component.platform) src.pathmap("#{system_config.out}/#{component.platform}/#{component.parent ? component.parent.name : ""}/#{component.name}/%n#{ext_obj}") end # Returns the path to the unit test binary corresponding to the component def unit_test(component, system_config) _, _, ext_exe = *system_config.extensions(component.platform) File.join(system_config.out, component.platform, "tests", "#{component.name}Test#{ext_exe}") end # Is this a unit test or not? # # If you change the StandardPaths# unit_test naming convention you should # implement this accordingly. def is_unit_test?(filename) filename.pathmap("%n").end_with?("Test") end # Returns the path to the file containing the commands for the given target def command_file(tgt, system_config, platform) ext = "" if is_library?(tgt, system_config, platform) ext << "_#{platform}.library" elsif is_exe?(tgt, system_config, platform) ext << "_#{platform}.link" else ext << ".breadcrumb" end return tgt.pathmap("%X#{ext}") end # Gaudi supports code generation under the convention that all generated files # are created in the output directory. def is_generated?(filename, system_config) /#{system_config.out}/ =~ File.expand_path(filename) end end end
class SetDefaultHouseOfferType < ActiveRecord::Migration def up default_value = 0 # admin change_column_default :houses, :offer_type, default_value # admin House.all.each do |h| h.update_column(:offer_type, default_value) if h.offer_type.nil? end end def down change_column_default :houses, :offer_type, nil # admin end end
require 'test_helper' class ApplicationHelperTest < ActionView::TestCase before do @text_question = create(:question, :text, :required) @number_question = create(:question, :number, :required) @text_response = build(:response, :text, question_id: @text_question.id) @number_response = build(:response, :number, question_id: @number_question.id) @error_class = 'has-error' @invalid_text_response = build(:response, :text, question_id: @text_question.id) @invalid_number_response = build(:response, :number, question_id: @number_question.id) @invalid_text_response.errors.add(:require_question, :unique_response) @invalid_number_response.errors.add(:require_question, :unique_response) end # # Test for #error_class # Tested with a response object, but should work for any model instance # describe '#error_class' do it 'returns a css class as a string when object has an error' do text_response = error_class(@invalid_text_response) number_response = error_class(@invalid_number_response) assert_equal text_response, @error_class, 'Text response with error does not return correct css error class.' assert_equal number_response, @error_class, 'Number response with error does not return correct css error class' end it 'returns a css class as a string when object has error & attribute is provided' do text_response = error_class(@invalid_text_response, :require_question) number_response = error_class(@invalid_number_response, :require_question) assert_equal text_response, @error_class, 'Text response with error does not return correct css error class.' assert_equal number_response, @error_class, 'Number response with error does not return correct css error class' end it 'returns an empty string when response does not contain an error' do text_response = error_class(@text_question) number_response = error_class(@number_question) assert text_response.empty?, "Does not return an empty string for a valid text response. Got: #{text_response}" assert number_response.empty?, "Does not return an empty string for a valid number response. Got: #{number_response}" end it 'returns an empty string when response does not contain an error & attribute is provided' do text_response = error_class(@text_question, :require_question) number_response = error_class(@number_question, :require_question) assert text_response.empty?, "Does not return an empty string for a valid text response. Got: #{text_response}" assert number_response.empty?, "Does not return an empty string for a valid number response. Got: #{number_response}" end end # # Test for #error_class # Tested with a response object, but should work for any model instance # describe '#error_class' do it 'returns a css class as a string when object has an error' do text_response = error_class(@invalid_text_response) number_response = error_class(@invalid_number_response) assert_equal text_response, @error_class, 'Text response with error does not return correct css error class.' assert_equal number_response, @error_class, 'Number response with error does not return correct css error class' end it 'returns an empty string when response does not contain an error' do text_response = error_class(@text_question) number_response = error_class(@number_question) assert text_response.empty?, "Does not return an empty string for a valid text response. Got: #{text_response}" assert number_response.empty?, "Does not return an empty string for a valid number response. Got: #{number_response}" end end # # Test for #error_messages # Tested with a response object, but should work for any model instance # describe '#error_messages' do it 'contains css error class' do text_response = error_messages(@invalid_text_response) number_response = error_messages(@invalid_number_response) assert text_response.include?(@error_class), 'Invalid text error message does not contain correct error class' assert number_response.include?(@error_class), 'Invalid number error message does not contain error class' end it 'returns nil for a response without errors' do text_response = error_messages(@text_response) number_response = error_messages(@number_response) assert text_response.nil?, 'Valid text response returned value other than nil' assert number_response.nil?, 'Valid number response returned value other than nil' end end # # Testing #render_list # describe '#render_list' do it 'returns each message in an array as a <li> element' do msg_array = ['Hello World', 'Hola Mundo', 'Dlrow Olleh', 'Odnum Aloh'] raw_string = render_list(msg_array) list_length = raw_string.split('</li>').length assert raw_string.include?('<li>'), 'does not create any <li> elements' assert_equal msg_array.length, list_length, 'does not create <li> for each message.' end it 'works with error messages' do text_errors = @invalid_text_response.errors.full_messages number_errors = @invalid_number_response.errors.full_messages raw_text_string = render_list(text_errors) raw_number_string = render_list(number_errors) text_list_length = raw_text_string.split('</li>').length number_list_length = raw_number_string.split('</li>').length assert_equal text_errors.length, text_list_length, 'Text errors do not match resulting list' assert_equal number_errors.length, number_list_length, 'Number errors do not match resulting list' end end end
module ReqresRspec module Formatters class Pdf < Base # generates PDF file from existing HTML docs # TODO: more info def write # http://www.princexml.com/download/ pdf_tool_path = 'prince' pdf_doc_path = File.join(output_path, 'reqres_rspec.pdf') if `which #{pdf_tool_path}`.size > 0 files = Dir["#{output_path}/*.html"] files.reject!{ |filename| filename.scan(/rspec_doc/).empty? } files.delete("#{output_path}/rspec_doc_table_of_content.html") files.unshift("#{output_path}/rspec_doc_table_of_content.html") if files.size > 0 files_arg = files.join('" "') `#{pdf_tool_path} "#{files_arg}" -o "#{pdf_doc_path}"` logger.info "ReqresRspec::Formatters::Pdf saved doc to #{pdf_doc_path}" if File.exists? pdf_doc_path else logger.error 'No HTML files found' end else logger.error "#{pdf_tool_path} is not installed! Check README.md for more info" end end def cleanup_pattern 'reqres_rspec.pdf' end end end end
class UsersController < ApplicationController before_action :authenticate_user! # before_action :set_user, only: [:show] def index # user profiles feed if params[:query].present? @users = User.search_by_name_and_job(params[:query]) else @users = User.all end def show # user profile @user = User.find(params[:id]) end private # def set_user # @user = User.find(params[:username]) # end def user_params params.require(:user).permit(:first_name, :last_name, :bio, :cv) end end
# -*- coding: utf-8 -*- # hatsune lisp is moest language require_relative 'miku' require_relative 'error' require 'stringio' module MIKU def self.parse(str) if(str.is_a?(String)) _parse(StringIO.new(str, 'r').extend(StaticCode)) else str.extend(StaticCode) if not str.is_a? StaticCode str.staticcode_file = str.path if defined? str.path _parse(str) end end def self._parse(s) while(true) do c = skipspace(s) if c == ';' _comment(s) else break end end pos = s.staticcode_dump r = case c when '(' then _list(s) when '#' then _structure(s) when '"' then _string(s) when '`' then Cons.list(:backquote, _parse(s)).extend(StaticCode).staticcode_copy_info(pos) when ',' then c = s.getc.chr if c == '@' then Cons.list(:comma_at, _parse(s)).extend(StaticCode).staticcode_copy_info(pos) else s.ungetc(c[0]) Cons.list(:comma, _parse(s)).extend(StaticCode).staticcode_copy_info(pos) end when '\'' then Cons.list(:quote, _parse(s)).extend(StaticCode).staticcode_copy_info(pos) else _symbol(c, s) end _after(s, r) end def self._after(s, r) read_to(s){ |c| not(c =~ /[\t ]/) } skipped = s.getc if skipped.respond_to?(:chr) and skipped.chr == "[" pos = s.staticcode_dump return _after(s, Cons.new(r, _list(s, ']').extend(StaticCode).staticcode_copy_info(pos) ).extend(StaticCode).staticcode_copy_info(pos)) else s.ungetc(skipped) if skipped end r end def self._comment(s) read_to(s){ |c| c == "\n" } end def self._structure(s) c = skipspace(s) pos = s.staticcode_dump if(c == '(') Cons.new(:lambda, _list(s)).extend(StaticCode).staticcode_copy_info(pos) else type = _symbol(c, s) c = skipspace(s) if c != '(' raise SyntaxError.new("##{type}の後に文字#{c}があります。必ず中括弧をおいてください",s) end pos = s.staticcode_dump lst = _list(s).extend(StaticCode).staticcode_copy_info(pos) case when [:array, :a].include?(type) lst.to_a.extend(StaticCode).staticcode_copy_info(pos) when [:hash, :h].include?(type) genlist = Cons.new(:list, lst).extend(StaticCode).staticcode_copy_info(pos) Cons.list(:to_hash, genlist).extend(StaticCode).staticcode_copy_info(pos) # Hash[*lst.to_a].extend(StaticCode).staticcode_copy_info(pos) when [:lambda, :function, :func, :f].include?(type) Cons.new(:lambda, lst).extend(StaticCode).staticcode_copy_info(pos) end end end def self._list(s, pend=')') scd = s.staticcode_dump c = s.getc.chr return nil if c == pend s.ungetc(c[0]) car = _parse(s) c = skipspace(s) if(c == '.') then cdr = _parse(s) s.ungetc(skipspace(s)[0]) raise SyntaxError.new('ドット対がちゃんと終わってないよ',s) if(s.getc.chr != pend) return Cons.new(car, cdr).extend(StaticCode).staticcode_copy_info(scd) else s.ungetc(c[0]) return Cons.new(car, _list(s, pend)).extend(StaticCode).staticcode_copy_info(scd) end end def self._string(s) result = read_to(s){ |c| c == '"' } s.getc result.extend(StaticCode).staticcode_copy_info(s) end def self._symbol(c, s) sym = c + read_to(s){ |c| not(c =~ /[^\(\)\{}\[\].',#\s]/) } raise SyntaxError.new('### 深刻なエラーが発生しました ###',s) if not(sym) if(sym =~ /^-?[0-9]+$/) then sym.to_i elsif(sym =~ /^-?[0-9]+\.[0-9]+$/) then sym.to_f elsif(sym == 'nil') then nil elsif(sym == '') raise MIKU::EndofFile else sym.to_sym end end def self.read_to(s, escape=false, &cond) c = s.getc return '' if not c c = c.chr if !escape and cond.call(c) s.ungetc(c[0]) return '' end case when '\\' == c read_to(s, true, &cond) when ('n' == c) && escape "\n" + read_to(s, &cond) else c + read_to(s, &cond) end end def self.skipspace(s) c = s.getc return '' if not c c = c.chr s.staticcode_line += 1 if c == "\n" return skipspace(s) if(c =~ /\s/) c end def self.unparse(val) if val === nil 'nil' elsif(val.is_a?(List)) val.unparse elsif(val.is_a?(String)) '"' + val.dup.gsub("\n", '\\n').gsub('"', '\\"') + '"' elsif(val.respond_to?(:unparse)) val.unparse else val.inspect end end end
# frozen_string_literal: true require "test_helper" require "action_controller" module QuiltRails module Quilt class UiControllerTest < ActionDispatch::IntegrationTest include ActiveSupport::Testing::Isolation setup { boot_dummy } test "error when no react server" do time = Benchmark.realtime { get("/") } assert_response(:internal_server_error) assert_operator(time, :in?, (10..12)) end private def boot_dummy Rails.env = "development" require_relative "../../../dummy/config/environment" @routes = Rails.application.routes @controller = nil end end end end
unless defined?(NATS) require "nats/client" end require "concurrent" module NATS def initialize(options) @options = options process_uri_options @buf = nil @ssid, @subs = 1, {} @err_cb = NATS.err_cb @close_cb = NATS.close_cb @reconnect_cb = NATS.reconnect_cb @disconnect_cb = NATS.disconnect_cb @reconnect_timer, @needed = nil, nil @connected, @closing, @reconnecting, @conn_cb_called = false, false, false, false @msgs_received = @msgs_sent = @bytes_received = @bytes_sent = @pings = 0 @pending = ::Concurrent::Map.new(:pending => "", :subs => "") @pending_size = ::Concurrent::AtomicFixnum.new(0) @server_info = { } # Mark whether we should be connecting securely, try best effort # in being compatible with present ssl support. @ssl = false @tls = nil @tls = options[:tls] if options[:tls] @ssl = options[:ssl] if options[:ssl] or @tls send_connect_command end def flush_pending #:nodoc: pending = @pending.get_and_set(:pending, nil) sub_commands = @pending.get_and_set(:subs, nil) send_data(sub_commands) if sub_commands send_data(pending) if pending @pending_size.decrement(@pending_size.value) rescue raise if connected? puts "throwing things away" end def get_outbound_data_size if connected? super else 0 end rescue return 0 end def pending_data_size get_outbound_data_size + @pending_size.value end def process_connect #:nodoc: # Reset reconnect attempts since TCP connection has been successful at this point. current = server_pool.first current[:was_connected] = true current[:reconnect_attempts] ||= 0 cancel_reconnect_timer if reconnecting? # Whip through any pending SUB commands since we replay # all subscriptions already done anyway. @pending.get_and_set(:subs, nil) @subs.each_pair { |k, v| send_command("SUB #{v[:subject]} #{v[:queue]} #{k}#{CR_LF}") } unless user_err_cb? or reconnecting? @err_cb = proc { |e| raise e } end # We have validated the connection at this point so send CONNECT # and any other pending commands which we need to the server. flush_pending if (connect_cb and not @conn_cb_called) # We will round trip the server here to make sure all state from any pending commands # has been processed before calling the connect callback. queue_server_rt do connect_cb.call(self) @conn_cb_called = true end end # Notify via reconnect callback that we are again plugged again into the system. if reconnecting? @reconnecting = false @reconnect_cb.call(self) unless @reconnect_cb.nil? end # Initialize ping timer and processing @pings_outstanding = 0 @pongs_received = 0 @ping_timer = EM.add_periodic_timer(@options[:ping_interval]) do send_ping end end def unbind #:nodoc: # Allow notifying from which server we were disconnected, # but only when we didn't trigger disconnecting ourselves. if @disconnect_cb and connected? and not closing? disconnect_cb.call(NATS::ConnectError.new(disconnect_error_string)) end # If we are closing or shouldn't reconnect, go ahead and disconnect. process_disconnect and return if (closing? or should_not_reconnect?) @reconnecting = true if connected? @connected = false @pending.clear @pongs = nil @buf = nil cancel_ping_timer schedule_primary_and_connect end def send_command(command, priority = false) #:nodoc: was_empty = false if command[0..2] == SUB_OP @pending.compute(:subs) do |val| "#{val}#{command}" end else @pending.compute(:pending) do |val| was_empty = val.nil? priority ? "#{command}#{val}" : "#{val}#{command}" end end @pending_size.increment(command.bytesize) if connected? && (was_empty || @pending_size.value > MAX_PENDING_SIZE) EM.next_tick { flush_pending } end if (@options[:fast_producer_error] && pending_data_size > FAST_PRODUCER_THRESHOLD) err_cb.call(NATS::ClientError.new("Fast Producer: #{pending_data_size} bytes outstanding")) end true end end
# frozen_string_literal: true require_relative 'piece' # logic for knight chess piece class Knight < Piece def initialize(board, args) super(board, args) @symbol = " \u265E " @captures = [] end # iterates over move_set and adds the location as a move when valid def find_possible_moves(board) possibilities = [] move_set.each do |move| rank = @location[0] + move[0] file = @location[1] + move[1] next unless valid_location?(rank, file) possibilities << [rank, file] unless board.data[rank][file] end possibilities end # iterates over move_set and adds the location as a capture when valid def find_possible_captures(board) result = [] move_set.each do |move| rank = @location[0] + move[0] file = @location[1] + move[1] next unless valid_location?(rank, file) result << [rank, file] if opposing_piece?(rank, file, board.data) end @captures = result end private def move_set [[-1, -2], [1, 2], [-1, 2], [1, -2], [-2, -1], [2, 1], [-2, 1], [2, -1]] end end
class CategoriesController < ApplicationController before_action :set_category, only: [:update, :destroy] before_action :authenticate_user! def index @categories = Category.all @total_categories = @categories.size flash[:notice] = nil if params[:query].present? @categories = Category.where('name iLIKE ?', "%#{params[:query]}%") @total_categories = @categories.size else flash[:notice] = '' end end def create @category = Category.new(category_params) respond_to do |format| aux = 0 Category.all.each do |category| if category.name == @category.name aux = 1 end end if aux == 0 @category.save format.html { redirect_to categories_url} flash[:info] = '' else format.html { redirect_to :back} flash[:error] = '' end end end def update respond_to do |format| if @category.update(category_params) format.html { redirect_to categories_url} flash[:update] = '' else format.html { render :edit } end end end def destroy @category.destroy respond_to do |format| format.html { redirect_to categories_url} flash[:warning] = '' format.json { head :no_content } end end private def set_category @category = Category.find(params[:id]) end def category_params params.require(:category).permit(:name) end end
def setup_cookie # When this step-definition executes, the Browser has just opened and is sitting on the 'data:' URL # We need to go somewhere first before we can set the cookie in the Browser. # So we'll go to the login page visit(LoginPage) on(LoginPage).print_cookies on(LoginPage).add_cookie(@cookie_name, generate_mock_cookie_value) on(LoginPage).print_cookies end def setup_default_mocks(feature) old_yml = DataMagic.yml DataMagic.load 'mock_aapi_mappings.yml' default_responses = data_for(:default_responses) feature_specific_responses = load_feature_specific_responses feature DataMagic.yml = old_yml puts 'Setting up default mappings for COS' default_responses.each do |mock_uri, json_file| url = '/' + mock_uri.gsub('-', '/') configure_response(json_file, 'ANY', url, nil, 10) end puts 'Setting up default mappings for ' + feature feature_specific_responses.each do |mock_uri, json_file| url = '/' + mock_uri.gsub('-', '/') configure_response(json_file, 'ANY', url, nil, 9) end end def load_feature_specific_responses(feature) feature_specific_response_key = feature.downcase.gsub(" ", "_") + "_responses" begin feature_specific_responses = data_for feature_specific_response_key rescue ArgumentError => error puts "Error loading data for #{feature_specific_response_key}. Possibly, the key does not exist because no feature specific mappings are required for #{feature}." feature_specific_responses = {} end return feature_specific_responses end def setup_user_mock(userinfo) userinfo.each do |key, value| if( key.start_with?('api-') ) url = '/' + key.gsub('-', '/') request_data = value.split(',') # Setting up the match_context only because we want this mapping to be identified by the user's SSOID. # If you would prefer not to use the SSOID and just generate a random UUID for this mapping, don't setup # match_context and then just call configure_response with just the first 3 arguments @match_context[:ssoid] = userinfo['ssoid'] configure_response(request_data[0].strip, request_data[1].strip.upcase, url, @match_context) end end end
class AddSkillCategoryReferenceToSkills < ActiveRecord::Migration[5.0] def change add_reference :skills, :skill_category, foreign_key: true add_column :skills, :description, :string, default: "Please add description." end end
class CreateShips < ActiveRecord::Migration[6.0] def change create_table :ships do |t| t.integer :user_id t.integer :game_id t.integer :hp t.float :scores t.integer :position_x t.integer :position_y t.string :direction t.integer :start_time t.integer :player_option t.timestamps end end end
require 'rails_helper' RSpec.describe 'discover movies page' do before(:each)do @user = User.create(email: 'test123@xyz.com', password: 'viewparty') visit welcome_path fill_in :email, with: "test123@xyz.com" fill_in :password, with: "viewparty" click_button "Sign In" click_button "Discover Movies" end it 'has button Find Top Rated Movies' do expect(current_path).to eq(discover_path) expect(page).to have_content("Welcome test123!") expect(page).to have_button("Find Top Rated Movies") end it 'has search form and button Find Top Rated Movies' do expect(current_path).to eq(discover_path) expect(page).to have_button('Find Top Rated Movies') expect(page).to have_button('Find Movies') end it 'has Dashboard link to Dashboard Page' do expect(current_path).to eq(discover_path) expect(page).to have_link("Dashboard") click_link("Dashboard") expect(current_path).to eq(dashboard_path) expect(page).to_not have_link("Dashboard") expect(page).to have_button("Discover Movies") end it 'has Logout link to Welcome Page' do expect(current_path).to eq(discover_path) expect(page).to have_link("Log out") click_link("Log out") expect(current_path).to eq(welcome_path) expect(page).to_not have_link("Log out") expect(page).to have_content("Welcome to Viewing Party") expect(page).to have_link("New to Viewing Party? Register Here") end end
# encoding: utf-8 class Admin::ProjectsController < Admin::AdminController def index @projects = Project.order('id desc') end def new # end def create @project = Project.new project_params @project.project_thumbnail = ProjectThumbnail.new(project_thumbnail_params) if @project.save redirect_to admin_projects_path else render 'new' end end def edit @project = Project.find(params[:id]) end def update @project = Project.find(params[:id]) if params[:project_thumbnail].present? @project.project_thumbnail = ProjectThumbnail.new(project_thumbnail_params) end if @project.update_attributes(project_params) redirect_to admin_projects_path else redirect_to edit_admin_project_path(@project.id) end end def destroy @project = Project.find(params[:id]) if @project.destroy render :json =>{msg: 'ok'} else render :json =>{msg: 'error'} end end private def project_params params.require(:project).permit(:name, :brand_name, :company_name, :project_category_id, :service_content, :desc, :is_public) end def project_thumbnail_params params.require(:project_thumbnail).permit(:image) end end
class Tower < Cask version 'latest' sha256 :no_check url 'https://www.git-tower.com/download' homepage 'http://www.git-tower.com/' link 'Tower.app' end
# Invoice Requires # # Invoice contains the dynamic data needed to make an invoice. # Invoice works with the static date (invoice_text) to create a viewable and # printable invoice. # # Invoices are created during a run by the invoices_maker. # # An Invoice is made of: # # property # - property_ref (human_ref) # - occupiers (name of tenant) # - property_address (building's address) # - billing_address (agent or building's address) # - client_address # # snapshot # - Product (Invoice line item) # - charge_type # - date_due # - automatic_payment # - amount # - period (period_first..period_last) - period the charge covers. # # invoice_date - date the invoice is made on. # comments - one off information to be read by the bill's addressee. # class Invoice < ApplicationRecord enum color: { blue: 0, red: 1 } enum deliver: { mail: 0, retain: 1, forget: 2 } belongs_to :run, inverse_of: :invoices, optional: true belongs_to :snapshot, autosave: true, inverse_of: :invoices has_many :comments, dependent: :destroy has_many :products, dependent: :destroy, inverse_of: :invoice do def earliest_date_due drop_arrears.map(&:date_due).min or raise InvoiceMissingProducts, 'Invoice being created without any products.' end def drop_arrears reject(&:arrears?) end def total_arrears return 0 if last.nil? max.balance # same as sort.last.balance end end InvoiceMissingProducts = Class.new(StandardError) validates :deliver, inclusion: { in: delivers.keys } validates :invoice_date, :property_ref, :property_address, presence: true has_many :letters, dependent: :destroy has_many :invoice_texts, through: :letters after_destroy :destroy_orphaned_snapshot delegate :earliest_date_due, to: :products delegate :total_arrears, to: :products # prepare # Assigns the attributes required in an invoice # Args: # property - property that the invoice is being prepared for # invoice_date - the date which this invoice is being said to have been sent. # snapshot - debits generated for the invoicing period # comments - array of strings to appear on invoice for special info. # def prepare property:, snapshot:, color:, invoice_date: Time.zone.today, comments: [] letters.build invoice_text: InvoiceText.first self.property = property self.color = color self.snapshot = snapshot self.products = snapshot.make_products(color: color).products self.deliver = snapshot.make_products(color: color).state self.invoice_date = invoice_date self.comments = generate_comments comments: comments self end def mail? deliver == 'mail' end def retain? deliver == 'retain' end def forget? deliver == 'forget' end def page2? blue_invoice? && products.any?(&:page2?) end # actionable? # Is it worth invoicing or not. Must be one or more property that will # be affected by a charge. # def actionable? mail? || retain? end def to_s "Billing Address: #{billing_address.inspect}\n"\ "Property Ref: #{property_ref.inspect}\n"\ "Invoice Date: #{invoice_date.inspect}\n"\ "Property Address: #{property_address.inspect}\n"\ "client: #{client_address.inspect}" end private def property { property_ref: property_ref, occupiers: occupiers, property_address: property_address, billing_address: billing_address, client_address: client_address } end def property=(property_ref:, occupiers:, property_address:, billing_address:, client_address:) self.property_ref = property_ref self.occupiers = occupiers self.property_address = property_address self.billing_address = billing_address self.client_address = client_address end # Destroy the associated snapshot if it has no other invoice reference left. # (wanted snapshot to destroy itself if there were no other invoice but # didn't get it working.) # def destroy_orphaned_snapshot snapshot.invoices.empty? && snapshot.destroy end # First Invoice for a set of debited charges (red invoice is the second) # def blue_invoice? snapshot.first_invoice? self end def generate_comments(comments:) comments.reject(&:blank?).map { |comment| Comment.new clarify: comment } end end
class AddSalesRankToAmazonProducts < ActiveRecord::Migration[5.0] def change add_column :amazon_products, :sales_rank, :integer end end
require 'rails_helper' RSpec.describe Schedule, type: :model do it "has a valid factory" do expect(build(:schedule)).to be_valid end let(:schedule) { build(:schedule) } describe "ActiveModel validations" do # Basic validations it { expect(schedule).to validate_presence_of(:starts_at) } it { expect(schedule).to validate_presence_of(:ends_at) } end end
require "crypto_env_var/version" require "crypto_env_var/cipher" require "crypto_env_var/utils" module CryptoEnvVar CRYPTO_ENV_VAR = "CRYPTO_ENV" DECRYPT_KEY_VAR = "CRYPTO_ENV_DECRYPT_KEY" CRYPTO_ENV = lambda { ENV.fetch(CRYPTO_ENV_VAR) } DECRYPT_KEY = lambda { ENV.fetch(DECRYPT_KEY_VAR) } class << self def bootstrap!(read_from: CRYPTO_ENV, decrypt_with: DECRYPT_KEY, override_env: true) data = read_value(read_from) key = read_value(decrypt_with) hash = decrypt(data, key) hash.each_pair do |key, value| next if (!override_env && ENV.member?(key)) ENV[key] = value end end def encrypt(data, private_key_string) json = Utils.serialize(data) cipher = Cipher.new(private_key_string) encrypted_data = cipher.encrypt(json) Utils.encode(encrypted_data) end def decrypt(string, public_key_string) encrypted_data = Utils.decode(string) cipher = Cipher.new(public_key_string) json = cipher.decrypt(encrypted_data) Utils.deserialize(json) end private def read_value(source) source.respond_to?(:call) ? source.call() : source end end end
class AddNoticeToLeagueMatches < ActiveRecord::Migration[5.0] def change add_column :league_matches, :notice, :string, null: false, default: '' end end
class User < ApplicationRecord has_secure_password has_many :user_items has_many :items, through: :user_items has_many :item_types, -> { distinct }, through: :items has_and_belongs_to_many :freezers, {:join_table => :user_freezers} #has_many :freezers, -> { distinct }, through: :items has_many :notes def self.from_omniauth(auth) where(email: auth[:info][:email]).first_or_initialize.tap do |user| user.email = auth[:info][:email] user.uid = auth[:uid] user.username = auth[:info][:name] user.password = SecureRandom.hex user.image = auth[:info][:image] unless !!user.image user.save! end end end
class AuthenticateUser def initialize(email, password) @email = email @password = password end def authenticate JwtHelper.encode(user_id: user.id) if user end private def user @user = User.find_by(email: @email) return @user if @user && @user.authenticate(@password) raise(AppExceptionHandler::AuthenticationError, 'Invalid credentials') end end
# DO WHAT WE CAN TO MAKE IT TRUE Given /^a (?:valid|open) silent auction$/ do create_silent_auction end Given /^there are valid auctions as the following:$/ do |table| table.hashes.each do | hash | hash["open"] = (hash["open"] == "yes") ? true : false auction = SilentAuction.make!(:title => hash['title'], :description => hash['description'], :min_price => hash['min_price']) hash['active bids'].to_i.times do User.make!(:user).bids.create(:silent_auction_id => auction.id, :amount => hash['min_price']) end auction.open = hash["open"] auction.save! end end Given /^there are no valid running auctions$/ do SilentAuction.running.destroy_all end Given /^there are no valid closed auctions$/ do SilentAuction.closed.destroy_all end # REAL USER ACTIONS When /^I create a silent auction with the following:$/ do |table| table.hashes.each do | hash | visit new_silent_auction_path current_path.should == new_silent_auction_path find_field('End date').value.should == 2.weeks.from_now.to_date.to_s(:day_date_and_month) fill_in("silent_auction[title]", :with => hash['title']) fill_in("silent_auction[min_price]", :with => hash['min_price']) fill_in("silent_auction[description]", :with => hash['description']) click_button "submit_done" end end When /^the auction is open$/ do get(:silent_auctions).open = true end When /^the auction is closed$/ do get(:silent_auctions).open = false end When /^I view all running auctions$/ do visit silent_auctions_path end When /^I view all closed auctions$/ do visit closed_silent_auctions_path end When /^I view all expired auctions$/ do visit expired_silent_auctions_path end When /^I close the auction$/ do within("tr#silentAuction_#{get(:silent_auctions).id}") do click_link 'close_auction' page.driver.browser.switch_to.alert.accept end end When /^I delete the auction$/ do within("tr#silentAuction_#{get(:silent_auctions).id}") do click_link 'delete_auction' end end When /^I choose to continue deleting$/ do click_link "delete_auction" end When /^choose to cancel deleting$/ do click_link "cancel_delete_auction" end # VALIDATE HOWEVER WE MUST Then /^a valid silent auction is created with the following:$/ do |table| table.hashes.each do | hash | hash["open"] = (hash["open"] == "yes") ? true : false SilentAuction.where(hash).count.should == 1 end end Then /^it will have a title$/ do verify_silent_auction_has_title get(:silent_auctions) end Then /^it will have a description$/ do verify_silent_auction_has_description get(:silent_auctions) end Then /^it will have a minimum price$/ do verify_silent_auction_has_min_price get(:silent_auctions) end Then /^the auction is running$/ do get(:silent_auctions).open?.should == true end Then /^the auction is not running$/ do get(:silent_auctions).open?.should == false end Then /^I can see all auctions$/ do page.find(:css,"tr.auction", :count => SilentAuction.count) end Then /^I can see running auctions and closed auctions separately$/ do page.should have_css('table#runningAuctions') page.should have_css('table#closedAuctions') end Then /^I can see all running auctions sorted by most recent first:$/ do |table| within_table('runningAuctions') do page.find(:css,"tr.auction", :count => SilentAuction.running.count) expected_order = table.raw.map {|titleRow| titleRow[0]} actual_order = page.all('p.itemTitle').collect(&:text) actual_order.should == expected_order end end Then /^I can see all closed auctions sorted by most recent first:$/ do |table| within_table('closedAuctions') do page.find(:css,"tr.auction", :count => SilentAuction.closed.count) expected_order = table.raw.map {|titleRow| titleRow[0]} actual_order = page.all('p.itemTitle').collect(&:text) actual_order.should == expected_order end end Then /^I can see all expired auctions sorted by most recent first:$/ do |table| within_table('expiredAuctions') do page.find(:css,"tr.auction", :count => SilentAuction.expired.count) expected_order = table.raw.map {|titleRow| titleRow[0]} actual_order = page.all('p.itemTitle').collect(&:text) actual_order.should == expected_order end end Then /^I am told that no auctions are currently running$/ do page.should have_content('There are no running auctions') end Then /^I am told that no closed auctions exist$/ do page.should have_content('There are no closed auctions') end Then /^I cannot close the auction$/ do within("tr#silentAuction_#{get(:silent_auctions).id}") do page.should have_no_link("close_auction") end end Then /^I should see the confirmation page$/ do auction = get(:silent_auctions) current_path.should == confirm_delete_silent_auction_path(auction) page.should have_content("Are you sure you want to delete this auction?") page.should have_content(auction.title) end Then /^I should see the list of active bidders as following:$/ do |table| table.hashes.each do |hash| page.should have_content(hash["bidder"]) end end Then /^I can see the end date$/ do # TODO improve the effectiveness of asserting the dynamic end date # that should appear for each open auction on the listing page page.should have_content 'End date' end Then /^the auction should be deleted$/ do auction = get(:silent_auctions) visit silent_auctions_path page.should have_no_content(auction.title) SilentAuction.find_by_title(auction.title).should == nil end
# -*- coding: utf-8 -*- # 実行メインクラスの概念はなく上から順次実行されます # 実行は ruby basic_practice.rb で行う # 外部ライブラリの使い方 require "json" obj = JSON.parse('{"key1":"value1","key2":"value2"}') p obj # 標準出力 print("This file name is basic_practice.rb\n") p "short ver" # 標準入力 p "Please input any key : " input = STDIN.gets p input # 引数 p ARGV[0] p ARGV.length # 環境変数 if ENV["KEY"] then p ENV["KEY"] end # 変数 i = 100 s = "str" # 配列 iarray = [] iarray = [1, 2, 3, 4, 5] sarray = ["a", "b", "c", "d", "e"] iarray.push(6) p iarray[0] ## 配列に他の配列の要素を追加 p iarray + sarray # 連想配列 hmap = {} hmap = { "key1" => "value1", "key2" => "value2", } hmap.store("key3", "value3") p hmap["key1"] # 関数の作り方 def my_func(arg1) p arg1 end # 関数の使い方 my_func(i) # 条件分岐(if) flag = false if flag then p "true" elsif !flag then p "false" end # 繰り返し(for and each) for i in 1..10 do p i end for j in sarray do p j end hmap.each { |key, value| p "key:" + key + ",value:" + value } loop = 0 begin loop = loop + 1 p loop end while loop < 10 # ファイル制御 f = File::open(Dir::getwd + "/read.txt", "r") f.each { |line| p line } f.close() f = File::open(File.dirname(__FILE__) + "/write.txt", "w") f.puts("write test") f.close() # エラーハンドリング index = 'a' begin p sarray[index] rescue p "entry rescue section" end # 正規表現 str = s if str =~ /^s|s$/ then p "regex ok" elsif /^[a-z]$/ =~ str then p "regex ok char 1" end r = /([a-z])/ p r.match("a") p $1 p r.match("B") p $1 # パッケージの概念(module) module MyModule # クラスの生成方法 class MyClass def my_class_func(arg1) p arg1 end end end # 独自クラスの使い方 mc = MyModule::MyClass.new mc.my_class_func("Bob")
require "minitest/autorun" require "minitest/pride" require 'net/http' require 'json' class APITest < Minitest::Test def test_request_success keyword = "thomas" results = keyword_search(keyword) assert_equal results.class, Hash assert_equal results[:Search].class, Array assert_equal results[:Response], "True" end def test_missing_api_key url = 'http://www.omdbapi.com/?apikey=' uri = URI(url) response = Net::HTTP.get(uri) to_json = JSON.parse(response, symbolize_names: true) assert_equal to_json[:Response], "False" assert_equal to_json[:Error], "No API key provided." end def test_search_for_thomas keyword = "thomas" results = keyword_search(keyword) results[:Search].each do |result| assert_includes result[:Title], keyword.capitalize || keyword.downcase assert_includes result, :Title && :Year && :imdbID && :Type && :Poster result.values.each do |v| assert_equal v.class, String end if result[:Type] == "movie" assert_equal result[:Year].to_i.between?(1900,2022), true end if result[:Type] == "series" assert_equal result[:Year][0..3].to_i.between?(1900,2022), true assert_equal result[:Year][-4..-1].to_i.between?(1900,2022), true end end end def test_search_results_have_valid_imdb_id keyword = "rush hour" results = keyword_search(keyword) results[:Search].each do |result| url = "http://www.omdbapi.com/?apikey=9b20bff6&i=#{result[:imdbID]}" uri = URI(url) response = Net::HTTP.get(uri) to_json = JSON.parse(response, symbolize_names: true) assert_equal to_json[:Response], "True" end end def test_search_results_have_working_poster_links keyword = "rush hour" results = keyword_search(keyword) results[:Search].each do |result| uri = URI(result[:Poster]) response = Net::HTTP.get(uri) assert_equal response.class, String end end def test_no_duplicate_records_up_to_page_5 pages = (1..5) keyword = 'thomas' titles = Hash.new pages.each do |page| url = "http://www.omdbapi.com/?apikey=9b20bff6&s=#{keyword}&page=#{page}" uri = URI(url) response = Net::HTTP.get(uri) to_json = JSON.parse(response, symbolize_names: true) to_json[:Search].each do |result| titles[result[:Title]] = result[:Year] end end assert_equal titles.size == titles.uniq.size, true end def test_search_results_include_only_movies_up_to_page_5 pages = (1..5) keyword = "thomas" type = "movie" pages.each do |page| url = "http://www.omdbapi.com/?apikey=9b20bff6&s=#{keyword}&page=#{page}&type=#{type}" uri = URI(url) response = Net::HTTP.get(uri) to_json = JSON.parse(response, symbolize_names: true) to_json[:Search].each do |result| assert_includes result[:Type], "movie" end end end private def keyword_search(keyword) url = "http://www.omdbapi.com/?apikey=9b20bff6&s=#{keyword}" uri = URI(url) response = Net::HTTP.get(uri) JSON.parse(response, symbolize_names: true) end end
# frozen_string_literal: true class GameUnitsFinder include BaseFinder def initialize(current_user, params = {}) @current_user = current_user @params = params end def call current_units = Unit .joins(:users) .where(users: { id: @current_user.id }) game_units = GameUnit.where(unit_id: current_units.pluck(:id)) game_units = by_opponent_users(game_units) game_units = by_game_user_count(game_units) game_units = by_outcome(game_units) by_created_at(game_units) end private def by_opponent_users(game_units) return game_units unless @params[:opponent_users_ids] opponent_users_ids = @params[:opponent_users_ids].split(',').map(&:to_i) opponent_units = Unit .joins(:users) .where.not(users: { id: @current_user.id }) .where(users: { id: opponent_users_ids }) opponent_game_units = GameUnit.where(unit_id: opponent_units.pluck(:id)) game_units.where(game_id: opponent_game_units.pluck(:game_id)) end def by_game_user_count(game_units) return game_units unless @params[:game_user_count] game_units.joins(:unit).where(units: { user_count: @params[:game_user_count] }) end def by_outcome(game_units) return game_units if @params[:outcome] == 'all' game_units.where(outcome: @params[:outcome]) end def by_created_at(game_units) game_units.where( created_at: [Time.parse(@params[:created_after])..Time.parse(@params[:created_before])] ) end end
class AddValueJsonToDynamicFields < ActiveRecord::Migration def change add_column :dynamic_annotation_fields, :value_json, :jsonb, default: '{}' add_index :dynamic_annotation_fields, :value_json, using: :gin end end
require 'spec_helper' shared_examples 'a classifiable model' do let(:model) { described_class.new } let(:default_type) do PanamaxApi::TYPES.find { |type| type['default'] }['name'] end context 'when the type field is nil' do it 'sets the type to be the default value' do model.valid? expect(model.type).to eq default_type end end context 'when the type field is an invalid value' do before do model.type = 'foobar' end it 'sets the type to be the default value' do model.valid? expect(model.type).to eq default_type end end context 'when the type field is a valid value' do before do model.type = PanamaxApi::TYPES.last['name'] end it 'leaves the value as-is' do model.valid? expect(model.type).to eq PanamaxApi::TYPES.last['name'] end end end
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "Meme::Post" do describe "::find" do before :each do query = "SELECT * FROM meme.search WHERE query='meme rocks'" fake_web(query, 'meme_search.json') @results = Meme::Post.find('meme rocks') end Meme::Post::VARS.each do |attr| it { @results.first.should respond_to(attr) } end it "should return pubid" do @results.first.pubid.should == "yC8nqOd" end it "should return guid" do @results.first.guid.should == "7Z7XFAPD5FLXFKJVT4NG6XTTA4" end it "should return url" do @results.first.url.should == "http://meme.yahoo.com/celizelove/p/yC8nqOd/" end it "should return timestamp" do @results.first.timestamp.should == "1268410909000" end it "should return category" do @results.first.category.should == "text" end it "should return type" do @results.first.type.should == "text" end it "should return content" do @results[4].content.should == "http://d.yimg.com/gg/u/2441eceb4b334c6fc29c9bd306fe1957693d605e.jpeg" end it "should return repost_count" do @results.first.repost_count.should == "0" end it "should return caption" do @results[1].caption.should == "This is good. But a lot of things happening means a high chance that I, the man who lives and breathes Panic and has a giant status board in my head, might not properly explain everything to everyone. Steve and I realized it was high time we made this Cabel Status Board public… using technology!" end it "if posts not found, should return nil" do query = "SELECT * FROM meme.search WHERE query='brhackday' and type='audio'" fake_web(query, 'meme_search_type_audio.json') Meme::Post.find('brhackday', :type => :audio).should be_nil end context "using the option :type" do it "type photo" do query = "SELECT * FROM meme.search WHERE query='meme rocks' and type='photo'" fake_web(query, 'meme_search_type_photo.json') @results = Meme::Post.find('meme rocks', :type => :photo) @results.count.should == 3 @results.first.type.should == "photo" end it "type video" do query = "SELECT * FROM meme.search WHERE query='keyboard cat' and type='video'" fake_web(query, 'meme_search_type_video.json') @results = Meme::Post.find('keyboard cat', :type => :video) @results.count.should == 2 @results.first.type.should == "video" end end end describe "::popular" do before :each do query = "SELECT * FROM meme.popular WHERE locale='pt'" fake_web(query, 'meme_popular_pt.json') @results = Meme::Post.popular end it { @results.count.should == 10 } it "should return content" do @results.first.content.should == "http://d.yimg.com/gg/u/38b15b9620e38090aa092420790d3b5a528e8e99.jpeg" end it "return the user post" do query = "SELECT * FROM meme.info WHERE owner_guid='QKSXELRVSAWRI77FVKODDYTKB4'" fake_web(query, 'meme_info_guid.json') @results.first.user.guid.should == "QKSXELRVSAWRI77FVKODDYTKB4" end context "using the locale" do it "locale 'id' for Bahasa Indonesia" do query = "SELECT * FROM meme.popular WHERE locale='id'" fake_web(query, 'meme_popular_id.json') @results = Meme::Post.popular('id') @results.count.should == 10 @results.first.content.should == "Kemarin dia menawarkan cinta, hmm sayang harganya terlalu mahal jadi aku putuskan untuk tak memilikinya..." end end end end
class BusinessController < ApplicationController def initialize super @var = BusinessDecorator.new @var.link = { I18n.t("cmn_sentence.listTitle", model:Business.model_name.human)=>{controller:"business", action:"index"}, I18n.t("cmn_sentence.newTitle", model:Business.model_name.human)=>{controller:"business", action:"new"}, I18n.t('cmn_sentence.listTitle',model: Office.model_name.human) => {controller:'office', action:'index'}, I18n.t('cmn_sentence.listTitle', model: Offer.model_name.human) => {controller:'offer', action: 'index'} } end def index @var.title = t('cmn_sentence.listTitle', model: @var.model_name) if request.post? cond_list = {name: CondEnum::LIKE, business_type_id: CondEnum::EQ} free_word = {keyword: [:descriptions, :welcome]} cond_set = self.createCondition(params, cond_list, free_word) @businesses = Business.where(cond_set[:cond_arr]) @var.search_cond = cond_set[:cond_param] else @var.search_cond = nil end @businesses = Business.all if @business.nil? @var.view_count = @businesses.count end # ?office_id=?で親の事業所idがわたる def new @var.title = t('cmn_sentence.newTitle', model: t('cmn_dict.business')) @var.mode = "new" @business = Business.new return insert_new_business(params) if request.post? @business.init_new_instance(params) end def edit @var.title = I18n.t("cmn_sentence.editTitle", model: I18n.t("cmn_dict.business"), id: params[:id]) @var.mode = params[:id] @business = Business.find(params[:id]) render "new" end def update end def contact_list end def search @businesses = search_by_post(@var) @businesses = Business.all if @businesses.size == 0 @msg = 'Search done!' rescue => e logger.debug(e) @msg=e.message end private def search_by_post(var) cond_list = {name: CondEnum::LIKE, business_type_id: CondEnum::EQ} free_word = {keyword: [:description, :welcome]} cond_set = self.createCondition(params, cond_list, free_word) var.search_cond = cond_set[:cond_param] Business.where(cond_set[:cond_arr]) end def insert_new_business(params) begin Business.transaction do @business.attributes = Business.business_params(params, :business) @business.save! respond_to do |format| format.html {redirect_to(action: 'edit', id: @business.id)} format.json {render :show, status: :created, location: @business} end end rescue => e raise e if Rails.env == "development" flash.now[:alert] = e.message respond_to do |format| format.html {render 'new'} format.json {render json: format, status: :unprocessable_entity} end end end end
# frozen_string_literal: true module Api module V1 # Room Reservation database model class RoomResRoom < RoomResRecord self.table_name = APPLICATION_CONFIG['api']['database']['roomres']['rooms']['table_name'] has_many :reservations, class_name: 'Api::V1::RoomResReservation', foreign_key: 'room_id' scope :except_rooms, ->(room_ids) { where('id NOT IN(?)', room_ids) } ## # Return all rooms which do not have an active reservation during the start_time provided # @param [DateTime] start_time - the start time to check, Ruby Time formatted (ie. YYYYmmddHHMMSS) # @return [ActiveRecord::Query] - the rooms def self.available_rooms(start_time) room_ids = active_room_ids(start_time) room_ids << 91 # also exclude the id 91 (room 2525), which has been disabled for reservations except_rooms(room_ids) end ## # Return all room ids which don't have an active reservation during the start_time provided # @param [DateTime] start_time - the start time to check, Ruby Time formatted (ie. YYYYmmddHHMMSS) # @return [ActiveRecord::Query] - the room ids which have an active reservation now or within 10 minutes def self.active_room_ids(start_time) joins(:reservations) .where('(reservations.start_time <= ? AND reservations.end_time > ? AND reservations.deleted_at IS NULL) OR (reservations.start_time <= ? AND reservations.end_time > ? AND reservations.deleted_at IS NULL)', start_time, start_time, start_time + 10.minutes, start_time + 10.minutes) .pluck(:id) end end end end
module Cinemas class CinemaRepository CinemaNotFound = Class.new(StandardError) CinemaNumberAlreadyTaken = Class.new(StandardError) attr_reader :repository def initialize(repository: Cinemas::Model) @repository = repository end def find_by_id(id) repository.find(id) rescue ActiveRecord::RecordNotFound raise CinemaNotFound end def create_cinema params repository.create!(params) end def destroy_cinema id cinema = repository.find(id) cinema.destroy end def cinema_seats(cinema) repository.seats end def find_by_params(params) repository.find_by(params) end end end
class Mutations::CompleteResolution < Mutations::BaseMutation null true # arguments passed as "args" argument :id, ID, required: true argument :completed, Boolean, required: true # return type from the mutation #type Types::ResolutionType field :resolution, Types::ResolutionType, null: true field :errors, [String], null: false def resolve(id:, completed:) resolution = Resolution.find(id) if completed resolution.completed_at = DateTime.now.utc else resolution.completed_at = nil end if resolution.save # Successful save, return the object with no errors { resolution: resolution, errors: [], } else # Failed save, return the errors to the client { resolution: resolution, errors: resolution.errors.full_messages } end end end
class CartProduct < ActiveRecord::Base belongs_to :user # return products in the cart of the current user def self.show_cart(page, current_user_id) @cart_products = order("created_at DESC").where(user_id: current_user_id) @show_cart_list = [] @cart_products.each do |cart_product| show_cart_item = {} product = Product.find cart_product.product_id show_cart_item[:id] = cart_product.id show_cart_item[:title] = product.title show_cart_item[:price] = product.price show_cart_item[:total] = product.price * cart_product.quantity show_cart_item[:quantity] = cart_product.quantity show_cart_item[:stock] = product.quantity show_cart_item[:created_at] = cart_product.created_at @show_cart_list << show_cart_item end @show_cart_list.paginate(page: page, per_page: 5) end =begin if the same product exists in the cart, return the CartProduct else return nil =end def self.ifSameProductExist (productId, current_user_id) @cart_products = CartProduct.where(user_id: current_user_id) @cart_products.each do |cart_product| if cart_product.product_id.to_s == productId return cart_product end end return nil end def self.update_quantity(cartProductId, quantity) cartProduct = CartProduct.find cartProductId product = Product.find cartProduct.product_id if quantity <= product.quantity cartProduct.update(quantity: quantity) return quantity else return product.quantity end end end
class DamsDatastream < ActiveFedora::RdfxmlRDFDatastream property :complexSubject, predicate: DAMS.complexSubject, class_name: "MadsComplexSubject" property :scheme, predicate: MADS.isMemberOfMADSScheme, class_name: "MadsScheme" property :temporal, predicate: DAMS.temporal, class_name: "MadsTemporal" property :topic, predicate: DAMS.topic, class_name: "MadsTopic" accepts_nested_attributes_for :complexSubject, :scheme, :temporal, :topic end
class DropNights < ActiveRecord::Migration def change drop_table :nights end end
# encoding: utf-8 # See LICENSE.txt for licensing information. require 'logger' require './c64asm/data' require './c64asm/basic' require 'pry' # Fixnum monkey-patches class Fixnum # Return the least significant byte def ls_byte; self & 255; end # Return the most significant byte def ms_byte; self >> 8; end end # Our namespace module C64Asm attr_accessor :logger # Default logging is verbose and to STDERR @logger = Logger.new(STDERR) @logger.level = Logger::DEBUG @logger.formatter = lambda do |s, d, p, m| "#{d.strftime('%H:%M:%S.%L')} #{s.to_s.ljust(7)} -- #{m}\n" end # Log a message if we have a logger present def self.log(level, msg) @logger.send(level, msg) if @logger end # General C64Asm exception class class Error < Exception; end # Operand error class OperandError < Error; end # Operand, the most important building block class Operand attr_reader :op, :mode, :arg, :label # Setup and validate an operand def initialize(op, arg = false, mod = false) raise OperandError, 'No such operand' unless OP_CODES.has_key? op @op = op @mode = false @arg = arg @mod = mod @label = false @ready = false opcode = OP_CODES[op] # mode resolution if opcode.has_key? :n # all immediates @mode = :n @ready = true elsif not arg and opcode.has_key? :e @mode = :e @ready = true elsif opcode.keys.length == 1 # branching and jsr @mode = opcode.keys.first elsif arg and arg.instance_of? Fixnum # for the rest, let's try figure out mode by checking argument # we treat addressing modes as of higher priority, eg. :z over :d if arg >= 0 and arg <= 255 if opcode.has_key? :z @mode = :z elsif opcode.has_key? :d @mode = :d else raise OperandError, 'No mode handling byte' end elsif arg >= 256 and arg <= 65535 if opcode.has_key? :a @mode = :a else raise OperandError, 'Argument out of range' end end end # future reference handling, aka labels if arg and arg.instance_of? Symbol # labels can point only to absolute addresses unless (has_a = opcode.has_key? :a) or opcode.has_key? :r raise OperandError, 'Used with label but no :a or :r modes' end @mode = has_a ? :a : :r @label = arg end # argument checking if @mode and not @label raise OperandError, 'Invalid argument' unless validate @ready = true end # modifier checking check_mod if mod end # create addressing mode methods ADDR_MODES.keys.each do |mode| class_eval "def #{mode}(arg, mod = nil); check_mode(:#{mode}, arg, mod); end" end # Do we have all data in raw form def ready?; @ready; end # Resolve addresses, if needed def resolve(arg) return true unless @label @mod ? @arg = arg.send(*@mod) : @arg = arg raise OperandError, 'Invalid argument' unless validate @ready = true end # Turn the operand into source code string def to_source source = @op.to_s if @label if @mod case @mod.first when :+ label = @label.to_s + ('%+d' % @mod[1]) when :ls_byte label = '<' + @label.to_s when :ms_byte label = '>' + @label.to_s else label = @label.to_s + @mod.join end else label = @label.to_s end end unless @mode == :n || @mode == :e if @label source += ADDR_MODES[@mode][:src] % label else if @mode == :r source += ' *%+d' % @arg.to_s else source += ADDR_MODES[@mode][:src] % ('$' + @arg.to_s(16)) end end end source end # Return the length of the additional operand in machine code bytes, or false def length; @mode ? 1 + ADDR_MODES[@mode][:len] : false; end # Return pretty string representation of the operand def to_s; "<Operand: #{to_source}>"; end # Turn the operand into a byte array # Won't work if we haven't got all the necessary data yet. def to_a return [] unless @ready bytes = [OP_CODES[@op][@mode][:byte]] if [:a, :ar].include?(@mode) || (@arg && @arg > 255) bytes += [@arg.ls_byte, @arg.ms_byte] elsif @arg bytes += [@arg] else bytes end end # Turn the operand into a byte string # Won't work if we haven't got all the necessary data yet. def to_binary return '' unless @ready @mode == :r ? to_a.pack('Cc') : to_a.pack('C*') end private # Validate addressing mode def check_mode(mode, arg, mod) # raise OperandError, 'Operand was ready' if @ready raise OperandError, 'No such mode' unless OP_CODES[@op].has_key? mode @mode = mode @arg = arg @mod = mod case arg when Fixnum raise OperandError, 'Invalid argument' unless validate @ready = true when Symbol modec = @mode.to_s[0] if @mod raise OperandError, 'Label used with wrong mode' unless (modec == 'a') or (modec == 'd') else raise OperandError, 'Label used with wrong mode' unless modec == 'a' end @label = arg else raise OperandError, 'Invalid argument type' end check_mod if mod self end # Validate modifier def check_mod if @mod.instance_of? Fixnum @mod = [:+, @mod] elsif @mod.instance_of? Array and @mod.length == 2 and [:/, :*, :<<, :>>, :& , :|].member? @mod.first raise OperandError, 'Arithmetic argument has to be a fixnum' unless @mod[1].instance_of? Fixnum elsif [:<, :>].member? @mod # this two modifiers make sense only for :d addressing mode if not @mode or (@mode and @mode != :d) unless OP_CODES[@op].has_key? :d raise OperandError, 'Byte modifier used with non-direct addressing mode' end @mode = :d end @mod = [@mod == :< ? :ls_byte : :ms_byte] else raise OperandError, 'Unknown modifier' end end # Low-level validation def validate if (@mode == :n and @arg) or \ (@mode == :r and not (@arg >= -128 and @arg <= 127)) or \ ([:a, :ax, :ay, :ar].member? @mode and not (@arg >= 0 and @arg <= 65535)) or \ ([:d, :z, :zx, :zy, :zxr, :zyr].member? @mode and not (@arg >= 0 and @arg <= 255)) binding.pry false else true end end end # Nop error class NopError < Error; end # Nops don't translate to machine code # Things like labels, align statements etc. class Nop # No need to resolve anything here def ready?; true; end # Not a label def label; false; end # We don't generate machine code def to_a; []; end # We don't generate machine code def to_binary; ''; end end # Label error class LabelError < NopError; end # Label references an address # Which might as well be not know at the time of declaration. class Label < Nop attr_reader :name # Create new label nop def initialize(name) raise LabelError, 'Label name must be a symbol' unless name.instance_of? Symbol @name = name end # Return source code representation def to_source; @name.to_s; end # Return pretty string representation def to_s; "<Label: #{@name}>"; end end # Alignment error class AlignError < NopError; end # Align sets the linker current address class Align < Nop attr_reader :addr # Create new alignment nop def initialize(addr) unless addr.instance_of? Fixnum and (addr >= 0 and addr <= 65535) raise AlignError, 'Alignment address has to be in range $0 - $ffff' end @addr = addr end # Return source code representation def to_source; "* = $#{@addr.to_s(16)}"; end # Return pretty string representation def to_s; "<Align: $#{@addr.to_s(16)}"; end end # Data error class DataError < NopError; end # Data is a bunch of bytes class Data < Nop attr_reader :data, :mode, :length, :label, :ready # Create new data nop # Handles a couple of input modes. def initialize(data, mod = false, mode = :default) @label = false @ready = true @mod = mod case data when Symbol raise DataError, 'Unimplemented mode' unless [:default, :label].member? mode @length = 2 @label = data @ready = false when String raise DataError, 'Unimplemented mode' unless [:default, :screen].member? mode @length = data.length when Array raise DataError, 'Unimplemented mode' unless [:default, :word].member? mode @length = mode == :word ? 2 * data.length : data.length when Fixnum raise DataError, 'Unimplemented mode' unless [:default, :word].member? mode @length = 2 data = [data] mode = :word end @data = data @mode = mode check_mod if mod validate end # Do we have all data in raw form def ready?; @ready; end # Resolve addresses, if needed def resolve(arg) return true unless @label @mod ? res = arg.send(*@mod) : res = arg @data = [res] @mode = :word raise DataError, 'Invalid argument' unless validate @ready = true end # Return pretty string representation def to_s string = '<Data: ' case @data when String string += '"' + (@data.length > 16 ? @data.slice(0, 16) + '...' : @data) + '"' when Array slice = @data.length > 8 ? @data.slice(0, 8) : @data string += slice.collect{|e| '$' + e.to_s(16)}.join(',') string += '...' if slice.length != @data.length end if @mode != :default string += " (#{mode})" end string += '>' end # Return source code representation def to_source case @data when String case @mode when :default ".text \"#{@data}\"" when :screen ".screen \"#{@data}\"" end when Array case @mode when :default ".byte #{@data.collect{|e| '$' + e.to_s(16)}.join(',')}" when :word ".word #{@data.collect{|e| '$' + e.to_s(16)}.join(',')}" end when Symbol ".word #{@data}" end end # Turn the data into a byte array # Won't work if we haven't got all the necessary data yet. def to_a return [] unless @ready case @data when String case @mode when :default @data.each_codepoint.to_a.collect{|p| PETSCII[p]} when :screen @data.upcase.each_codepoint.to_a.collect{|p| CHAR_MAP[p]} end when Array case @mode when :default @data.dup when :word @data.collect{|e| [e.ls_byte, e.ms_byte]}.flatten end end end # Turn the operand into a byte string # Won't work if we haven't got all the necessary data yet. def to_binary return '' unless @ready to_a.pack('C*') rescue binding.pry end private # Validate data def validate case @data when String case @mode when :default @data.each_codepoint{|p| raise DataError, 'Invalid data' unless PETSCII.has_key? p} when :screen @data.upcase.each_codepoint{|p| raise DataError, 'Invalid data' unless CHAR_MAP.has_key? p} end when Array case @mode when :default @data.each{|e| raise DataError, 'Invalid data' unless (e >= 0 and e <= 255)} when :word @data.each{|e| raise DataError, 'Invalid data' unless (e >= 0 and e <= 65535)} end end true end # Validate modifier def check_mod if @mod.instance_of? Fixnum @mod = [:+, @mod] elsif @mod.instance_of? Array and @mod.length == 2 and [:/, :*, :<<, :>>, :& , :|].member? @mod.first raise DataError, 'Arithmetic argument has to be a fixnum' unless @mod[1].instance_of? Fixnum elsif [:<, :>].member? @mod @mod = [@mod == :< ? :ls_byte : :ms_byte] else raise DataError, 'Unknown modifier' end end end # Block error class BlockError < Error; end # Block is a raw machine code block # Implements the non-magic of linking, aka symbol resolution. class Block < Array attr_reader :labels, :linked # Create new block def initialize @labels = {} @linked = false @chunks = {} end # Link resolves symbols and relative jumps given the origin def link(origin = 0x1000) raise BlockError, 'Invalid origin' unless (origin >= 0 and origin <= 65535) # override origin if first non-Block element is an Align object felem = first while felem.class == Block felem = felem.first end if felem.instance_of? Align origin = felem.addr end endaddr = linker_pass(origin, :one) linker_pass(origin, :two) @linked end # Return source code representation def to_source (['.block'] + collect{|e| e.to_source} + ['.bend']).flatten end # Return pretty string representation def to_s; "<Block #{length}>"; end # Turn block into byte string def to_binary link unless @linked [@linked[0].ls_byte, @linked[0].ms_byte].pack('CC') + binary_pass end # Return verbose representation def dump link unless @linked lines = dump_pass lines.shift lines end # Write block to a given file in the given format # This will probably overwrite the target file without warning. def write!(fname, mode = 'w', what = :prg) File.open(fname, mode) do |fd| case what when :prg fd.write(to_binary) when :src fd.write(to_source.join("\n")) when :dump fd.write(dump.join("\n")) else raise BlockError, 'Unknown generation mode' end end end # Internal method, treat as private def dump_pass addr = @linked.first lines = [] lines.push('$%0.4x ' % addr + " \t.block") each do |e| line = ('$%0.4x ' % addr).upcase block = false case e when Data, Operand if e.mode == :r bytes = e.to_a.pack('Cc').unpack('C*') else bytes = e.to_a end bytes = bytes[0...3] if bytes.size > 3 line += bytes.to_a.collect{|e| '%0.2X' % e}.join(' ') line += ' ' * (9 - (3 * bytes.length)) line += " \t#{e.to_source}" addr += e.length when Align line += " \t#{e.to_source}" addr = e.addr when Label line += " #{e.to_source}" when Block addr, lines_passed = e.dump_pass lines += lines_passed block = true end lines.push(line) unless block end lines.push('$%0.4x ' % addr + " \t.bend") [addr, lines] end # Internal method, treat as private def binary_pass binary = '' each do |e| case e when Align binary += ([0] * (e.addr - @chunks[e.addr])).pack('C*') when Label true when Data, Operand binary += e.to_binary when Block binary += e.binary_pass end end binary end # Internal method, treat as private def linker_pass(addr, pass) @labels = {} if pass == :one origin = addr each do |e| case e when Align raise BlockError, "Invalid alignment from $#{addr.to_s(16)} to $#{e.addr.to_s(16)}" if e.addr < addr @chunks[e.addr] = addr if pass == :one addr = e.addr when Label if pass == :one if @labels.has_key? e.name C64Asm.log :warn, "Redefinition of label #{e.name} from $#{@labels[e.name].to_s(16)} to $#{addr.to_s(16)}" end @labels[e.name] = addr end when Data, Operand if pass == :two unless e.ready? if e.label == :* arg = addr elsif @labels.has_key? e.label arg = @labels[e.label] else C64Asm.log :error, "Can't resolve label #{e.label} for #{e.to_s}" raise BlockError end if e.mode == :r arg = arg - addr -2 end e.resolve(arg) end end addr += e.length when Block addr = e.linker_pass(addr, pass) else C64Asm.log :error, "Invalid element #{e.to_s} in Block" raise BlockError end end @linked = [origin, addr] if pass == :one addr end end # Macro error class MacroError < Error; end # Macro is the top-level building block class Macro attr_reader :variables # Create new macro # You can supply a hash of default variables that will be available within the block. def initialize(vars = {}, &blk) @variables = vars @procs = [] @procs.push(blk) if blk end # Add more code to a block def add_code(&blk); @procs.push(blk); end # Return pretty string representation def to_s; "<Macro #{@procs.length} #{@variables.to_s}>"; end # Return a block from the macro given variables def call(vars = {}) return Block.new if @procs.empty? @code = Block.new @labels = [] # check for extraneous variables extra = vars.keys - @variables.keys raise MacroError, "Extraneous variables #{extra.join(', ')}" unless extra.empty? # merge variable hash @vars = @variables.merge(vars) @procs.each{|b| instance_eval(&b)} @code end private # Add alignment nop def align(addr) begin @code.push(Align.new(addr)) rescue AlignError => e parse_error "Align instruction error: #{e.to_s}" end addr end # Add label nop def label(name) parse_warn "Redefinition of label #{name}" if @labels.member? name begin @code.push(Label.new(name)) rescue LabelError => e parse_error "Label instruction error: #{e.to_s}" end @labels.push(name) name end # Add data nop def data(arg, mod = false, mode = :default) begin data = Data.new(arg, mod, mode) @code.push(data) rescue DataError => e parse_error "Data instruction error: #{e.to_s}" end data.length end # Add block nop def block(stuff) parse_error 'Block not an instance of Block' unless stuff.instance_of? Block @code.push(stuff) stuff.length end # Add more code def insert(stuff) parse_error 'Block not an instance of Block' unless stuff.instance_of? Block @code += stuff stuff.length end # The DSL happens here def method_missing(name, *args, &blk) name = :and if name == :ane if OP_CODES.has_key? name begin if args.length == 0 op = Operand.new(name) else arg = args.first mod = args[1] or false op = Operand.new(name, arg, mod) end rescue OperandError => e parse_error "Operand error: #{e.to_s}" end @code.push(op) op elsif @vars.has_key? name @vars[name] else name.to_sym end end # General logging helper def say(level, msg) from = caller[2].match(/.*?\:\d+/)[0] C64Asm.log level, "(#{from}) #{msg}" end # Parse error logging helper def parse_error(msg) say :error, msg raise MacroError end # Parse error logging helper def parse_warn(msg); say :warn, msg; end end end
class AllPatientsService def initialize(params) @search = params[:search] end #get patients depending on whether a search is present def call if @search.blank? patients = Patient.limit(28) elsif @search.present? patients = Patient.search(@search) else end end end
module Quanta ###################################################################### # Usage ###################################################################### # datamap = { # ## Declare variables that can be used withing the map # _var_: { # "area_value": { # "sq-ft": "square-feet" # } # }, # # # ## Map carpet_area.value(using variable mapping) # carpet_area: { # value: { # "_var_": "area_value" # } # }, # # ## Map covered_area.value(using variable mapping) # covered_area: { # value: { # "_var_": "area_value" # } # }, # # ## Map age(using range mapping) # age: { # _r_: { # "..5": "Less than 5 years", # "5..10": "5 to 10 years", # "10..": "greater than 10 years" # }, # _wc_one_wc_: "Less than 5 years" # }, # ## Map city(using wild card, standard and default mapping) # city: { # Bangalore: 'Bengaluru', # Gurgaon: 'Gurugram', # # Default when `city` is nil # _d_: 'No City', # # Wild Card when `city` is like Delhi # _wc_Delhi_wc_: 'New Delhi' # } # } # # No Mapping # res = Quanta::HashMapped.new({ city: 'Noida' }, datamap) # res['city'] # Noida # # Standard Mapping # res = Quanta::HashMapped.new({ city: 'Bangalore' }, datamap) # res['city'] # Bengaluru # # Wild Card Mapping # res = Quanta::HashMapped.new({ city: 'South Delhi' }, datamap) # res['city'] # New Delhi # # Default Mapping # res = Quanta::HashMapped.new({}, datamap) # res['city'] # No City # # Range Mapping # res = Quanta::HashMapped.new({age: 1}, datamap) # res['age'] # Less than 5 years # # Variable Mapping # res = Quanta::HashMapped.new({carpet_area: {value: 'sq-ft'}}, datamap) # res['carpet_area']['value'] # square-feet ###################################################################### class HashMapped < HashWithIndifferentAccess KEYWORDS = { default: '_d_', wild_card: '_wc_', range: '_r_', var: '_var_' }.freeze VAR_SEPARATOR = '.' WILD_CARD_REGEX = '.{0,}'.freeze RANGE_SEPARATOR = '..'.freeze STRUCTURES = [Hash].freeze attr_accessor :hash, :mapped, :vars def initialize(hash, mapped, vars = nil) @hash = hash @mapped = (mapped || {}).with_indifferent_access @vars = (vars || @mapped[KEYWORDS[:var]]) || {} super(hash) end def [](key) val = super(key) if struct?(val) HashMapped.new(val, mapped[key], @vars) else val = val.to_s unless [true, false].include? val map = mapped[key] if map.present? apply(map, val) else val end end end private def apply(hash, key) hash_keys = hash.keys apply_standard(hash, hash_keys, key) || apply_variables(hash, hash_keys, key) || apply_range(hash, hash_keys, key) || apply_wildcard(hash, hash_keys, key) || apply_default(hash, hash_keys, key) end def apply_standard(hash, hash_keys, key) hash[key.to_s] if hash_keys.include? key.to_s end def apply_default(hash, hash_keys, key) return key if key.present? hash[KEYWORDS[:default]] if hash_keys.include? KEYWORDS[:default] end def apply_wildcard(hash, _hash_keys, key) kwc = KEYWORDS[:wild_card] found = nil hash.each do |k, _v| if k.include?(kwc) && (/#{k.gsub(kwc, WILD_CARD_REGEX)}/ =~ key).present? found = k break end end hash[found] if found end def apply_range(hash, _hash_keys, key) range = hash[KEYWORDS[:range]] return unless range key = key.to_f if key.to_s =~ /\d/ key_class = key.class res = nil range.each do |k, v| s = k.split('..') start = s[0] endd = s[1] next if start.blank? && endd.blank? start = start.to_f if start =~ /\d/ endd = endd.to_f if endd =~ /\d/ exp = if start.blank? && endd.is_a?(key_class) key <= endd elsif endd.blank? && start.is_a?(key_class) key >= start else start.is_a?(key_class) && endd.is_a?(key_class) && key >= start && key <= endd end if exp res = v break end end res end def apply_variables(hash, hash_keys, key) return unless hash_keys.include? KEYWORDS[:var] var_key = hash[KEYWORDS[:var]] vars[var_key][key] end def struct?(val) return false if val.nil? STRUCTURES.map { |s| val.is_a? s }.reduce(:|) end end end