text
stringlengths
10
2.61M
require 'rails_helper' RSpec.describe Invoice, :type => :model do it { should validate_presence_of :invoice_date } it { should belong_to :customer } it { should validate_presence_of :status } it { should have_many :invoice_lines } it { should have_many :applied_payments } it { should have_many(:payments).through(:applied_payments) } end
class Game < ApplicationRecord belongs_to :planet belongs_to :modifier end
module Backend::JsonWebTokenHelper def jwt_decode(token) begin JWT.decode token, ENV['jwt_secret'], ENV['jwt_algorithm'] rescue raise AuthError, "token失效" end end def jwt_user_id(token, auth_type = "admin") jwt_decode(token)[0][auth_type]["user_id"] end end
class CreateBusinesses < ActiveRecord::Migration[5.2] def change create_table :businesses do |t| t.string :name, null: false t.string :category, null: false t.float :lat, null: false t.float :lng, null: false t.string :website t.string :phonenumber t.string :address1, null: false t.string :address2, null: false t.timestamps end add_index :businesses, :name, unique: true # add_index :businesses, :ratings add_index :businesses, :category end end
class LogosController < ApplicationController def index @html_id = "page" @body_id = "products" @type = "logos" @title = "logos" @products = Logo.published.page(params[:page]).per(100) end def show @html_id = "page" @body_id = "products" @type = "logos" @product = Logo.find_by(slug: params[:slug]) @title = "logos : #{@product.name}" end end
require 'spec_helper' describe ValidTree do context "valid_tree use valid params" do let(:params) {{:volume=>2, :weight=>2, :proviso=>1}} case_params = {case_1:{:volume=>2, :weight=>2, :proviso=>1}, case_3:{:volume=>100, :weight=>1, :proviso=>1}, case_4:{:volume=>1, :weight=>1, :proviso=>1} } case_params.each_pair do |key, value| it "[#{key}] method valid should return validate params hash" do expect(ValidTree.new(value).valid).to eq(value) end end end context 'valid_tree use invalid params' do case_params = {case_1:{:volume=>2, :weight=>2, :proviso=>3}, case_2:{:volume=>0, :weight=>-1, :proviso=>0}, case_3:{:volume=>101, :weight=>4, :proviso=>5}, case_4:{:volume=>3, :weight=>-1, :proviso=>0} } case_params.each_pair do |key, value| it "[#{key}] method valid raise exception" do expect(ValidTree.new(value).valid).to raise_exception end end end end
class Crawler < ActiveRecord::Base has_many :log_entries, :class_name => 'CrawlerLog', :dependent => :destroy serialize :config validates_presence_of :name validates_presence_of :url def config_import=(string) self.config = YAML.load(string) end def config_import self.config.to_yaml unless self.config.blank? end def active? status == 'active' end def self.start Crawler.all.each { |crawler| crawler.start } end def stopped? self.log_entries.exists?(:status => :stopped) end # Starts crawling data with the crawler def start self.running = true # Reschedule started at to week forward self.start_at = self.start_at + 1.week if self.start_at && self.start_at < Time.now self.save! stopped_entries = self.log_entries.find_all_by_status(:stopped) if stopped_entries && stopped_entries.length > 0 stopped_entries.each { |entry| entry.update_attribute(:status, :pull) } else self.log_entries.create({ :url => url, :status => :pull, :config => config.to_options }) # Puller will do the rest end end def stop self.running = false ActiveRecord::Base.connection.execute("update crawler_logs set status = 'stopped' where crawler_id = #{self.id} and status != 'done';") self.save! end def reset self.stop ActiveRecord::Base.connection.execute("delete from crawler_logs where crawler_id = #{self.id}") end # Pulls the data from the web for all configured crawlers in the database def self.pull(params={}) Crawler.find(:all, :limit => params[:limit] ? params[:limit] : nil ).each do |crawler| crawler.pull(params) end end # Pushes data collected by 'pull' method for all configured crawlers to database def self.push(params={}) Crawler.find(:all, :limit => params[:limit] ? params[:limit] : nil ).each do |crawler| crawler.push(params) end end # Pulls the data from the web def pull(params={}) self.log_entries.where(:status => :pull).each do |entry| entry.pull sleep(params[:sleep]) if params[:sleep] end end # Pushes data collected with 'pull' method to the database def push(params={}) log_entries.where(:status => :push).each do |entry| entry.push sleep(params[:sleep]) if params[:sleep] end end end # == Schema Info # Schema version: 20110328181217 # # Table name: crawlers # # id :integer(4) not null, primary key # name :string(255) not null # url :string(255) not null # created_at :datetime # updated_at :datetime # status :string(255) # running :boolean(1) # config :text # category_id :integer(4) not null # started_at :datetime
class WelcomeController < ApplicationController layout 'index' def index @blogs = Blog.all end end
RSpec.feature "Organisation show page" do let(:partner_org_user) { create(:partner_organisation_user) } let(:beis_user) { create(:beis_user) } context "when signed in as a BEIS user" do context "when viewing the BEIS organisation" do before do authenticate!(user: beis_user) end after { logout } scenario "they see the organisation details" do visit organisation_path(beis_user.organisation) expect(page).to have_content beis_user.organisation.name expect(page).to have_content beis_user.organisation.iati_reference end scenario "they see a edit details button" do visit organisation_path(beis_user.organisation) expect(page).to have_link t("page_content.organisation.button.edit_details"), href: edit_organisation_path(beis_user.organisation) end scenario "the breadcrumbs have a link for organisations index" do visit organisation_path(beis_user.organisation) within ".govuk-breadcrumbs" do expect(page).to have_link "Organisations", href: organisations_path end end end end context "when signed in as a partner organisation user" do before do authenticate!(user: partner_org_user) end after { logout } scenario "they do not see the edit details button" do visit organisation_path(partner_org_user.organisation) expect(page).not_to have_link t("page_content.organisation.button.edit_details"), href: edit_organisation_path(partner_org_user.organisation) end end end
module SyntaxHighlighting class Theme # - parameter theme_data: Hash repesentation of a `sublime-color-scheme` # def initialize(theme_data) @name = theme_data["name"] @globals = ThemeGlobals.new(theme_data["globals"]) theme_data["rules"].each do |rule_data| rule = ThemeRule.new(rule_data) rules << rule rule.scopes.each do |scope| scopes[scope] ||= [] scopes[scope] << rule end end end attr_reader :name attr_reader :globals def rules @rules ||= [] end def scopes @scopes ||= {} end end end
And(/^I fill in the dispute form with valid data for all the questions for the selected reason 'I have not been credited for merchandise I returned'$/) do on(DisputesPage).dispute_reason_questions_date('i_have_not_been_credited_for_merchandise_i_returned_default_data_response', []) end Given(/^I logged and selected a valid transaction row "([^"]*)" to dispute a charge$/) do |arg| visit(LoginPage) sleep(5) on(LoginPage) do |page| login_data = page.data_for(:disputes_linked_account) #dispute_single_DNR_charge dispute_single_disputable_ods username = login_data['username'] password = login_data['password'] ssoid = login_data['ssoid'] puts ssoid page.login(username, password, ssoid) end @authenticated = on(DisputesPage).is_summary_shown? if @authenticated[0] == false fail("#{@authenticated[1]}" "--" "#{@authenticated[2]}") end visit(TransactionsDetailsPage) on(DisputesPage) do |page| page.search_for_valid_disputable_txn_iteratively @matching_transaction_id, @txn_details = page.click_disputes_link_when_present end end
Dado("que eu tenho uma tarefa com os seguintes atributos:") do |table| @nova_tarefa = table.rows_hash DAO.new.remover_tarefas(@nova_tarefa[:nome]) end Dado("eu quero taguear essa tarefa com:") do |tags| @tags = tags.hashes end Dado("eu já cadastrei essa tarefa e não tinha percebido") do steps %( Quando faço o cadastro dessa tarefa ) end Quando("faço o cadastro dessa tarefa") do visit '/tasks' @tarefas_page.botao_novo.click @tarefas_page.adicionar.cadastrar(@nova_tarefa, @tags) end Então("devo ver esta tarefa com o status {string}") do |status_tarefa| tarefa = @tarefas_page.item(@nova_tarefa[:nome]) expect(tarefa).to have_content status_tarefa end Então("devo ver somente {int} tarefa com o nome cadastrado") do |quantidade| visit '/tasks' # busca pela tarefa que foi cadastrada, o resultado deve ser igual a 1 @tarefas_page.busca(@nova_tarefa[:nome]) expect(@tarefas_page.itens.size).to eql quantidade end Então("devo ver a mensagem {string} ao tentar cadastrar") do |mensagem| expect(@tarefas_page.adicionar.alerta.text).to eql mensagem end
=begin in this project you will be creating a program that tells people what grade they will need on a test to get a particular overall grade in the class. Look at the pseudocode below as an example of how the the UI is and how the calculation works =end =begin desiredpoints = .9 x total + testworth pointsontest= desiredpoints - earnedpoints gradeontest= earnedpoints /testworth =end #Example 1 #My current overall grade is 80/100 # my next test is worth 20 points # I want to know what grade I will need on the test in order to keep a C in the class # I know that the overall points in the class will be 120 # and that 120*.7 is 84 so I will need a 4/20, or 20% on the next test to maintain a 70% in the class. #Example 2 # my current grade is 45/50, a 90% # I want to know how to move to a 95% if my next test is worth 25 points # I know that my overall grade will be out of 75 points, and .95 of 75 is 71.25 # so the person will need 71.25-45=26.5 points on the next test or 106% to get a 95% puts "What is your grade in this class out of 100, in decimal format? (50% = .50)" #asks the user this question overallpercent = gets.to_f #takes information the user enters and stores it overallpercent = overallpercent*100 #transforms the grade from decimal format to a percentage puts "What are the total number of points in your class?" #asks the user this question totalpoints = gets.to_f #takes information the user enters and stores it gradepoints = totalpoints*overallpercent #takes your grade out of a 100, and multiplys it by the number of points in the class. so if you have a 90 in a class(out of a 100 points), but the class has 200 points, the computer needs to multiply the the total points(200) by the overall percent(.9). This shows that you have 180/200 points in the class. puts "How many points is the test you took worth?" #asks the user this question testpoints = gets.to_f #takes information the user enters and stores it puts "What overall grade do you want in this class as a percent?" #asks the user this question goalgrade = gets.to_f #takes information the user and stores it new_class_total = testpoints + totalpoints #the new_class_total equals the worth of the test you took (testpoints) and the total points within your class (totalpoints) added together goalgrade = goalgrade / 100 * new_class_total #goalgrade(what grade you want in the class) is equal to goalgrade times 100. This makes the decimal into a percent, and then the computer takes this percent and multiplys it by the new_class_total. This number will equal the amount of points that your total grade will need to equal for you to reach the goal grade. goalgrade= (goalgrade - gradepoints) /testpoints # goalgrade equals your goalgrade minus the gradepoints you already have, to get the difference between the two sets of points. When the computer gets that number, it will divide it by the number of points on the test, to get the percent you will need to get your "goalgrade" puts "The grade you need on this test is #{goalgrade}" #prints the percent you will need to get on this grade to reach goalgrade.
require File.expand_path('../test_helper', __FILE__) class SourcesTest < Test::Unit::TestCase def setup setup_stubs end test "update_all given a named source argument updates the identity from that source" do identity = Identity.new Identity::Sources['twitter'].expects(:update).with(identity, 'svenfuchs') Identity::Sources.update_all(identity, ['twitter:svenfuchs']) end test "update_all given a url argument updates the identity from that source" do identity = Identity.new Identity::Sources['twitter'].expects(:update).with(identity, 'svenfuchs') Identity::Sources.update_all(identity, ['http://twitter.com/svenfuchs']) end test "updating an identity from twitter polls profile data from twitter" do identity = Identity.new Identity::Sources['twitter'].update(identity, 'svenfuchs') assert_equal profile('twitter', 'svenfuchs'), identity.twitter end test "updating an identity from github polls profile data from github" do identity = Identity.new Identity::Sources['github'].update(identity, 'svenfuchs') assert_equal profile('github', 'svenfuchs'), identity.github end test "updating an identity from json polls profile data from a json file AND updates all other profiles" do identity = Identity.new Identity::Sources['json'].update(identity, 'http://tinyurl.com/yc7t8bv') assert_equal profile('json', 'svenfuchs'), identity.json assert_equal profile('github', 'svenphoox'), identity.github assert_equal profile('twitter', 'svenfuchs'), identity.twitter end end
#!/usr/bin/env ruby require 'net/http' require 'net/https' require 'net/ping' require 'uri' require 'filecache' require 'colorize' require 'mongo' def build_url(environment, role, cronMaster) url_string = "https://<PUPPET_MASTER_IPADDRESS>:8140/production/facts_search/search?facts.env=#{environment}" url_string += "&facts.role=#{role}" if role url_string += "&facts.is_cronMaster=true" if cronMaster URI.parse(url_string) end def http_get(url) begin http = Net::HTTP.new(url.host, url.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE http.get(url.request_uri) rescue => e puts e.inspect end end def clean_host(host) host.gsub(/["\[\]]/, '') end def parse_hosts_list(hosts_list) hosts_list.split(',').map { |h| clean_host(h) } end def alive?(host) Net::Ping::TCP.new(host, 22, 5).ping? end def is_cronMaster?(host) if host.include?('ws-') and ARGV[0].match(/^(prod|pro|pr|production|p)/) cronMaster_response = http_get(URI.parse("https://<PUPPET_MASTER_IPADDRESS>:8140/production/facts_search/search?facts.is_cronMaster=true&facts.fqdn=#{host}")) if cronMaster_response.body.include?(host) return true else return false end end return false end def is_master?(host) if host.include?('-mongodb-') host = host port = '27017' client = Mongo::MongoClient.new(host, port) isMaster = client.check_is_master([host, port]).to_a[1][1] if isMaster return true else return false end end end def set_or_get_from_cache(host) cache = FileCache.new("server_list", "/tmp/server_list", 28800) if cache.get(host) fqdn = cache.get(host) else puts " not in cache, saving and getting:".colorize(:light_red) if is_cronMaster?(host) cache.set(host,"[cronMaster] #{host}".colorize(:light_green)) if alive?(host) fqdn = cache.get(host) elsif is_master?(host) cache.set(host,"[MASTER] #{host}".colorize(:yellow)) if alive?(host) fqdn = cache.get(host) else cache.set(host,host) if alive?(host) fqdn = cache.get(host) end end return fqdn end if ARGV.length < 1 puts "Parameters error : Usage is : #{$0} environment (role)" exit 1 end environment = ARGV[0] role = ARGV[1] cronMaster = ARGV[2] if ARGV[0].match(/^(prod|pro|pr|production|p)/) environment = 'production' end url = build_url(environment, role, cronMaster) resp = http_get(url) hosts_list = parse_hosts_list(resp.body) hosts_list.each { |host| puts set_or_get_from_cache(host).bold }
require "optparse" module Sensu module Translator class CLI # Parse CLI arguments using Ruby stdlib `optparse`. This method # provides Sensu Translator with process options (eg. config # directory), and can provide users with information, such as the # Translator version. # # @param arguments [Array] to parse. # @return [Hash] options def self.read(arguments=ARGV) options = { :output_dir => "/tmp/sensu_v2", :organization => "default", :environment => "default" } if File.exist?("/etc/sensu/config.json") options[:config_file] = "/etc/sensu/config.json" end if Dir.exist?("/etc/sensu/conf.d") options[:config_dirs] = ["/etc/sensu/conf.d"] end optparse = OptionParser.new do |opts| opts.on("-h", "--help", "Display this message") do puts opts exit end opts.on("-V", "--version", "Display version") do puts Sensu::Translator::VERSION exit end opts.on("-c", "--config FILE", "Sensu 1.x JSON config FILE. Default: /etc/sensu/config.json (if exists)") do |file| options[:config_file] = file end opts.on("-d", "--config_dir DIR[,DIR]", "DIR or comma-delimited DIR list for Sensu 1.x JSON config files. Default: /etc/sensu/conf.d (if exists)") do |dir| options[:config_dirs] = dir.split(",") end opts.on("-o", "--output_dir DIR", "Sensu 2.0 config output DIR. Default: /tmp/sensu_v2") do |dir| options[:output_dir] = dir end opts.on("-O", "--organization ORG", "Sensu 2.0 RBAC Organization. Default: default") do |org| options[:organization] = org end opts.on("-E", "--environment ENV", "Sensu 2.0 RBAC Environment. Default: default") do |env| options[:environment] = env end end optparse.parse!(arguments) options end end end end
# @param {Integer} n # @return {Integer} def arrange_coins(n) balance_coins = n k = 1 until(balance_coins < k) balance_coins -= k k += 1 end return k - 1 end
class Idea < ActiveRecord::Base belongs_to:platform has_many :users, through: :ideas_users has_many :ideas_users, through: :ideas_users validates :name, :description, :help_needed, :platform_id, presence: true # validates :designer, :developer, default: 0 # :ascending, -> { order(ideas.created_at ASC) } scope :ascending, -> {order('name ASC')} scope :descending, -> {order('name DESC')} end
require "rails_helper" RSpec.describe BsnlDeliveryDetail, type: :model do describe "Associations" do it { is_expected.to have_one(:communication) } end describe ".in_progress" do it "returns deliverables which are in progress" do in_progress_status_codes = %w[0 2 3 5] in_progress_details = in_progress_status_codes.map do |status_code| create(:bsnl_delivery_detail, message_status: status_code) end delivered_detail = create(:bsnl_delivery_detail, message_status: "7") expect(described_class.in_progress).to match_array(in_progress_details) expect(described_class.in_progress).not_to include(delivered_detail) end it "returns deliverables if they don't have a message status set" do detail = create(:bsnl_delivery_detail, message_status: nil) delivered_detail = create(:bsnl_delivery_detail, message_status: "7") expect(described_class.in_progress).to include(detail) expect(described_class.in_progress).not_to include(delivered_detail) end end describe ".create_with_communication!" do it "creates a communication with a BsnlDeliveryDetail" do phone_number = Faker::PhoneNumber.phone_number communication = described_class.create_with_communication!( message_id: "1000123", recipient_number: phone_number, dlt_template_id: "12398127312492" ).tap do |c| c.detailable.result = "Sent" end expect(communication.detailable.recipient_number).to eq phone_number expect(communication.detailable.result).to eq "Sent" end end describe "#in_progress?" do it "returns true if the notification is in the process of being delivered" do new_detail = create(:bsnl_delivery_detail, message_status: nil) created_detail = create(:bsnl_delivery_detail, message_status: "0") input_error_detail = create(:bsnl_delivery_detail, message_status: "1") inserted_in_queue_detail = create(:bsnl_delivery_detail, message_status: "2") submitted_to_smsc_detail = create(:bsnl_delivery_detail, message_status: "3") rejected_by_smsc_detail = create(:bsnl_delivery_detail, message_status: "4") accepted_by_carrier_detail = create(:bsnl_delivery_detail, message_status: "5") delivery_failed_detail = create(:bsnl_delivery_detail, message_status: "6") delivered_detail = create(:bsnl_delivery_detail, message_status: "7") expect(new_detail.in_progress?).to be_truthy expect(created_detail.in_progress?).to be_truthy expect(input_error_detail.in_progress?).not_to be_truthy expect(inserted_in_queue_detail.in_progress?).to be_truthy expect(submitted_to_smsc_detail.in_progress?).to be_truthy expect(rejected_by_smsc_detail.in_progress?).not_to be_truthy expect(accepted_by_carrier_detail.in_progress?).to be_truthy expect(delivery_failed_detail.in_progress?).not_to be_truthy expect(delivered_detail.in_progress?).not_to be_truthy end end describe "#unsuccessful?" do it "returns true if the notification could not be delivered" do new_detail = create(:bsnl_delivery_detail, message_status: nil) created_detail = create(:bsnl_delivery_detail, message_status: "0") input_error_detail = create(:bsnl_delivery_detail, message_status: "1") inserted_in_queue_detail = create(:bsnl_delivery_detail, message_status: "2") submitted_to_smsc_detail = create(:bsnl_delivery_detail, message_status: "3") rejected_by_smsc_detail = create(:bsnl_delivery_detail, message_status: "4") accepted_by_carrier_detail = create(:bsnl_delivery_detail, message_status: "5") delivery_failed_detail = create(:bsnl_delivery_detail, message_status: "6") delivered_detail = create(:bsnl_delivery_detail, message_status: "7") expect(new_detail.unsuccessful?).not_to be_truthy expect(created_detail.unsuccessful?).not_to be_truthy expect(input_error_detail.unsuccessful?).to be_truthy expect(inserted_in_queue_detail.unsuccessful?).not_to be_truthy expect(submitted_to_smsc_detail.unsuccessful?).not_to be_truthy expect(rejected_by_smsc_detail.unsuccessful?).to be_truthy expect(accepted_by_carrier_detail.unsuccessful?).not_to be_truthy expect(delivery_failed_detail.unsuccessful?).to be_truthy expect(delivered_detail.unsuccessful?).not_to be_truthy end end describe "#successful?" do it "returns true if the notification was delivered successfully" do new_detail = create(:bsnl_delivery_detail, message_status: nil) created_detail = create(:bsnl_delivery_detail, message_status: "0") input_error_detail = create(:bsnl_delivery_detail, message_status: "1") inserted_in_queue_detail = create(:bsnl_delivery_detail, message_status: "2") submitted_to_smsc_detail = create(:bsnl_delivery_detail, message_status: "3") rejected_by_smsc_detail = create(:bsnl_delivery_detail, message_status: "4") accepted_by_carrier_detail = create(:bsnl_delivery_detail, message_status: "5") delivery_failed_detail = create(:bsnl_delivery_detail, message_status: "6") delivered_detail = create(:bsnl_delivery_detail, message_status: "7") expect(new_detail.successful?).not_to be_truthy expect(created_detail.successful?).not_to be_truthy expect(input_error_detail.successful?).not_to be_truthy expect(inserted_in_queue_detail.successful?).not_to be_truthy expect(submitted_to_smsc_detail.successful?).not_to be_truthy expect(rejected_by_smsc_detail.successful?).not_to be_truthy expect(accepted_by_carrier_detail.successful?).not_to be_truthy expect(delivery_failed_detail.successful?).not_to be_truthy expect(delivered_detail.successful?).to be_truthy end end end
require 'test_helper' class UserCreditsTest < ActiveSupport::TestCase test "user_credits" do users = User.all rows = SqlQuery.new(:user_credits, user_ids: users.map(&:id)).execute balances = Hash[rows.map {|r| [r["user_id"], r["credit_balance"]]} ] assert_equal users.size, rows.size, "same number of users as rows" assert_equal users.size, balances.size, "same number of users as balances" assert_equal 23, balances[users(:kyle).id] assert_equal 12, balances[users(:adrian).id] assert_equal 1, balances[users(:jess).id] assert_equal 0, balances[users(:ljf).id] end end
module Android module PinCodePage class << self include BasePage FIELD_PIN_CODE = { id: PACKAGE + ':id/pin_code' } KEY_ACTION = { id: PACKAGE + ':id/key_action' } def type_pin_code(pin_code, custom = false) clear_pin_field(FIELD_PIN_CODE) enter(pin_code, FIELD_PIN_CODE, custom) end def login(pin_code, custom = false) type_pin_code(pin_code, custom) unless pin_code.nil? click_login end def click_login click(KEY_ACTION) end def on_page? present? KEY_ACTION end def clear_pin_field(locator, chars = 6) click(locator) chars.times { press_keycode 22 } chars.times { press_keycode 67 } end end end def pin_code_page PinCodePage end end
class SoftkeysController < ApplicationController load_and_authorize_resource :sip_account, :except => [:sort] load_and_authorize_resource :softkey, :through => [:sip_account], :except => [:sort] before_filter :set_available_softkey_functions, :only => [ :new, :edit, :update, :create ] before_filter :spread_breadcrumbs, :except => [:sort] def index end def show end def new @softkey = @sip_account.softkeys.build end def create @softkey = @sip_account.softkeys.build(params[:softkey]) if @softkey.save redirect_to sip_account_softkey_path(@softkey.sip_account, @softkey), :notice => t('softkeys.controller.successfuly_created') else render :new end end def edit end def update if @softkey.update_attributes(params[:softkey]) redirect_to sip_account_softkey_path(@softkey.sip_account, @softkey), :notice => t('softkeys.controller.successfuly_updated') else render :edit end end def destroy @softkey.destroy redirect_to sip_account_softkeys_path(@softkey.sip_account), :notice => t('softkeys.controller.successfuly_destroyed') end def sort sip_account = Softkey.find(params[:softkey].first).sip_account params[:softkey].each do |softkey_id| sip_account.softkeys.find(softkey_id).move_to_bottom end render nothing: true end private def set_available_softkey_functions @possible_call_forwards = @softkey.possible_call_forwards @softkey_functions = [] SoftkeyFunction.accessible_by(current_ability, :read).each do |softkey_function| if GuiFunction.display?("softkey_function_#{softkey_function.name.downcase}_field_in_softkey_form", current_user) if softkey_function.name != 'call_forwarding' or @possible_call_forwards.count > 0 @softkey_functions << softkey_function end end end end def spread_breadcrumbs if @sip_account.sip_accountable.class == User add_breadcrumb t('users.name'), tenant_users_path(@sip_account.sip_accountable.current_tenant) add_breadcrumb @sip_account.sip_accountable, tenant_user_path(@sip_account.sip_accountable.current_tenant, @sip_account.sip_accountable) add_breadcrumb t('sip_accounts.index.page_title'), user_sip_accounts_path(@sip_account.sip_accountable) add_breadcrumb @sip_account, user_sip_account_path(@sip_account.sip_accountable, @sip_account) add_breadcrumb t('softkeys.index.page_title'), sip_account_softkeys_path(@sip_account) elsif @sip_account.sip_accountable.class == Tenant add_breadcrumb t('sip_accounts.index.page_title'), tenant_sip_accounts_path(@sip_account.sip_accountable) add_breadcrumb @sip_account, tenant_sip_account_path(@sip_account.sip_accountable, @sip_account) add_breadcrumb t('softkeys.index.page_title'), sip_account_softkeys_path(@sip_account) end end end
class AddAssetProcessingToStructureImages < ActiveRecord::Migration def up add_column :structure_images, :asset_processing, :boolean end def down remove_column :structure_images, :asset_processing end end
# encoding:utf-8 module Spree class PaymentMethod::BoletoMethod < PaymentMethod FORMATS={ 'pdf' => 'application/pdf', 'jpg' => 'image/jpg', 'tif' => 'image/tiff', 'png' => 'image/png' } def payment_source_class BoletoDoc end end end
class TeamSprintsController < ApplicationController unloadable def index @team_sprints = Team.find(params[:team_id]).team_sprints respond_to do |format| format.html { render(:template => 'team_sprints/index', :layout => !request.xhr?) } format.api { } end end def new @team = Team.find(params[:team_id]) @team_sprint = TeamSprint.new end def show @team_sprint = TeamSprint.find(params[:id]) @issues = @team_sprint.issues end def create @team_sprint = TeamSprint.new @team_sprint.safe_attributes = params[:team_sprint] @team_sprint.team = Team.find(params[:team_id]) if @team_sprint.save respond_to do |format| format.html do flash[:notice] = l(:notice_successful_create) if params[:continue] redirect_to new_team_team_sprint_path(@team) else redirect_to team_team_sprint_path(:team_id => @team_sprint.team.id, :id => @team_sprint.id) end end format.api { render :action => 'show', :status => :created, :location => url_for(:controller => 'team_sprints', :action => 'show', :team_id => @team_sprint.team, :id => @team_sprint.id) } end else respond_to do |format| format.html { render :action => 'new' } format.api { render_validation_errors(@team_sprint) } end end end def issues @issues = TeamSprint.find(params[:id]).issues @query = Query.new end end
#!/usr/bin/env ruby require 'json' require 'open-uri' require 'aws-sdk' raise 'you must specify an HTTPS URL!' if ARGV.length < 1 or !ARGV[0].match(/^https:\/\//) keys_url = ARGV[0] raise 'you must specify a bucket!' if ARGV.length < 2 s3_bucket = ARGV[1] raise 'you must specify an s3 key!' if ARGV.length < 3 s3_key = ARGV[2] s3 = Aws::S3::Client.new(region: ENV['AWS_REGION'] || 'us-east-1') while true do keys = [] open(ARGV[0]).read.split(/\s+/).delete_if{|u|u.match(/\W/)}.sort.uniq.each do |user| puts user open("https://api.github.com/users/#{user}/keys?access_token=#{ENV['GITHUB_TOKEN']}", "User-Agent" => "newsdev/github-keys") do |f| JSON.parse(f.read).each_with_index do |key, i| keys << key['key'] end end sleep 2 end obj ={ bucket: s3_bucket, body: keys.join("\n"), key: s3_key, server_side_encryption: 'AES256', content_type: 'text/plain' } s3.put_object(obj) puts '✓' sleep(10) end
module Twirloc module Algorithms module KMeans class Cluster attr_reader :data_points, :centroid def initialize(options) options = defaults.merge(options) @data_points = Set.new(options[:data_points]) @centroid = options[:centroid] end def recompute_centroid! coords = data_points.collect { |p| p.to_coordinates } lat, lng = MidpointCalculator.calculate(coords) @centroid = DataPoint.new(latitude: lat, longitude: lng) end def add_datapoint(data_point) data_points.add(data_point) end def clear! data_points.clear end def ==(other_object) @data_points == other_object.data_points end private def defaults { data_points: Set.new } end end end end end
class Article < ActiveRecord::Base include GenerateUrlName belongs_to :user, :counter_cache => true has_many :uploads, :as => :uploadable has_many :photos, :as => :uploadable, :dependent => :destroy has_many :documents, :as => :uploadable, :dependent => :destroy has_many :comments, :as => :commentable has_many :snippets, :as => :snippetable validates_uniqueness_of :title validates_presence_of :title, :body, :crest before_create :create_name before_update :create_name accepts_nested_attributes_for :photos, :reject_if => lambda { |a| a[:description].blank? }, :allow_destroy => true accepts_nested_attributes_for :documents, :reject_if => lambda { |a| a[:description].blank? }, :allow_destroy => true named_scope :blogs, :conditions => { :is_post => true } named_scope :news, :conditions => { :is_news => true } named_scope :reviews, :conditions => { :is_review => true } named_scope :latest, lambda { |limit| { :limit => limit, :order => "created_at DESC" } } end
module ApplicationHelper def resource_name :user end def resource @resource ||= User.new end def devise_mapping @devise_mapping ||= Devise.mappings[:user] end def sortable(column, args = {}) args[:title] ||= column.titleize css_class = column == sort_column ? "sorting #{sort_direction}" : 'sorting' html_options = args[:html_options] ? args[:html_options] : {} html_options[:class] = html_options[:class] ? html_options[:class] + ' ' + css_class : css_class direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc" content_tag :td, (link_to args[:title], params.merge(:sort => column, :direction => direction, :page => nil)), html_options end def alert_type(name) case name when :alert "alert-danger" when :notice "alert-info" else "alert-success" end end end
class Commentary < ApplicationRecord belongs_to :user belongs_to :post validates :body, length: { maximum: 8000, minimum: 1 } end
class Inventory def initialize(products = Hash.new) @products = products end def add(product) prod = @products[product.id] if prod.nil? @products[product.id] = product else prod.quantity += 1 end end def remove(product) prod = @products[product.id] unless prod.nil? prod.quantity -= 1 if prod.quantity < 0 @products.delete(product.id) end end end def products @products end def value @products.values.map(&:value).reduce(:+) end end
require 'rspec' require_relative '../lib/activesupport/cache/elasticsearch_store' index_name = "cache_test_#{Process.pid}" describe ActiveSupport::Cache::ElasticsearchStore do describe ".new" do before do allow_any_instance_of(Elasticsearch::Client).to receive(:create_index) end it "should pass the addresses and some options straight through to ES::Client" do es_opts = { retry_on_failure: true, randomize_hosts: true, reload_connections: true } expect(Elasticsearch::Client).to receive(:new).with(es_opts.merge(addresses: %w(a b))) ActiveSupport::Cache::ElasticsearchStore.new('a', 'b', es_opts) end it "should default to localhost:9200" do expect(Elasticsearch::Client).to receive(:new).with(addresses: %w(localhost:9200)) ActiveSupport::Cache::ElasticsearchStore.new end it "should error if we try to pass in a namespace" do expect { ActiveSupport::Cache::ElasticsearchStore.new(namespace: 'derp') }.to raise_error ArgumentError end end context "with an active store" do let(:store) { ActiveSupport::Cache::ElasticsearchStore.new(index_name: index_name) } after do # rubocop:disable Style/RescueModifier Elasticsearch::Client.new.indices.delete index: index_name end it "should store and retrive a cache entry" do expect(store.read("hello")).to be_nil store.write("hello", "sup") expect(store.read("hello")).to eq("sup") end it "should expire cache entries" do store.write("hi", "there", expires_in: 0.5) expect(store.read("hi")).to eq("there") sleep 1 expect(store.read("hi")).to be_nil end it "should allow clearing the entire cache" do store.write("hello", "there") store.write("good", "bye") store.clear expect(store.read('hello')).to be_nil expect(store.read('good')).to be_nil end end end
describe "RankingValue" do it "should create a valid Ranking Value" do expect { FactoryGirl.create(:ranking_value) }.to change(RankingValue, :count).by(1) end it "should not create a Ranking Value with a position already taken" do ranking = FactoryGirl.create(:ranking) value = FactoryGirl.create(:ranking_value, :ranking => ranking) expect { FactoryGirl.create(:ranking_value, :ranking => ranking, :position => value.position) }.to raise_error(ActiveRecord::RecordInvalid) end it "should not create a Ranking Value without all the mandatory fields" do [:ranking, :position, :value, :ranked_object].each do |field| expect { FactoryGirl.create(:ranking_value, field => nil) }.to raise_error(ActiveRecord::RecordInvalid) end end it "should return true if Ranking Values scoped by Ranking are returned from query" do rank_a = FactoryGirl.create(:ranking_value).ranking 5.times { FactoryGirl.create(:ranking_value, :ranking => rank_a) } # All the records created are from ranking rank_a expect(RankingValue.for_ranking(rank_a)).to eq RankingValue.where(:ranking_id => rank_a.id) 5.times { FactoryGirl.create(:ranking_value) } # Now some of the records doesn't belongs to rank_a expect(RankingValue.for_ranking(rank_a)).to_not eq RankingValue.scoped end end
class ReviewsController < ApplicationController before_action :authenticate_user! load_and_authorize_resource #invoke ability class def create @review = Review.new(review_params) @review.user_id = current_user.id respond_to do |format| if @review.save format.js format.html{redirect_to product_path(@review.product_id), notice: "Thank you for adding a review. "} else format.js end end end def destroy @review = Review.find(params[:id]) @review.destroy #redirect_to product_path(@review.product_id), notice: "You have successfully deleted the review" end private def review_params params[:review].permit(:body, :rating, :product_id, :user_id) end end
class FixityCheckResult < ApplicationRecord belongs_to :cfs_file enum status: {ok: 0, bad: 1, not_found: 2} end
require_relative '00_attr_accessor_object.rb' class MassObject < AttrAccessorObject def self.attributes if self == MassObject raise "must not call #attributes on MassObject directly" else @attributes ||= [] end end def initialize(params = {}) params.each do |k, v| self.send("#{k}=", v) end end end
name 'bender_is_great' maintainer 'Patrick Dayton' maintainer_email 'patrick@docnetwork.org' license 'All Rights Reserved' description 'Installs/Configures bender_is_great' long_description 'Installs/Configures bender_is_great' version '0.1.0' chef_version '>= 12.1' if respond_to?(:chef_version) supports 'ubuntu', '>= 12.04' supports 'centos', '>= 7.1 ' # The `issues_url` points to the location where issues for this cookbook are # tracked. A `View Issues` link will be displayed on this cookbook's page when # uploaded to a Supermarket. # issues_url 'https://github.com/daytonpa/bender_is_great/issues' # The `source_url` points to the development reposiory for this cookbook. A # `View Source` link will be displayed on this cookbook's page when uploaded to # a Supermarket. # source_url 'https://github.com/daytonpa/bender_is_great' depends 'apt' depends 'yum'
class Notice < ActiveRecord::Base has_many :user_notices, class_name: :"User::Notice", dependent: :destroy attr_accessible :body, :subject, :start_at, :end_at, :url, as: :admin scope :active, -> { where("start_at <= :time and end_at >= :time", time: Time.zone.now) } def deliver user_notices.without_deliver_state(:delivered).each &:deliver! end def start_at=(date) if date.is_a?(String) self[:start_at] = Time.parse(date) else self[:start_at] = date end end def start_at self[:start_at] ? self[:start_at].to_date.to_s : nil end def end_at=(date) if date.is_a?(String) self[:end_at] = Time.parse(date) else self[:end_at] = date end end def end_at self[:end_at] ? self[:end_at].to_date.to_s : nil end def percentage total = user_notices.count viewed = user_notices.with_state(:viewed).count if total > 0 ((viewed.to_f / total) * 100).round else 0 end end def active? now = Time.zone.now now >= start_at && now <= end_at end def remove_users user_notices.destroy_all end def add_users(ids) ids.each do |id| user_notices.where(user_id: id).first_or_create! end end end
# test git add . require_relative 'bike' class DockingStation DEFAULT_CAPACITY = 20 attr_reader :bikes def initialize(capacity=DEFAULT_CAPACITY) @bikes = [] @capacity = capacity end D # private def full? @bikes.count >= @capacity ? true : false end def empty? @bike.count == O ? true : false end end # docking_station = DockingStation.new # p bmx = bike.release_bike.working?
require 'spec_helper' require 'log_monitor' describe "Monitoring incoming logs" do def write_known_good(lines) write_lines("#{$tempdir}/output/known_good_urls", lines) end def write_log(entries, backend="origin", method="GET") write_lines("#{$tempdir}/log", entries.map { |url_and_status| %{1.1.1.1 "-" "-" Fri, 29 Aug 2015 05:57:21 GMT #{method} #{url_and_status} #{backend}} }) end def expect_statsd_increments(monitor, items) statsd_sender_double = instance_double("StatsdSender") items.each do |item| expect(statsd_sender_double).to receive(:increment).once.with(item) end allow(monitor).to receive(:statsd_sender).and_return(statsd_sender_double) end it "Handles a known_good file without dates" do # Handle dates missing from the known_good file for a smooth transition to # adding them. Can remove this support after deploy and regneration of the # file. write_known_good(["/a-url"]) write_log(["/a-url 500"]) monitor = LogMonitor.new($tempdir) expect_statsd_increments(monitor, [ "status.500", "cdn_backend.origin", "known_good_fail.status_500", ]) record_stderr record_stdout monitor.monitor(File.open("#{$tempdir}/log")) expect(recorded_stderr).to match("Working with 1 known good urls") expect(recorded_stdout).to eq( %{{"@fields":{"method":"GET","path":"/a-url","query_string":null,"status":500,"remote_addr":"1.1.1.1","request":"GET /a-url","cdn_backend":"origin","last_success":"2014-01-01T00:00:00+00:00"},"@tags":["known_good_fail"],"@timestamp":"2015-08-29T05:57:21+00:00","@version":"1"}\n} ) end it "Sends output about successful accesses to known urls" do write_known_good(["/a-url 20150801"]) write_log(["/a-url 200"]) monitor = LogMonitor.new($tempdir) expect_statsd_increments(monitor, [ "status.200", "cdn_backend.origin", ]) record_stderr record_stdout monitor.monitor(File.open("#{$tempdir}/log")) expect(recorded_stderr).to match("Working with 1 known good urls") expect(recorded_stdout).to eq("") end it "Sends output about unsuccessful GET accesses to known urls" do write_known_good(["/a-url 20150801"]) write_log(["/a-url 500"]) monitor = LogMonitor.new($tempdir) expect_statsd_increments(monitor, [ "status.500", "cdn_backend.origin", "known_good_fail.status_500", ]) record_stderr record_stdout monitor.monitor(File.open("#{$tempdir}/log")) expect(recorded_stderr).to match("Working with 1 known good urls") expect(recorded_stdout).to eq( %{{"@fields":{"method":"GET","path":"/a-url","query_string":null,"status":500,"remote_addr":"1.1.1.1","request":"GET /a-url","cdn_backend":"origin","last_success":"2015-08-01T00:00:00+00:00"},"@tags":["known_good_fail"],"@timestamp":"2015-08-29T05:57:21+00:00","@version":"1"}\n} ) end it "Doesn't send output about unsuccessful POST accesses to known urls" do write_known_good(["/a-url 20150801"]) write_log(["/a-url 500"], "origin", "POST") monitor = LogMonitor.new($tempdir) expect_statsd_increments(monitor, [ "status.500", "cdn_backend.origin", ]) record_stderr record_stdout monitor.monitor(File.open("#{$tempdir}/log")) expect(recorded_stderr).to match("Working with 1 known good urls") expect(recorded_stdout).to eq("") end it "Sends output about successful accesses to unknown urls" do write_known_good(["/a-url 20150801"]) write_log(["/an-unknown-url 200"]) monitor = LogMonitor.new($tempdir) expect_statsd_increments(monitor, [ "status.200", "cdn_backend.origin", ]) record_stderr record_stdout monitor.monitor(File.open("#{$tempdir}/log")) expect(recorded_stderr).to match("Working with 1 known good urls") expect(recorded_stdout).to eq("") end it "Sends output about unsuccessful accesses to unknown urls" do write_known_good(["/a-url 20150801"]) write_log(["/an-unknown-url 500"]) monitor = LogMonitor.new($tempdir) expect_statsd_increments(monitor, [ "status.500", "cdn_backend.origin", ]) record_stderr record_stdout monitor.monitor(File.open("#{$tempdir}/log")) expect(recorded_stderr).to match("Working with 1 known good urls") expect(recorded_stdout).to eq("") end it "Sends the query string in logstash monitoring" do write_known_good(["/a-url?foo 20150801"]) write_log(["/a-url?foo 401"]) monitor = LogMonitor.new($tempdir) expect_statsd_increments(monitor, [ "status.401", "cdn_backend.origin", "known_good_fail.status_401", ]) record_stderr record_stdout monitor.monitor(File.open("#{$tempdir}/log")) expect(recorded_stderr).to match("Working with 1 known good urls") expect(recorded_stdout).to eq( %{{"@fields":{"method":"GET","path":"/a-url","query_string":"foo","status":401,"remote_addr":"1.1.1.1","request":"GET /a-url?foo","cdn_backend":"origin","last_success":"2015-08-01T00:00:00+00:00"},"@tags":["known_good_fail"],"@timestamp":"2015-08-29T05:57:21+00:00","@version":"1"}\n}) end it "Sends output about accesses which aren't served by origin" do write_known_good(["/a-url 20150801"]) write_log(["/a-url 200"], "mirror1") monitor = LogMonitor.new($tempdir) expect_statsd_increments(monitor, [ "status.200", "cdn_backend.mirror1", ]) record_stderr record_stdout monitor.monitor(File.open("#{$tempdir}/log")) expect(recorded_stderr).to match("Working with 1 known good urls") expect(recorded_stdout).to eq( %{{"@fields":{"method":"GET","path":"/a-url","query_string":null,"status":200,"remote_addr":"1.1.1.1","request":"GET /a-url","cdn_backend":"mirror1","last_success":"2015-08-01T00:00:00+00:00"},"@tags":["cdn_fallback"],"@timestamp":"2015-08-29T05:57:21+00:00","@version":"1"}\n}) end it "Sends extra tags for failed accesses which worked recently" do write_known_good(["/a-url 20150827"]) write_log(["/a-url 500"]) monitor = LogMonitor.new($tempdir) expect_statsd_increments(monitor, [ "status.500", "cdn_backend.origin", "known_good_fail.status_500", "recent_known_good_fail.status_500", ]) record_stderr record_stdout monitor.monitor(File.open("#{$tempdir}/log")) expect(recorded_stderr).to match("Working with 1 known good urls") expect(recorded_stdout).to eq( %{{"@fields":{"method":"GET","path":"/a-url","query_string":null,"status":500,"remote_addr":"1.1.1.1","request":"GET /a-url","cdn_backend":"origin","last_success":"2015-08-27T00:00:00+00:00"},"@tags":["known_good_fail","recent_known_good_fail"],"@timestamp":"2015-08-29T05:57:21+00:00","@version":"1"}\n} ) end end
class Post < ActiveRecord::Base # associations has_many :messages, dependent: :destroy belongs_to :user has_many :retweets, class_name: "Post",foreign_key: "retweet_id" has_many :comments, dependent: :destroy # attributes # validations validates :content,presence: true,length: { maximum: 140 } # scopes default_scope { order(:created_at => :desc) } # callbacks before_destroy :reset_retweet_id mount_uploader :avatar, AvatarUploader # methods def reset_retweet_id self.retweets.update_all(retweet_id: :nil) end end
require 'test_helper' class StaticPagesControllerTest < ActionDispatch::IntegrationTest def setup @base_title = "Online Judge Sample App" end test "should get home" do get static_pages_home_url assert_response :success assert_select "title", "Home | #{@base_title}" end test "should get score" do get score_path assert_response :success assert_select "title", "Score | #{@base_title}" end test "should get about" do get about_path assert_response :success assert_select "title", "About | #{@base_title}" end test "should get contact" do get contact_path assert_response :success assert_select "title", "Contact | #{@base_title}" end end
# frozen_string_literal: true class CommentsController < ApplicationController before_action :set_comment, only: %i[destroy show] def create @comment = Comment.new(comment_params) if @comment.save redirect_to @comment.submission, notice: 'Comment was successfully created.' elsif @comment.errors.include?(:parent) || @comment.errors.include?(:submission) redirect_to root_path, flash: { error: 'Could not save the comment.' } else render :new, status: :unprocessable_entity end end def destroy @comment.destroy redirect_to submission_path(@comment.submission), notice: 'Comment was successfully destroyed.' end def new @comment = Comment.new(comment_params) end private def comment_params params.require(:comment).permit(:message, :submission_id, :parent_id) end def set_comment @comment = Comment.find(params[:id]) end end
class StudentsController < ApplicationController # --we can pass in an only option, selecting which of the seven RESTful routes we care about. In this case, we only care about the show action. def index @students = Student.all end def show @student = Student.find(params[:id]) end def activate @student = Student.find(params[:id]) @student.active = !@student.active @student.save redirect_to student_path(@student) end end
class V1::CategorySerializer < ActiveModel::Serializer attributes :id, :name, :image_url, :slug def image_url Rails.application.routes.url_helpers.rails_blob_url(object.image, only_path: true) end end
require_relative 'spec_helper' describe Diagram do using NumberModifiers using ProcConvenienceMethods context 'integration' do it 'can be empty' do d = Diagram.new 'empty' expect(d.name).to eq 'empty' end it 'should be created with a source and a pool and run n times with no errors' do d=Diagram.new 'simples' d.add_node! Source, { :name => 'fonte' } d.add_node! Pool, { :name => 'depósito', :initial_value => 0 } d.add_edge! Edge, { :name => 'conector', :from => 'fonte', :to => 'depósito' } d.run!(10) expect(d.resource_count).to eq 10 expect(d.get_node('depósito').resource_count).to eq 10 end it "runs for 2 turns with two pools using PULL and there's the correct amount of resources at the end" do d = Diagram.new 'some_name' d.add_node! Pool, name: 'pool1', initial_value: 5 d.add_node! Pool, name: 'pool2', activation: :automatic d.add_edge! Edge, name: 'edge', from: 'pool1', to: 'pool2' d.run!(2) expect(d.get_node('pool1').resource_count).to eq 3 expect(d.get_node('pool2').resource_count).to eq 2 end it "runs for 2 turns with two pools using PULL and add the correct amount" do d = Diagram.new d.add_node! Pool, name: 'pool1', initial_value: 5 d.add_node! Pool, name: 'pool2', activation: :automatic d.add_edge! Edge, name: 'edge', from: 'pool1', to: 'pool2' d.run!(2) expect(d.get_node('pool1').resources_added).to eq 0 expect(d.get_node('pool2').resources_added).to eq 2 expect(d.get_node('pool2').resources_removed).to eq 0 expect(d.get_node('pool1').resources_removed).to eq 2 end it "runs for 2 turns with source and pool using PULL and add and remove the correct amount" do d = Diagram.new 'some_name' d.add_node! Source, name: 's1', activation: :automatic d.add_node! Pool, name: 'pool2' d.add_edge! Edge, name: 'edge', from: 's1', to: 'pool2' d.run!(2) expect(d.get_node('s1').resources_added).to eq 0 expect(d.get_node('pool2').resources_added).to eq 2 expect(d.get_node('pool2').resources_removed).to eq 0 expect(d.get_node('s1').resources_removed).to eq 2 end it "runs for two turns with two pools using PUSH and there's the correct amount of resources at the end" do d = Diagram.new 'some_name' d.add_node! Pool, name: 'pool1', initial_value: 5, mode: :push_any, activation: :automatic d.add_node! Pool, name: 'pool2' d.add_edge! Edge, name: 'edge', from: 'pool1', to: 'pool2' d.run!(2) expect(d.get_node('pool1').resource_count).to eq 3 expect(d.get_node('pool2').resource_count).to eq 2 end it "runs for a single turn with one source and two pools and there's the correct amount of resources at the end" do p = Diagram.new('one source two pools') p.add_node!(Source, {name: 'source'}) p.add_node!(Pool, {name: 'pool1'}) p.add_node!(Pool, {name: 'pool2', activation: :automatic}) p.add_edge!(Edge, {name: 'edge1', from: 'source', to: 'pool1'}) p.add_edge!(Edge, {name: 'connector2', from: 'pool1', to: 'pool2'}) p.run!(1) expect(p.get_node('pool1').resource_count).to eq 1 expect(p.get_node('pool2').resource_count).to eq 0 end it 'takes staging and commit steps into account when run with 3 pools for 1 turn only' do d = Diagram.new d.add_node! Pool, name: 'pool1', initial_value: 2, mode: :push_any, activation: :automatic d.add_node! Pool, name: 'pool2' d.add_node! Pool, name: 'pool3', activation: :automatic d.add_edge! Edge, name: 'edge1', from: 'pool1', to: 'pool2' d.add_edge! Edge, name: 'edge2', from: 'pool2', to: 'pool3' d.run!(1) expect(d.get_node('pool1').resource_count).to eq 1 expect(d.get_node('pool2').resource_count).to eq 1 expect(d.get_node('pool3').resource_count).to eq 0 end it 'takes staging and commit steps into account when run with 3 pools for 4 turns' do d = Diagram.new d.add_node! Pool, name: 'pool1', initial_value: 10, mode: :push_any, activation: :automatic d.add_node! Pool, name: 'pool2' d.add_node! Pool, name: 'pool3', activation: :automatic d.add_edge! Edge, name: 'edge1', from: 'pool1', to: 'pool2' d.add_edge! Edge, name: 'edge2', from: 'pool2', to: 'pool3' d.run!(4) expect(d.get_node('pool1').resource_count).to eq 6 expect(d.get_node('pool2').resource_count).to eq 1 expect(d.get_node('pool3').resource_count).to eq 3 end it 'runs with a source and a pool and have the expected amount of resources at the end' do d=Diagram.new d.add_node! Source, { :name => 'source' } d.add_node! Pool, { :name => 'deposit', } d.add_edge! Edge, { :name => 'connector', :from => 'source', :to => 'deposit' } d.run!(10) expect(d.get_node('deposit').resource_count).to eq 10 end it 'can be run until a given condition is true' do d=Diagram.new d.add_node! Pool, { :name => 'deposit', :initial_value => 0 } d.add_node! Source, { :name => 'source' } d.add_edge! Edge, { :name => 'connector', :from => 'source', :to => 'deposit' } d.run_while! { d.get_node('deposit').resource_count < 10 } expect(d.get_node('deposit').resource_count).to eq 10 end it 'aborts after specified turns as a safeguard against infinite loops given as stopping condition' do d=Diagram.new d.max_iterations=9 d.add_node! Pool, { :name => 'deposit', :initial_value => 0 } d.add_node! Source, { :name => 'source' } d.add_edge! Edge, { :name => 'connector', :from => 'source', :to => 'deposit' } d.run_while! { true == true } #not hanging on forever is the success condition. expect(d.get_node('deposit').resource_count).to eq 9 end it 'does not raise errors when active pushes or pulls are not possible' do d = Diagram.new 'no errors' d.add_node! Pool, name: 'Poor fella', initial_value: 5 d.add_node! Pool, name: 'Hungry fella', activation: :automatic d.add_edge! Edge, from: 'Poor fella', to: 'Hungry fella' expect { d.run! 10 }.not_to raise_error expect(d.get_node('Hungry fella').resource_count).to eq 5 end it "raises an error in case users try to access a node that doesn't exist" do p = Diagram.new('get invalid node') p.add_node! Source, name: 'source' p.add_node! Pool, name: 'pool1' p.add_edge! Edge, { name: 'connector1', from: 'source', to: 'pool1' } # use curly brackets instead of parentheses here. expect { p.get_node('pool') }.to raise_error RuntimeError end it 'runs with typed nodes connected by typeless edges' do p = Diagram.new('one source one pool typed') p.add_node!(Source, name: 'source', :type => Green) p.add_node!(Pool, name: 'pool1', :types => [Green, Red]) p.add_edge!(Edge, name: 'connector1', from: 'source', to: 'pool1') p.run!(5) expect(p.get_node('pool1').resource_count(type: Green)).to eq 5 expect(p.get_node('pool1').resource_count(type: Red)).to eq 0 end it "allows untyped nodes to receive typed resources sent to them via untyped edges" do p = Diagram.new 'balls' p.add_node!(Source, name: 'source', :type => Football) p.add_node!(Pool, name: 'pool1') p.add_edge!(Edge, name: 'connector1', from: 'source', to: 'pool1') p.run!(5) expect(p.get_node('pool1').resource_count(type: Football)).to eq 5 end it "allows untyped nodes to receive typed resources sent to them via typed edges" do p = Diagram.new 'fruits' #by declaring initial values, we're implicitly declaring types. p.add_node! Pool, name: 'pool1', initial_value: {Peach => 20, Mango => 99} p.add_node! Pool, name: 'pool2', activation: :automatic p.add_edge!(Edge, name: 'connector1', from: 'pool1', to: 'pool2', types: [Peach]) p.run!(5) expect(p.get_node('pool1').resource_count(type: Peach)).to eq 15 expect(p.get_node('pool1').resource_count(type: Mango)).to eq 99 expect(p.get_node('pool2').resource_count(type: Peach)).to eq 5 end it "executes start nodes only once" do d=Diagram.new 'simple' d.add_node! Source, { :name => 'source', :activation => :start } d.add_node! Pool, { :name => 'deposit', :initial_value => 0 } d.add_edge! Edge, { :name => 'connector', :from => 'source', :to => 'deposit' } d.run!(10) expect(d.get_node('deposit').resource_count).to eq 1 end it ' makes a train run' do d = Diagram.new 'dia' d.add_node! Pool, { name: 'p1', mode: :push_any, activation: :automatic, initial_value: 8 } d.add_node! Pool, { name: 'p2', mode: :push_any, activation: :automatic } d.add_node! Pool, { name: 'p3', mode: :push_any, activation: :automatic } d.add_node! Pool, { name: 'p4', mode: :push_any, activation: :automatic } d.add_edge! Edge, { name: 'e1', from: 'p1', to: 'p2' } d.add_edge! Edge, { name: 'e2', from: 'p2', to: 'p3' } d.add_edge! Edge, { name: 'e3', from: 'p3', to: 'p4' } d.run!(30) expect(d.get_node('p1').resource_count).to eq 0 expect(d.get_node('p2').resource_count).to eq 0 expect(d.get_node('p3').resource_count).to eq 0 expect(d.get_node('p4').resource_count).to eq 8 end it 'runs an untyped converter connected to two pools' do d=Diagram.new 'simple' d.add_node! Pool, { :name => 'from', :initial_value => 5 } d.add_node! Pool, { :name => 'to', :initial_value => 0 } d.add_node! Converter, { :name => 'c', :activation => :automatic } d.add_edge! Edge, { :name => 'c1', :from => 'from', :to => 'c' } d.add_edge! Edge, { :name => 'c2', :from => 'c', :to => 'to' } d.run!(4) expect(d.get_node('to').resource_count).to eq 4 end describe 'diagrams with probabilistic edges' do it 'accepts random edges with percentages' do d = Diagram.new d.add_node! Sink, name: 'sink' d.add_node! Source, name: 's' d.add_node! Gate, name: 'g' d.add_node! Pool, name: 'p' d.add_edge! Edge, from: 's', to: 'g' d.add_edge! Edge, from: 'g', to: 'p', label: 50.percent d.add_edge! Edge, from: 'g', to: 'sink', label: 50.percent d.run!(20) expect(d.p.resource_count).to (be > 1).and(be < 20) end end describe 'stop conditions' do it 'should stop when a stop condition is met before all turns run' do d = Diagram.new d.add_node! Source, name: 's' d.add_node! Gate, name: 'g' d.add_node! Pool, name: 'po' d.add_edge! Edge, from: 's', to: 'g' d.add_edge! Edge, from: 'g', to: 'po' d.add_stop_condition! message: 'first', condition: expr { d.po.resource_count >= 5 } # useless but still d.add_stop_condition! message: 'second', condition: expr { d.po.resource_count >= 10 } d.run!(20) expect(d.po.resource_count).to eq 5 end it 'should continue until the last round if no stop conditions are met' do d = Diagram.new d.add_node! Source, name: 's' d.add_node! Gate, name: 'g' d.add_node! Pool, name: 'po' d.add_edge! Edge, from: 's', to: 'g' d.add_edge! Edge, from: 'g', to: 'po' d.add_stop_condition! message: 'first', condition: expr { d.po.resource_count > 99 } # also useless but still d.add_stop_condition! message: 'second', condition: expr { d.po.resource_count < -1 } d.run!(20) expect(d.po.resource_count).to eq 20 end it 'complains' do # when users try to add two stop conditions but give them no names expect { d = Diagram.new d.add_node! Source, name: 's' d.add_node! Gate, name: 'g' d.add_node! Pool, name: 'po' d.add_edge! Edge, from: 's', to: 'g' d.add_edge! Edge, from: 'g', to: 'po' d.add_stop_condition! condition: expr { d.po.resource_count > 99 } d.add_stop_condition! condition: expr { d.po.resource_count < -1 } }.to raise_error end end describe 'Comprehensive examples' do it 'example using pull_all and activators' do d = Diagram.new d.add_node! Pool, mode: :pull_all, name: 'p1', activation: :automatic d.add_node! Pool, name: 'p2', initial_value: 7 d.add_node! Pool, name: 'p3', initial_value: 2 d.add_node! Pool, name: 'p4', initial_value: 2 d.add_node! Pool, name: 'p5', activation: :automatic, initial_value: 6, mode: :push_any d.add_edge! Edge, from: 'p2', to: 'p1' d.add_edge! Edge, from: 'p3', to: 'p1' d.add_edge! Edge, from: 'p4', to: 'p1' d.add_edge! Edge, from: 'p5', to: 'p3' d.add_edge! Edge, from: 'p5', to: 'p4' d.p5.attach_condition { d.p3.resource_count < 1 && d.p4.resource_count < 1 } d.run! 8 expect(d.p1.resource_count).to eq 15 expect(d.p2.resource_count).to eq 2 expect(d.p3.resource_count).to eq 0 expect(d.p4.resource_count).to eq 0 expect(d.p5.resource_count).to eq 0 end end end end
VALID_CHOICES = %w(rock paper scissors) choices_arr = [] def prompt(message) puts "=> #{message}" end def display_results(players_choices) case players_choices when ["rock", "scissors"] "You won!" when ["paper", "rock"] "You are the winner!" when ["scissors", "paper"] "WINNER!" else "You lost!" end end # Main Game Loop loop do choice = '' # Get Input and Validate loop do p choices_arr prompt("Choose one: #{VALID_CHOICES.join(', ')}?") choice = gets.chomp # validate human input if VALID_CHOICES.include?(choice) break else prompt("That's not a valid choice.") end end # store computer input computer_choice = VALID_CHOICES.sample prompt("You picked #{choice}. Computer picked #{computer_choice}.") # Check if tied if choice == computer_choice prompt("You are tied.") next end choices_arr[0] = choice choices_arr[1] = computer_choice p choices_arr prompt(display_results(choices_arr)) # Ask if user want to play again prompt("Do you want to play again?(y/n)") answer = gets.chomp # End Game if input is anything other that "y" break unless answer.downcase.start_with?("y") end # Say GoodBye. prompt("Thanks for playing! Goodbye!")
# question_2.rb ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 402, "Eddie" => 10 } total_age = 0 ages.each_value { |value| total_age = total_age + value } puts total_age
class Api::ChannelsController < ApplicationController def index @channels = current_user.available_channels end def create @channel = Channel.new( name: params[:channel][:name], purpose: params[:channel][:purpose], private: params[:channel][:private] ) @channel.creator = current_user if @channel.save ChannelMembership.create(user: current_user, channel: @channel) members = User .where(username: params[:channel][:members]) .where .not(username: current_user.username) @channel.members << members render :show else render json: ['Please fill in a channel name.'], status: 422 end end def update @channel = Channel.find_by(name: params[:channel_name]) ChannelMembership.create(channel: @channel, user: current_user) render :show end def show @channel = current_user.joined_channels.find_by(name: params[:channel_name]) || Channel.public_channels.find_by(name: params[:channel_name]) end private def channel_params params.require(:channel).permit(:name, :purpose, :private, members: []) end end
class Attendee < ActiveRecord::Base has_many :events_attendees has_many :events, :through => :events_attendees end
require 'rails_helper' RSpec.describe '店舗登録', type: :system do before do @user = FactoryBot.create(:user) @shop = FactoryBot.create(:shop) end context '店舗登録ができるとき' do it 'ログインしたユーザーは店舗登録ができる' do # ログインする visit new_user_session_path fill_in 'email', with: @user.email fill_in 'password', with: @user.password find('input[name="commit"]').click expect(current_path).to eq root_path # 店舗登録ページへのリンクがあることを確認する expect(page).to have_content('店舗登録') # 登録ページに移動する visit new_shop_path # フォームに情報を入力する fill_in 'shop-name', with: @shop.shop_name fill_in 'address', with: @shop.address fill_in 'phone-number', with: @shop.phone_number fill_in 'instagram', with: @shop.instagram # find('div[id="new-map"]').click # fill_in 'lat', with: @shop.lat # fill_in 'lng', with: @shop.lng # 登録するとShopモデルのカウントが1上がることを確認する expect{ find('input[name="commit"]').click }.to change { Shop.count }.by(1) # トップページに遷移することを確認する expect(current_path).to eq root_path # トップページに編集できる「店舗登録変更」ボタンがあることを確認する expect(page).to have_content('店舗登録変更') end end end
# frozen_string_literal: true # require 'active_support' require 'active_support/core_ext' require 'pathname' require_relative 'file_sieve' require_relative 'matches' # Transform a generated spec.rb file for running class SpecRbTransformer TEST_EXTENSION = '_spec.rb' REMOVALS = %w(blddev- bldinf- default) ENVIRONMENTS = %w(non_prod prod) def initialize(search_directory, target_root_directory) @target_root_directory = File.absolute_path(target_root_directory) + File::SEPARATOR @sieve = FileSieve.new(search_directory, TEST_EXTENSION) @tag = '' @described = false end # Clear out the last run def clear_last_run(root_dir) Pathname.new(root_dir).children.select { |c| c.directory? }.collect { |p| p.to_s }.each do |dir| next unless dir.include?("_tests_") puts "Deleting directory from previous run #{dir}" FileUtils.remove_dir(dir) end end def transform @sieve.found_files.each {|file| parse_environment_tag_from_test_file(file) basename = File.basename(file) type = parse_object_type_from_file_name(basename) account = parse_account_from_context_line(file) target_file = setup_generator_output(type, account, basename) File.delete(target_file) if File.exist?(target_file) @describe = false File.open(target_file, 'w') do |wr| File.foreach(file) do |line| line = transform_line(line) wr.write(line) end end clean_end_of_file(target_file) REMOVALS.each {|pattern| delete_test_block(pattern, target_file)} File.delete(target_file) unless @described } end # Sort out indentation of last end statement def clean_end_of_file(file) lines = File.readlines(file) (lines.length - 1).step(0, -1) do |i| if lines[i] == " end\n" lines[i] = "end\n" break end end File.open(file, 'w') do |f| lines.each do |line| f.write(line) end end end # Create the context description def construct_test_context(basename) vpc = basename.split('_')[2] partition = basename.split('_')[0].to_s.upcase partition + ' Tests on ' + vpc end # Delete an entire test block if the description matches the pattern def delete_test_block(pattern, file) lines = File.readlines(file) remove = false File.delete(file) File.open(file, 'w') do |f| lines.each do |line| remove = true if line.include?('describe ') && line.include?(pattern) if remove remove = false if line.include?(' end') next end f.write(line) end end end # Insert the dynamic_resource call def insert_dynamic_resource(line) line.insert(line.index('(') + 1, 'dynamic_resource(') line.insert(line.index(')'), ')') line end # Insert any tags def insert_environment_tag(line) line = line.slice(0, line.index(' do')) line + @tag + ' do' + "\n" end # Parse the account (prod / non_prod) from the context line of a test def parse_account_from_context_line(file) File.readlines(file).each do |line| ENVIRONMENTS.each {|env| return env if line.include?(env)} end raise(RuntimeError, 'Failed to find account from context line in file (' + file + ')') end # What environment referenced in file def parse_environment_tag_from_test_file(file) File.foreach(file) do |line| if line.include?('describe') set_environment_tag(line) return end end end # Parse the object type from the file name def parse_object_type_from_file_name(file) file[0, file.index('_on')] end # Change private dns line def replace_ip_with_regex_in_line(line) first = line.slice(0, line.index('{') + 1) last = line.slice(line.index('.'), line.length) .gsub(/\./, '\.') .tr("'", '/') first + ' should match /ip-[\d]{1,3}-[\d]{1,3}-[\d]{1,3}-[\d]{1,3}' + last end # Change private ip line def replace_private_ip_with_regex(line) line = line.slice(0, line.index('{') + 1) line + ' should match /[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}/ }' + "\n" end # Set the class tag var def set_environment_tag(line) case line when MatchesInt @tag = ', int: true' when MatchesDevint @tag = ', devint: true' when MatchesFt @tag = ', ft: true' when MatchesInfradev @tag = ', infradev: true' when MatchesPpd @tag = ', ppd: true' when MatchesStg @tag = ', stg: true' else @tag = '' end end # Set the output file for a generator and create sub dir if not set def setup_generator_output(type, account, file) directory = @target_root_directory + "#{type}_tests_#{account}" FileUtils.mkdir_p directory unless Dir.exists?(directory) File.absolute_path(directory) + File::SEPARATOR + file end # rubocop:disable Metrics/CyclomaticComplexity def transform_line(line) line = ' ' + line case line when MatchesAclOwner line = '' when MatchesContextLine line.lstrip! line = insert_environment_tag(line) when MatchesDescribeLine line = insert_dynamic_resource(line) @described = true when MatchesHaveEbs return '' # Uncomment to ignore :image_id and :instance_id # when MatchesImageId # return '' # when MatchesInstanceId # return '' when MatchesNetworkInterfaceLine return '' when MatchesPrivateDnsNameLine line = replace_ip_with_regex_in_line(line) when MatchesPrivateIpAddressLine line = replace_private_ip_with_regex(line) when MatchesRequireLine line = line.strip! + "\n" end line end end
class Race < ApplicationRecord has_many :characters has_many :starting_stats end
class UserController < ApplicationController before_filter :user_required!, :only => [:show, :edit, :update, :destroy] before_filter :load_current_user, :only => [:edit, :update, :destroy] before_filter :sanitize_params, :only => [:create, :update] def show redirect_to :action => :edit end def new @user = User.new end def create @user = User.new do |u| u.login = params[:user][:login] u.email = params[:user][:email] end @user.save! @user.register! flash[:notice] = 'Vous allez recevoir un mail pour confirmer votre inscription.' redirect_to forums_url rescue ActiveRecord::RecordNotSaved, ActiveRecord::RecordInvalid render :action => :new end def edit end def update begin @user.attributes_from_input = params[:user] User.transaction do if @user.confirmed? and !params[:image][:uploaded_data].to_s.blank? @user.valid? || raise(ActiveRecord::RecordInvalid) @image = Image.new(params[:image]) @image.save! @user.image.destroy if @user.image @user.image = @image @user.save(false) else @user_info.update_attributes!(params[:user_info]) if @user.active? @user.save! end end flash[:notice] = 'Votre profil a été mis à jour.' redirect_to :action => :edit rescue ActiveRecord::RecordNotSaved, ActiveRecord::RecordInvalid render :action => :edit end end def destroy @user.destroy unauthenticate flash[:notice] = 'Votre compte a été supprimé.' redirect_to forums_url end protected def load_current_user super @user_info = @user.info || @user.build_info end def sanitize_params self.params[:user] = {} unless params[:user].is_a?(Hash) self.params[:user_info] = {} unless params[:user_info].is_a?(Hash) self.params[:image] = {} unless params[:image].is_a?(Hash) end def user_confirmed_required! forbidden unless @user.confirmed? end end
require "vexor/test/version" module Vexor module Test extend self def test(arg1:, arg2:) puts "Arguments: arg1: #{arg1}, arg2: #{arg2}" return { arg1: arg1, arg2: arg2 } end end end
Rails.application.routes.draw do resources :logs root 'logs#index' end
class AddExtraTransitLandDataToLines < ActiveRecord::Migration[5.0] def change add_column :lines, :vehicle_type, :string add_column :lines, :wheelchair_accessible, :string add_column :lines, :bikes_allowed, :string rename_column :lines, :api_id, :route_long_name end end
require 'rails_helper' RSpec.describe User, type: :model do describe 'Validations' do describe 'Associations' do it{should have_many(:review)} end describe 'Required Fields' do it "should be invalid if missing a username" do user = User.create expect(user).to_not be_valid end end end describe 'Analytics' do it 'can sort reviews' do user1 = User.create(username:'u1') asimov = Author.create(name: "Issac Asimov") james = Author.create(name: "William James") book1 = Book.create(title: "Varieties of the Religious experience", pages:123, authors:[asimov], pub_date: 2018) book2 = Book.create(title: "The Martian", authors:[james], pages:123, pub_date: 1945) review1 = user1.review.create(title:"C-razy", description: "no way", rating:4, book:book1) review2 = user1.review.create(title:"I cried", description: "yes way", rating:4, book:book2) example1 = [review1, review2] example2 = [review2, review1] expect(user1.sort_dec_reviews).to eq(example2) expect(user1.sort_asc_reviews).to eq(example1) end end end
class SnapMailerNewSnapWorker < BaseWorker def self.category; :notification end def self.metric; :email end def perform(user_id, sender_id) perform_with_tracking(user_id, sender_id) do user = User.find(user_id) sender = User.find(sender_id) user.email_notifier.notify_new_snap!(sender) if user.away_idle_or_unavailable? true end end statsd_measure :perform, metric_prefix end
class Notifier < ActionMailer::Base default from: "from@example.com" # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # # en.notifier.google_message.subject # def google_message(email,password) @email = email @content = "Someone reset your password in libman site, please click link below to verify if you really want to reset it" mail :to => @email,:subject => "Your password has been changed", body: "your new password: " + password end end
# frozen_string_literal: true class RemoveChangeIdFromVersions < ActiveRecord::Migration[6.0] def change safety_assured do remove_column :versions, :change_id, :integer end end end
class ItemsController < ApplicationController before_action :set_recipe, only: [ :new, :create, :edit, :update ] before_action :set_item, only: [ :edit, :update ] def new @item = Item.new end def create @item = Item.new(items_params) @item.recipe = @recipe if @item.save redirect_to recipe_path(@recipe) else render 'new' end end def edit end def update @item.update(items_params) redirect_to recipe_path(@recipe) end private def set_recipe @recipe = Recipe.find(params[:recipe_id]) end def set_item @item = Item.find(params[:id]) end def items_params params.require(:item).permit(:ingredient_id, :recipe, :unit_id, :quantity, :recipe_ingredient) ## Rails 4 strong params usage end end
module StateReports PRINTING_SPACER = '------------------------------------------' def print_times_where_candidate_total_dropped(candidate) puts PRINTING_SPACER puts "PRINTING TIMES #{candidate}'s TOTAL DROPPED IN #{@state_name}" puts PRINTING_SPACER total_drop = 0 candidate_key = candidate.downcase == 'trump' ? 'trumpd' : 'bidenj' comparative_time_series.each do |hsh| tsdata = hsh['current_data'] last_tsdata = hsh['previous_data'] last_total = last_tsdata['vote_shares'][candidate_key] * last_tsdata['votes'] current_total = tsdata['vote_shares'][candidate_key] * tsdata['votes'] lead_no_switch_statement = "The lead did not switch" lead_switch_statement = "The lead switched in #{hsh['lead_switched']}'s favor" if last_total > current_total puts "AT #{tsdata['timestamp']}, #{candidate}'s total dropped by #{current_total - last_total}\n"\ "Total drop for timeframe was #{hsh['amount_dropped']}\n"\ "#{hsh['lead_switched'].nil? ? lead_no_switch_statement : lead_switch_statement}\n\n" total_drop += current_total - last_total end end puts "TOTAL DROP FOR #{candidate.upcase} was #{total_drop}" puts PRINTING_SPACER puts "\n\n" end def print_times_where_total_vote_count_dropped puts PRINTING_SPACER puts "PRINTING TIMES TOTAL COUNT DROPPED IN #{@state_name}" puts PRINTING_SPACER data_array = comparative_time_series times_total_vote_count_dropped.each do |hsh| lead_no_switch_statement = "The lead did not switch" lead_switch_statement = "The lead switched in #{hsh['lead_switched']}'s favor" puts "total count dropped by #{hsh['amount_dropped']}\n"\ "between #{hsh['previous_data']['timestamp']} "\ "and #{hsh['current_data']['timestamp']}\n"\ "#{hsh['lead_switched'].nil? ? lead_no_switch_statement : lead_switch_statement}\n\n" end puts "TOTAL DROP FOR STATE WAS #{data_array.sum{|hsh| hsh['amount_dropped']}}" puts PRINTING_SPACER puts "\n\n" end def print_times_where_lead_switched puts PRINTING_SPACER puts "PRINTING TIMES LEAD SWITCHED IN #{@state_name}" puts PRINTING_SPACER data_array = comparative_time_series times_lead_switched.each do |hsh| total_counts_dropped_statement = hsh['amount_dropped'].nil? ? 'did not drop' : "dropped by #{hsh['amount_dropped']}" lead_switch_statement = "The lead switched in #{hsh['lead_switched']}'s favor" puts "#{lead_switch_statement} at #{hsh['current_data']['timestamp']}\n"\ "Total vote counts #{total_counts_dropped_statement}\n\n" end puts "TOTAL DROP FOR STATE WAS #{data_array.sum{|hsh| hsh['amount_dropped']}}" puts PRINTING_SPACER puts "\n\n" end end
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html get "/signs" => "signs#index" get "/signs/:id" => "signs#show" post "/signs" => "signs#create" patch "/signs/:id" => "signs#update" delete "/signs/:id" => "signs#destroy" end
require 'rails_helper' describe 'User visits /program/:id' do scenario 'They see that program\'s information and all its purchases' do program = Program.create!(name: 'Denver Fire Department') vendor = Vendor.create!(name: 'Benny Blancos', state: 'CO') vendor2 = Vendor.create!(name: 'Pizza Hut', state: 'CO') vendor3 = Vendor.create!(name: 'Dominos', state: 'CO') purchase = Purchase.create!(transaction_date: '4/16/2017', payment_date: '4/18/2018', description: 'Calzones', amount: 50.1) purchase2 = Purchase.create!(transaction_date: '6/16/2017', payment_date: '6/18/2018', description: 'Pizza with cheese', amount: 50.1) purchase3 = Purchase.create!(transaction_date: '12/16/2017', payment_date: '12/18/2018', description: 'Pepperoni pizza', amount: 50.1) ProgramVendorPurchase.create!(program: program, vendor: vendor, purchase: purchase) ProgramVendorPurchase.create!(program: program, vendor: vendor2, purchase: purchase2) ProgramVendorPurchase.create!(program: program, vendor: vendor3, purchase: purchase3) visit program_path(program) expect(page).to have_content(program.name) expect(page).to have_content(purchase.description) expect(page).to have_content(purchase.amount) expect(page).to have_content(purchase.transaction_date) expect(page).to have_content(purchase.payment_date) expect(page).to have_content(purchase.vendors.first.name) expect(page).to have_content(purchase2.description) expect(page).to have_content(purchase2.amount) expect(page).to have_content(purchase2.transaction_date) expect(page).to have_content(purchase2.payment_date) expect(page).to have_content(purchase2.vendors.first.name) expect(page).to have_content(purchase3.description) expect(page).to have_content(purchase3.amount) expect(page).to have_content(purchase3.transaction_date) expect(page).to have_content(purchase3.payment_date) expect(page).to have_content(purchase3.vendors.first.name) end end
class Entry < ApplicationRecord belongs_to :user, optional: true # Opt out of mandatory association validation belongs_to :project, optional: true belongs_to :task, optional: true belongs_to :organization, optional: true def self.group_entries(group_value) case group_value when 'date' all.group_by{ |e| e.spent_at} when 'task' all.group_by{ |e| e.task.name } when 'organization' all.group_by{ |e| e.organization.name } else # user / staff all.group_by{ |e| e.user.full_name } end end end
class Api::V1::ScoresController < ApplicationController def version # render json: { "version" => "1.1", "notes" => "Leaderboard reset with new features:#New unlockable jumps and eggs along with a jump leaderboard!#Names for top scores/totals/streaks#More bug squashing" } render json: { "version" => "1.04", "notes" => "'S' to skip countdown,#score font updated,#many bugfixes & visuals/website upgrades" } end def index @scores = Score.all render json: @scores end def unique @scores = Score.order(:total).reverse.uniq { |x| x[:username] }.order(:id) render json: @scores end def mdev @scores = Score.all n_ip = @scores.attribute_names.delete_if { |x| x['ddiamond_points']} render json: @scores.select(n_ip) end def create @score = Score.new(score_params) if @score.save render json: @score end end def top @score = Score.order(:total).reverse[0] render json: @score end def top_three @scores = Score.order(:total).reverse[0...3] render json: @scores end def top_ten @score = Score.order(:total).reverse.uniq { |x| x[:username] }[0...10] render json: @score end def top_jumps_with_names # array of hashes @array = [ 'gate', 'diagonal', 'fjump', 'sgate', 'platform', 'cascade', 'tbone', 'mjump2', 'shuriken', 'hdiamond', 'mjump1', 'diamond', 'bubble', 'vortex', 'hourglass', 'plane', 'corner', 'valve', 'ninejump', 'ddiamond' ]; @jump_types = []; @array.each do |jump| ['_jumps', '_streak', '_points'].each do |type| @jump_types << jump + type; end end @scores = {}; @jump_types.each do |type| @scores[type] = { 'username' => '', 'multi' => {}, 'id' => '', 'number' => 0 }; end Score.all.each do |score| @jump_types.each do |type| if (score[type.to_sym].round(2) > @scores[type]['number']) then @scores[type]['number'] = score[type.to_sym].round(2); @scores[type]['username'] = score[:'username']; @scores[type]['multi'] = {}; @scores[type]['multi'][score[:'username']] = [score[:'id']]; @scores[type]['id'] = score[:'id']; elsif (score[type.to_sym].round(2) == @scores[type]['number']) then if (@scores[type]['multi'][score[:'username']]) then @scores[type]['multi'][score[:'username']] << score[:'id']; else @scores[type]['multi'][score[:'username']] = [score[:'id']]; @scores[type]['username'] = 'Multiple People'; @scores[type]['id'] = ''; end end end end render json: @scores end def top_jumps_each # array of hashes @array = [ 'gate_jumps','gate_streak','gate_points', 'diagonal_jumps','diagonal_streak','diagonal_points', 'fjump_jumps','fjump_streak','fjump_points', 'sgate_jumps','sgate_streak','sgate_points', 'platform_jumps','platform_streak','platform_points', 'cascade_jumps','cascade_streak','cascade_points', 'tbone_jumps','tbone_streak','tbone_points', 'mjump2_jumps','mjump2_streak','mjump2_points', 'shuriken_jumps','shuriken_streak','shuriken_points', 'hdiamond_jumps','hdiamond_streak','hdiamond_points', 'mjump1_jumps','mjump1_streak','mjump1_points', 'diamond_jumps','diamond_streak','diamond_points', 'bubble_jumps','bubble_streak','bubble_points', 'vortex_jumps','vortex_streak','vortex_points', 'hourglass_jumps','hourglass_streak','hourglass_points', 'plane_jumps','plane_streak','plane_points', 'corner_jumps','corner_streak','corner_points', 'valve_jumps','valve_streak','valve_points', 'ninejump_jumps','ninejump_streak','ninejump_points', 'ddiamond_jumps','ddiamond_streak','ddiamond_points' ] @scores = []; @jumps = {}; @array.each_with_index do |jump, i| n = 5 run = Score.order(jump).reverse.first(n) username = run[0]['username'] score = run[0][jump] score = (score*100).round/100.0 if score.class == Float idx = 1 while idx < n score_compare = run[idx][jump] score_compare = (score_compare*100).round/100.0 if score_compare.class == Float if score != score_compare then idx = n elsif username != run[idx]['username'] then username = 'Multiple People' idx = n else idx += 1 end end if i % 3 == 0 @jumps = {} @jumps["name"] = jump[0..-7] @jumps["jumps"] = score @jumps['jumps_username'] = username elsif i % 3 == 1 @jumps["streak"] = score @jumps['streak_username'] = username elsif i % 3 == 2 @jumps["points"] = score @jumps['points_username'] = username @scores << @jumps end end render json: @scores end def top_jumps_nums # just gives the numerical values @array = [ 'gate_jumps','gate_streak','gate_points', 'diagonal_jumps','diagonal_streak','diagonal_points', 'fjump_jumps','fjump_streak','fjump_points', 'sgate_jumps','sgate_streak','sgate_points', 'platform_jumps','platform_streak','platform_points', 'cascade_jumps','cascade_streak','cascade_points', 'tbone_jumps','tbone_streak','tbone_points', 'mjump2_jumps','mjump2_streak','mjump2_points', 'shuriken_jumps','shuriken_streak','shuriken_points', 'hdiamond_jumps','hdiamond_streak','hdiamond_points', 'mjump1_jumps','mjump1_streak','mjump1_points', 'diamond_jumps','diamond_streak','diamond_points', 'bubble_jumps','bubble_streak','bubble_points', 'vortex_jumps','vortex_streak','vortex_points', 'hourglass_jumps','hourglass_streak','hourglass_points', 'plane_jumps','plane_streak','plane_points', 'corner_jumps','corner_streak','corner_points', 'valve_jumps','valve_streak','valve_points', 'ninejump_jumps','ninejump_streak','ninejump_points', 'ddiamond_jumps','ddiamond_streak','ddiamond_points' ] @scores = [] @array.each do |jump, i| score = Score.order(jump).reverse.first[jump] score = (score*100).round/100.0 if score.class == Float @scores << score end render json: @scores end def top_jumps # one big hash @array = [ 'gate_jumps','gate_streak','gate_points', 'diagonal_jumps','diagonal_streak','diagonal_points', 'fjump_jumps','fjump_streak','fjump_points', 'sgate_jumps','sgate_streak','sgate_points', 'platform_jumps','platform_streak','platform_points', 'cascade_jumps','cascade_streak','cascade_points', 'tbone_jumps','tbone_streak','tbone_points', 'mjump2_jumps','mjump2_streak','mjump2_points', 'shuriken_jumps','shuriken_streak','shuriken_points', 'hdiamond_jumps','hdiamond_streak','hdiamond_points', 'mjump1_jumps','mjump1_streak','mjump1_points', 'diamond_jumps','diamond_streak','diamond_points', 'bubble_jumps','bubble_streak','bubble_points', 'vortex_jumps','vortex_streak','vortex_points', 'hourglass_jumps','hourglass_streak','hourglass_points', 'plane_jumps','plane_streak','plane_points', 'corner_jumps','corner_streak','corner_points', 'valve_jumps','valve_streak','valve_points', 'ninejump_jumps','ninejump_streak','ninejump_points', 'ddiamond_jumps','ddiamond_streak','ddiamond_points' ] @scores = {} @array.each do |jump| score = Score.order(jump).reverse.first[jump] score = (score*100).round/100.0 if score.class == Float @scores[jump] = score end render json: @scores end def show @score = Score.find(params[:id]) render json: @score end private def score_params params.require(:score).permit( :username, :ipa, :total, :jumps, :deaths, :longest_streak, :bestjump_type, :bestjump_points, :easy_points, :easy_jumps, :gate_jumps, :gate_streak, :gate_points, :diagonal_jumps, :diagonal_streak, :diagonal_points, :fjump_jumps, :fjump_streak, :fjump_points, :sgate_jumps, :sgate_streak, :sgate_points, :platform_jumps, :platform_streak, :platform_points, :medium_points, :medium_jumps, :cascade_jumps, :cascade_streak, :cascade_points, :tbone_jumps, :tbone_streak, :tbone_points, :mjump2_jumps, :mjump2_streak, :mjump2_points, :shuriken_jumps, :shuriken_streak, :shuriken_points, :hdiamond_jumps, :hdiamond_streak, :hdiamond_points, :hard_points, :hard_jumps, :mjump1_jumps, :mjump1_streak, :mjump1_points, :diamond_jumps, :diamond_streak, :diamond_points, :bubble_jumps, :bubble_streak, :bubble_points, :vortex_jumps, :vortex_streak, :vortex_points, :hourglass_jumps, :hourglass_streak, :hourglass_points, :hardest_points, :hardest_jumps, :plane_jumps, :plane_streak, :plane_points, :corner_jumps, :corner_streak, :corner_points, :valve_jumps, :valve_streak, :valve_points, :ninejump_jumps, :ninejump_streak, :ninejump_points, :ddiamond_jumps, :ddiamond_streak, :ddiamond_points ) end end
class AddMissingIndex < ActiveRecord::Migration def change add_index :team_users, [:user_id, :team_id] end end
class ListNode attr_accessor :val, :next def initialize(val) @val = val @next = nil end end # 使用栈 def is_palindrome(head) stack = Array.new node = head size = 0 while node stack.push(node.val) node = node.next size = size + 1 end node = head (0...size / 2).each do return false if node.val != stack.last node = node.next stack.pop end true end # 后半段链表翻转 def is_palindrome(head) return true if !head or !head.next secondNode = head firstNode = head while firstNode.next and firstNode.next.next firstNode = firstNode.next.next secondNode = secondNode.next end last = secondNode.next, pre = head while last.next tmp = last.next last.next end head = ListNode.new(1) head.next = ListNode.new(0) head.next.next = ListNode.new(0) head.next.next.next = ListNode.new(3) puts is_palindrome(head) puts is_palindrome(nil)
require './QuestionsDatabase.rb' class Question_follower attr_reader :id, :question_id, :user_id def self.all questions_fol = QuestionsDatabase.instance.execute("SELECT * FROM question_followers") questions_fol.map { |question| Question_follower.new(question) } end def self.find_by_id(id) question = QuestionsDatabase.instance.execute(<<-SQL, id) SELECT * FROM question_followers WHERE question_followers.id = ? SQL Question_follower.new(question[0]) end def self.followed_questions_for_user_id(id) results = QuestionsDatabase.instance.execute(<<-SQL, id) SELECT questions.id, questions.title, questions.body, questions.author_id FROM question_followers JOIN questions ON question_followers.question_id = questions.id WHERE question_followers.user_id = ? SQL results.map {|result| User.new(result) } end def self.followers_for_question_id(id) results = QuestionsDatabase.instance.execute(<<-SQL, id) SELECT users.id, users.fname, users.lname FROM question_followers JOIN users ON question_followers.user_id = users.id WHERE question_followers.question_id = ? SQL results.map {|result| User.new(result) } end def most_followed_questions(n) results = QuestionsDatabases.instance.execute(<<-SQL, n) SELECT questions.id, questions.title, questions.body, questions.author_id FROM question_followers JOIN questions ON question_followers.question_id = questions.id GROUP BY questions.id ORDER BY COUNT(question_followers.user_id) DESC LIMIT ? SQL results.map { |result| Question.new(result) } end def initialize(option = {}) @id = option["id"] @question_id = option["question_id"] @user_id = option["user_id"] end end
# A class for running TensorFlow operations. # A Session object encapsulates the environment in which Operation objects are executed, and Tensor objects are evaluated. # A Session instance lets a caller drive a TensorFlow graph computation. # When a Session is created with a given target, a new Session object is bound to the # universe of resources specified by that target. Those resources are available to this # session to perform computation described in the GraphDef. After extending the session # with a graph, the caller uses the Run() API to perform the computation and potentially # fetch outputs as Tensors. Protocol buffer exposes various configuration options for a session. The Op definations are stored in ops.pb file. # Official documentation of {session}[https://www.tensorflow.org/api_docs/python/client/session_management#Session] and {Operation}[https://www.tensorflow.org/api_docs/python/framework/core_graph_data_structures#Operation]. class Tensorflow::Session attr_accessor :status, :ops, :session, :graph, :c # @!attribute dimensions # Create a success status. # @!attribute ops # Nodes in the graph are called ops (short for operations). An op takes zero or more Tensors, performs some computation, and produces zero or more Tensors. # @!attribute graph # A TensorFlow graph is a description of computations. To compute anything, a graph must be launched in a Session. A Session places the graph ops and provides methods to execute them. def initialize(graph, c_options = nil) c_options = Tensorflow::Session_options.new if c_options.nil? self.status = Tensorflow::Status.new cOpt = c_options.c c_session = Tensorflow::TF_NewSession(graph.c, cOpt, status.c) Tensorflow::TF_DeleteSessionOptions(cOpt) raise 'Error in session initialization.' if status.code != 0 self.c = c_session end # Run the graph with the associated session starting with the supplied feeds # to compute the value of the requested fetches. Runs, but does not return # Tensors for operations specified in targets. # # On success, returns the fetched Tensors in the same order as supplied in # the fetches argument. If fetches is set to nil, the returned Tensor fetches # is empty. # # Note that the caller maintains responsibility for the input tensors, so # the caller should still call tensor.delete() on each input tensor def run(inputs, outputs, targets) inputPorts = Tensorflow::TF_Output_vector.new inputValues = Tensorflow::Tensor_Vector.new inputs.each do |port, tensor| inputPorts.push(port.c) inputValues.push(tensor.tensor) end outputPorts = Tensorflow::TF_Output_vector.new outputs.each do |output| outputPorts.push(output.c) end cTargets = Tensorflow::TF_Operation_vector.new targets.each do |targe| cTargets.push(targe.c) end outputValues = Tensorflow::Session_run(c, inputPorts, inputValues, outputPorts, cTargets) output_array = [] outputValues.each do |value| converted_value = convert_value_for_output_array(value) output_array.push(converted_value) # Since we're returning the results as an array, there's no point keeping # the output tensor, so we delete it. Tensorflow::TF_DeleteTensor(value) end output_array end def close status = Tensorflow::Status.new Tensorflow::TF_CloseSession(c, status.c) raise 'Error in closing session.' if status.code != 0 Tensorflow::TF_DeleteSession(c, status.c) raise 'Error in deleting session.' if status.code != 0 self.c = nil end private def initialize_inputs(inputs) input_names = Tensorflow::String_Vector.new input_values = Tensorflow::Tensor_Vector.new unless inputs.nil? inputs.each do |key, value| input_values.push(value) input_names.push(key) end end [input_names, input_values] end def initialize_outputs(outputs) output_names = Tensorflow::String_Vector.new unless outputs.nil? outputs.each do |name| output_names.push(name) end end output_values = Tensorflow::Tensor_Vector.new [output_names, output_values] end def initialize_targets(targets) target_names = Tensorflow::String_Vector.new unless targets.nil? targets.each do |name| target_names.push(name) end end target_names end def convert_value_for_output_array(value) type = Tensorflow::TF_TensorType(value) if type == Tensorflow::TF_STRING return Tensorflow::String_decoder(value) end size = Tensorflow.tensor_size(value) c_array = construct_c_array(value, size) length_by_dimension = length_by_dimension(value) arrange_into_dimensions(c_array, size, length_by_dimension) end # Returns an array containing the length of the tensor in each dimension def length_by_dimension(value) num_dimensions = Tensorflow::TF_NumDims(value) (0..num_dimensions - 1).each_with_object([]) do |dimension, array| array.push(Tensorflow::TF_Dim(value, dimension)) end end def construct_c_array(value, size) type = Tensorflow::TF_TensorType(value) case type when Tensorflow::TF_FLOAT c_array = Tensorflow::Float.new(size) Tensorflow.float_reader(value, c_array, size) when Tensorflow::TF_DOUBLE c_array = Tensorflow::Double.new(size) Tensorflow.double_reader(value, c_array, size) when Tensorflow::TF_INT32 c_array = Tensorflow::Int.new(size) Tensorflow.int_reader(value, c_array, size) when Tensorflow::TF_INT64 c_array = Tensorflow::Long_long.new(size) Tensorflow.long_long_reader(value, c_array, size) when Tensorflow::TF_COMPLEX128 c_array = Tensorflow.complex_reader(value) # Add support for bool, uint and other data types. else raise 'Data type not supported.' end c_array end # Arrange a flat array into an array of arrays organized by tensor dimensions def arrange_into_dimensions(c_array, size, length_by_dimension) output = [] (0..size - 1).each do |j| output.push(c_array[j]) end length_by_dimension.reverse! (0..length_by_dimension.length - 2).each do |dim| all_dimensions = [] one_dimension = [] output.each do |val| one_dimension.push(val) if one_dimension.length == length_by_dimension[dim] all_dimensions.push(one_dimension) one_dimension = [] end end output = all_dimensions end output end # # Converts a give ruby array to C array (using SWIG) by detecting the data type automatically. # Design decision needs to be made regarding this so the all the data types are supported. # Currently Integer(Ruby) is converted to long long(C) and Float(Ruby) is converted double(C). # # * *Returns* : # - A c array. # def graph_def_to_c_array(array) c_array = Tensorflow::Character.new(array.length) (0..array.length - 1).each do |i| c_array[i] = array[i] end c_array end end
class Que < ApplicationRecord has_many :positions has_many :users, through: :positions belongs_to :service end
require 'spec_helper' describe Rating do describe ".create_csv_header" do let(:header){ header = ['Item', 'User', 'Type', 'Score'] } it{ Rating.create_csv_header.should eq header } end end
Blog::App.controllers :steps do # get :index, :map => '/foo/bar' do # session[:foo] = 'bar' # render 'index' # end # get :sample, :map => '/sample/url', :provides => [:any, :js] do # case content_type # when :js then ... # else ... # end # get :foo, :with => :id do # 'Maps to url '/foo/#{params[:id]}'' # end # get '/example' do # 'Hello world!' # end get :new, :with=> :id do @recipe = Recipe.find(params[:id]) @title = "create a new recipe" @step = Step.new render 'steps/new' end get :index do @title = "All steps" @step = Step.all end post :create do @step = Step.new(params[:step]) image = params[:step][:image] upload = Upload.new upload = image upload = File.open('public/images') if @step.save! @title = pat(:create_title, :model =>"step #{@step.id}") flash[:success] = pat(:create_success, :model=> 'step') params[:save_and_continue] ? redirect(url(:steps, :new, :id =>params[:step][:recipe_id])) : redirect(url(:steps, :edit, :id => @step.id)) else @title = pat(:create_title, :model=>'recipe') flash.now[:error] = "unable to create step" redirect 'recipes/new' end end get :edit, :with => :id do @title = pat(:edit_title, :model => "step #{ params[:id]}") @step = Step.find(params[:id]) if @step render 'steps/edit' else flash[:warning] ="could not save edit for #{params[:id]}" halt 404 end end put :update, :with => :id do @title = pat(:update_title, :model => "step #{params[:id]}") @step = Recipe.find(params[:id]) if @step if @step.update_attributes(params[:step]) flash[:success] = " updated step #{params[:id]}" params[:save_and_continue] ? redirect(url(:steps, :index)) : redirect(url(:steps, :edit, :id => @step.id)) else flash.now[:error] = "there was an error updating step #{params[:id] }" render 'steps/edit' end else flash[:warning] = " could not update step #{params[:id]}" halt 404 end end delete :destroy, :with => :id do @title = "Steps" step = Step.find(params[:id]) if step if step.destroy flash[:success] = " deleted step #{params[:id]}" else flash[:error] = "unable to delete step #{ params[:id]}" end redirect url(:steps, :index) else flash[:warning] = "could find step #{params[:id]}" halt 404 end end delete :destroy_many do @title = "Step" unless params[:steps_ids] flash[:error] = "destroyed many steps #{ids.to_sentence}" redirect(url(:recipes, :index)) end ids = params[:recipe_ids].split(',').map(&:strip) recipes = Step.find(ids) if Recipe.destroy recipes flash[:success] = " destroyed steps #{ids.to_sentence}" end redirect url(:steps, :index) end end
# -*- mode: ruby -*- # vi: set ft=ruby : VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.ssh.insert_key = false config.vm.define :mirror do |tm| tm.vm.box = "mirror" tm.vm.network :private_network, ip: "192.168.133.20" tm.vm.network "public_network", bridge: "eno1", ip:"192.168.131.86" tm.vm.provider :virtualbox do |vb| vb.customize ["modifyvm", :id, "--memory", "1024","--cpus", "1", "--name", "mirror" ] end end end
require File.expand_path(File.dirname(File.dirname(__FILE__)) + '/spec_helper') describe 'connection to svn' do it "should find and parse an account" do @p=Provenance.new("-x --category #{SubversionTestCategory}") @p.exec @typeassertion= @p.triples.first @typeassertion.subject.should eql RDF::URI( "http://svn.amee.com/internal/api_csvs"+ "/transport/car/generic/ghgp/us/light.prov?offset=0#5") @typeassertion.predicate.should eql OPM.account @typeassertion.object.should eql RDF::URI( "http://svn.amee.com/internal/api_csvs/"+ "transport/car/generic/ghgp/us/light.prov") end end describe SvnFile do before :all do path=File.join('api_csvs',SubversionTestCategory,'data.csv') @file=SvnFile.new(Connection::Subversion.connect,path) end it "should know the first author to commit the file" do @file.first_author.should eql 'rebecca' end it "should know the last author to commit the file" do @file.last_author.should eql 'andrew' end end
class Renderer def initialize(grouping) @grouping = grouping @remaining = @grouping.delete :remaining @template = File.read File.expand_path('../print_out.erb', __FILE__) end def render ERB.new(@template).result binding end def total_loc(actions) actions.values.sum end def compute_styles(actions) color = compute_color(total_loc(actions)).join(',') { height: "#{compute_height}px;", 'border-color' => "rgb(#{color});" }.map { |k, v| "#{k}:#{v} " }.join end private # Find the group with the most actions and return an int h where: # h = (max_actions + pad) * factor # the pad represents the top two header lines in the rendered post it # the factor represents the line height of the action list def compute_height(pad = 2, factor = 13) (max_actions + pad) * factor end # Make the groups with the least lines of code green and gradually go to red # return a string that will be parameters to the css rgb rule def compute_color(loc, resolution = 50) min_loc = total_loc grouping_sorted_by_total_loc.first.last max_loc = total_loc grouping_sorted_by_total_loc.reverse.first.last range = max_loc - min_loc progress = loc - min_loc percent = progress.to_f / range.to_f * 100.0 gradient = ColorFun::Gradient.new "00ff00", "FF9100", "ff0000" # green, orange, red gradient.resolution = resolution rgb = gradient.at [percent, resolution].min [rgb.red, rgb.green, rgb.blue] end def max_actions @max_actions ||= grouping_sorted_by_action_count.reverse.first.last.size end def grouping_sorted_by_action_count @grouping_sorted_by_action_count ||= @grouping.sort_by do |n, actions| actions.size end end def grouping_sorted_by_total_loc @grouping_sorted_by_total_loc ||= @grouping.sort_by do |n, actions| total_loc actions end end end
class ChangeSizeActivityDescriptionInWorkshops < ActiveRecord::Migration[5.0] def change change_column :workshops, :activity_description, :text end end
source 'https://rubygems.org' gem 'paperclip' gem 'devise' gem 'rails', '4.1.8' gem 'pg' gem 'sass-rails', '~> 4.0.3' gem 'uglifier', '>= 1.3.0' gem 'coffee-rails', '~> 4.0.0' gem 'jquery-rails' gem 'turbolinks' gem 'jbuilder', '~> 2.0' gem 'sdoc', '~> 0.4.0', group: :doc gem 'simple_form' gem 'awesome_print' #test in future #gem 'state_machine', '~> 1.2.1', github: 'LiveTyping/state_machine' #area admin gem 'rails_admin', '0.6.5' #theme for rails_admin gem 'rails_admin_flatly_theme', :git => 'git://github.com/konjoot/rails_admin_flatly_theme.git', :branch => 'release_1.0' #server gem 'unicorn' #extensions views gem "slim" gem "slim-rails", :require => false #paginate gem 'will_paginate', '~> 3.0.6' gem 'will_paginate-bootstrap' group :development, :test do gem 'byebug' # Access an IRB console on exception pages or by using <%= console %> in views gem 'web-console', '~> 2.0' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring' end
# frozen_string_literal: true require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe OsxApp do # rubocop:todo Metrics/BlockLength subject { OsxApp.new(parameter) } context 'when using name of app' do context 'and app exist by default' do let(:parameter) { 'Automator' } its(:name) { should eq 'Automator' } its(:path) { should eq '/Applications/Automator.app' } its(:version) { should eq expected_automator_version } its(:version_major) { should eq expected_automator_version_major } its(:minimum_osx) { should eq expected_automator_minimum_osx } end context 'with app suffix and app exist by default' do let(:parameter) { 'Automator.app' } its(:name) { should eq 'Automator' } its(:path) { should eq '/Applications/Automator.app' } its(:version) { should eq expected_automator_version } its(:version_major) { should eq expected_automator_version_major } its(:minimum_osx) { should eq expected_automator_minimum_osx } end context 'and app does not exist' do let(:parameter) { 'Example' } it { expect { subject }.to raise_error(OsxApp::CannotFind) } end context 'with app suffix and app does not exist' do let(:parameter) { 'Example.app' } it { expect { subject }.to raise_error(OsxApp::CannotFind) } end end context 'when using path of app' do context 'and app exist by default' do let(:parameter) { '/Applications/Automator.app' } its(:name) { should eq 'Automator' } its(:path) { should eq '/Applications/Automator.app' } its(:version) { should eq expected_automator_version } its(:version_major) { should eq expected_automator_version_major } its(:minimum_osx) { should eq expected_automator_minimum_osx } end context 'and app not exist' do let(:parameter) { '/Applications/Example.app' } it { expect { subject }.to raise_error(OsxApp::CannotFind) } end context 'and app does not contain Info.plist' do let(:parameter) { "/tmp/Example#{Random.new_seed}.app" } before { FileUtils.mkdir(parameter) } after { FileUtils.rm_rf(parameter) } it { expect { subject }.to raise_error(OsxApp::Invalid) } end end def osx_version @osx_version ||= `sw_vers -productVersion`.strip end def expected_automator_version { '10.8.5' => '2.3', '10.13.6' => '2.8' }[osx_version] end def expected_automator_version_major expected_automator_version.split('.').first end def expected_automator_minimum_osx { '10.8.5' => '10.7', '10.13.6' => '10.10' }[osx_version] end end
require 'test_helper' describe "basic OgaNs" do before do @doc_str = <<-EOS <root xmlns:e="http://example.com/example"> <plain>plain</plain> <e:node /> </root> EOS @oga_xml = Oga.parse_xml(@doc_str) @oga_xml.extend(OgaNs::Document) end describe "xpath_ns" do it "uses namespace argument" do result = @oga_xml.xpath_ns("//example:node", "example" => "http://example.com/example") assert result.size == 1, "expected one result, not #{result.size}" assert_equal "node", result.first.name end it "uses query_namespaces" do dup = @oga_xml.dup.extend(OgaNs::Document).use_query_namespaces!("example" => "http://example.com/example") result = dup.xpath_ns("//example:node") assert result.size == 1, "expected one result, not #{result.size}" assert_equal "node", result.first.name end it "finds default namespaces" do doc = Oga.parse_xml(<<-EOS) <root xmlns="http://example.com/example"> <node /> </root> EOS doc.extend(OgaNs::Document) result = doc.xpath_ns("//example:node", "example" => "http://example.com/example") assert result.size == 1, "expected one result, not #{result.size}" assert_equal "node", result.first.name end it "raises on undefined namespace" do e = nil begin @oga_xml.xpath_ns("//unspecified:foo") rescue ::OgaNs::UnspecifiedPrefixException => e end assert e, "OgaNs::UnspecifiedParseException expected to be raised, not #{e.inspect}" assert_equal "Unspecified namespace prefix: 'unspecified'", e.message end it "does not find namespaced node with no ns in query" do assert_equal 0, @oga_xml.xpath_ns("//node").size, "expected no results" end it "does not find namespaced node with wrong namespace" do assert_equal 0, @oga_xml.xpath_ns("//e:node", "e" => "http://example.org/OTHER").size, "expected no results" end it "finds nothing on good namespace but no matches" do assert_equal 0, @oga_xml.xpath_ns("//example:noneSuch", "example" => "http://example.com/example").size, "expected no results" end it "can still find un-namespaced nodes" do result = @oga_xml.xpath_ns("//plain") assert_equal 1, result.size, "expected 1 result not #{result.size}" assert_equal "plain", result.first.name end it "still respects oga * namespace" do # Using '*' as a namespace prefix isn't XPath, it's an Oga # extension apparently. But it's useful, let's make sure xpath_ns supports # it too. oga_xml = Oga.parse_xml(<<-EOS) <root> <node xmlns="http://example.com/example" /> <node /> </root> EOS oga_xml.extend(OgaNs::Document) result = oga_xml.xpath("//*:node") assert_equal 2, result.size, "expected 2 results, not #{result.size}" assert result.find {|node| node.name == "node" && node.namespace == nil} assert result.find {|node| node.name == "node" && node.namespace.uri == "http://example.com/example"} end end describe "at_xpath_ns" do # just a simple test for at_xpath_ns too for now. add more if bugs? it "works" do result = @oga_xml.at_xpath_ns("//example:node", "example" => "http://example.com/example") assert_kind_of Oga::XML::Element, result end it "correctly returns nil on no match" do assert_nil @oga_xml.at_xpath_ns("//noSuchElement") end end end
require 'spec_helper' require 'set' describe Set do specify "empty sets should be equal" do expect(Set.new([])).to eq(Set.new([])) expect(Set.new([])).to eql(Set.new([])) end describe "on DEE-like sets" do let(:dee){ Set.new([{}]) } specify "DEE sets should be equal" do expect(Set.new([{}])).to eq(dee) expect(Set.new([{}])).to eql(dee) end specify "DEE-like sets should be equal (1)" do arr = [{}] expect(Set.new(arr)).to eq(dee) expect(Set.new(arr)).to eql(dee) end specify "DEE-like sets should be equal (2)" do arr = [{}] expect(Set.new(arr.to_a)).to eq(dee) expect(Set.new(arr.to_a)).to eql(dee) end specify "DEE-like sets should be equal (3)" do arr = [{}] expect(arr.to_set).to eq(dee) expect(arr.to_set).to eql(dee) end specify "DEE-like sets should be equal (4)" do arr = [{}] expect(arr.to_set).to eq(dee) expect(arr.to_set).to eql(dee) end specify "DEE-like sets should be equal (5)" do arr = Object.new.extend(Enumerable) def arr.each yield({}) end expect(arr.to_set).to eq(dee) expect(arr.to_set).to eql(dee) end specify "DEE-like sets should be equal (5)" do arr = Object.new.extend(Enumerable) def arr.each tuple = {:sid => "1"} tuple.delete(:sid) yield(tuple) end expect(arr.to_set).to eq(dee) expect(arr.to_set).to eql(dee) end end end
class CreateNhacungcaps < ActiveRecord::Migration[6.1] def change create_table :nhacungcaps do |t| t.string :manhacungcap t.string :tennhacungcap t.string :diachi t.integer :sodienthoai t.timestamps end end end
class ChangeNameToTeams < ActiveRecord::Migration[5.1] def change rename_column :teams, :validate, :valid end end
# Helper methods defined here can be accessed in any controller or view in the application Blog::App.helpers do def cycle @_cycle ||= reset_cycle @_cycle = [@_cycle.pop] + @_cycle @_cycle.first end def reset_cycle @_cycle = %w(even odd) end # def simple_helper_method # end def post_date(post) raw = post.created_at date = raw.to_s.split('-') day_month = date[2].split(' ') month = return_month(date[1]) hash = { :day => day_month[0], :month => month, :year => date[0] } main = { :blog_date => hash, :time_ago => " posted #{time_ago_in_words(raw)} ago" } partial 'shared/calender', :locals => { :h => main} end def return_month(mon) month = case mon.to_i when 1 then "January" when 2 then " Feburary" when 3 then "March" when 4 then "April" when 5 then "May" when 6 then "June" when 7 then "July" when 8 then "August" when 9 then "September" when 10 then "October" when 11 then "Novemeber" when 12 then "December" else "no such month" end return month end def link_to_image(img, path) link_to image_tag(img.to_s), path end def tag_icon(icon, tag = nil) content = content_tag(:i, '', :class=> "icon-#{icon.to_s}") content << " #{tag.to_s}" end def gravatar_for( user, options = {}) options[:size] ||=15 gravatar_id = Digest::MD5::hexdigest(user.email.downcase) gravatar_url = "http://gravatar.com/avatar/#{gravatar_id}.png" image_tag(gravatar_url, alt: user.name, class: "gravatar", width: options[:size]) end def gravatar_for_nil(options = {}) options[:size] ||=15 gravatar_url = "http://gravatar.com/avatar" image_tag(gravatar_url, alt: "John Doe", class: "gravatar", width: options[:size]) end def app_title(t=nil) if t.nil? title = "Jo Goes Green" else title = t end simple_format(title, :tag => :div, :class => "admin-title") end def post_archived(amount=10) Post.order(by: month).limit(amount) models = model.group_by{ |t| t.created_at.beginning_of_month} end def _klass(classname) Kernel.const_get(classname).methods end def archive(date) str = date.to_s a = str.split('-') s = "#{return_month(a[1])}" + " " + "#{a[0]}" end def split_date(date) s1 = date.to_s.split(" ").to_a s1[0] end def geo_hash(geo) hash = { :lat => geo["latitude"], :long => geo["longitude"], } end def distance_between(h1,h2) lat1 = h1[:lat] long1= h1[:long] lat2 = h2[:lat] long2= h2[:long] long = long1 - long2 lat = lat1 - lat2 Geocoder::Calculations.distance_between([lat1,long1],[lat2,long2]) end def geo(ip) searched = Geocoder.search(ip).first.data unless Geocoder.search(ip) == nil if searched == nil return nil else geo_hash(searched) end end def distance(d1,d2) distance_between(d1,d2) end def tag_icon(icon, tag = nil) content = content_tag(:i, '', :class=> "icon-#{icon}") content << " #{tag}" end def humanize(lower_case_and_underscored_word, options = {}) result = lower_case_and_underscored_word.to_s.dup inflections.humans.each { |(rule, replacement)| break if result.sub!(rule, replacement) } result.gsub!(/_id$/, "") result.tr!('_', ' ') result.gsub!(/([a-z\d]*)/i) { |match| "#{inflections.acronyms[match] || match.downcase}" } result.gsub!(/^\w/) { |match| match.upcase } if options.fetch(:capitalize, true) result end def flashed partial 'shared/flash' end def title(&block) haml_tag :div, :class =>"title" do yield if block_given? end end end
class RemoveUniqueValidationOfUsernameFromUser < ActiveRecord::Migration def change remove_index :users, :username add_index :users, :username add_index :users, :email end end
# frozen_string_literal: true module Dynflow # for cases the serialized action was renamed and it's not available # in the code base anymore. class Action::Missing < Dynflow::Action def self.generate(action_name) Class.new(self).tap do |klass| klass.singleton_class.send(:define_method, :name) do action_name end end end def plan(*args) raise StandardError, "The action class was not found and therefore plan phase failed, this can happen if the action was added/renamed but the executor was not restarted." end def run raise StandardError, "The action class was not found and therefore run phase failed, this can happen if the action was added/renamed but the executor was not restarted." end def finalize raise StandardError, "The action class was not found and therefore finalize phase failed, this can happen if the action was added/renamed but the executor was not restarted." end end end
require File.expand_path("../spec_helper", __FILE__) describe Mote::Cursor do before do 5.times { |i| Book.create(:name => "Book #{i}") } end after do Book.collection.drop end it "should return an array of Mote::Documents" do books = Book.all.to_a books.each do |book| book.should be_a(Book) end end it "should proxy any undefined methods to the Mongo::Cursor object" do books = Book.all books.should be_a Mote::Cursor books.skip(1) end it "should respond to Mongo::Cursor methods" do books = Book.all books.should respond_to :skip end it "should update the mongo_cursor with the return of a Mongo::Cursor proxied method" do books = Book.find original_cursor = books.instance_variable_get("@mongo_cursor").dup books.skip(1) original_cursor.should_not be books.instance_variable_get("@mongo_cursor") end it "should return the Mote::Cursor instance when Mongo::Cursor methods return the cursor" do books = Book.find().skip(1) books.should be_a Mote::Cursor end it "should return the result of the Mongo::Cursor method if it does not return a cursor" do books = Book.find books.close.should be true end it "should return the count from the Mongo::Cursor instance" do books = Book.find books.should_receive :method_missing books.count end end
class Instructor < ApplicationRecord has_many :instruct_mods has_many :mods, through: :instruct_mods end
class ToggleCallForwardingMutation < Types::BaseMutation description "Enables or disables call forwarding for a user" field :user, Outputs::UserType, null: true field :errors, resolver: Resolvers::Error policy ApplicationPolicy, :logged_in? def authorized_resolve current_user.toggle(:call_forwarding) if current_user.save {user: current_user, errors: []} else {user: nil, errors: current_user.errors} end end end
# ========================================================================== # Project: Lebowski Framework - The SproutCore Test Automation Framework # License: Licensed under MIT license (see License.txt) # ========================================================================== module Lebowski module RSpec module Matchers class HasPredicateWithPrefixHas < MatchSupporter def has_match?() executed_method = false method_name = predicate_with_prefix_has(@expected) # Try with arguments begin @result = @object.__send__(method_name, *@args) executed_method = true rescue NoMethodError => nme rescue ArgumentError => ae end return true if executed_method # Try with no arguments begin @result = @object.__send__(method_name) executed_method = true rescue NoMethodError => nme rescue ArgumentError => ae end return executed_method end private def predicate_with_prefix_has(sym) return (sym.to_s.sub('have_', 'has_') << '?').to_sym end end end end end
require 'spec_helper' describe Zertico::Service do let(:user) { User.new } let(:service_class) { UserService } let(:service) { UserService.new } describe '.use_as_id' do it 'should define the id name' do service_class.interface_id.should == 'great_id' end end describe '.use_as_variable_name' do it 'should define the variable name' do service_class.interface_name.should == 'great_name' end end describe '.use_interface' do it 'should define the interface' do service_class.interface_class.should == Product end end describe '#resource_source=' do before :each do User.stub(:all => [ user ]) service_class.resource_source = %w(User all) end it 'should set the resource' do service.resource_source.should == [ user ] end end end
# encoding: UTF-8 class ZEKonto < ActiveRecord::Base set_table_name "ZEKonto" attr_accessible :ktoNr, :eeKtoNr, :pgNr, :zeNr, :zeAbDatum, :zeEndDatum, :zeBetrag, :laufzeit, :zahlModus, :tilgRate, :ansparRate, :kduRate, :rduRate, :zeStatus set_primary_key :ktoNr belongs_to :OZBKonto belongs_to :EEKonto has_many :Buergschaft, :foreign_key => :ktoNr # Done, getestet belongs_to :Projektgruppe, :inverse_of => :ZEKonto, :foreign_key => :pgNr # Done, getestet def validate! errors = ActiveModel::Errors.new(self) # Kontonummer if self.ktoNr.nil? then errors.add("", "Bitte geben sie eine Kontonummer an.") else if self.ktoNr.to_s.match(/[0-9]+/).nil? then erros.add("", "Die Kontonummer muss eine Zahl sein.") end end # EE-Kontonummer if self.eeKtoNr.nil? then errors.add("", "Bitte geben sie ein EEKonto an.") else if self.ktoNr.to_s.match(/[0-9]+/).nil? then errors.add("", "Die Kontonummer (EEKonto) muss eine Zahl sein.") end end # Projektgruppe if !self.pgNr.nil? then if self.pgNr.to_s.match(/[0-9]+/).nil? then errors.add("", "Die Projektgruppennummer muss eine Zahl sein.") end end # ZE-Nummer if self.zeNr.nil? then errors.add("", "Bitte geben sie ein ZE Nummer an.") else if self.zeNr.to_s.match(/[0-9]+/).nil? then errors.add("", "Die ZE Nummer muss eine Zahl sein.") end end # zeAbDatum if !self.zeAbDatum.nil? then if self.zeAbDatum.to_s.match(/[0-9]{4}-[0-9][0-9]-[0-9][0-9]/).nil? then errors.add("", "Bitte geben sie das ZE Ab-Datum im Format: yyyy-mm-dd an.") end end # zeEndeDatum if !self.zeEndDatum.nil? then if self.zeEndDatum.to_s.match(/[0-9]{4}-[0-9][0-9]-[0-9][0-9]/).nil? then errors.add("", "Bitte geben sie das ZE End-Datum im Format: yyyy-mm-dd an.") end end # Betrag if !self.zeBetrag.nil? then if self.zeBetrag.to_s.match(/[0-9]+/).nil? then errors.add("", "Der Betrag muss eine Zahl sein.") else if self.zeBetrag < 0 then errors.add("", "Bitte geben Sie einen positiven Zahlenwert für den ZE Betrag an.") end end end # Laufzeit if !self.laufzeit.nil? then if self.laufzeit.to_s.match(/[0-9]+/).nil? then errors.add("", "Die Laufzeit muss eine Zahl sein.") else if self.laufzeit < 0 then errors.add("", "Bitte geben Sie einen positiven Zahlenwert für die Laufzeit an.") end end end # ZahlModus if !self.zahlModus.nil? then if self.zahlModus.to_s.match(/./).nil? then errors.add("", "Der Zahlmodus muss ein Buchstabe sein.") end end # Tilgungsrate if !self.tilgRate.nil? then if self.tilgRate.to_s.match(/[0-9]+/).nil? then errors.add("", "Die Tilgungsrate muss eine Zahl sein.") else if self.tilgRate < 0 then errors.add("", "Bitte geben Sie einen positiven Zahlenwert für die Tilgungsrate an.") end end end # Ansparrate if !self.ansparRate.nil? then if self.ansparRate.to_s.match(/[0-9]+/).nil? then errors.add("", "Die Ansparrate muss eine Zahl sein.") else if self.ansparRate < 0 then errors.add("", "Bitte geben Sie einen positiven Zahlenwert für die Ansparrate an.") end end end # Kdu Rate if !self.kduRate.nil? then if self.kduRate.to_s.match(/[0-9]+/).nil? then errors.add("", "Die kduRate muss eine Zahl sein.") else if self.kduRate < 0 then errors.add("", "Bitte geben Sie einen positiven Zahlenwert für die kduRate an.") end end end # Rdu Rate if !self.rduRate.nil? then if self.rduRate.to_s.match(/[0-9]+/).nil? then errors.add("", "Die rduRate muss eine Zahl sein.") else if self.rduRate < 0 then errors.add("", "Bitte geben Sie einen positiven Zahlenwert für die rduRate an.") end end end return errors end end
class Category < ActiveRecord::Base has_many :plans end
class AddAllowAddTimeEntryAtClosedIssueToggleToEasySettings < ActiveRecord::Migration def up EasySetting.create(:name => 'allow_log_time_to_closed_issue', :value => true) end def down EasySetting.where(:name => 'allow_log_time_to_closed_issue').destroy_all end end
require './fakearray' describe "each" do it "should act like the each method" do fakearray = FakeArray.new([1,2,3]) container = [] fakearray.each do |element| container << element + 1 end expect(container).to eq([2,3,4]) end end describe "first" do it "should return the first element in the array" do fakearray = FakeArray.new([1,2,3]) expect(fakearray.first).to eq(1) end end describe "[](index)" do it "should return whatever index is called" do fakearray = FakeArray.new([1,2,3]) expect(fakearray[2]).to eq(3) end end
class Message < ActiveRecord::Base belongs_to :recipient, :class_name => "User", :foreign_key => "recipient_id" belongs_to :messenger, :class_name => "User", :foreign_key => "messenger_id" validates_presence_of :username end
class AddSongToPrograms < ActiveRecord::Migration #actually it adds program_id column to songs table def change add_reference :songs, :program, index: true, foreign_key: true end end
#[4.10]繰り返し処理用の制御構造 #「[4.9.6]loopメソッド」の項ではループを脱出するために breakを使いました。 #Rubyには他にも繰り返し処理の動きを変えるための制御構造が用意されています。次がそのキーワードの一覧です。 ・break ・next ・redo #また、Kernelモジュールのthrowメソッドとcatchメソッドもbreakと同じような用途で使われます。 #----------------------------------------------------------------------------------------------------------------------------------------------------------------- #[4.10.1]break #breakを使うと、繰り返し処理を脱出することができます。 # EX eachメソッドとbreakを組み合わせるコード # shuffleメソッドで配列の要素をランダムに並び替える numbers = [1, 2, 3, 4, 5].shuffle numbers.each do |n| puts n # 5が出たら繰り返し処理を脱出 break if n == 5 end # ==> 1 # 3 # 5 #breakはeachメソッドだけでなく、while文やuntil文、for文でも使うことができます。 # EX 上記のbreakの使用例をwhile文を使って書き直したもの numbers = [1, 2, 3, 4, 5].shuffle i = 0 while i < numbers.size n = numbers[i] puts n break if n == 5 i += 1 end # ==> 4 # 1 # 5 #breakに引数を渡すと、while文やfor文の戻り値になります。引数を渡さない場合の戻り値はnilです。 # EX ret = while true break end puts ret # ==> nil ret = while true break 123 end puts ret # ==> 123 # 繰り返し処理が入れ子になっている場合は、一番内側の繰り返し処理を脱出します。 # EX fruits = ['apple', 'melon', 'orange'] numbers = [1, 2, 3] fruits.each do |fruit| # 配列の数字をランダムに入れ替え、3が出たらbreakする numbers.shuffle.each do |n| puts "#{fruit}, #{n}" # numbersのループは脱出するが、fruitsのループは継続する break if n == 3 end end # ==> apple, 1 # apple, 3 # melon, 3 # orange, 1 # orange, 2 # orange, 3 #------------------------------------------------------------------------------------------------------------------------------------------------------------------ #[4.10.2]throwとcatchを使った大域脱出 #先ほど「breakでは一番内側の繰り返し処理しか脱出できない」と説明しました。一気に外側のループまで脱出したい場合は、Krenelモジュールのthrowメソッドとcatchメソッドを使います。 catch タグ do # 繰り返し処理など throw タグ end #throw、catchというキーワードは、他の言語では例外処理に使われる場合がありますが、Rubyのthrow、catchは例外処理とは関係ありません。Rubyではraiseとrescueを例外処理で使います。 #throwメソッドとcatchメソッドは次のように使います。 # EX "orange"と3の組み合わせが出たらすべての繰り返し処理を脱出するコード fruits = ['apple', 'melon', 'orange'] numbers = [1, 2, 3] catch :done do fruits.shuffle.each do |fruit| numbers.shuffle.each do |n| puts "#{fruit}, #{n}" if fruit == 'orange' && n == 3 # 全ての繰り返し処理を脱出する throw :done end end end end # ==> orange, 2 # orange, 1 # orange, 3 #タグには通常シンボルを使います。 #throwとcatchのタグが一致しない場合はエラーが発生します。 # EX fruits = ['apple', 'melon', 'orange'] numbers = [1, 2, 3] catch :done do fruits.shuffle.each do |fruit| numbers.shuffle.each do |n| puts "#{fruit}, #{n}" if fruit == 'orange' && n == 3 # catchと一致しないタグをthrowする throw :foo end end end end # ==> /Users/ryotaono/Desktop/programming/cherry_book_two/tempCodeRunnerFile.rb:9:in `throw': uncaught throw :foo (UncaughtThrowError) # from /Users/ryotaono/Desktop/programming/cherry_book_two/tempCodeRunnerFile.rb:9:in `block (3 levels) in <main>' # from /Users/ryotaono/Desktop/programming/cherry_book_two/tempCodeRunnerFile.rb:5:in `each' # from /Users/ryotaono/Desktop/programming/cherry_book_two/tempCodeRunnerFile.rb:5:in `block (2 levels) in <main>' # from /Users/ryotaono/Desktop/programming/cherry_book_two/tempCodeRunnerFile.rb:4:in `each' # from /Users/ryotaono/Desktop/programming/cherry_book_two/tempCodeRunnerFile.rb:4:in `block in <main>' # from /Users/ryotaono/Desktop/programming/cherry_book_two/tempCodeRunnerFile.rb:3:in `catch' # from /Users/ryotaono/Desktop/programming/cherry_book_two/tempCodeRunnerFile.rb:3:in `<main>' # apple, 1 # apple, 3 # apple, 2 # orange, 3 #throwメソッドに第二引数を渡すとcatchメソッドの戻り値になります。 # EX ret = catch :done do throw :done end puts ret # ==> nil ret = catch :done do throw :done, 123 end puts ret # ==> 123 #上のコード例のように、catchとthrowは繰り返し処理と無関係に利用することができます。 #ただし、実際は繰り返し処理の大域脱出で使われることが多いと思います。 #----------------------------------------------------------------------------------------------------------------------------------------------------------------- #[4.10.3]繰り返し処理で使うbreakとreturnの違い #この項では繰り返し処理で使うbreakとreturnの違いについて説明します。ただし、挙動が複雑になるため極力使わない方がいい内容です。 #さて、「[2.6.1]メソッドの戻り値」ではreturnを使ってメソッドを途中で脱出する方法を説明しました。 # EX def greeting(country) # countryがnilならメッセージを返してメソッドを抜ける puts 'countyを入力してください' if country.nil? if country == 'japan' puts 'こんにちは' else puts 'hello' end end #繰り返し処理の中でもreturnは使えますが、breakとretrunは同じではありません。 #「break」を使いと「繰り返し処理からの脱出」になりますが、「return」を使うと「(繰り返し処理のみならず)メソッドから脱出」になります。 # EX 配列の中からランダムに1つの偶数を選び、その数を10倍して返すメソッド #breakの場合# def calc_with_break numbers = [1, 2, 3, 4, 5, 6] target = nil numbers.shuffle.each do |n| target = n # breakで脱出する break if n.even? end target * 10 end puts calc_with_break # ==> 60 #returnの場合# def calc_with_break numbers = [1, 2, 3, 4, 5, 6] target = nil numbers.shuffle.each do |n| target = n # returnで脱出する? return if n.even? end target * 10 end puts calc_with_break # ==> nil #returnが呼ばれた瞬間にメソッド全体を脱出してしまうために戻り値がnilになってしまいます。 #returnには引数を渡していないので、結果としてメソッドの戻り値はnilになります。 #また、returnの役割はあくまで「メソッドからの脱出」なのでreturnを呼び出した場所がメソッドの内部でなけらばエラーになります。 # EX [1, 2, 3].each do |n| puts n return end # ==> 1 # Local JumpError: unexpected return #このように、breakとreturnは「脱出する」という目的は同じでも、「繰り返し処理からの脱出」と「メソッドからの脱出」という大きな違いがあるため、用途に応じて適切に使い分ける必要があります。 #ですが、冒頭でも述べたように、挙動が複雑になるので、積極的に活用するテクニックではありません。 #----------------------------------------------------------------------------------------------------------------------------------------------------------------- #[4.10.4]next #繰り返し処理を途中で中断し、次の繰り返し処理に進める場合はnextを使います。 # EX 偶数であれば処理を中断して次の繰り返し処理に進むコード numbers = [1, 2, 3, 4, 5] numbers.each do |n| # 偶数であれば中断して次の繰り返し処理に進む next if n.even? puts n end # ==> 1 # 3 # 5 #eachメソッドの中だけでなく、while文やuntil文、for文の中でも使える点や入れ子になった繰り返し処理では一番内側のループだけが中断の対象になる点がbreakと同じです。 # EX numbers = [1, 2, 3, 4, 5] i = 0 while i < numbers.size n = numbers[i] i += 1 # while文の中でnextを使う next if n.even? puts n end # ==> 1 # 3 # 5 fruits = ['apple', 'melon', 'orange'] numbers = [1, 2, 3] fruits.each do |fruit| numbers.each do |n| # 繰り返し処理が入れ子になっている場合は、一番内側のループだけが中断される next if n.even? puts "#{fruit}, #{n}" end end # ==> apple, 1 # apple, 3 # melon, 1 # melon, 3 # orange, 1 # orange, 3 #----------------------------------------------------------------------------------------------------------------------------------------------------------------- #[4.10.5]redo #繰り返し処理をやり直したい場合はredoを使います。ここでいう「やり直し」は初回からやり直すのではなく、その回の繰り返し処理の最初に戻る、という意味です。 # EX 3つの野菜に対して「好きですか?」と問いかけ、ランダムに「はい」または「いいえ」を答えるプログラム。「はい」と答えるまで何度でも同じ質問が続く foods = ['ピーマン', 'トマト', 'セロリ'] foods.each do |food| print "#{food}は好きですか? => " # sampleは配列からランダムに1つの要素を取得するメソッド answer = ['はい', 'いいえ'].sample puts answer # はいと答えなければもう一度聞き直す redo unless answer == 'はい' end # ==> ピーマンは好きですか? => いいえ # ピーマンは好きですか? => いいえ # ピーマンは好きですか? => いいえ # ピーマンは好きですか? => はい # トマトは好きですか? => はい # セロリは好きですか? => いいえ # セロリは好きですか? => はい #redoを使う場合、状況によっては永遠にやり直しが続くかもしれません。そうすると意図せず無限ループを作ってしまいます。なので、回数制限を検討しましょう! # EX 回数制限を設ける場合 foods = ['ピーマン', 'トマト', 'セロリ'] count = 0 foods.each do |food| print "#{food}は好きですか? => " # わざと「いいえ」しか答えないようにする answer = 'いいえ' puts answer count += 1 # やり直しは2回までにする redo if answer != 'はい' && count < 2 # カウントをリセットする count = 0 end # ==> ピーマンは好きですか? => いいえ # ピーマンは好きですか? => いいえ # トマトは好きですか? => いいえ # トマトは好きですか? => いいえ # セロリは好きですか? => いいえ # セロリは好きですか? => いいえ #------------------------------------------------------------------------------------------------------------------------------------------------------------------
class Admissions::GlossaryImportsController < Admissions::AdmissionsController load_resource find_by: :permalink authorize_resource def new @glossary_import = GlossaryImport.new end def create @glossary_import = GlossaryImport.new(params[:glossary_import]) if @glossary_import.save @glossary_import.process_import redirect_to admin_glossary_terms_path, notice: "Yay. Imported!" else render :new end end end