text
stringlengths
10
2.61M
# frozen_string_literal: true require 'stannum/rspec/match_errors' require 'support/contracts/manufacturer_contract' require 'support/entities/factory' require 'support/entities/gadget' require 'support/entities/manufacturer' # @note Integration spec for Stannum::Contract. RSpec.describe Spec::ManufacturerContract do include Stannum::RSpec::Matchers subject(:contract) { described_class.new } describe '.new' do it { expect(described_class).to be_constructible.with(0).arguments } end describe '#does_not_match?' do let(:status) { contract.does_not_match?(actual) } describe 'with an object that does not match any constraints' do let(:actual) { nil } it { expect(status).to be true } end describe 'with an object that matches some of the constraints' do let(:actual) do Spec::Manufacturer.new( name: 'Gadget Co.', factory: Spec::Factory.new ) end it { expect(status).to be false } end describe 'with an object that matches all of the constraints' do let(:actual) do Spec::Manufacturer.new( name: 'Gadget Co.', factory: Spec::Factory.new( gadget: Spec::Gadget.new( name: 'Ambrosia Software Licenses' ) ) ) end it { expect(status).to be false } end end describe '#errors_for' do let(:errors) { contract.errors_for(actual).with_messages } describe 'with an object that does not match any constraints' do let(:actual) { nil } let(:expected_errors) do [ { data: {}, message: 'is not a manufacturer', path: [], type: described_class::TYPE } ] end it { expect(errors).to match_errors(expected_errors) } end describe 'with an object that matches the sanity constraints' do let(:actual) { Spec::Manufacturer.new } let(:expected_errors) do [ { data: {}, message: 'is nil or empty', path: %i[registered_name], type: Stannum::Constraints::Presence::TYPE }, { data: {}, message: 'is nil or empty', path: %i[factory gadget name], type: Stannum::Constraints::Presence::TYPE } ] end it { expect(errors).to match_errors(expected_errors) } end describe 'with an object that matches some of the constraints' do let(:actual) do Spec::Manufacturer.new( name: 'Gadget Co.', factory: Spec::Factory.new ) end let(:expected_errors) do [ { data: {}, message: 'is nil or empty', path: %i[factory gadget name], type: Stannum::Constraints::Presence::TYPE } ] end it { expect(errors).to match_errors(expected_errors) } end describe 'with an object that matches all of the constraints' do let(:actual) do Spec::Manufacturer.new( name: 'Gadget Co.', factory: Spec::Factory.new( gadget: Spec::Gadget.new( name: 'Ambrosia Software Licenses' ) ) ) end it { expect(errors).to be == [] } end end describe '#match' do let(:status) { Array(contract.match(actual))[0] } let(:errors) { Array(contract.match(actual))[1].with_messages } describe 'with an object that does not match any constraints' do let(:actual) { nil } let(:expected_errors) do [ { data: {}, message: 'is not a manufacturer', path: [], type: described_class::TYPE } ] end it { expect(errors).to match_errors(expected_errors) } it { expect(status).to be false } end describe 'with an object that matches the sanity constraints' do let(:actual) { Spec::Manufacturer.new } let(:expected_errors) do [ { data: {}, message: 'is nil or empty', path: %i[registered_name], type: Stannum::Constraints::Presence::TYPE }, { data: {}, message: 'is nil or empty', path: %i[factory gadget name], type: Stannum::Constraints::Presence::TYPE } ] end it { expect(errors).to match_errors(expected_errors) } it { expect(status).to be false } end describe 'with an object that matches some of the constraints' do let(:actual) do Spec::Manufacturer.new( name: 'Gadget Co.', factory: Spec::Factory.new ) end let(:expected_errors) do [ { data: {}, message: 'is nil or empty', path: %i[factory gadget name], type: Stannum::Constraints::Presence::TYPE } ] end it { expect(errors).to match_errors(expected_errors) } it { expect(status).to be false } end describe 'with an object that matches all of the constraints' do let(:actual) do Spec::Manufacturer.new( name: 'Gadget Co.', factory: Spec::Factory.new( gadget: Spec::Gadget.new( name: 'Ambrosia Software Licenses' ) ) ) end it { expect(errors).to be == [] } it { expect(status).to be true } end end describe '#matches?' do let(:status) { contract.matches?(actual) } describe 'with an object that does not match any constraints' do let(:actual) { nil } it { expect(status).to be false } end describe 'with an object that matches some of the constraints' do let(:actual) do Spec::Manufacturer.new( name: 'Gadget Co.', factory: Spec::Factory.new ) end it { expect(status).to be false } end describe 'with an object that matches all of the constraints' do let(:actual) do Spec::Manufacturer.new( name: 'Gadget Co.', factory: Spec::Factory.new( gadget: Spec::Gadget.new( name: 'Ambrosia Software Licenses' ) ) ) end it { expect(status).to be true } end end describe '#negated_errors_for' do let(:errors) { contract.negated_errors_for(actual).with_messages } describe 'with an object that does not match any constraints' do let(:actual) { nil } it { expect(errors).to be == [] } end describe 'with an object that matches some of the constraints' do let(:actual) do Spec::Manufacturer.new( name: 'Gadget Co.', factory: Spec::Factory.new ) end let(:expected_errors) do [ { data: {}, message: 'is a manufacturer', path: [], type: described_class::NEGATED_TYPE }, { data: {}, message: 'is not nil or empty', path: %i[registered_name], type: Stannum::Constraints::Presence::NEGATED_TYPE } ] end it { expect(errors).to match_errors(expected_errors) } end describe 'with an object that matches all of the constraints' do let(:actual) do Spec::Manufacturer.new( name: 'Gadget Co.', factory: Spec::Factory.new( gadget: Spec::Gadget.new( name: 'Ambrosia Software Licenses' ) ) ) end let(:expected_errors) do [ { data: {}, message: 'is a manufacturer', path: [], type: described_class::NEGATED_TYPE }, { data: {}, message: 'is not nil or empty', path: %i[registered_name], type: Stannum::Constraints::Presence::NEGATED_TYPE }, { data: {}, message: 'is not nil or empty', path: %i[factory gadget name], type: Stannum::Constraints::Presence::NEGATED_TYPE } ] end it { expect(errors).to match_errors(expected_errors) } end end describe '#negated_match' do let(:status) { Array(contract.negated_match(actual))[0] } let(:errors) { Array(contract.negated_match(actual))[1].with_messages } describe 'with an object that does not match any constraints' do let(:actual) { nil } it { expect(errors).to be == [] } it { expect(status).to be true } end describe 'with an object that matches some of the constraints' do let(:actual) do Spec::Manufacturer.new( name: 'Gadget Co.', factory: Spec::Factory.new ) end let(:expected_errors) do [ { data: {}, message: 'is a manufacturer', path: [], type: described_class::NEGATED_TYPE }, { data: {}, message: 'is not nil or empty', path: %i[registered_name], type: Stannum::Constraints::Presence::NEGATED_TYPE } ] end it { expect(errors).to match_errors(expected_errors) } it { expect(status).to be false } end describe 'with an object that matches all of the constraints' do let(:actual) do Spec::Manufacturer.new( name: 'Gadget Co.', factory: Spec::Factory.new( gadget: Spec::Gadget.new( name: 'Ambrosia Software Licenses' ) ) ) end let(:expected_errors) do [ { data: {}, message: 'is a manufacturer', path: [], type: described_class::NEGATED_TYPE }, { data: {}, message: 'is not nil or empty', path: %i[registered_name], type: Stannum::Constraints::Presence::NEGATED_TYPE }, { data: {}, message: 'is not nil or empty', path: %i[factory gadget name], type: Stannum::Constraints::Presence::NEGATED_TYPE } ] end it { expect(errors).to match_errors(expected_errors) } it { expect(status).to be false } end end end
class BusinessesController < ApplicationController skip_before_filter :authorize, :only => [:index, :search, :show, :locations, :business_names, :send_to_phone] before_filter :find_business_by_id, :only => [:show, :edit, :send_to_phone, :update, :destroy, :add_favorite, :remove_favorite ] def index @businesses = Business.paginate :page => params[:page], :order => 'name ASC' @title = "Listing Businesses" end def show @title = "Business Details - #{@business.name}" #Get business map @map = @business.get_map p @map end def new @title = "Add Business" @business = Business.new end def edit @title = "Edit Business" end def send_to_phone @business.send_sms(params[:number]) respond_to do |format| format.js end end def create @business = Business.new(params[:business]) @business.owner = @member.full_name @business.business_relations.build(:member_id => @member.id,:status => RELATION[:OWNED]) if @business.save flash_redirect("message","Business was successfully added",businesses_path) else flash_render("notice", "Unable to save business", "new") end end def update #### Allow only if the user owns the business if is_owner(@business) if @business.update_attributes(params[:business]) flash_redirect("message","Business was successfully added",business_path(params[:id])) else render :action => :edit end else flash_redirect("notice", "Nice try", member_path(@member.id)) end end def destroy if is_owner(@business) if @business.destroy flash_redirect("message","Business was successfully deleted",member_path(@member.id)) else redirect_to business_path(@business.id) end else flash_redirect("notice","You can delete your own business",member_path(@member.id)) end end def add_favorite #Adding same business twice in the list is not allowed if is_favorite(@business) flash_redirect("notice", "Business already in your list", session[:return_to]) else if @business.business_relations.create(:member_id => @member.id, :status => RELATION[:FAVORITE]) respond_to do |format| format.js end else flash_redirect("notice","Unable to add business to your list. Try again.",session[:return_to]) end end end def remove_favorite #Cannot remove business if it is not in favorite unless is_favorite(@business) flash_redirect("notice","Business not in your list",session[:return_to]) else if BusinessRelation.destroy(@business_relation.id) respond_to do |format| format.js end else flash_redirect("notice","Unable to remove from list. Please try again.",session[:return_to]) end end end private def find_business_by_id @business = Business.find_by_id(params[:id]) end end
class Grid def initialize end x_axys = %w{a b c d e f g h i j} y_axys = (1..10).to_a.map {|y| y.to_s} x_axys.each do |x| y_axys.each do |y| define_method((x+y).to_sym) do if instance_variable_get("@#{x + y}") instance_variable_get("@#{x + y}") else instance_variable_set("@#{x + y}", Cell.new) end end end end end
class FacebookerQueueWorker def initialize # Load the facebooker_parser_patch to disable post-processing # TODO: Re-enable facebooker's parsing and allow the developer to send a string of Ruby to evaluate against the result # Unfortunately, this will involve some reworking of Facebooker::BatchRun # because it relies on the in-memory record of the batch call which isn't available at queue processing time require 'facebooker_parser_patch' end def process_next! if job = queue_service_adapter.get facebooker_session.secure_with!(job[:session_key], job[:uid], job[:expires]) facebooker_session.post_without_async(job[:method], job[:params], job[:use_session]) end end protected def facebooker_session @session ||= Facebooker::CanvasSession.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY']) end def queue_service_adapter @adapter ||= facebooker_session.queue_service_adapter end end
class Like < ActiveRecord::Base belongs_to :user belongs_to :product, counter_cache: true validates :user_id, uniqueness: { scope: :product_id } after_create :notify_product_owner def as_json options={} {} end private def notify_product_owner product.user.notifications.create! from_id: user.id, code: 'liked', product_id: product_id end end
class QuestionsTrial < ActiveRecord::Base belongs_to :question belongs_to :trial end
require File.dirname(__FILE__) + '/../../spec_helper' ruby_version_is ""..."1.9" do require 'ping' describe "Ping.pingecho" do it "responds to pingecho method" do Ping.should respond_to(:pingecho) end it "pings a host using the correct number of arguments" do Ping.pingecho('127.0.0.1', 10, 7).should be_true Ping.pingecho('127.0.0.1', 10).should be_true Ping.pingecho('127.0.0.1').should be_true end it "raises ArgumentError for wrong number of arguments" do lambda { Ping.pingecho }.should raise_error(ArgumentError) lambda { Ping.pingecho 'one', 'two', 'three', 'four' }.should raise_error(ArgumentError) end it "returns false for invalid parameters" do Ping.pingecho('127.0.0.1', 5, 'invalid port').should be_false Ping.pingecho('127.0.0.1', 'invalid timeout').should be_false Ping.pingecho(123).should be_false end end end
require 'rails_helper' describe "products/index" do before(:each) { assign(:products, create_list(:product, 2)) } it "renders a list of products" do render assert_select "tr>td", text: "Product title".to_s, count: 2 assert_select "tr>td", text: "Product description".to_s, count: 2 end end
require 'rails_helper' feature "adds a character" do # Acceptance Criteria: # * I can access a form to add a character on a TV show's page # * I must specify the character's name and the actor's name # * I can optionally provide a description # * If I do not provide the required information, I receive an error message # * If the character already exists in the database, I receive an error message scenario "visit adds character page" do show = TelevisionShow.create(title: 'Game of Thrones', network: 'HBO', years: 'July 2012-', synopsis: 'Best show evar!') visit television_show_path(show) save_and_open_page fill_in 'Character Name', with: "Don Cornelius" fill_in 'Actor Name', with: "Chris Rock" click_on 'Submit' expect(page).to have_content 'Game of Thrones' expect(page).to have_content 'HBO' expect(page).to have_content 'Don Cornelius' expect(page).to have_content 'Chris Rock' expect(page).to have_content 'Success' expect(page).to have_content 'July 2012-' expect(page).to have_content 'Best show evar!' end scenario "visit adds character page" do show = TelevisionShow.create(title: 'Game of Thrones', network: 'HBO') visit television_show_path(show) save_and_open_page click_on 'Submit' expect(page).to_not have_content 'Success' expect(page).to have_content "can't be blank" end scenario "visit adds character page" do show = TelevisionShow.create(title: 'Game of Thrones', network: 'HBO') visit television_show_path(show) save_and_open_page fill_in 'Character Name', with: "Don Cornelius" fill_in 'Actor Name', with: "Chris Rock" fill_in 'Description', with: "Crack" click_on 'Submit' expect(page).to have_content 'Game of Thrones' expect(page).to have_content 'HBO' expect(page).to have_content 'Don Cornelius' expect(page).to have_content 'Chris Rock' expect(page).to have_content 'Crack' end end
class RenameBoleto < ActiveRecord::Migration def self.up rename_table :spree_boletos, :spree_boleto_docs end def self.down rename_table :spree_boleto_docs, :spree_boletos end end
class CreateRelatedResources < ActiveRecord::Migration[5.2] def up create_table :related_resources do |t| t.integer :resources_category_id t.string :title t.text :content t.belongs_to :resources_category, index: true t.string :url t.timestamps end end def down drop_table :related_resources end end
#!/usr/bin/env ruby require 'json' require_relative 'anagram_client' require 'test/unit' # capture ARGV before TestUnit Autorunner clobbers it class TestCases < Test::Unit::TestCase # runs before each test def setup @client = AnagramClient.new(ARGV) # add words to the dictionary @client.post('/words.json', nil, {"words" => ["read", "dear", "dare", "DARE"] }) rescue nil end # runs after each test def teardown # delete everything @client.delete('/words.json') rescue nil end def test_adding_words res = @client.post('/words.json', nil, {"words" => ["read", "dear", "dare", "DARE"] }) assert_equal('201', res.code, "Unexpected response code") end def test_fetching_anagrams # fetch anagrams res = @client.get('/anagrams/read.json') assert_equal('200', res.code, "Unexpected response code") assert_not_nil(res.body) body = JSON.parse(res.body) assert_not_nil(body['anagrams']) expected_anagrams = %w(DARE dare dear) assert_equal(expected_anagrams, body['anagrams'].sort) end def test_fetching_anagrams_with_limit # fetch anagrams with limit res = @client.get('/anagrams/read.json', 'limit=1') assert_equal('200', res.code, "Unexpected response code") body = JSON.parse(res.body) assert_equal(1, body['anagrams'].size) end def test_fetch_for_word_with_no_anagrams # fetch anagrams with limit res = @client.get('/anagrams/zyxwv.json') assert_equal('200', res.code, "Unexpected response code") body = JSON.parse(res.body) assert_equal(0, body['anagrams'].size) end def test_deleting_all_words res = @client.delete('/words.json') assert_equal('204', res.code, "Unexpected response code") # should fetch an empty body res = @client.get('/anagrams/read.json') assert_equal('200', res.code, "Unexpected response code") body = JSON.parse(res.body) assert_equal(0, body['anagrams'].size) end def test_deleting_all_words_multiple_times 3.times do res = @client.delete('/words.json') assert_equal('204', res.code, "Unexpected response code") end # should fetch an empty body res = @client.get('/anagrams/read.json', 'limit=1') assert_equal('200', res.code, "Unexpected response code") body = JSON.parse(res.body) assert_equal(0, body['anagrams'].size) end def test_deleting_single_word # delete the word res = @client.delete('/words/dear.json') assert_equal('200', res.code, "Unexpected response code") # expect it not to show up in results res = @client.get('/anagrams/read.json') assert_equal('200', res.code, "Unexpected response code") body = JSON.parse(res.body) assert_equal(['DARE', 'dare'], body['anagrams']) end def test_deleting_single_word_and_anagrams # delete the anagrams res = @client.delete('/anagrams/dear.json') assert_equal('200', res.code, "Unexpected response code") # expect them not to show up in results res = @client.get('/anagrams/read.json') assert_equal('200', res.code, "Unexpected response code") body = JSON.parse(res.body) assert_equal([], body['anagrams']) end def test_proper_noun_exclusion res = @client.get('/anagrams/read.json', 'exclude_proper_nouns=true') assert_equal('200', res.code, "Unexpected response code") body = JSON.parse(res.body) assert_equal(2, body['anagrams'].size) end def test_proper_noun_inclusion res = @client.get('/anagrams/read.json') assert_equal('200', res.code, "Unexpected response code") body = JSON.parse(res.body) assert_equal(3, body['anagrams'].size) end def test_word_list_are_anagrams res = @client.post('/word_list.json', nil, {"words" => ["read", "dear", "dare", "DARE"] }) body = JSON.parse(res.body) assert_equal(true, body['anagrams']) end def test_word_list_arent_anagrams res = @client.post('/word_list.json', nil, {"words" => ["read", "dear", "dare", "DAREE"] }) body = JSON.parse(res.body) assert_equal(false, body['anagrams']) end end
class Category < ApplicationRecord has_many :category_products has_many :products, through: :category_products validates :name, presence: true, uniqueness: true end
module Escpos module ImageProcessors class Base attr_reader :image, :options def initialize(image_or_path, options = {}) @options = options assert_options! end # Require correct dimensions if auto resizing is not enabled def assert_dimensions_multiple_of_8! unless options.fetch(:extent, false) unless image.width % 8 == 0 && image.height % 8 == 0 raise DimensionsMustBeMultipleOf8 end end end end end end
# frozen_string_literal: true class ApplicationController < ActionController::Base before_action :configure_permitted_parameters, if: :devise_controller? before_action :set_locale def set_locale I18n.locale = params[:locale] || extract_locale_from_header || I18n.default_locale end def default_url_options {locale: I18n.locale} end protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:name]) devise_parameter_sanitizer.permit(:account_update, keys: [:name]) end private ## # Extract the preferred language from the browser request header def extract_locale_from_header if request.env["HTTP_ACCEPT_LANGUAGE"] request.env["HTTP_ACCEPT_LANGUAGE"].scan(/^[a-z]{2}/).first end end end
# frozen_string_literal: true class SearchResult < SitePrism::Section element :title, 'span.title' element :description, 'span.description' def cell_value=(value) execute_script( "document.getElementById('first_search_result').children[0].innerHTML = '#{value}'" ) end def cell_value evaluate_script( "document.getElementById('first_search_result').children[0].innerHTML" ) end end
# frozen_string_literal: true ADVANCED_SEARCH_TESTING_1 = { "id": "1", "abstract_tesim": ["Incomplete at beginning and end.", "The tale of Sindbād and his princely pupil, in colloquial Arabic."], "creator_ssim": ["Me and Frederick"], "creator_tesim": ["Me and Frederick"], "alternativeTitle_tesim": ["Book of Sindbad.", "Sindbad the sailor"], "child_oids_ssim": ["11", "12", "13", "14", "15"], "collectionId_ssim": ["1"], "collectionId_tesim": ["1"], "contents_tesim": ["A few leaves supplied in a later hand.", "Fair modern (18th century?) naskhī, in red and black.", "Islamic binding, paper covered, with flap."], "date_ssim": ["[17--?]"], "dateStructured_ssim": ["1456", "1459"], "dependentUris_ssim": ["/ladybird/oid/11607445"], "description_tesim": ["A few leaves supplied in a later hand.", "Fair modern (18th century?) naskhī, in red and black.", "Islamic binding, paper covered, with flap."], "digitization_note_tesi": "Digitized from microfilm", "extent_ssim": ["81 leaves ; 20.5 x 14.5 cm."], "extentOfDigitization_ssim": ["Complete work digitized."], "format_tesim": ["mixed material"], "fulltext_tesim": ["fulltext one", "fulltext two"], "callNumber_ssim": ["Landberg MSS 596"], "callNumber_tesim": ["Landberg MSS 596"], "imageCount_isi": 85, "indexedBy_tsim": ["Brockelmann, S I, pp. 237, 239, 252."], "oid_ssi": "11607445", "orbisBibId_ssi": "3832098", "public_bsi": true, "recordType_ssi": "oid", "preferredCitation_tesim": ["Brockelmann, S I, pp. 237, 239, 252."], "repository_ssim": ["Beinecke Library"], "rights_ssim": ["The use of this image may be subject to the copyright law of the United States (Title 17, United States Code) or to site license or other rights management terms and conditions. The person using the image is liable for any infringement."], "rights_tesim": ["The use of this image may be subject to the copyright law of the United States (Title 17, United States Code) or to site license or other rights management terms and conditions. The person using the image is liable for any infringement."], "source_ssim": ["ladybird"], "subjectEra_ssim": ["Islamic binding"], "subjectTitle_tsim": ["Islamic binding"], "subjectTitleDisplay_tsim": ["Arabic language and literature--Belles lettres", "Islamic binding"], "subjectName_ssim": ["Computer Science"], "subjectName_tesim": ["Computer Science"], "subjectTopic_tesim": ["Arabic language and literature--Belles lettres", "Islamic binding"], "subjectTopic_ssim": ["Arabic language and literature--Belles lettres", "Islamic binding"], "title_tesim": ["Record 1"], "title_ssim": ["Record 1"], "visibility_ssi": "Public", "year_isim": [1456, 1457, 1458, 1459] }.freeze ADVANCED_SEARCH_TESTING_2 = { "id": "2", "abstract_tesim": ["Manuscript on parchment of Jacopo Zeno, Vita Caroli Zeni. With a dedicatory preface to Pope Pius II. This manuscript is of special importance because it contains the complete work."], "creator_ssim": ["Zeno, Jacopo, 1417-1481"], "creator_tesim": ["Zeno, Jacopo, 1417-1481"], "collectionId_ssim": ["1"], "collectionId_tesim": ["1"], "contents_tesim": ["Binding: Eighteenth century. Brownish-red goatskin, gold-tooled; pale green and gold, Dutch gilt paper boards.", "On f. 1r, a foliage border which includes hares, stork, vase, and arms of the Piccolomini family (argent, a cross azur with 5 crescents or; surmounted by keys in saltire argent and a papal tiara; supported by a pair of angels). Eleven elaborate initials, 11- to 7-line, in gold, red, blue, and green entwined with foliage. The style of decoration is decidedly Roman.", "Purchased by William Loring Andrews who presented it to Yale in 1894.", "Script: Written in humanistic script by Franciscus de Tianis of Pistoia."], "contributor_tsim": ["Zeno, Carlo,--1334-1418", "Zeno, Jacopo,--1417-1481"], "contributorDisplay_tsim": ["Zeno, Carlo,--1334-1418", "Zeno, Jacopo,--1417-1481"], "creatorDisplay_tsim": ["Zeno, Jacopo, 1417-1481"], "child_oids_ssim": ["20", "21", "23", "24"], "dateStructured_ssim": ["1458"], "dependentUris_ssim": ["/ladybird/oid/11684565"], "description_tesim": ["Binding: Eighteenth century. Brownish-red goatskin, gold-tooled; pale green and gold, Dutch gilt paper boards.", "On f. 1r, a foliage border which includes hares, stork, vase, and arms of the Piccolomini family (argent, a cross azur with 5 crescents or; surmounted by keys in saltire argent and a papal tiara; supported by a pair of angels). Eleven elaborate initials, 11- to 7-line, in gold, red, blue, and green entwined with foliage. The style of decoration is decidedly Roman.", "Purchased by William Loring Andrews who presented it to Yale in 1894.", "Script: Written in humanistic script by Franciscus de Tianis of Pistoia."], "extent_ssim": ["ff. ii + 192 + i : parchment ; 271 x 177 (177 x 106) mm."], "extentOfDigitization_ssim": ["Complete work digitized."], "fulltext_tesim": ["fulltext four", "fulltext five"], "genre_tesim": ["Decorated initials", "Manuscripts"], "callNumber_ssim": ["Beinecke MS 2"], "callNumber_tesim": ["Beinecke MS 2"], "imageCount_isi": 398, "indexedBy_tsim": ["Jacopo Zeno, Vita Caroli Zeni. General Collection, Beinecke Rare Book and Manuscript Library, Yale University.", "Shailor, B. Catalogue of Medieval and Renaissance Manuscripts in the Beinecke Rare Book and Manuscript Library, MS 2."], "language_ssim": ["Latin"], "oid_ssi": "11684565", "orbisBibId_ssi": "9801995", "public_bsi": true, "creationPlace_ssim": ["Italy,"], "creationPlace_tesim": ["Italy,"], "recordType_ssi": "oid", "preferredCitation_tesim": ["Jacopo Zeno, Vita Caroli Zeni. General Collection, Beinecke Rare Book and Manuscript Library, Yale University.", "Shailor, B. Catalogue of Medieval and Renaissance Manuscripts in the Beinecke Rare Book and Manuscript Library, MS 2."], "repository_ssim": ["Beinecke Library"], "resourceType_ssim": ["Archives or Manuscripts"], "resourceType_tesim": ["Archives or Manuscripts"], "rights_ssim": ["The use of this image may be subject to the copyright law of the United States (Title 17, United States Code) or to site license or other rights management terms and conditions. The person using the image is liable for any infringement."], "rights_tesim": ["The use of this image may be subject to the copyright law of the United States (Title 17, United States Code) or to site license or other rights management terms and conditions. The person using the image is liable for any infringement."], "source_ssim": ["ladybird"], "subjectEra_ssim": ["Medieval and Renaissance Manuscripts in Beinecke Library"], "subjectTitle_tsim": ["Medieval and Renaissance Manuscripts in Beinecke Library"], "subjectTitleDisplay_tsim": ["Biography--Middle Ages, 500-1500", "Crusades--13th-15th centuries", "Illumination of books and manuscripts, Medieval", "Manuscripts, Medieval--Connecticut--New Haven", "Medieval and Renaissance Manuscripts in Beinecke Library"], "subjectName_ssim": ["Zeno, Carlo,--1334-1418", "Zeno, Jacopo,--1417-1481"], "subjectName_tesim": ["Zeno, Carlo,--1334-1418", "Zeno, Jacopo,--1417-1481"], "subjectTopic_tesim": ["Biography--Middle Ages, 500-1500", "Crusades--13th-15th centuries", "Illumination of books and manuscripts, Medieval", "Manuscripts, Medieval--Connecticut--New Haven", "Medieval and Renaissance Manuscripts in Beinecke Library"], "subjectTopic_ssim": ["Biography--Middle Ages, 500-1500", "Crusades--13th-15th centuries", "Illumination of books and manuscripts, Medieval", "Manuscripts, Medieval--Connecticut--New Haven", "Medieval and Renaissance Manuscripts in Beinecke Library"], "title_tesim": ["Record 2"], "url_suppl_ssim": ["https://pre1600ms.beinecke.library.yale.edu/docs/pre1600.ms002.htm"], "visibility_ssi": "Public", "year_isim": [1458] }.freeze
class JobOffering < ApplicationRecord belongs_to :company belongs_to :job end
def get_letter_grade(integer) case integer when 90..100 then 'A' when 80..89 then 'B' when 70..79 then 'C' when 60..69 then 'D' else 'F' end end def shortest_string(array) array.sort_by(&:length).first end ### Don't touch anything below this line ### p "Fetch Letter Grade: You should have 2 trues" p get_letter_grade(89) == "B" p get_letter_grade(73) == "C" p p "Shortest String: You should have 3 trues" p shortest_string(["touch","this", "car"]) == "car" p shortest_string([]) == nil p shortest_string(["can", "a", "solve", "Find", "solution"]) == "a"
require 'rails_helper' RSpec.describe Game::StartSingle, type: :service do subject(:service) { described_class } it "creates a single game for the user" do user = double(User) allow(user).to receive(:can_create_game?).and_return(true) expect(user).to receive(:create_single_game!) service.call(user) end context "while in beta" do it "doesn't let the user create more than 10 games" do user = double(User) allow(user).to receive(:can_create_game?).and_return(false) expect { service.call(user) }.to raise_exception(Givdo::Exceptions::GamesQuotaExeeded) end end end
require 'CSV' require 'bigdecimal' require 'time' class InvoiceItem attr_reader :id, :item_id, :invoice_id, :unit_price, :quantity, :created_at, :updated_at def initialize(item_data, repo) @id = item_data[:id].to_i @item_id = item_data[:item_id].to_i @invoice_id = item_data[:invoice_id].to_i @unit_price = BigDecimal(item_data[:unit_price]) / 100 @quantity = item_data[:quantity].to_i @created_at = Time.parse(item_data[:created_at].to_s) @updated_at = Time.parse(item_data[:updated_at]) @repo = repo end def unit_price_to_dollars @unit_price.to_f.round(2) end def change_quantity(quantity) @quantity = quantity.to_i end def change_unit_price(unit_price) @unit_price = unit_price end def update_time @updated_at = Time.now end end
class TransactionProduct < ActiveRecord::Base belongs_to :product belongs_to :order, class_name: "Transaction" end
class AddForeignIdColumnToDislikes < ActiveRecord::Migration[5.0] def change add_reference :dislikes, :dislikers, foreign_key: true end end
class MoneyRenderer < ResourceRenderer::AttributeRenderer::Base def display(attribute_name, label, options = {}, &block) options.reverse_merge!(format: :long) format = options.delete(:format) money = value_for_attribute(attribute_name) "#{h.humanized_money(money)} #{money.currency}".html_safe end end
require 'formula' class Exenv < Formula homepage 'https://github.com/mururu/exenv' url 'https://github.com/mururu/exenv/archive/v0.1.0.tar.gz' sha1 '0984b6c260e42d750c8df68c8f48c19a90dc5db9' head 'https://github.com/mururu/exenv.git' def install inreplace 'libexec/exenv', '/usr/local', HOMEBREW_PREFIX prefix.install Dir['*'] end def caveats; <<-EOS.undent To use Homebrew's directories rather than ~/.exenv add to your profile: export EXENV_ROOT=#{var}/exenv To enable shims and autocompletion add to your profile: if which exenv > /dev/null; then eval "$(exenv init -)"; fi EOS end end
module MigrationComments::ActiveRecord::ConnectionAdapters module Table def change_comment(column_name, comment_text) @base.set_column_comment(_table_name, column_name, comment_text) end def change_table_comment(comment_text) @base.set_table_comment(_table_name, comment_text) end alias comment :change_table_comment private def _table_name if ::ActiveRecord::VERSION::MAJOR >= 4 && ::ActiveRecord::VERSION::MINOR >= 2 name else @table_name end end end end
RSpec.shared_context "tag", shared_context: :metadata do let(:tag_json) { file_fixture("tag.json").read } let(:tags_json) { file_fixture("tags.json").read } let(:tag) { JSON.parse(tag_json) } end
require 'rails_helper' RSpec.describe Project, type: :model do before(:all) do @user = User.first || create(:user) @category = Category.first || create(:category, user_id: @user.id) @project = Project.first || create(:project, user_id: @user.id, category_id: @category.id) end it "is valid with valid attributes" do project = build(:project, user_id: @user.id, category_id: @category.id) expect(project.valid?).to be_truthy end it "is nil name attribute" do project = build(:project, name: nil, user_id: @user.id, category_id: @category.id) expect(project.valid?).to be_falsey end it "is nil category attribute" do project = build(:project, user_id: @user.id) expect(project.valid?).to be_falsey end it "is nil user attribute" do project = build(:project, category_id: @category.id) expect(project.valid?).to be_falsey end it "has a unique name" do project = build(:project, name: @project.name, user_id: @user.id, category_id: @category.id) expect(project.valid?).to be_falsey end end
class EasySchedulerTaskInfo < ActiveRecord::Base self.table_name = 'easy_scheduler_tasks' STATUS_INITIALIZED = 1 STATUS_PLANNED = 2 STATUS_RUNNING = 3 STATUS_ENDED_FAILED = 4 STATUS_ENDED_OK = 5 def self.find_unfinished(page_url_ident = nil) find(:first, :conditions => {:page_url_ident => page_url_ident, :status => [STATUS_INITIALIZED, STATUS_PLANNED, STATUS_RUNNING]}) end end
class Band < ActiveRecord::Base has_many :venues, through: :shows validates(:name, {:presence => true}) validates(:genre, {:presence => true}) before_save :capitalize_name, :capitalize_genre private define_method(:capitalize_name) do name = self.name name_split = name.split name_split.each do |word| word.capitalize!() end self.name = name_split.join(" ") end define_method(:capitalize_genre) do genre = self.genre genre_split = genre.split genre_split.each do |word| word.capitalize!() end self.genre = genre_split.join(" ") end end
class GmpointAddColumnsToLands < ActiveRecord::Migration def change add_column :lands, :location_latitude, :float add_column :lands, :location_longitude, :float add_column :lands, :location_address, :string end end
RSpec.describe 'Categories', type: :request do describe 'GET /tag/画像.html' do describe 'contents' do it 'renders' do get '/tag/%E7%94%BB%E5%83%8F.html' expected = (Rails.root + 'spec/fixtures/views/画像.html').read got = response.body.split("\n") expected.split("\n").each_with_index do |line, index| expect([got[index].remove(/^\s+/), index]).to eq([line.remove(/^\s+/), index]) end end end end describe 'GET /m/tag/画像.html' do describe 'contents' do it 'renders' do get '/m/tag/%E7%94%BB%E5%83%8F.html', {}, { "HTTP_USER_AGENT" => "iPhone" } expected = (Rails.root + 'spec/fixtures/views/m/画像.html').read got = response.body.split("\n") expected.split("\n").each_with_index do |line, index| expect([got[index].remove(/^\s+/), index]).to eq([line.remove(/^\s+/), index]) end end end end end
module Shadowsocks class Listener < ::Shadowsocks::Connection attr_accessor :stage, :remote_addr, :remote_port, :addr_to_send, :cached_pieces, :header_length, :connector, :config, :ip_detector def receive_data data data_handler data outbound_scheduler if connector end def post_init @stage = 0 @cached_pieces = [] puts "A client has connected..." end def unbind puts "A client has left..." connection_cleanup end def remote connector end private def parse_data parser @addrtype = parser.addr_type if parser.mode == :unsupported warn "unsupported addrtype: " + @addrtype.unpack('c')[0].to_s connection_cleanup end @addr_len = parser.addr_len @addr_to_send = parser.addr_to_send @remote_addr = parser.remote_addr @remote_port = parser.remote_port @header_length = parser.header_length end def connection_cleanup connector.close_connection if connector self.close_connection end end end
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2020 MongoDB Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Net autoload :HTTP, 'net/http' end module Mongo module Auth class Aws # Helper class for working with AWS requests. # # The primary purpose of this class is to produce the canonical AWS # STS request and calculate the signed headers and signature for it. # # @api private class Request # The body of the STS GetCallerIdentity request. # # This is currently the only request that this class supports making. STS_REQUEST_BODY = "Action=GetCallerIdentity&Version=2011-06-15".freeze # The timeout, in seconds, to use for validating credentials via STS. VALIDATE_TIMEOUT = 10 # Constructs the request. # # @note By overriding the time, it is possible to create reproducible # requests (in other words, replay a request). # # @param [ String ] access_key_id The access key id. # @param [ String ] secret_access_key The secret access key. # @param [ String ] session_token The session token for temporary # credentials. # @param [ String ] host The value of Host HTTP header to use. # @param [ String ] server_nonce The server nonce binary string. # @param [ Time ] time The time of the request. def initialize(access_key_id:, secret_access_key:, session_token: nil, host:, server_nonce:, time: Time.now ) @access_key_id = access_key_id @secret_access_key = secret_access_key @session_token = session_token @host = host @server_nonce = server_nonce @time = time %i(access_key_id secret_access_key host server_nonce).each do |arg| value = instance_variable_get("@#{arg}") if value.nil? || value.empty? raise Error::InvalidServerAuthResponse, "Value for '#{arg}' is required" end end if host && host.length > 255 raise Error::InvalidServerAuthHost, "Value for 'host' is too long: #{@host}" end end # @return [ String ] access_key_id The access key id. attr_reader :access_key_id # @return [ String ] secret_access_key The secret access key. attr_reader :secret_access_key # @return [ String ] session_token The session token for temporary # credentials. attr_reader :session_token # @return [ String ] host The value of Host HTTP header to use. attr_reader :host # @return [ String ] server_nonce The server nonce binary string. attr_reader :server_nonce # @return [ Time ] time The time of the request. attr_reader :time # @return [ String ] formatted_time ISO8601-formatted time of the # request, as would be used in X-Amz-Date header. def formatted_time @formatted_time ||= @time.getutc.strftime('%Y%m%dT%H%M%SZ') end # @return [ String ] formatted_date YYYYMMDD formatted date of the request. def formatted_date formatted_time[0, 8] end # @return [ String ] region The region of the host, derived from the host. def region # Common case if host == 'sts.amazonaws.com' return 'us-east-1' end if host.start_with?('.') raise Error::InvalidServerAuthHost, "Host begins with a period: #{host}" end if host.end_with?('.') raise Error::InvalidServerAuthHost, "Host ends with a period: #{host}" end parts = host.split('.') if parts.any? { |part| part.empty? } raise Error::InvalidServerAuthHost, "Host has an empty component: #{host}" end if parts.length == 1 'us-east-1' else parts[1] end end # Returns the scope of the request, per the AWS signature V4 specification. # # @return [ String ] The scope. def scope "#{formatted_date}/#{region}/sts/aws4_request" end # Returns the hash containing the headers of the calculated canonical # request. # # @note Not all of these headers are part of the signed headers list, # the keys of the hash are not necessarily ordered lexicographically, # and the keys may be in any case. # # @return [ <Hash> ] headers The headers. def headers headers = { 'content-length' => STS_REQUEST_BODY.length.to_s, 'content-type' => 'application/x-www-form-urlencoded', 'host' => host, 'x-amz-date' => formatted_time, 'x-mongodb-gs2-cb-flag' => 'n', 'x-mongodb-server-nonce' => Base64.encode64(server_nonce).gsub("\n", ''), } if session_token headers['x-amz-security-token'] = session_token end headers end # Returns the hash containing the headers of the calculated canonical # request that should be signed, in a ready to sign form. # # The differences between #headers and this method is this method: # # - Removes any headers that are not to be signed. Per AWS # specifications it should be possible to sign all headers, but # MongoDB server expects only some headers to be signed and will # not form the correct request if other headers are signed. # - Lowercases all header names. # - Orders the headers lexicographically in the hash. # # @return [ <Hash> ] headers The headers. def headers_to_sign headers_to_sign = {} headers.keys.sort_by { |k| k.downcase }.each do |key| write_key = key.downcase headers_to_sign[write_key] = headers[key] end headers_to_sign end # Returns semicolon-separated list of names of signed headers, per # the AWS signature V4 specification. # # @return [ String ] The signed header list. def signed_headers_string headers_to_sign.keys.join(';') end # Returns the canonical request used during calculation of AWS V4 # signature. # # @return [ String ] The canonical request. def canonical_request headers = headers_to_sign serialized_headers = headers.map do |k, v| "#{k}:#{v}" end.join("\n") hashed_payload = Digest::SHA256.new.update(STS_REQUEST_BODY).hexdigest "POST\n/\n\n" + # There are two newlines after serialized headers because the # signature V4 specification treats each header as containing the # terminating newline, and there is an additional newline # separating headers from the signed header names. "#{serialized_headers}\n\n" + "#{signed_headers_string}\n" + hashed_payload end # Returns the calculated signature of the canonical request, per # the AWS signature V4 specification. # # @return [ String ] The signature. def signature hashed_canonical_request = Digest::SHA256.hexdigest(canonical_request) string_to_sign = "AWS4-HMAC-SHA256\n" + "#{formatted_time}\n" + "#{scope}\n" + hashed_canonical_request # All of the intermediate HMAC operations are not hex-encoded. mac = hmac("AWS4#{secret_access_key}", formatted_date) mac = hmac(mac, region) mac = hmac(mac, 'sts') signing_key = hmac(mac, 'aws4_request') # Only the final HMAC operation is hex-encoded. hmac_hex(signing_key, string_to_sign) end # Returns the value of the Authorization header, per the AWS # signature V4 specification. # # @return [ String ] Authorization header value. def authorization "AWS4-HMAC-SHA256 Credential=#{access_key_id}/#{scope}, SignedHeaders=#{signed_headers_string}, Signature=#{signature}" end # Validates the credentials and the constructed request components # by sending a real STS GetCallerIdentity request. # # @return [ Hash ] GetCallerIdentity result. def validate! sts_request = Net::HTTP::Post.new("https://#{host}").tap do |req| headers.each do |k, v| req[k] = v end req['authorization'] = authorization req['accept'] = 'application/json' req.body = STS_REQUEST_BODY end http = Net::HTTP.new(host, 443) http.use_ssl = true http.start do resp = Timeout.timeout(VALIDATE_TIMEOUT, Error::CredentialCheckError, 'GetCallerIdentity request timed out') do http.request(sts_request) end payload = JSON.parse(resp.body) if resp.code != '200' aws_code = payload.fetch('Error').fetch('Code') aws_message = payload.fetch('Error').fetch('Message') msg = "Credential check for user #{access_key_id} failed with HTTP status code #{resp.code}: #{aws_code}: #{aws_message}" msg += '.' unless msg.end_with?('.') msg += " Please check that the credentials are valid, and if they are temporary (i.e. use the session token) that the session token is provided and not expired" raise Error::CredentialCheckError, msg end payload.fetch('GetCallerIdentityResponse').fetch('GetCallerIdentityResult') end end private def hmac(key, data) OpenSSL::HMAC.digest("SHA256", key, data) end def hmac_hex(key, data) OpenSSL::HMAC.hexdigest("SHA256", key, data) end end end end end
require_relative 'Hang-Woman2' require_relative 'utils' class Runner def initialize run end def get_user_input puts "Enter a letter or write solve and guess the puzzle." user_input = gets.chomp user_input.downcase! if user_input.include? "solve" @game.solver(user_input) elsif user_input.length > 1 && user_input[0] != 'solve' puts "Invalid input. Try again" get_user_input elsif @game.guessed_letters.include? user_input puts "That letter has already been guessed. Try again" get_user_input elsif @game.letters_remaining.include? user_input @game.solver(user_input) else puts "That's not a letter. Try again" get_user_input end end def run @game = GameBoard.new($phrase_array) @game.game_view until @game.solved? || @game.guessed_letters.length > 6 #initiates loop clear_screen! #called from the utils file @game.game_view #board printed sleep(0.5) get_user_input # prompt user for input or solution end #After loop is broken: (this should be its own method) @game.game_view #display final results # self.outcome #when game is over, print 'win/lose' message return puts "Congrats!" if @game.solved? return puts "You were hung." end end new_game = Runner.new
class FoodsController < ApplicationController def index @foods = Food.all end def soup @soups = Food.sort_by(params[:sort_by], "soup").paginate(page: params[:page], per_page: 3) end def salad @salads = Food.sort_by(params[:sort_by], "salad").paginate(page: params[:page], per_page: 3) end def new @food = Food.new end def create @food = current_user.foods.build(food_params) if @food.save flash[:success] = "Ready To Eat!" redirect_to user_path(@food.user_id) else render 'new' end end def show @food = Food.find(params[:id]) end def edit @food = Food.find(params[:id]) end def update @food = Food.find(params[:id]) if @food.update(food_params) flash[:success] = "Fresh out of the oven... again!" redirect_to food_path(@food.id) else render 'edit' end end def destroy @food = Food.find(params[:id]) if @food.destroy redirect_to user_path(current_user.id) end end def result @winning_food = Food.find(params[:id]) Food.food_win(@winning_food) Food.update_win_percentage(@winning_food) @losing_food = Food.find(params[:lose_id]) Food.food_lose(@losing_food) Food.update_win_percentage(@losing_food) redirect_to home_path end private def food_params params.require(:food).permit(:id, :kind, :title, :user_id, :image, :wins, :loses, :recipe, :description) end end
class ApiWorker include Sidekiq::Worker def perform(domain_id) domain = Domain.find(domain_id) hostname = domain[:hostname] # steps to grab origin_ip_address dns = Dnsruby::Resolver.new result = dns.query(hostname) request = result.answer.last.rdata_to_string domain.update_attribute(:origin_ip_address, request) # quick console test puts "JOB COMPLETE for #{domain[:hostname]}" end end
require 'test_helper' class UsersEditTest < ActionDispatch::IntegrationTest def setup @user = users(:drew) end test "return user show view when user is activated" do get user_path(@user) assert_template 'users/show' end test "return home page when user is not activated" do @user.activated = false @user.save get user_path(@user) assert_redirected_to root_url end end
require 'rails_helper' RSpec.describe PopulationsController, type: :controller do render_views describe "GET #index" do it "returns http success" do get :index expect(response).to have_http_status(:success) end end describe "GET #show" do it "returns http success" do get :show, params: { year: "1900" } expect(response).to have_http_status(:success) end it "returns a population for a date" do year = 1900 get :show, params: { year: year } expect(response.content_type).to eq "text/html" expect(response.body).to match /Population: #{Population.get(year)}/im end it "returns a population for a date when invoked as xhr" do year = 1900 get :show, params: { year: year }, xhr: true expect(response.content_type).to eq "text/javascript" expect(response.body).to match /Population: #{Population.get(year)}/im end it "prevents rendering script tags" do year = "<script>alert('XSS')</script>" get :show, params: { year: year } expect(response.body).not_to match /for: <script>alert/im end it "calls population calculation method with exponential method" do year = 2005 expect(Population).to receive(:get).with(year, :exponential) get :show, params: { year: year, calculation_method: "exponential" }, xhr: true expect(response).to have_http_status(:success) end it "calls population calculation method with logistic method" do year = 2005 expect(Population).to receive(:get).with(year, :logistic) get :show, params: { year: year, calculation_method: "logistic" }, xhr: true expect(response).to have_http_status(:success) end it "creates record user's answer and query" do year = "1990" expect(LogRecord).to receive(:create).with(ip: "0.0.0.0", year: Date.new(year.to_i), population: 248709873, exact: true).and_call_original expect { get(:show, params: { year: year }) }.to change { LogRecord.count }.by(1) end end end
module RailsAdminNestable class Engine < ::Rails::Engine initializer "RailsAdminNestable precompile hook", group: :all do |app| app.config.assets.precompile += %w(rails_admin/rails_admin_nestable.js rails_admin/jquery.nestable.js rails_admin/rails_admin_nestable.css) end initializer 'Include RailsAdminNestable::Helper' do |app| ActionView::Base.send :include, RailsAdminNestable::Helper end end end
class Router def initialize(controller) @controller = controller @running = true end def run puts ' -- 👩‍🍳👨‍🍳 My CookBook 👩‍🍳👨‍🍳 --' while @running display_tasks action = gets.chomp.to_i print `clear` route_action(action) puts '' puts '-----------------------' end end private def display_tasks puts 'What would you like to do?' puts '' puts '1 - List all recipes' puts '2 - Create a new recipe' puts '3 - Remove a recipe' puts "4 - Mark recipe as 'done'" puts '100 - Exit' end def route_action(action) case action when 1 then @controller.list when 2 then @controller.create when 3 then @controller.destroy when 4 then @controller.mark_as_done when 100 then stop else puts 'Please choose one of the actions above.' end end def stop puts 'Good bye chef 👋' sleep(1) @running = false end end
class Benefit < ActiveRecord::Base mount_uploader :photo, AvatarUploader belongs_to :benefit_type has_many :accompanimentbenefits has_many :articlebenefits has_many :benefitcoupons has_many :accompaniments, through: :accompanimentbenefits has_many :articles, through: :articlebenefits has_many :coupons, through: :benefitcoupons validates :benefit_type, presence: true validates :title, presence: true, length: { maximum: 40 } validates :threshold, presence: true validates :price_cents, presence: true validates :time_periode, presence: true validates :time_limit, presence: true monetize :price_cents def time_periode_text { 'month' => 'mois', 'day' => 'jour(s)', 'week' => 'semaine(s)', 'year' => "année(s)" }[time_periode] end def date_limit time_limit.to_i.send(time_periode.to_s) end end
class RemoveCallLetters < ActiveRecord::Migration[4.2] def change remove_column :shows, :call_letters, :string end end
module PostToS3 module ViewHelpers def s3_upload_form_for(upload, &block) open_form = <<HTML <form action="#{upload.bucket_url}" enctype="multipart/form-data" method="post"> <div> <input name="key" type="hidden" value="#{upload.key}" /> <input name="AWSAccessKeyId" type="hidden" value="#{upload.access_key_id}" /> <input name="acl" type="hidden" value="#{upload.acl}" /> <input name="policy" type="hidden" value="#{upload.policy}" /> <input name="signature" type="hidden" value="#{upload.signature}" /> <input name="success_action_redirect" type="hidden" value="#{upload.success_action_redirect}" /> HTML close_form = "\n</div>\n</form>\n" if respond_to?(:safe_concat) content = capture(&block) output = ActiveSupport::SafeBuffer.new output.safe_concat(open_form.html_safe) output << content output.safe_concat(close_form.html_safe) else concat(open_form) yield concat(close_form) end end end end
require "./test/test_helper" class GameRepoTest < MiniTest::Test def setup @game_repo = GameRepo.new('./data/game_fixture.csv') end def test_game_repo_exists assert_instance_of GameRepo, @game_repo end def test_game_repo_has_games assert_equal 30, @game_repo.repo.count assert_equal Array, @game_repo.repo.class assert_equal 3, @game_repo.repo.first.away_goals end end
class Client < ActiveRecord::Base belongs_to :company has_many :invoices, dependent: :destroy has_many :company_invoices, through: :invoices, source: :company has_secure_password email_regex = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]+)\z/i validates :name, :address_line1, :city, :state, :zip, :phone, :company_id, :presence => true validates :email, :presence => true, :format => {:with => email_regex }, :uniqueness => { :case_sensitive => false } end
# Copyright 2010 Mark Logic, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'rubygems' require 'nokogiri' require 'ActiveDocument/search_match' module ActiveDocument class SearchResult include Enumerable def initialize(node) @node = node end #def index # Integer(@node.xpath("./@index").to_s) #end def uri @node.xpath("./corona:result/corona:uri").text.to_s end #def path # @node.xpath("./@path").to_s #end #def score # Float(@node.xpath("./@score").to_s) #end def confidence Float(@node.xpath("./corona:result/corona:confidence").text.to_s) end #def fitness # Float(@node.xpath("./@fitness").to_s) #end def each(&block) nodeset = @node.xpath("./corona:result/corona:snippet/span") if nodeset.length == 1 yield SearchMatch.new(nodeset[0]) else @node.xpath("./corona:result/corona:snippet/span").each { |node| yield SearchMatch.new(node) } end end def root_type full_path = @node.xpath("./corona:result/corona:snippet/span").xpath("./@path").to_s root = full_path.match(/^\/[[:alpha:]]*((:)[[:alpha:]]*)?/) # find the first :something/ which should indicate the root root.to_s.delete(":/") # remove the : and / to get the root element name end def [](index) SearchMatch.new(@node.xpath("./corona:result/corona:snippet/span")[index]) end def length @node.xpath("./corona:result/corona:snippet/span").length end def realize(klass) klass.load(uri) end end end
require 'rails_helper' RSpec.describe Item, type: :model do before do @item = FactoryBot.build(:item) end describe '出品する商品の保存' do context '商品が保存されるとき' do it '全て入力されていれば保存される' do expect(@item).to be_valid end end context '商品が保存されないとき' do it 'imageが空だと保存されない' do @item.images = nil @item.valid? expect(@item.errors.full_messages).to include "画像を入力してください" end it 'nameが空だと保存されない' do @item.name = '' @item.valid? expect(@item.errors.full_messages).to include "商品名を入力してください" end it 'textがからだと保存されない' do @item.text = '' @item.valid? expect(@item.errors.full_messages).to include "説明文を入力してください" end it 'category_idが1だと保存されない' do @item.category_id = 1 @item.valid? expect(@item.errors.full_messages).to include "カテゴリーを選択してください" end it 'status_idが1だと保存されない' do @item.status_id = 1 @item.valid? expect(@item.errors.full_messages).to include "ステータスを選択してください" end it 'charges_idが1だと保存されない' do @item.charges_id = 1 @item.valid? expect(@item.errors.full_messages).to include "配送料の負担を選択してください" end it 'area_idが1だと保存されない' do @item.area_id = 1 @item.valid? expect(@item.errors.full_messages).to include "地域を選択してください" end it 'day_idが1だと保存されない' do @item.day_id = 1 @item.valid? expect(@item.errors.full_messages).to include "日数を選択してください" end it 'priceが空だと保存されない' do @item.price = '' @item.valid? expect(@item.errors.full_messages).to include "値段を入力してください" end it 'priceの値が299以下だと保存されない' do @item.price = 299 @item.valid? expect(@item.errors.full_messages).to include "値段は299より大きい値にしてください" end it 'priceの値が10000000以上だと保存されない' do @item.price = 10_000_000 @item.valid? expect(@item.errors.full_messages).to include "値段は10000000より小さい値にしてください" end it 'ユーザーが紐づいていなければ保存されない' do @item.user = nil @item.valid? expect(@item.errors.full_messages).to include "Userを入力してください" end it 'priceが全角文字では保存されない' do @item.price = '1000' @item.valid? expect(@item.errors.full_messages).to include "値段は数値で入力してください" end it 'priceが半角英数混合では登録できないこと' do @item.price = 'a1234' @item.valid? expect(@item.errors.full_messages).to include "値段は数値で入力してください" end it 'priceが半角英語だけでは登録できないこと' do @item.price = 'abcdef' @item.valid? expect(@item.errors.full_messages).to include "値段は数値で入力してください" end end end end
class AddExtColumnToReports < ActiveRecord::Migration def change add_column :reports, :corp_id, :integer,index: true add_column :reports, :begin_at, :timestamp add_column :reports, :end_at, :timestamp add_column :reports, :license_number, :string add_column :reports, :mobile, :string end end
require 'spec_helper' describe Comment do it { should belong_to :user } it { should belong_to :app } let(:blanks){[nil, '']} it { should have_content(:body).when('This app is pretty sweet', 'lets see it come to life!') } it { should_not have_content(:body).when(*blanks) } end
class Bank def self.print_statement(account) print_headings print_transactions(account) end def self.print_headings puts 'date || credit || debit || balance' end def self.print_transactions(account) transactions = account.transaction_history.reverse transactions.each do |transact| puts "#{transact.date.strftime('%d/%m/%Y')} || #{transact.balance_change > 0 ? '%.2f' % transact.balance_change.to_s.ljust(7) : ' '} || #{transact.balance_change < 0 ? '%.2f' % transact.balance_change.abs.to_s.ljust(7) : ' '} || #{'%.2f' % transact.new_balance}" end end end
json.array!(@agencies) do |agency| json.extract! agency, :id, :name, :description, :grade, :tag_list end
class Stop < ActiveRecord::Base has_many :direction_stop, dependent: :destroy end
require "nokogiri" module Bliss class ParserMachine < Nokogiri::XML::SAX::Document def initialize(parser) @depth = [] # @settings = {} # downcased @root = nil @nodes = {} @current_node = {} @on_root = nil @on_tag_open = {} @on_tag_close = {} #@constraints = [] @ignore_close = [] @parser = parser @closed = false end def current_depth @depth end #def constraints(constraints) #@constraints = constraints #end def on_root(&block) @on_root = block end def on_tag_open(element, block) @on_tag_open.merge!({Regexp.new("#{element}$") => block}) end def on_tag_close(element, block) # TODO # check how do we want to handle on_tag_close depths (xpath, array, another) @on_tag_close.merge!({Regexp.new("#{element}$") => block}) end def close @closed = true end def is_closed? @closed end def start_element(element, attributes) return if is_closed? # element_transformation @depth.push(element) # TODO search on hash with xpath style # for example: # keys: */ad/url # keys: root/ad/url # @on_tag_close.keys.select {|key| @depth.match(key)} # other example: # keys: root/(ad|AD)/description ## search_key = @depth.join('/') # element @on_tag_open.keys.select{ |r| search_key.match(r) }.each do |reg| @on_tag_open[reg].call(@depth) end ### if @depth.size == 1 current = @nodes.pair_at_chain(@depth[0..-2]) value_at = @nodes.value_at_chain(@depth[0..-2]) else current = @nodes.pair_at_chain(@depth) value_at = @nodes.value_at_chain(@depth) end # puts "start_element-INITS@#{@depth.inspect}" # puts "nodes: #{@nodes.inspect}" # puts "current: #{current.inspect}" # puts "valueAt: #{value_at.inspect}" #puts "depth: #{@depth.inspect}," #puts "starts: #{@nodes.inspect}" #puts "\n" if current.is_a? Array current = current.last end if current.is_a? Hash exists = true if current[element] if exists #puts "nodo ya existe" if current[element].is_a? Array current[element].concat [{}] else # TODO use this code to collect elements as batches current[element] = [current[element], {}] # DO NOT REMOVE end else current[element] = {} end elsif current.is_a? NilClass @nodes[element] = {} end #puts "depth: #{@depth.inspect}," #puts "finishes: #{@nodes.inspect}" #puts "\n" @current_content = Bliss::StringWithAttributes.new('') @current_content.attributes.merge!(Hash[*attributes.flatten]) @current_content end def characters(string) return if is_closed? concat_content(string) end def cdata_block(string) return if is_closed? concat_content(string) end def ignore_next_close(tag) @ignore_close.push(tag) end def current_node current = @nodes.pair_at_chain(@depth[0..-2]).dup value_at = @nodes.value_at_chain(@depth[0..-2]).dup #if value_at.is_a? Hash # current[element] = @current_content if @current_content.size > 0 #elsif value_at.is_a? NilClass # if current.is_a? Array # current = current.last # current[element] = @current_content if @current_content.size > 0 # end #end current_node = nil if value_at.empty? #|| value_at.strip == '' current_node = current #@on_tag_close[reg].call(current, @depth) else current_node = value_at #@on_tag_close[reg].call(value_at, @depth) end if current_node.is_a? Array current_node = current_node.last end current_node[@depth.last] = "" current_node end def end_element(element, attributes=[]) return if is_closed? # element_transformation current = @nodes.pair_at_chain(@depth) value_at = @nodes.value_at_chain(@depth) #if @depth.last == "id" # puts "ending@#{@depth.inspect}" # puts "nodes: #{@nodes.inspect}" # puts "current: #{current.inspect}" # puts "value_at: #{value_at.inspect}" # puts "\n" #end if current.is_a? Array current = current.last end if current.is_a? Hash if (value_at.is_a? Hash and value_at.size == 0) #or value_at.is_a? NilClass current[element] = @current_content if @current_content.size > 0 end #if value_at.is_a? Array #or !(value_at.last.is_a? Hash and value_at.size == 0) override = true if value_at.is_a?(Array) override = false if value_at.is_a?(Array) and value_at.last.is_a?(Hash) and value_at.last.size > 0 if override current[element][-1] = @current_content if @current_content.size > 0 end end @current_content = '' # TODO search on hash with xpath style # for example: # keys: */ad/url # keys: root/ad/url # @on_tag_close.keys.select {|key| @depth.match(key)} ## #if @depth.last == "id" # puts "ended@#{@depth.inspect}" # puts "nodes: #{@nodes.inspect}" # puts "current: #{current.inspect}" # puts "value_at: #{value_at.inspect}" # puts "\n" #end search_key = @depth.join('/') # element #if @depth.last == 'ad' #puts search_key #puts value_at.keys.inspect #ad array #puts @constraints.select{|c| search_key.match(Regexp.new("#{c.depth.split('/').join('/')}$"))}.inspect #puts current.keys.inspect # others puts @constraints.select{|c| search_key.match(Regexp.new("#{c.depth.split('/')[0..-2].join('/')}$"))}.inspect #end @on_tag_close.keys.select{ |r| search_key.match(r) }.each do |reg| #puts "search_key: #{search_key.inspect}" if @ignore_close.include? search_key @ignore_close.delete(search_key) else if value_at.is_a? Array value_at = value_at.last end if value_at.is_a? NilClass or value_at.empty? @on_tag_close[reg].call(current.dup, @depth) else @on_tag_close[reg].call(value_at.dup, @depth) end end end # TODO constraint should return Regexp like depth too #puts @constraints.collect(&:state).inspect #puts @constraints.collect{|c| "#{c.depth}" } #puts @constraints.collect{|c| "#{c.depth.split("/").join('/')}" } @parser.formats.each do |format| format.constraints.select{|c| [:not_checked, :passed].include?(c.state) }.select {|c| search_key.match(Regexp.new("#{c.depth.split('/').join('/')}$")) }.each do |constraint| #puts "search_key: #{search_key}" #puts "value_at.inspect: #{value_at.inspect}" #puts "current.inspect: #{current.inspect}" constraint.run!(current) end end @depth.pop if @depth.last == element end def concat_content(string) if string @current_content << string end end def end_document #puts @nodes.inspect end end end
class Deposit < ActiveRecord::Base attr_accessible :quality, :weight, :farm_id, :cp_id, :weighed_at, :possible_duplicate belongs_to :farm belongs_to :cp before_create :check_for_erroneous_input validates_presence_of :weight, :weighed_at, :cp, :farm validates :weight, :numericality => {:greater_than_or_equal_to => 0} validates_associated :cp, :farm def self.minimum return Deposit.calculate(:minimum, 'weighed_at') || Time.new(2000, "Jan", 1) #need to make inclusive? end def self.maximum return Deposit.calculate(:maximum, 'weighed_at') || Time.new(2100, "Jan", 1) end def self.all_qualities ["Very Good","Good","OK", "Bad", "Very Bad" ] end def days_since next_td = Deposit.find(:first, :order => "weighed_at DESC", :conditions => [ "farm_id = ? AND weighed_at < ?", self.farm_id, self.weighed_at]) if next_td == nil return -1 else return (self.weighed_at - next_td.weighed_at).to_i / 1.day end end # Sets possible_duplicate to true if it finds another deposit entered within # a given time delta of this deposit **AND** have a weight within a given # weight delta of this deposit. def check_for_erroneous_input dw = Deposit.weight_delta dt = Deposit.time_delta possible_duplicates = Deposit.all(conditions: { :weight => (self.weight - dw)..(self.weight + dw), :weighed_at => (self.weighed_at - dt)..(self.weighed_at + dt) }) self.possible_duplicate = true unless possible_duplicates.empty? end def self.weight_delta 0.4 end def self.time_delta 5 end def resolve self.possible_duplicate = false end def self.to_csv(deposits = all) CSV.generate do |csv| csv << column_names deposits.each do |deposit| csv << deposit.attributes.values_at(*column_names) end end end def self.import(file) CSV.foreach(file.path, headers: true) do |row| deposit = find_by_id(row["id"]) || new deposit.attributes = row.to_hash.slice(*accessible_attributes) deposit.save! end end end
require 'generators/seed_migrator/helper' # Generator to install tmx data update in a new rails system. class SeedMigrator::InstallGenerator < Rails::Generators::Base include Generators::SeedMigrator::Helper source_root File.expand_path('../templates', __FILE__) # Create the initializer file with default options. def create_initializer log :initializer, "Adding custom data update module" if application? template "data_update_module.rb", "config/initializers/#{application_name}_data_update.rb" else template "data_update_module.rb", "lib/#{application_name}/#{application_name}_data_update.rb" end end # Update seeds.rb def update_seeds log :initializer, "Adding data update seeder to seeds.rb" seed_code =<<SEED include SeedMigrator::Seeds apply_updates #{full_application_class_name}.root.join('db', 'data_updates') SEED in_root do inject_into_file 'db/seeds.rb', "\n#{seed_code}\n", { :before => /\z/, :verbose => false } end end end
class DrinkValidator < ActiveModel::Validator def validate(record) drink_type = record.drink_type.to_sym record.errors[:drink_type] = "Invalid drink type" and return false unless Drink::DRINK_TYPES.include? drink_type needed_aspects = Drink::DRINK_TYPES[drink_type] needed_aspects.each do |aspect| aspect_values = Drink::DRINK_ASPECTS[aspect] if aspect_values.is_a?(Array) validate_aspect(record, aspect, aspect_values) else aspect_values.each do |k,v| validate_aspect(record, [aspect, k].join("_"), v) end end end return true end def validate_aspect(record, aspect, values) value = record.send(aspect.to_sym) record.errors[aspect.to_sym] << "Missing aspect" and return false if value.blank? record.errors[aspect.to_sym] << "Invalid aspect" and return false unless values.include? value.to_sym return true end end
require 'io/console' require_relative 'gameplay' require_relative 'board_status' require_relative 'interface' require_relative 'reset' require_relative 'exit_on_escape' require_relative 'command_options' class Game attr_reader :gameplay attr_reader :board_status attr_reader :interface attr_reader :reset attr_reader :input def initialize(input) @interface = Interface.new(input) @gameplay = GamePlay.new(@interface) @board_status = BoardStatus.new @reset = Reset.new @input = input end def start main_menu game_loop end def main_menu interface.main_menu gameplay.turn_x = interface.player1 gameplay.turn_y = interface.player2 end def game_loop loop do interface.draw_scoreboard board_status.draw_board interface.show_instructions(gameplay.turn) gameplay.turn_base_TEMPORAL(input, board_status.boxes) winner = board_status.check_for_winner(gameplay.option_selected, gameplay.last_turn) if winner != nil interface.results(gameplay.last_turn, board_status.icon_x, board_status.icon_o) board_status.draw_board reset.values(gameplay, board_status) end if gameplay.plays_counter >= 9 interface.results("tie", board_status.icon_x, board_status.icon_o) reset.values(gameplay, board_status) end gameplay.last_turn = gameplay.turn end end def restart reset.values(gameplay, board_status, interface) interface.main_menu gameplay.turn_x = interface.player1 gameplay.turn_x = interface.player2 end end begin CommandOptions.new exit_on_escape = ExitOnEscape.new game = Game.new(exit_on_escape) game_thread = Thread.new do game.start end exit_on_escape.run(game_thread) game_thread.join end
class TipoPergunta < ActiveRecord::Base has_many :perguntas end
require './test/minitest_helper' class DispatchmeOauthTest < MiniTest::Test def test_that_a_token_is_returned assert_kind_of Dispatchme::AccessToken, @@access_token refute_nil @@access_token.token refute_nil @@access_token.expires_in refute_nil @@access_token.created_at end end
define :rails_chores, :task => 'chores' do namespace = params[:name] taskname = params[:task] rakefile = "#{@node[:rails][:deploy_to]}/current/Rakefile" logdir = "#{@node[:rails][:deploy_to]}/shared/log/cron" cron_user = "#{@node[:rails][:user]}" directory logdir do owner cron_user group "sysadmin" recursive true end cron "#{namespace}_minute_chores" do minute '*/5' command "RAILS_ENV=production rake -f #{rakefile} #{taskname}:every_five_minutes >> #{logdir}/#{namespace}_every_five_minutes.txt" user cron_user end cron "#{namespace}_hourly_chores" do minute '0' command "RAILS_ENV=production rake -f #{rakefile} #{taskname}:hourly >> #{logdir}/#{namespace}_hourly.txt" user cron_user end cron "#{namespace}_daily_chores" do minute '01' hour '0' command "RAILS_ENV=production rake -f #{rakefile} #{taskname}:daily >> #{logdir}/#{namespace}_daily.txt" user cron_user end cron "#{namespace}_weekly_chores" do minute '02' hour '0' weekday '1' command "RAILS_ENV=production rake -f #{rakefile} #{taskname}:weekly >> #{logdir}/#{namespace}_weekly.txt" user cron_user end end
require_relative '../lib/discourse_segment/common' module Jobs class SegmentAfterCreateBookmark < Jobs::Base def execute(args) segment = DiscourseSegment::Common.connect post = Post.find_by(id: args[:post_id]) segment.track( user_id: args[:user_id], event: 'Post Bookmarked', properties: { slug: post.topic.slug, title: post.topic.title, url: post.topic.url } ) segment.flush end end end
class FayeClientsController < ApplicationController before_action :load_faye_client def update @faye_client.user_id = current_user.id @faye_client.status = params[:status] @faye_client.client_type = params[:client_type] @faye_client.idle_duration = params[:idle_duration] old_status = current_user.computed_status if @faye_client.save new_status = current_user.computed_status(true) current_user.reset_digests_if_needed(old_status, new_status) current_user.reset_badge_count_if_needed(old_status, new_status) render_json current_user else render_error @faye_client.errors.full_messages end end private def load_faye_client @faye_client = FayeClient.new(id: params[:id]) raise Peanut::Redis::RecordNotFound if @faye_client.attrs.present? && @faye_client.user_id != current_user.id end end
require_relative "players" require_relative "word_bank" require_relative "game" class Runner def initialize @word_bank = WordBank.new @game = Game.new(@word_bank.get_word) @players = Players.new get_player_names @players.shuffle end def is_player_count_valid?(number) number.between?(1,5) end def get_player_count puts "How many Players are there? (1-5)" number = gets.chomp.to_i unless is_player_count_valid?(number) puts "INVALID NUMBER" get_player_count end number end def get_a_player_name(place) puts "what is player's #{place+1} name" name = gets.chomp if @players.check_name(name) @players.add_name(name) else puts "INVALID NAME" get_a_player_name end end def get_player_names number = get_player_count number.times do |place| get_a_player_name(place) end end def ask_for_a_char puts "Guess a character or type ! to guess!!" guess = gets.chomp if already_guessed?(guess) puts "Already guessed noob" ask_for_a_char end if guess == '!' all_or_nothing(guess) elsif guess.length == 1 place_char(guess) @game.win? else puts "NOT A CHAR" ask_for_a_char end display_remainder end def already_guessed?(guess) @game.used_words.include?(guess) end def all_or_nothing(guess) puts "ALL OR NOTHING!!!! WHAT IS THE ANSWER!!!" guess = gets.chomp @game.compare_string(guess) end def place_char(char) if @game.compare_char(char) puts "NICE" else puts "FAIL" end @game.place_char(char) end def display_remainder puts @game.return_display_word end def one_round @players.each do |player| puts " " puts "****************************" puts "#{player} what is your guess?" ask_for_a_char if @game.game_over puts "The word is: #{@game.word}" puts "#{player} has won!" break end end end def play one_round play unless @game.game_over end end test = Runner.new test.play
class CreatePeople < ActiveRecord::Migration def change create_table :people do |t| t.string :first_name t.string :last_name t.date :birthday t.string :email t.string :password t.string :phone t.string :address t.string :city t.string :state t.integer :past_id t.text :notes t.timestamps null: true end end end
class ChangeUserTable < ActiveRecord::Migration def change add_column :users, :password, :string remove_column :users, :icon, :stirng end end
class Notifier < ApplicationMailer def notify(evaluation, user, subject) @evaluation = evaluation mail(from: "evaluation@think-bridge.com", to: user.email, subject: subject, delivery_method_options: Rails.application.secrets.evaluation_smtp) end def new_project(project, email, user) @project = project @user = user mail(to: email, subject: "#{project.job_code}(#{project.company})#{project.mail_title_suffix}") render layout: false end def salary(payroll) @payroll = payroll mail(to: payroll.email, subject: "Payroll information - #{Date.today.strftime("%B %y")}") end end
require 'spec/spec_helper' require 'archive' describe "WorksNewPage" do before do @fandom = "Supernatural" @rating = "Not Rated" @content = "Bad things happen, etc." @character = "Dean Winchester" @pairing = "Dean Winchester/Sam Winchester" @title1 = "Wendigo" @title2 = "Bad Day At Black Rock" @title3 = "Lazarus Rising" @add_tag = "Testing, Regression" @summary = "Regression" $coauthor = "astolat" end it "should preview and post a minimally valid new work" do Archive.new do |a| a.login_flow #Addes a new work a.new_work_required_flow(:rating => @rating,:fandom => @fandom,:title => @title1,:content => @content) #Preview New Work a.works_new_page.preview_btn.click a.header.flash_notice == ("Draft Successfully Created") a.works_new_page.meta_title == @title1 a.works_new_page.meta_author == $user a.works_new_page.meta_rating == @rating a.works_new_page.meta_warning == "No Archive Warnings Apply" a.works_new_page.meta_stats.empty? == true a.works_new_page.post_content == @content #Post New Work a.works_new_page.post_btn.click a.header.flash_notice == ("Work was successfully posted.") a.works_new_page.meta_title == @title1 a.works_new_page.meta_author == $user a.works_new_page.meta_rating == @rating a.works_new_page.meta_warning == "No Archive Warnings Apply" a.works_new_page.meta_stats.empty? == true a.works_new_page.post_content == @content a.works_new_page.meta_fandom == @fandom # #Assert it's been added to the Works List a.header.works_link.click a.works_index_page.work_blurb_title.text.include?(@title1) a.works_index_page.work_blurb_author.text.include?($user) end end # it "should post a work that is not a gift, remix, and without a coauthor" do # Archive.new do |a| # a.login_flow # #Add a new work # a.new_work_required_flow(:rating => @rating,:fandom => @fandom,:title => @title2,:content => @content) # a.works_new_page.cat_mm.set # a.works_new_page.pairing_field.set(@pairing) # a.works_new_page.char_field.set(@character) # a.works_new_page.add_tag_field.set(@add_tag) # a.works_new_page.summary.set(@summary) # #Post New Work # a.works_new_page.post_btn.click # a.header.flash_notice == ("Draft Successfully Created") # a.works_new_page.meta_title == @title2 # a.works_new_page.meta_author == $user # a.works_new_page.meta_rating == @rating # a.header.meta_warning == "No Archive Warnings Apply" # a.works_new_page.meta_stats.empty? == true # a.works_new_page.post_content == @content # a.works_new_page.meta_category == "M/M" # a.works_new_page.meta_fandom == @fandom # a.works_new_page.meta_char == @character # a.works_new_page.meta_freeform == @add_tag # #Assert it's been added to the Works List # a.header.works_link.click # a.works_index_page.work_blurb_title.text.include?(@title2) # a.works_index_page.work_blurb_author.text.include?($user) # end # end # it "should Create a new work with a coauthor" do # Archive.new do |a| # a.login_flow # #Add a new work # a.new_work_required_flow(:rating => @rating,:fandom => @fandom,:title => @title3,:content => @content) # a.works_new_page.coauthor.set # a.works_new_page.coauthor_field.set($coauthor) # a.header.enter # #Post new Work # a.works_new_page.post_btn.click # a.header.flash_notice == ("Work was successfully posted.") # a.works_new_page.meta_title == @title3 # a.header.user == $user # a.works_new_page.meta_rating == @rating # a.header.meta_warning == "No Archive Warnings Apply" # a.works_new_page.meta_stats.empty? == true # a.works_new_page.post_content == @content # a.works_new_page.meta_fandom == @fandom # a.works_new_page.meta_coauthor.text.include?($user) # #Assert it's been added to the Works List # a.header.works_link.click # a.header.user.text.include?(@title3) # a.works_new_page.meta_coauthor.text.include?($user) # end # end # it "should Create a new work that is a remix of an archive work" do # Archive.new do |a| # a.login_flow # #Add a Remix # a.get_url_flow # a.new_work_required_flow(:rating => @rating,:fandom => @fandom,:title => "Remix",:content => @content) # a.works_new_page.remix_show.set # a.works_new_page.remix_panel.visible? == true # a.works_new_page.remix_url_field.set($url) # #Post Work # a.works_new_page.post_btn.click # a.header.flash_notice == ("Work was successfully posted.") # a.works_new_page.meta_title == "Remix" # a.header.user == $user # a.works_new_page.meta_rating == @rating # a.works_new_page.meta_warning == "No Archive Warnings Apply" # a.works_new_page.meta_stats.empty? == true # a.works_new_page.post_content == @content # a.works_new_page.meta_fandom == @fandom # a.works_new_page.post_notes.text.include?("Inspired by " + $title + " by testy.") # a.works_new_page.post_inspauthor.exists? == true # puts a.works_new_page.post_inspauthor.text # a.works_new_page.post_inswork.exists? == true # end # end # it "should Create a new work that is a remix of an external work" do # Archive.new do |a| # a.login_flow # #Add a Remix # a.new_work_required_flow(:rating => @rating,:fandom => @fandom,:title => "External",:content => @content) # a.works_new_page.remix_show.set # a.works_new_page.remix_panel.visible? == true # a.works_new_page.remix_url_field.set("http://weimar27.livejournal.com/44831.html") # a.works_new_page.remix_author_field.set("weimar27") # a.works_new_page.remix_title_field.set("A Fic") # sleep 10 # #Post Work # a.works_new_page.post_btn.click # a.works_new_page.meta_title == "External" # a.header.user == $user # a.works_new_page.meta_rating == @rating # a.works_new_page.meta_warning == "No Archive Warnings Apply" # a.works_new_page.meta_stats.empty? == true # a.works_new_page.post_content == @content # a.works_new_page.meta_fandom == @fandom # a.works_new_page.post_notes.text.include?("Inspired by A Fic by testy.") # #Go to External Work # a.works_new_page.remix_ext_url.exists? # a.works_new_page.remix_ext_url.text == "A Fic" # a.works_new_page.remix_ext_url.click # a.header.notice == ("This work isn't hosted on the Archive so this blurb might not be complete or accurate.") # a.works_new_page.remix_ext_link.click # #TODO: Validate that I've gone to the External Work # end # end # it "should" end
require_relative 'everything' require 'sqlite3' require 'singleton' class QuestionLikes attr_accessor :user_id, :question_id def self.all data = QuestionDBConnection.instance.execute("SELECT * FROM question_likes") data.map { |datum| QuestionLikes.new(datum) } end def self.find_by_id(id) question_likes = QuestionDBConnection.instance.execute(<<-SQL, id) SELECT * FROM question_likes WHERE id = ? SQL return nil unless question_likes.length > 0 QuestionLikes.new(question_likes.first) end def self.likers_for_question_id(question_id) users = QuestionDBConnection.instance.execute(<<-SQL, question_id) SELECT u.id, u.fname, u.lname FROM question_likes as ql JOIN users as u ON ql.user_id = u.id WHERE ql.question_id = ? SQL return nil unless users.length > 0 users.map {|user| Users.new(user)} end def self.num_likes_for_question_id(question_id) questions = QuestionDBConnection.instance.execute(<<-SQL, question_id) SELECT COUNT(*) FROM question_likes as ql WHERE ql.question_id = ? SQL return nil unless questions.length > 0 questions[0].values[0] end def self.liked_questions_for_user_id(user_id) questions = QuestionDBConnection.instance.execute(<<-SQL, user_id) SELECT q.id, q.title, q.body, q.author_id FROM question_likes as ql JOIN questions as q ON q.id = ql.question_id WHERE ql.user_id = ? SQL return nil unless questions.length > 0 questions.map {|question| Questions.new(question)} end def self.most_liked_questions(n) questions = QuestionDBConnection.instance.execute(<<-SQL, n) SELECT COUNT(q.author_id) as num_likes, q.title, q.body, q.author_id, q.id FROM question_likes as ql JOIN questions as q ON ql.question_id = q.id GROUP BY ql.question_id ORDER BY num_likes DESC LIMIT ? SQL return nil unless questions.length > 0 questions.map {|question| Questions.new(question)} end def initialize(options) @id = options['id'] @user_id = options['user_id'] @question_id = options['question_id'] end end
class UpdateSmoochBotSettings < ActiveRecord::Migration[4.2] def change bot = BotUser.smooch_user unless bot.nil? TeamBotInstallation.where(user_id: bot.id).each do |tbi| settings = tbi.settings || {} bot.get_settings.each do |setting| s = setting.with_indifferent_access type = s[:type] default = s[:default] default = default.to_i if type == 'number' default = (default == 'true') if type == 'boolean' default ||= [] if type == 'array' settings[s[:name]] = default unless settings.has_key?(s[:name]) end tbi.settings = settings tbi.save! end end end end
require 'cinch' module AIBot::Protocol::IRC include AIBot::Protocol ## # The IRC protocol. class IRC < Protocol attr_reader :threads, :bots def initialize(configuration) super configuration @threads = [] @bots = [] end ## # Starts the IRC protocol. def start(aibot) if configuration[:networks] # Loop through our networks, creating an <i>IRCBot</i> from the configuration for each. configuration[:networks].each do |network_name, network_config| bot = Cinch::Bot.new do # Our bot configuration. configure do |bot_config| bot_config.realname = network_config[:name] bot_config.nick = network_config[:nick] bot_config.user = network_config[:user] bot_config.server = network_config[:server] bot_config.port = network_config[:port] || 6667 bot_config.ssl.use = network_config[:ssl] bot_config.channels = network_config[:channels] bot_config.plugins.prefix = /#{network_config[:plugin_prefix] || '^::'}/ bot_config.plugins.plugins = [] network_config[:plugins].each do |plugin_name, plugin_config| require_path = plugin_config[:require_path] class_path = plugin_config[:class_path] unless class_path.nil? require require_path unless require_path.nil? plugin_constant = Kernel.const_get(class_path) bot_config.plugins.plugins << plugin_constant configuration = plugin_config[:configuration] bot_config.plugins.options[plugin_constant] = configuration unless configuration.nil? end end if network_config[:plugins] end # Learn and respond to messages. # TODO: This is temporary. Will use plugins in the near future. on :message do |msg| bot = msg.bot message = msg.message if message.include?(bot.nick) message = message.gsub(bot.nick, '').squeeze(' ') response = aibot.respond(message).split if response.first.eql?("\x01action") response.delete(response.first) msg.safe_action_reply(response.join(' ')) if network_config[:silenced].nil? else msg.safe_reply(response.join(' ')) if network_config[:silenced].nil? end else aibot.learn(message) end end # Auto join after being kicked. on :kick do |msg| bot = msg.bot bot.join(msg.channel.name) end end @bots << bot end # Start our bots. @bots.each do |bot| @threads << Thread.new do bot.start end end # Wait (indefinitely) for the threads to join. @threads.each { |thread| thread.join } else raise "Could not find a 'networks' entry in the IRC configuration!" end end end ## # Registers the IRC protocol. AIBot::Protocol::register :irc do |configuration| IRC.new(configuration) end end
module Monsove class Configuration include ActiveSupport::Configurable config_accessor :storage # For scp config_accessor :server config_accessor :username config_accessor :ssh_key # For fog based config_accessor :access_id config_accessor :secret_key # General config_accessor :location config_accessor :versions config_accessor :database end class << self # Parse YAML configuration file. # # @param [String] config_file the path of the configuration file. # # @return [Configuration] def load_config(config_file) YAML.load(File.read(config_file)) # TODO: Transform the config file to Configuration object rescue Errno::ENOENT Monsove.logger.error("Could not find config file file at #{ARGV[0]}") exit rescue ArgumentError => e Monsove.logger.error("Could not parse config file #{ARGV[0]} - #{e}") exit end def configure(&block) yield @config ||= Configuration.new end def config @config end end configure do |config| # config.storage = Monsove::Storage::S3 end end
module RSence module ArgvUtil # Main argument parser for the save command. Sends the USR1 POSIX signal to the process, if running. def parse_save_argv init_args expect_option = false option_name = false if @argv.length >= 2 @argv[1..-1].each_with_index do |arg,i| if expect_option if option_name == :conf_files if not File.exists?( arg ) or not File.file?( arg ) puts ERB.new( @strs[:messages][:no_such_configuration_file] ).result( binding ) exit else @args[:conf_files].push( arg ) end else @args[option_name] = arg end expect_option = false else if arg.start_with?('--') if arg == '--debug' set_debug elsif arg == '--verbose' set_verbose elsif arg == '--conf' or arg == '--config' expect_option = true option_name = :conf_files else invalid_option(arg) end elsif arg.start_with?('-') arg.split('')[1..-1].each do |chr| if chr == 'd' set_debug elsif chr == 'v' set_verbose else invalid_option(arg,chr) end end elsif valid_env?(arg) @args[:env_path] = File.expand_path(arg) @args[:conf_files].unshift( File.expand_path( File.join( arg, 'conf', 'config.yaml' ) ) ) else invalid_env( arg ) end end end if expect_option puts ERB.new( @strs[:messages][:no_value_for_option] ).result( binding ) exit end end if valid_env?(@args[:env_path]) conf_file = File.expand_path( File.join( @args[:env_path], 'conf', 'config.yaml' ) ) @args[:conf_files].unshift( conf_file ) unless @args[:conf_files].include?( conf_file ) else invalid_env end require 'rsence/default_config' config = Configuration.new(@args).config if RSence.pid_support? pid_fn = config[:daemon][:pid_fn] if File.exists?( pid_fn ) pid = File.read( pid_fn ).to_i saving_message = @strs[:messages][:saving_message] pid_status = RSence::SIGComm.wait_signal_response( pid, pid_fn, 'USR2', 30, saving_message, '.', 0.1, true ) else warn @strs[:messages][:no_pid_file] if @args[:verbose] pid_status = nil end else warn @strs[:messages][:no_pid_support] if @args[:verbose] pid_status = nil end if RSence.pid_support? if pid_status == nil puts @strs[:messages][:no_pid_unable_to_save] elsif pid_status == false puts @strs[:messages][:no_process_running] else puts @strs[:messages][:session_data_saved] end end end end end
require 'test_helper' describe UsersController do include Devise::TestHelpers let(:archer) { users(:archer) } let(:lana) { users(:lana) } it 'should get index' do get :index assert_response :success end it 'should get show' do get :show, id: archer assert_response :success end describe '#show' do it 'should list all pastes for current user' do sign_in archer get :show, id: archer assert_match 'fa-globe', response.body assert_match 'fa-unlock-alt', response.body assert_match 'fa-lock', response.body end it 'should only list public pastes for other users' do get :show, id: archer assert_match 'fa-globe', response.body refute_match 'fa-unlock-alt', response.body refute_match 'fa-lock', response.body end it 'should only list stats for owners' do get :show, id: archer refute_match(/your stats/i, response.body) sign_in archer get :show, id: archer assert_match(/your stats/i, response.body) end end end
class CreateAnswerSpaces < ActiveRecord::Migration[5.2] def change create_table :answer_spaces do |t| t.string :category t.string :user_answer t.integer :answer_column_id t.timestamps end end end
class Log def initialize(url, ip) @url = url @ip = ip end attr_reader :url, :ip end
class PointsTransaction < DomainModel belongs_to :points_user has_end_user :end_user_id has_end_user :admin_user_id validates_presence_of :amount validates_presence_of :points_user before_create :set_defaults def self.by_user(user) self.where(:end_user_id => user.id) end def set_defaults self.end_user_id = self.points_user.end_user_id if self.points_user end end
# frozen_string_literal: true require "application_system_test_case" class ReportsTest < ApplicationSystemTestCase setup do login_user(user_email: "user_1@mail", password: "111111") end test "日報一覧ページを表示できる" do visit reports_url assert_selector "h1", text: I18n.t("reports.index.index") end test "新規に日報を登録できる" do visit reports_url click_on I18n.t("reports.index.new_report") fill_in "Title", with: "とても良い日報" fill_in "Memo", with: "わかりやすく濃い内容" click_on "commit" assert_text I18n.t("reports.create.success.create") end test "個別の日報ページを表示できる" do visit reports_url click_on I18n.t("reports.index.show"), match: :first assert_selector "h1", text: I18n.t("reports.show.show") end test "自分が書いた日報を更新できる" do visit reports_url click_on I18n.t("reports.index.edit"), match: :first fill_in "Title", with: "ながい日報" fill_in "Memo", with: "10万字" click_on "commit" assert_text I18n.t("reports.update.success.update") click_on I18n.t("reports.show.back") end test "自分が書いた日報を削除できる" do visit reports_url page.accept_confirm do click_on I18n.t("reports.index.destroy"), match: :first end assert_text I18n.t("reports.destroy.success.destroy") end test "自分が書いた日報にのみ編集ボタンが表示される" do visit reports_url num_of_edit_links = page.all(:link, I18n.t("reports.index.edit")).count assert_equal 3, num_of_edit_links end test "自分が書いた日報にのみ削除ボタンが表示される" do visit reports_url num_of_delete_links = page.all(:link, I18n.t("reports.index.destroy")).count assert_equal 3, num_of_delete_links end end
# A work entry, belonging to a user & task # Has a duration in seconds for work entries class WorkLog < ActiveRecord::Base acts_as_ferret({ :fields => ['body', 'company_id', 'project_id'], :remote => true }) belongs_to :user belongs_to :company belongs_to :project belongs_to :customer belongs_to :task belongs_to :scm_changeset has_one :ical_entry, :dependent => :destroy has_one :event_log, :as => :target, :dependent => :destroy after_update { |r| r.ical_entry.destroy if r.ical_entry l = r.event_log l.created_at = r.started_at l.save if r.task && r.duration.to_i > 0 r.task.recalculate_worked_minutes r.task.save end } after_create { |r| l = r.create_event_log l.company_id = r.company_id l.project_id = r.project_id l.user_id = r.user_id l.event_type = r.log_type l.created_at = r.started_at l.save if r.task && r.duration.to_i > 0 r.task.recalculate_worked_minutes r.task.save end } after_destroy { |r| if r.task r.task.recalculate_worked_minutes r.task.save end } def self.full_text_search(q, options = {}) return nil if q.nil? or q=="" default_options = {:limit => 10, :page => 1} options = default_options.merge options options[:offset] = options[:limit] * (options.delete(:page).to_i-1) results = WorkLog.find_by_contents(q, options) return [results.total_hits, results] end def ended_at self.started_at + self.duration + self.paused_duration end end
class ChampionsController < ApplicationController def index @champions = Champion.all render json: @champions end end
# -*- encoding : utf-8 -*- module Retailigence #:nodoc: # Configure Retailigence with your credentials. # # === Example # Retailigence.configure do |config| # config.api_key = 'yourapikeyhere' # config.production = false # Use the test route # end class Configuration # The API key issued to you by Retailigence attr_accessor :api_key # Wether or not to use the production Retailigence API attr_writer :production # Returns true if using the production API def production? @production ||= true end # Returns true if using the test API def test? !production? end end end
class Sessions < ActiveRecord::Migration[6.1] def change create_sessions add_column_to_pair_users end def create_sessions create_table :sessions do |t| t.timestamps end end def add_column_to_pair_users add_column :pair_users, :session_id, :integer end end
require "#{File.expand_path(File.dirname(__FILE__))}/helper.rb" class TestElseWithCounters < Test::Unit::TestCase def test_given_CONDITION_evaluates_to_true_ELSE_is_not_performed else_proc = Proc.new{raise StandardError.new('You\'ll never catch me!') } t = Class.new(TestClass) { storage_bucket :stars, :counter => true, :condition => Proc.new{true}, :else => else_proc }.new assert_nothing_raised do t.increment_stars assert_equal 1, t.retrieve_stars(0) end end def test_given_CONDITION_evaluates_to_false_ELSE_is_performed else_proc = Proc.new{ |instance, method_name, *args| raise StandardError.new('You\'ll never catch me!') if method_name == 'increment_stars' } t = Class.new(TestClass) { storage_bucket :stars, :counter => true, :condition => Proc.new{false}, :else => else_proc }.new assert_raises StandardError do t.increment_stars end assert_equal 0, t.retrieve_stars(0) end def test_given_CONDITION_evaluates_to_false_ELSE_calls_a_method_on_the_object klass = Class.new(TestClass) do condition_proc = Proc.new{ |instance, method_name, *args| method_name != 'increment_stars'} storage_bucket :stars, :counter => true, :condition => condition_proc, :else => :set_stars_to_20 def set_stars_to_20(frivol_method, *args) store_stars 20 end end t = klass.new t.increment_stars assert_equal 20, t.retrieve_stars(0) end end
Rails.application.routes.draw do # get 'departments/name:string' root "students#index" # get "students" => "students#index" # get "students/:id" => "students#show", as: "student" # delete "students/:id" => "students#destroy" # get "students/:id/edit" => "students#edit", as: "edit_student" # patch "students/:id" => "students#update" resources :students resources :departments end
require 'spec_helper' describe GildedRose do describe "#update_quality" do before do @foo = Item.new("foo", 1, 1) @brie = Item.new("Aged Brie", 1, 47) @sulfuras = Item.new("Sulfuras, Hand of Ragnaros", 100, 49) @ticket = Item.new("Backstage passes to a TAFKAL80ETC concert", 1, 40) @items = [@foo, @brie, @sulfuras, @ticket] GildedRose.new(@items).update_quality() end it "Normal item does not change the name and change quality and day" do expect(@items[0].name).to eq "foo" expect(@items[0].quality).to eq(0) expect(@items[0].sell_in).to eq(0) end it "brie item does not change the name and change quality and day" do expect(@items[1].name).to eq "Aged Brie" expect(@items[1].quality).to eq(48) GildedRose.new(@items).update_quality() expect(@items[1].quality).to eq(50) GildedRose.new(@items).update_quality() expect(@items[1].quality).to eq(50) end it "sulfuras item does not change quality or day" do expect(@items[2].name).to eq "Sulfuras, Hand of Ragnaros" expect(@items[2].quality).to eq(49) expect(@items[2].sell_in).to eq(100) end it "ticket item change quality or day" do expect(@items[3].quality).to eq(43) expect(@items[3].sell_in).to eq(0) GildedRose.new(@items).update_quality() expect(@items[3].quality).to eq(0) end it "doubles the quality decay time if item is conjured" do rotten_tomatoes = Item.new("Conjured Tomatoes", 4, 20) @items.push(rotten_tomatoes) GildedRose.new(@items).update_quality() expect(@items[4].quality).to eq(18) end end end
require "application_system_test_case" class WishesTest < ApplicationSystemTestCase setup do @wish = wishes(:one) end test "visiting the index" do visit wishes_url assert_selector "h1", text: "Wishes" end test "creating a Wish" do visit wishes_url click_on "New Wish" fill_in "Budget achieved", with: @wish.budget_achieved fill_in "Budget plan", with: @wish.budget_plan fill_in "Description", with: @wish.description fill_in "Goal date", with: @wish.goal_date fill_in "Nb contributors", with: @wish.nb_contributors fill_in "Nb likes", with: @wish.nb_likes check "Privacy" if @wish.privacy fill_in "Title", with: @wish.title click_on "Create Wish" assert_text "Wish was successfully created" click_on "Back" end test "updating a Wish" do visit wishes_url click_on "Edit", match: :first fill_in "Budget achieved", with: @wish.budget_achieved fill_in "Budget plan", with: @wish.budget_plan fill_in "Description", with: @wish.description fill_in "Goal date", with: @wish.goal_date fill_in "Nb contributors", with: @wish.nb_contributors fill_in "Nb likes", with: @wish.nb_likes check "Privacy" if @wish.privacy fill_in "Title", with: @wish.title click_on "Update Wish" assert_text "Wish was successfully updated" click_on "Back" end test "destroying a Wish" do visit wishes_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Wish was successfully destroyed" end end
#!/usr/bin/env ruby # # Created on 2007-11-9. # Copyright (c) 2007. All rights reserved. begin require 'rubygems' rescue LoadError # no rubygems to load, so we fail silently end require 'optparse' OPTIONS = { } MANDATORY_OPTIONS = %w( ) parser = OptionParser.new do |opts| opts.banner = <<BANNER Usage: #{File.basename($0)} Options are: BANNER opts.separator "" opts.on("-p", "--password=secret", ""){|v| OPTIONS[:password] = v } opts.on("-h", "--help", "Show this help message.") { puts opts; exit } opts.parse!(ARGV) if MANDATORY_OPTIONS && MANDATORY_OPTIONS.find { |option| OPTIONS[option.to_sym].nil? } puts opts; exit end end def prompt_password puts "Truecrypt password: " system "stty -echo" OPTIONS[:password] = $stdin.gets.chomp system "stty echo" end prompt_password unless OPTIONS[:password] path = `pwd`.gsub("\n", '') command = "tc_mount --password=#{OPTIONS[:password]} #{path}/nodes.tc #{path}/nodes" pipe = IO.popen(command) while (line = pipe.gets) print line end
# -*- mode: ruby -*- # vi: set ft=ruby : ## When running `vagrant up` run it with the `--no-parallel` option. ## This ensures that the fuel_master comes up first vm_box = 'yk0/ubuntu-xenial' pxe_ip = '10.1.1.2' Vagrant.configure(2) do |config| # The most common configuration options are documented and commented below. # For a complete reference, please see the online documentation at # https://docs.vagrantup.com. # Disable the synced_folder feature config.vm.synced_folder '.', '/vagrant', :disabled => true config.vm.define :pxeserver do |node| node.vm.provider :libvirt do |domain| domain.memory = 1024 domain.cpus = 1 end node.vm.box = vm_box node.vm.hostname = "pxeserver" node.vm.network :private_network, :ip => pxe_ip, :prefix => '24', :libvirt__forward_mode => 'veryisolated', :libvirt__network_name => 'pxetest_net', :libvirt__dhcp_enabled => false node.vm.provision :ansible do |ansible| ansible.playbook = "pxeserver.yml" ansible.extra_vars = { "pxe_ip": pxe_ip } end end config.vm.define :pxevm do |node| node.vm.provider :libvirt do |domain| domain.memory = 512 domain.cpus = 1 domain.storage :file, :size => '10G', :type => 'qcow2' domain.boot 'hd' domain.boot 'network' domain.management_network_name = 'pxetest_net' domain.management_network_mac = '521122334455' domain.management_network_mode = 'veryisolated' end end end
class File def self.which? cmd dir = ENV['PATH'].split(':').find {|p| File.executable? File.join(p, cmd)} File.join(dir, cmd) unless dir.nil? end end
require 'rails_helper' describe User do it 'is instantiable' do expect{ user = User.new }.not_to raise_error end it 'defaults attributes to nil' do user = User.new expect(user.first_name).to be_nil expect(user.last_name).to be_nil expect(user.name).to be_nil expect(user.email).to be_nil expect(user.phone).to be_nil expect(user.password_digest).to be_nil end end
require "spec_helper" describe XSD::ElementsList do before do @xml = <<-XML <xs:schema targetNamespace="http://www.example.com/common" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:cm="http://www.example.com/common"> <xs:complexType name="Sequence"> <xs:sequence> <xs:sequence minOccurs="0" maxOccurs="1"> <xs:element name="first" type="xs:string" minOccurs="0"/> <xs:element name="second" type="xs:string" minOccurs="0"/> </xs:sequence> </xs:sequence> </xs:complexType> <xs:complexType name="Choice"> <xs:sequence> <xs:choice> <xs:element name="first" type="xs:string" minOccurs="0"/> <xs:element name="second" type="xs:string" minOccurs="0"/> </xs:choice> </xs:sequence> </xs:complexType> <xs:complexType name="All"> <xs:sequence> <xs:all> <xs:element name="first" type="xs:string" minOccurs="0"/> <xs:element name="second" type="xs:string" minOccurs="0"/> </xs:all> <xs:sequence> </xs:complexType> </xs:schema> XML end it "should be kind of Array" do described_class.new(stub(elements: [], :[] => nil), double).should be_kind_of Array end let(:reader) { create_reader(@xml) } subject { XSD::ComplexType.new(type, reader.schemas.first).elements.first } context "XSD::Sequence" do let(:type) { node(@xml).search('./xs:complexType')[0] } it { should be_a XSD::Sequence } it { should be_kind_of XSD::ElementsList } its(:inspect_name_type) { should eql 'Sequence[first:"string", second:"string"]'} its(:min) { should be 0 } its(:max) { should be 1 } its(:instance) { "<cm:first></cm:first><cm:second></cm:second>" } end context "XSD::Choice" do let(:type) { node(@xml).search('./xs:complexType')[1] } it { should be_a XSD::Choice } its(:inspect_name_type) { should eql 'Choice[first:"string", second:"string"]'} its(:instance) { "<!-- Choice start --><cm:first></cm:first><cm:second></cm:second><!-- Choice end -->" } end context "XSD::All" do let(:type) { node(@xml).search('./xs:complexType')[2] } it { should be_a XSD::All } its(:inspect_name_type) { should eql 'All[first:"string", second:"string"]'} its(:instance) { "<cm:first></cm:first><cm:second></cm:second>" } end end
require 'java' java_import 'net.scapeemulator.game.model.player.interfaces.Interface' java_import 'net.scapeemulator.game.model.player.skills.Skill' LEVEL_UP_WINDOW = 741 SKILL_INFO_WINDOW = 499 AMOUNT_CHILD_BUTTONS = 15 CHILD_START_BUTTON = 10 FLASHING_ICON_VARBIT = 4729 MAIN_INFO_VARBIT = 3288 CHILD_INFO_VARBIT = 3289 SKILL_BUTTONS = { Skill::ATTACK => 125, Skill::STRENGTH => 126, Skill::DEFENCE => 127, Skill::RANGED => 128, Skill::PRAYER => 129, Skill::MAGIC => 130, Skill::RUNECRAFTING => 131, Skill::CONSTRUCTION => 132, Skill::HITPOINTS => 133, Skill::AGILITY => 134, Skill::HERBLORE => 135, Skill::THIEVING => 136, Skill::CRAFTING => 137, Skill::FLETCHING => 138, Skill::SLAYER => 139, Skill::HUNTER => 140, Skill::MINING => 141, Skill::SMITHING => 142, Skill::FISHING => 143, Skill::COOKING => 144, Skill::FIREMAKING => 145, Skill::WOODCUTTING => 146, Skill::FARMING => 147, Skill::SUMMONING => 148 } module RuneEmulator class SkillMenu class << self def open_window(player, skill_id) if player.state_set.is_bit_state_active(Skill::getFlashingIcon(skill_id)) # Set the skill that we are alerting that was leveled up player.state_set.set_bit_state(FLASHING_ICON_VARBIT, Skill::getConfigValue(skill_id)) # Stop the skill icon from flashing player.state_set.set_bit_state(Skill::getFlashingIcon(skill_id), false) # Open up the level up window player.interface_set.open_window(LEVEL_UP_WINDOW) else # Set the skill info child config player.state_set.set_bit_state(CHILD_INFO_VARBIT, 0) # Set the skill that we will be viewing the menu for player.state_set.set_bit_state(MAIN_INFO_VARBIT, Skill::getConfigValue(skill_id)) # Open the window for the skill menu player.interface_set.open_window(SKILL_INFO_WINDOW) end end end end end for i in (0...AMOUNT_CHILD_BUTTONS) bind :btn, :id => SKILL_INFO_WINDOW, :component => (CHILD_START_BUTTON + i) do player.state_set.set_bit_state(CHILD_INFO_VARBIT, component - CHILD_START_BUTTON) end end for i in (0...Skill::AMOUNT_SKILLS) bind :btn, :id => Interface::SKILLS, :component => SKILL_BUTTONS[i] do RuneEmulator::SkillMenu.open_window(player, SKILL_BUTTONS.key(component)) end end
class AddColumnsToApplicantActivities < ActiveRecord::Migration def change add_column :applicant_activities, :subject, :string add_column :applicant_activities, :body, :text end end
# 正则表达式匹配 # 给定一个字符串 (s) 和一个字符模式 (p)。实现支持 '.' 和 '*' 的正则表达式匹配。 # # '.' 匹配任意单个字符。 # '*' 匹配零个或多个前面的元素。 # 匹配应该覆盖整个字符串 (s) ,而不是部分字符串。 # # 说明: # # s 可能为空,且只包含从 a-z 的小写字母。 # p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 *。 # 示例 1: # # 输入: # s = "aa" # p = "a" # 输出: false # 解释: "a" 无法匹配 "aa" 整个字符串。 # 示例 2: # # 输入: # s = "aa" # p = "a*" # 输出: true # 解释: '*' 代表可匹配零个或多个前面的元素, 即可以匹配 'a' 。因此, 重复 'a' 一次, 字符串可变为 "aa"。 # 示例 3: # # 输入: # s = "ab" # p = ".*" # 输出: true # 解释: ".*" 表示可匹配零个或多个('*')任意字符('.')。 # 示例 4: # # 输入: # s = "aab" # p = "c*a*b" # 输出: true # 解释: 'c' 可以不被重复, 'a' 可以被重复一次。因此可以匹配字符串 "aab"。 # 示例 5: # # 输入: # s = "mississippi" # p = "mis*is*p*." # 输出: false # 从第一个字符开始一个一个往后匹配,直到不能匹配或完全匹配 class OneMatch # attr_accessor :str, :pattern, :result @result = '' def initialize(s, p) @str = s @pattern = p @s_step = 0 @p_step = 0 end def do_match s_len = @str.length while @s_step < s_len end end # 可以是递归 # 匹配子串的字符,如果不匹配则做特殊匹配。默认前面字符匹配通过了才会进这里 def do_char_match end end # @param {String} s # @param {String} p # @return {Boolean} def is_match(s, p) OneMatch.new(s, p).do_match end puts is_match("aa", "a*")
class Gallories::ProductsController < ApplicationController def show @product = Product.active.find(params[:id]) roomtype = @product.showroom_type # returns bedroom or livingroom root showroom = current_user.send(roomtype.name.downcase.to_sym) @has_product = showroom ? showroom.has_product?(@product.id) : false respond_to do |format| format.json { render :json => { :product => @product.as_json( :only => [ :id, :name, :description, :external_link ], :methods => :featured_product_image), :has_product => @has_product } } end end def create @product = Product.find(params[:product_id]) roomtype = @product.showroom_type # returns bedroom or livingroom root showroom = current_user.send(roomtype.name.downcase.to_sym) if showroom && !ShowroomProduct.where(:product_id => params[:product_id], :showroom_id => showroom.id, :active => true ).first @showroom_product = showroom.showroom_products.new(:product_id => @product.id) @showroom_product.save respond_to do |format| format.json { render :json => @showroom_product.to_json( :only => [ :id, :product_id]) } end else respond_to do |format| format.json { render :json => :ok, :status => 400 } end end end def destroy @product = Product.find(params[:product_id]) roomtype = @product.showroom_type # returns bedroom or livingroom root showroom = current_user.send(roomtype.name.downcase.to_sym) showroom_product = ShowroomProduct.where(:product_id => params[:product_id], :showroom_id => showroom.id, :active => true).first showroom_product.inactivate if showroom_product render :json => :ok end private def form_info end end
class User < ActiveRecord::Base devise :database_authenticatable, :registerable, :confirmable, :recoverable, :rememberable, :trackable, :validatable # Associations for User with Users_role and Role has_many :users_roles has_many :roles, through: :users_roles # Associations for User with profile has_one :profile accepts_nested_attributes_for :profile attr_accessor :skip_password_validation attr_accessor :name has_attached_file :avatar, default_url: 'profile-icon.png', styles: { thumb: '100x100#', small: '150x150>', medium: '200x200!' } # has_attached_file :avatar, # :path => ":rails_root/public/system/:attachment/:id/:style/:filename", # :url => "/system/:attachment/:id/:style/:filename", # :styles => { :medium => "300x300>", :thumb => "100x100>" }, # :default_url => "profile-icon.png" # # Validating Image For Specific Types. validates_attachment :avatar, content_type: { content_type: ['image/jpeg', 'image/gif', 'image/png'] } # This Action will allow to find whether the user holds the role as Admin def is_admin? status = false roles.each do |role_entry| status = true if role_entry.name == 'Admin' end status end # This Action will allow to find whether the user holds the role as Prospect def is_prospect? status = false roles.each do |role_entry| status = true if role_entry.name == 'Prospect' end status end # This action will allow to set default role as prospect at sign up def set_prospect_role_at_sign_up UsersRole.new.add(Role.where(name: 'Prospect').first.id, User.last.id) end # This action will allow to set role at the time of admin create new user def set_role_by_admin(role_id, user_id) UsersRole.new.add(role_id, user_id) end private def password_required? return false if skip_password_validation super end def strip_whitespace self.first_name = first_name.strip unless first_name.nil? self.last_name = last_name.strip unless last_name.nil? end def self.get_all_users return User.all end end
# frozen_string_literal: true module Types MutationType = GraphQL::ObjectType.define do name 'Mutation' description 'Root query to mutate data' field :createChallenge, function: ::Mutations::Create::Challenge.new field :createCompletion, function: ::Mutations::Create::Completion.new field :createParticipation, function: ::Mutations::Create::Participation.new field :createRecordBook, function: ::Mutations::Create::RecordBook.new field :createUser, function: ::Mutations::Create::User.new field :login, function: ::Mutations::Login.new field :updateChallenge, function: ::Mutations::Update::Challenge.new field :updateCompletion, function: ::Mutations::Update::Completion.new field :updateParticipation, function: ::Mutations::Update::Participation.new field :updateRecordBook, function: ::Mutations::Update::RecordBook.new field :updateUser, function: ::Mutations::Update::User.new field :destroyUser, function: ::Mutations::Destroy::User.new end end
class Galette < Formula homepage "https://github.com/simon-frankau/galette" head "https://github.com/simon-frankau/galette.git" depends_on "rust" => :build def install system "cargo", "build", "--release", "--bin", "galette" bin.install "target/release/galette" end end
Given(/^user logged in with new user name "([^"]*)" credentials$/) do |username| @user_name=username visit(LoginPage) on(LoginPage) do |page| DataMagic.load("account_combination.yml") login_data = page.data_for(:account_combination) password = login_data['password'] ssoid = login_data[username + "_ssoid"] page.login(username, password, ssoid) end # visit(LoginPage) # on(LoginPage) do |page| # username = page.data_for(:make_one_time_payment_multi_acct_login)['username'] # password = page.data_for(:make_one_time_payment_multi_acct_login)['password'] # ssoid = page.data_for(:make_one_time_payment_multi_acct_login)['ssoid'] # page.login(username,password,ssoid) # sleep 10 # end end And(/^the user click on the "([^"]*)" option from the service menu drop down$/) do |arg| on(NavigationBar).go_to("more") sleep 10 end And(/^the user click on the Services button$/) do visit MoreServicePage on (MoreServicePage) do |page| page.wait_for_page_to_load DataMagic.load("moreservices.yml") expect(page.service_button_element.text).to eq (data_for(:more_services)['service_button']) page.service_button end end Then(/^the user will view the text "([^"]*)"$/) do |message| visit MoreServicePage on (MoreServicePage) do |page| page.wait_for_page_to_load page.cos_page page.wait_for_few_sec DataMagic.load("moreservices.yml") expect(page.header_element.text).to eq (data_for(:more_services)['header']) end end Then(/^the user will have the phone number "(.*)" displayed on the More Services Page$/) do |callusno| on(MoreServicePage) do |page| expect(page.call_us_info_number_element.text).to eq (data_for(:more_services)['call_us_number']) end end Then(/^text "TDD \(for hearing impaired\)" will display on the More Services Page$/) do on(MoreServicePage) do |page| expect(page.hearing_impaired_element.text).to eq (data_for(:more_services)['tdd_hearing']) end end And(/^the "1 \(800\) 205\-7966" will display on the More Services Page$/) do on(MoreServicePage) do |page| expect(page.hearing_impaied_number_element.text).to eq (data_for(:more_services)['tdd_hearing_number']) end end Then(/^the text "([^"]*)" will display on the More Services Page$/) do |message| on (MoreServicePage) do |page| expect(page.international_collect_element.text).to eq (data_for(:more_services)['international_collect']) end end And(/^"1 \(800\) 934\-2001" will display on the More Services Page$/) do on (MoreServicePage) do |page| expect(page.international_collect_number_element.text).to eq(data_for(:more_services)['international_collect_number']) end end Then(/^the text "([^"]*)" will display on the More Services Page$/) do |message| on (MoreServicePage) do |page| expect(page.rewards_center_text_element.text).to eq (data_for(:more_services)['rewards_text']) end end And(/^"1\-801\-834\-2001" will display on the More Services Page$/) do on (MoreServicePage) do |page| expect(page.rewards_center_number).to eq (data_for(:more_services)['rewards_number']) end end Then(/^the user clicks the link named "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| page.wait_for_few_sec expect(page.viewAllContactOptions_element.text).to eq (data_for(:more_services)['view_all_contact']) page.viewAllContactOptions end end And(/^the user is on the "([^"]*)" Section of the More Services Page\.$/) do |message| on (MoreServicePage) do |page| @browser.windows.last.use expect(page.eos_contact_us).to eq (data_for(:more_services)['contact_header']) end end And(/^the user is on the "([^"]*)" section of the More Services Page$/) do |message| on (MoreServicePage) do |page| DataMagic.load("moreservices.yml") expect(page.customer_services).to eq (data_for(:more_services)['customer_header']) end end And(/^the user select the one option under "([^"]*)"$/) do |message| on (MoreServicePage) do |page| expect(page.get_help).to eq(data_for(:more_services)['get_help_header']) end end And(/^the user clicks on the link named "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| expect(page.lost_stolen_element.text).to eq (data_for(:more_services)['report_lstln']) page.lost_stolen end end Then(/^the user will be presented with information "([^"]*)" on the process for handling lost or stolen cards\.$/) do |message| on(MoreServicePage) do |page| page.wait_for_page_to_load expect(page.cos_lost_stolen_element.text).to eq (data_for(:more_services)['report_lstln_page']) page.cos_lost_stolen end end Then(/^the user clicks on Dispute a Charge link$/) do on (MoreServicePage) do |page| page.wait_for_page_to_load expect(page.dispute_a_charge_element.text).to eq (data_for(:more_services)['dispute_a_charge']) page.dispute_a_charge end end And(/^the user will be presented with information on the process for Disputing a Charge "([^"]*)"$/) do |message| on (MoreServicePage) do |page| page.wait_for_page_to_load expect(page.can_dispute_a_charge_title_element.text).to eq (data_for(:more_services)['dispute_a_charge_page']) end end Then(/^the user clicks the link Close Your Account$/) do on (MoreServicePage) do |page| expect(page.close_your_account_element.text).to eq (data_for(:more_services)['close_account']) page.close_your_account end end And(/^the user will be presented with information on the process for closing their account "([^"]*)"$/) do |message| on (MoreServicePage) do |page| # page.wait_for_page_to_load expect(page.cos_close_your_account_element.text).to eq (data_for(:more_services)['close_account_page']) end end Then(/^the user clicks the link FAQ$/) do on (MoreServicePage) do |page| expect(page.faq_element.text).to eq (data_for(:more_services)['faq']) page.faq end end And(/^the user will be routed to FAQ Page$/) do pending end And(/^the user is on the "([^"]*)" section of the services Page$/) do |message| on (MoreServicePage) do |page| page.wait_for_page_to_load expect(page.accountInfo).to eq (data_for(:more_services)['account_info']) end end When(/^the user clicks the link named as "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| expect(page.requestCreditCardAgreement_element.text).to eq (data_for(:more_services)['req_credit']) page.requestCreditCardAgreement end end Then(/^the user will be presented with the credit card agreement$/) do on (MoreServicePage) do |page| expect(page.requestCreditCardAgreement_page_element.text).to eq (data_for(:more_services)['req_credit_page']) end end When(/^the user click the link named "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| expect(page.onlineBankingTermsAndConditions_element.text).to eq (data_for(:more_services)['online_bank']) page.onlineBankingTermsAndConditions end end Then(/^the user will be presented with the online banking terms and conditions "([^"]*)"$/) do |message| on (MoreServicePage) do |page| @browser.windows.last.use expect(page.eos_onlineBanking_element.text).to eq (data_for(:more_services)['online_bank_page']) end end When(/^the user select the link named "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| expect(page.autoPayTermsAndConditions_element.text).to eq (data_for(:more_services)['auto_pay']) page.autoPayTermsAndConditions end end Then(/^the user will be presented with the auto pay terms and conditions "([^"]*)"$/) do |message| on (MoreServicePage) do |page| @browser.windows.last.use expect(page.auto_pay_element.text).to eq (data_for(:more_services)['auto_pay_page']) end end And(/^the user is on the "([^"]*)" section of the more Services Page$/) do |message| on (MoreServicePage) do |page| expect(page.financialInfo).to eq (data_for(:more_services)['financial_info']) end end When(/^the user clicks the "([^"]*)" link$/) do |arg| on (MoreServicePage) do |page| expect(page.paymentCalculator_element.text).to eq (data_for(:more_services)['pay_cal']) page.paymentCalculator end end Then(/^the user will be presented with payment calculator functionality "([^"]*)"$/) do |message| on (MoreServicePage) do |page| @browser.windows.last.use expect(page.payment_calculator_element.text).to eq (data_for(:more_services)['pay_cal_page']) end end When(/^the user clicks the "([^"]*)" link$/) do |arg| on (MoreServicePage) do |page| expect(page.financialeducation_element.text).to eq (data_for(:more_services)['financial_edu']) page.financialeducation end end Then(/^the user will be presented with financial education information "([^"]*)"$/) do |message| on (MoreServicePage) do |page| @browser.windows.last.use expect(page.financial_education_element.text).to eq (data_for(:more_services)['financial_edu_page']) end end And(/^the user is on the "([^"]*)" Section of the More Services Page$/) do |message| on (MoreServicePage) do |page| DataMagic.load("moreservices.yml") expect(page.digital_servicing).to eq(data_for(:more_services)['digital_header']) end end And(/^the user is on "([^"]*)" Section of the More Services Page$/) do |message| on (MoreServicePage) do |page| expect(page.mobile_banking_element.text).to eq (data_for(:more_services)['mob_header']) end end When(/^clicks the link named "([^"]*)"$/) do |arg| DataMagic.load("moreservices.yml") on (MoreServicePage) do |page| expect(page.mobile_download_apps_element.text).to eq (data_for(:more_services)['mob_download']) page.mobile_download_apps end end Then(/^the canadian user will be presented with the functionality to download mobile applications "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| @browser.windows.last.use expect(page.download_mobile_element.text).to eq (data_for(:more_services)['canada_mob_download_page']) end end Then(/^the user will be presented with the functionality to download mobile applications "([^"]*)"$/) do |message| on (MoreServicePage) do |page| @browser.windows.last.use expect(page.download_mobile_element.text).to eq (data_for(:more_services)['mob_download_page']) end end When(/^click the link named "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| expect(page.manage_text_messaging_element.text).to eq (data_for(:more_services)['mob_text_message']) page.manage_text_messaging end end Then(/^the user will be presented with the functionality to manage text messaging "([^"]*)"$/) do |message| on (MoreServicePage) do |page| @browser.windows.last.use expect(page.manage_text_mobile_element.text).to eq (data_for(:more_services)['mob_text_message_page']) end end And(/^the user is on the "([^"]*)" section$/) do |message| on(MoreServicePage) do |page| DataMagic.load("moreservices.yml") expect(page.card_services_title_element.text).to eq (data_for(:more_services)['digital_card']) end end When(/^user clicks the link named "([^"]*)"$/) do |arg| on(MoreServicePage) do |page| expect(page.manage_authorized_element.text).to eq (data_for(:more_services)['manage_auth_user']) page.manage_authorized end end Then(/^the user will be presented with the functionality to manage authorized users "([^"]*)"$/) do |message| on(MoreServicePage) do |page| page.wait_for_few_sec # page.wait_for_page_to_load expect(page.manage_authorized_user_element.text).to eq (data_for(:more_services)['manage_auth_user_page']) end end When(/^the user clicks the link "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| expect(page.travel_notification_element.text).to eq (data_for(:more_services)['travel_notification']) page.travel_notification end end Then(/^the user will be presented with the functionality to set travel notifications "([^"]*)"$/) do |message| on (MoreServicePage) do |page| expect(page.set_travel_notification_element.text).to eq (data_for(:more_services)['travel_notification_page']) end end When(/^the user clicks the link named "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| expect(page.link_account_element.text).to eq (data_for(:more_services)['link_account']) page.link_account end end Then(/^the user will be presented with the functionality to link accounts "([^"]*)"$/) do |message| on (MoreServicePage) do |page| expect(page.link_accounts_element.text).to eq (data_for(:more_services)['link_account_page']) end end When(/^the user clicks the link named "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| expect(page.image_link_element.text).to eq (data_for(:more_services)['image_link']) page.image_link end end Then(/^the user will be presented with the functionality to change the image on a card "([^"]*)"$/) do |message| on (MoreServicePage) do |page| expect(page.image_card_link_element.text).to eq (data_for(:more_services)['image_link_page']) end end When(/^the user clicks the link named "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| expect(page.change_payment_duedate_element.text).to eq (data_for(:more_services)['pymt_due_date']) page.change_payment_duedate end end Then(/^the user will be presented with the functionality to change a payment due date "([^"]*)"$/) do |message| on (MoreServicePage) do |page| expect(page.pymt_due_date_element.text).to eq (data_for(:more_services)['pymt_due_date_page']) end end When(/^user clicks the link named Set Over\-Limit Preferences$/) do on (MoreServicePage) do |page| expect(page.over_lmt_pref_element.text).to eq (data_for(:more_services)['set_over_lmt']) page.over_lmt_pref end end Then(/^the user will be presented with the functionality to set over\-limit preferences "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| #puts page.over_lmt_check.include? 'Set Over-Limit Preference' #puts @browser.Element("strong" #expect(@browser.div(:id, 'content').text.include? 'Set Over-Limit Preference').to eq(true) puts @browser.div(:id, 'intro').visible? #puts (page.over_lmt_check_element).visible? #puts page.over_lmt_check #puts expect(@browser.text.include? 'Set Over-Limit Preference').to eq(true) #puts expect(page.text.include? 'Set Over-Limit Preference').to eq(true) #puts expect(page.text.include? 'Over-limit refers to when you exceed the credit limit on your credit card account.').to eq(true) # expect(page.over_lmt_check_element.text).to eq (data_for(:more_services)['set_over_lmt_page']) end end When(/^the user clicks the link named "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| expect(page.transfer_balance_element.text).to eq (data_for(:more_services)['transfer_balance']) page.transfer_balance end end Then(/^the user will be presented with the functionality to transfer a balance "([^"]*)"$/) do |message| on (MoreServicePage) do |page| @browser.windows.last.use puts expect(page.transfer_a_balance_page_element.text).to eq (data_for(:more_services)['transfer_balance_page']) end end When(/^the user clicks the link named "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| expect(page.credit_line_increase_element.text).to eq (data_for(:more_services)['req_crd_lmt']) page.credit_line_increase end end Then(/^the user will be presented with the functionality to request a credit line increase "([^"]*)"$/) do |message| on (MoreServicePage) do |page| page.wait_for_few_sec expect(page.credit_line_increase_validation_element.text).to eq (data_for(:more_services)['req_crd_lmt_page']) end end When(/^the user clicks the link named "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| DataMagic.load("moreservices.yml") expect(page.account_combination_element.text).to eq (data_for(:more_services)['acc_combo']) page.account_combination end end Then(/^the user will be routed to account combination modal page "([^"]*)"$/) do |message| on (MoreServicePage) do |page| page.wait_for_page_to_load DataMagic.load("moreservices.yml") expect(page.acc_combination_header_element.text).to eq (data_for(:more_services)['acc_combo_page']) end end When(/^the user clicks the link named as "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| expect(page.set_alerts_element.text).to eq (data_for(:more_services)['set_alert']) page.set_alerts end end Then(/^the user will be presented with the functionality to Set Alerts "([^"]*)"$/) do |message| on (MoreServicePage) do |page| expect(page.set_alerts_title_element.text).to eq (data_for(:more_services)['set_alert_page']) end end When(/^the user clicks the link name "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| expect(page.manage_nick_names_element.text).to eq (data_for(:more_services)['manage_nick_names']) page.manage_nick_names end end Then(/^the following text will be displayed on the Manage Nick Name page "([^"]*)"$/) do |message| on (MoreServicePage) do |page| page.wait_for_few_sec expect(page.manage_nick_names_title_element.text).to eq (data_for(:more_services)['manage_nick_names_page']) end end Then(/^the user finds the chat link named "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| page.wait_for_page_to_load expect(page.chat_live_now_element.text).to eq (data_for(:more_services)['chat']) page.chat_live_now end end And(/^the user will be routed to the "([^"]*)" in a pop up window in eos$/) do |arg| on (MoreServicePage) do |page| page.wait_for_page_to_load expect(page.view_contact_us_element.text).to eq (data_for(:more_services)['view_all_contact_page']) end end Then(/^the user clicks the link named "([^"]*)"$/) do |arg| on (MoreServicePage) do |page| page.wait_for_page_to_load expect(page.make_secured_card_element.text).to eq (data_for(:more_services)['secured_card']) page.make_secured_card end end And(/^the user will be routed to the "([^"]*)" in a pop up window in ssp$/) do |arg| on (MoreServicePage) do |page| @browser.windows.last.use puts expect(page.make_secured_card_page_element.text).to eq (data_for(:more_services)['secured_card_page']) end end Then(/^"([^"]*)" link will not be displayed\.$/) do |arg| on (MoreServicePage) do |page| expect(page.make_secured_card_element.visible?).to eq (false) end end And(/^the image should be displayed above the Card Services$/) do # puts expect(@browser.image(:class =>'blue-icon').alt).to eq("card services icon") on (MoreServicePage) do |page| expect(page.more_service_page_image (1)).to eq (data_for(:more_services)['img_card_services']) end end And(/^the image should be displayed above the Mobile Banking$/) do on (MoreServicePage) do |page| expect(page.more_service_page_image (2)).to eq(data_for(:more_services)['img_mobile_banking']) end end And(/^the image should be displayed above the Get Help$/) do on (MoreServicePage) do |page| expect(page.more_service_page_image (3)).to eq(data_for(:more_services)['img_get_help']) end end And(/^the image should be displayed above the Account Info$/) do on (MoreServicePage) do |page| expect(page.more_service_page_image (4)).to eq(data_for(:more_services)['img_account_info']) end end And(/^the image should be displayed above the Financial Info$/) do on (MoreServicePage) do |page| expect(page.more_service_page_image (5)).to eq(data_for(:more_services)['img_financial_info']) end end And(/^the image should be displayed above the Contact US$/) do on (MoreServicePage) do |page| expect(page.more_service_page_image (6)).to eq(data_for(:more_services)['img_contact_us']) end end Then(/^the user will view all the link on the page$/) do on (MoreServicePage) do |page| page.wait_for_page_to_load expect(page.digital_servicing).to eq (data_for(:more_services)['digital_header']) expect(page.card_services_title).to eq (data_for(:more_services)['digital_card']) expect(page.make_secured_card_element.text).to eq (data_for(:more_services)['secured_card']) expect(page.manage_authorized_element.text).to eq (data_for(:more_services)['manage_auth_user']) expect(page.set_alerts_element.text).to eq (data_for(:more_services)['set_alert']) expect(page.manage_nick_names_element.text).to eq (data_for(:more_services)['manage_nick_names']) expect(page.travel_notification_element.text).to eq (data_for(:more_services)['travel_notification']) expect(page.link_account_element.text).to eq (data_for(:more_services)['link_account']) expect(page.image_link_element.text).to eq (data_for(:more_services)['image_link']) expect(page.change_payment_duedate_element.text).to eq (data_for(:more_services)['pymt_due_date']) expect(page.over_lmt_pref_element.text).to eq (data_for(:more_services)['set_over_lmt']) expect(page.transfer_balance_element.text).to eq (data_for(:more_services)['transfer_balance']) expect(page.credit_line_increase_element.text).to eq (data_for(:more_services)['req_crd_lmt']) # expect(page.account_combination_element.text).to eq (data_for(:more_services)['acc_combo']) expect(page.mobile_banking_element.text).to eq (data_for(:more_services)['mob_header']) # expect(page.mobile_download_apps_element.text).to eq (data_for(:more_services)['mob_download']) expect(page.manage_text_messaging_element.text).to eq (data_for(:more_services)['mob_text_message']) expect(page.customer_services).to eq (data_for(:more_services)['customer_header']) expect(page.get_help).to eq (data_for(:more_services)['get_help_header']) expect(page.lost_stolen_element.text).to eq (data_for(:more_services)['report_lstln']) expect(page.dispute_a_charge_element.text).to eq (data_for(:more_services)['dispute_a_charge']) expect(page.close_your_account_element.text).to eq (data_for(:more_services)['close_account']) expect(page.faq_element.text).to eq (data_for(:more_services)['faq']) expect(page.accountInfo).to eq (data_for(:more_services)['account_info']) expect(page.requestCreditCardAgreement_element.text).to eq (data_for(:more_services)['req_credit']) expect(page.onlineBankingTermsAndConditions_element.text).to eq (data_for(:more_services)['online_bank']) expect(page.autoPayTermsAndConditions_element.text).to eq (data_for(:more_services)['auto_pay']) expect(page.financialInfo).to eq (data_for(:more_services)['financial_info']) expect(page.paymentCalculator_element.text).to eq (data_for(:more_services)['pay_cal']) expect(page.financialeducation_element.text).to eq (data_for(:more_services)['financial_edu']) expect(page.eos_contact_us).to eq (data_for(:more_services)['contact_header']) # expect(page.call_us_info_number).to eq (data_for(:more_services)['call_us_number']) expect(page.hearing_impaired_element.text).to eq (data_for(:more_services)['tdd_hearing']) expect(page.hearing_impaied_number_element.text).to eq (data_for(:more_services)['tdd_hearing_number']) expect(page.international_collect_element.text).to eq (data_for(:more_services)['international_collect']) expect(page.international_collect_number_element.text).to eq(data_for(:more_services)['international_collect_number']) expect(page.rewards_center_text_element.text).to eq (data_for(:more_services)['rewards_text']) expect(page.rewards_center_number_element.text).to eq (data_for(:more_services)['rewards_number']) expect(page.viewAllContactOptions_element.text).to eq (data_for(:more_services)['view_all_contact']) # expect(page.more_service_page_image (1)).to eq (data_for(:more_services)['img_card_services']) # expect(page.more_service_page_image (2)).to eq(data_for(:more_services)['img_mobile_banking']) # expect(page.more_service_page_image (3)).to eq(data_for(:more_services)['img_get_help']) # expect(page.more_service_page_image (4)).to eq(data_for(:more_services)['img_account_info']) # expect(page.more_service_page_image (5)).to eq(data_for(:more_services)['img_financial_info']) # expect(page.more_service_page_image (6)).to eq(data_for(:more_services)['img_contact_us']) end end And(/^the user select different sub menu$/) do on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("transactions_and_details") on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("statements_and_documents") on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("download_transactions") on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("accounts_rewards_summary") on(NavigationBar).go_to("more") # puts on(NavigationBar).go_to("modify_your_features") # on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("payment_activity") on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("make_a_payment") on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("manage_autopay") on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("manage_payment_accounts") on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("message_center") on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("compose_secure_message") on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("set_alerts") on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("alert_history") on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("alert_contact_points") on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("benefits_rewards_summary") on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("credit_tracker") on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("card_benefits") on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("update_contact_info") on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("update_income_info") on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("update_sign_in_info") on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("update_paperless_settings") on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("manage_authorized_users") on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("set_travel_notification") on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("lost_stolen_replacement_card") on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("replace_lost_or_damaged_card") on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("request_replacement_card") on(NavigationBar).go_to("more") # on(NavigationBar).go_to("account_combination") # on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("link_your_accounts") on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("change_image_on_card") on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("change_payment_due_date") on(NavigationBar).go_to("more") puts on(NavigationBar).go_to("transfer_a_balance") on(NavigationBar).go_to("more") end
class AddDefaultValueToEmail < ActiveRecord::Migration[6.0] def change change_column_default(:stores, :email, 'francisco.abalan@pjchile.com') end end