text
stringlengths
10
2.61M
class AddAssociationsBetweenTransactionsAndSubmissions < ActiveRecord::Migration[6.0] def change add_reference :transactions, :submission, type: :uuid end end
class Order < ApplicationRecord validates :address, :name, presence: true has_many :order_items, dependent: :destroy belongs_to :customer, optional: true enum order_status: { wait: 0, payment: 1, make: 2, preparing: 3, done: 4 } enum payment: { card: 0, bank: 1 } VALID_POSTAL_CODE_REGEX = /\A\d{7}\z/ #\Aใ‹ใ‚‰ๅง‹ใพใ‚Š\zใซ็ต‚ใ‚ใ‚‹\d{7}7ๆกใฎๆ•ฐๅญ— validates :postal_code, presence: true, format: { with: VALID_POSTAL_CODE_REGEX } def subtotal order_items.to_a.sum { |item| item.subtotal } end end
require 'rake/clean' require 'rspec/core/rake_task' require 'maestro/plugin/rake_tasks' require 'json' # to merge manifests $:.push File.expand_path('../src', __FILE__) CLEAN.include('manifest.json', '*-plugin-*.zip', 'vendor', 'package', 'tmp', '.bundle', 'manifest.template.json') task :default => :all task :all => [:clean, :spec, :bundle, :package] RSpec::Core::RakeTask.new Maestro::Plugin::RakeTasks::BundleTask.new Maestro::Plugin::RakeTasks::PackageTask.new task :package => :mergemanifest desc "Generate manifest" task :mergemanifest do # merge manifests into manifest.json manifest = [] merge_manifests(manifest, "provision") merge_manifests(manifest, "deprovision") merge_manifests(manifest, "find") merge_manifests(manifest, "update") merge_manifests(manifest, "create") merge_manifests(manifest, "modify") merge_manifests(manifest, "associate-address") merge_manifests(manifest, "disassociate-address") File.open("manifest.template.json",'w'){ |f| f.write(JSON.pretty_generate(manifest)) } end # Parse all partial manifests and merge them def merge_manifests(manifest, action) files = FileList["manifests/*-#{action}.json"] parent = JSON.parse(IO.read("manifests/#{action}.json")) files.each do |f| provider = f.match(/manifests\/(.*)-#{action}.json/)[1] puts "Processing file [#{provider}] #{f}" # merge connection options into both provision and deprovision for each provider connect_parent_f = "manifests/#{provider}-connect.json" if File.exist? connect_parent_f connect_parent = JSON.parse(IO.read(connect_parent_f)) # no fields are required for deprovision, set them to nil connect_parent["task"]["inputs"].each{|k,v| v["value"]=nil; v["required"]=false} if action == "deprovision" merged = merge_manifest(parent, JSON.parse(IO.read(f))) merged = merge_manifest(merged, connect_parent) else merged = merge_manifest(parent, JSON.parse(IO.read(f))) end manifest << merged end end def merge_manifest(parent, json) json.merge(parent) do |key, jsonval, parentval| if parentval.kind_of?(Hash) merged = merge_manifest(parentval, jsonval) elsif parentval.kind_of?(Array) jsonval.map {|i| i.kind_of?(Hash) ? merge_manifest(parentval.first, i) : jsonval} else jsonval end end end
# # top-fans will take a stdin list of collapsed graphs (see note-collapse) # read through the posts, and then print out the top rebloggers # and fans from all those in stdin. # # By using stdin, this allows one to read over multiple blogs. # require 'rubygems' require 'bundler' Bundler.require def find_similar(list) limit = 35 whoMap = {} count = 0 list.split(',').each { | row | blog, entry = row.split(';') file = "/raid/tumblr/#{blog}.tumblr.com/graphs/#{entry}.json" count += 1 File.open(file, 'r') { | content | json=JSON.parse(content.read) metric = Math.sqrt(1.0/json.length) json[0..1000].each { | entry | if entry.is_a?(String) who = entry else who, source, post = entry who=source end whoMap[who] = metric + (whoMap[who] || 0.0) } } } whoMap.sort_by { | who, count | (1 - count) }[0..limit] end
# -*- coding: utf-8 -*- require 'rspec' require 'catan' require 'colorize' describe Board do let(:game) { Game.new()} subject(:board) { Board.new(game) } context "after initialization" do it "has the right amount of roads" do expect(board.rds.count).to eq(72) end it "has the right amount of tiles" do expect(board.find_all(Tile).uniq.count).to eq(19) end it "has the right amount of intersections" do expect(board.find_all(Intersection).count).to eq(54) end it "finds intersections by their number" do expect( board.intersection_at("E2") ).to be_a(Intersection) end it "finds the neighbors of intersections and tiles" do e2 = board.intersection_at("E2") expect(e2.neighboring(Intersection).map{ |ixs| ixs.number }.join(' ') ) .to eq("D2 F2 F3") end end context "when game is in progress" do it "finds the longest road" it "finds the largest army" end end
require File.expand_path(File.join(File.dirname(__FILE__), "..", "support", "paths")) Given /^I am not logged in$/ do end Then /^I should see a link to "([^\"]*)"$/ do |text| response.should have_selector("a", :content => text) end Then /^I should see an? "([^\"]*)" field$/ do |label| field_labeled(label).should_not be_nil end Then /^I should see a radio button with name "([^\"]*)"$/ do |label| response.should have_selector("input", :type => 'radio', :name => label) end Then /^I should see an? "([^\"]*)" button$/ do |label| response.should have_selector("input", :type => 'submit', :value => label) end Then /^I should see a user menu for "([^\"]*)"$/ do |username| response.should have_selector("div#user-menu") do |um| um.should contain(username) um.should contain("Logout") end end Then /^I should see an error saying "([^\"]*)"$/ do |msg| response.should have_selector("p", :content => msg) end Then /^I should see a notice saying "([^\"]*)"$/ do |msg| response.should have_selector("p.flash.notice", :content => msg) end Then /^I should see an error notice saying "([^\"]*)"$/ do |msg| response.should have_selector("p.flash.error", :content => msg) end When /^I register as:$/ do |table| hash = table.hashes[0] When 'I go to new user' When "I fill in \"Username\" with \"#{hash[:username]}\"" When "I fill in \"Password\" with \"#{hash[:password]}\"" When "I fill in \"Password confirmation\" with \"#{hash[:password_confirmation]}\"" When "I fill in \"Email Address\" with \"#{hash[:email]}\"" When "I select \"#{hash[:birthdate]}\" as the date" When "I select \"#{hash[:county]}\" from \"County\"" When "I fill in \"City\" with \"#{hash[:city]}\"" if hash[:gender] =~ /man/i choose 'user_gender_id_1' else choose 'user_gender_id_2' end if hash[:looking_fo] =~ /man/i choose 'user_looking_for_id_1' else choose 'user_looking_for_id_2' end When 'I press "Register"' end
require File.join(File.dirname(__FILE__), 'setup') require 'active_support/test_case' require 'logger' active_record_spec = Gem::Specification.find_by_name("activerecord") active_record_path = active_record_spec.gem_dir $LOAD_PATH << File.join(active_record_path, "test") module SlimScrooge class Test class << self def setup setup_constants make_sqlite_config make_sqlite_connection load_models load(SCHEMA_ROOT + "/schema.rb") require 'test/unit' end def test_files glob("#{File.dirname(__FILE__)}/**/*_test.rb") end def test_model_files %w{course} end private def setup_constants set_constant('TEST_ROOT') {File.expand_path(File.dirname(__FILE__))} set_constant('SCHEMA_ROOT') {TEST_ROOT + "/schema"} end def make_sqlite_config ActiveRecord::Base.configurations = { 'db' => { :adapter => 'sqlite3', :database => ':memory:', :timeout => 5000 } } end def load_models test_model_files.each {|f| require File.join(File.dirname(__FILE__), "models", f)} end def make_sqlite_connection ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['db']) ActiveRecord::Base.logger = Logger.new(STDERR) end def set_constant(constant) Object.const_set(constant, yield) unless Object.const_defined?(constant) end def glob(pattern) Dir.glob(pattern) end end end class ActiveRecordTest < Test class << self def setup setup_constants end def test_files (glob("#{active_record_path}/test/cases/**/*_test.rb").reject { |x| x =~ /\/adapters\// } + Dir.glob("test/cases/adapters/sqlite3/**/*_test.rb")).sort end def active_record_path active_record_spec = Gem::Specification.find_by_name("activerecord") active_record_spec.gem_dir end def connection File.join(active_record_path, 'connections', 'native_mysql') end end end end
class Dog attr_accessor :name, :breed, :age, :bark, :favorite_foods def initialize(name,breed,age,bark,favorite_foods) @name = name @breed = breed @age = age @bark = bark @favorite_foods = favorite_foods end def bark if @age<=3 return @bark.downcase else return @bark.upcase end end def favorite_food?(food_item) return @favorite_foods.map{|x|x.downcase}.include?(food_item.downcase) end end noodles = Dog.new("Noodles", "German Shepard", 3, "Bork!", ["Sausage", "Chicken"]) p noodles.bark p noodles.favorite_foods p noodles.favorite_food?("SaUsage") p noodles.age noodles.age = 5 p noodles.age
feature 'Hit points' do scenario "I can see player 2's hit points" do sign_in_and_play expect(page).to have_content "Guilliman: 60/60hp" end end
class CreateInvoices < ActiveRecord::Migration def change create_table :invoices do |t| t.string :name t.string :address1 t.string :address2 t.string :num_ext t.string :num_int t.string :state t.string :city t.string :country t.string :rfc t.string :cp t.boolean :favorite, default: false t.references :doctor, index: true, foreign_key: true t.timestamps null: false end end end
require 'date' Gem::Specification.new do |s| s.name = 'git-run' s.version = '0.0.0' s.date = Date.today.to_s s.summary = "git run" s.description = "git run runs commands in git revisions" s.authors = ["Jeff Kreeftmeijer"] s.email = 'jeff@kreeftmeijer.nl' s.files = ["lib/git_run.rb"] s.executables = ["git-run"] s.homepage = 'https://github.com/jeffkreeftmeijer/git-run' s.license = 'MIT' s.add_runtime_dependency 'rugged', '~> 0.23' s.add_development_dependency 'minitest', '~> 5.8' end
class PetPersonality < ApplicationRecord belongs_to :pet validates :personality, presence: true enum personality: { ใŠใจใชใ—ใ„: 1, ใ•ใฟใ—ใŒใ‚Š: 2, ใ‚„ใ‚“ใกใ‚ƒ: 3, ใ‹ใ—ใ“ใ„: 4, ใฎใ‚“ใ: 5, ใŠใใณใ‚‡ใ†: 6, ใใพใใ‚Œ: 7, ไธ–่ฉฑๅฅฝใ: 8, ๅ…ƒๆฐ—: 9, ้ฃŸใ„ใ—ใ‚“ๅŠ: 10 } end
# frozen_string_literal: true module SystemCtl class ExperimentalRunInfoGenerator def initialize(commandline) @commandline = commandline end def run_info(service_id) snapshot = run_snapshot { user: snapshot.key?(service_id) ? snapshot[service_id] : nil, status: snapshot.key?(service_id) ? :started : :stopped, } end def reset @run_snapshot = nil end private def run_snapshot @run_snapshot ||= begin snapshot = {} uid = nil lines = @commandline.invoke("status --no-pager --no-legend").lines lines.each do |line| line.match(/system\.slice/) { |match| uid = 0 } line.match(/user-([\d]+)\.slice/) { |match| uid = match[1].to_i } line.match(/([\w+-.@]+)\.service/) do |match| raise("This should not happen. `#{@systemctl} status` output might differ from what is expected.") unless uid service_id = match[1] snapshot[service_id] = uid end end snapshot end end end end
# frozen_string_literal: true module API module Exceptions class AuthenticationError < StandardError; end def self.included(base) base.rescue_from AuthenticationError do |e| message = e.message == e.class.name ? 'Wrong email or password' : e.message error!({ errors: message }, 401, 'Content-Type' => 'text/json') end base.rescue_from ActiveRecord::RecordNotFound do |_e| error!({ errors: e.message }, 404 , { 'Content-Type' => 'text/json' }) end base.rescue_from ActiveRecord::RecordInvalid do |e| error!({ errors: e.record.errors.messages }, 422, 'Content-Type' => 'text/json') end base.rescue_from ArgumentError do |e| error!({ errors: e.message }, 422, 'Content-Type' => 'text/json') end base.rescue_from CanCan::AccessDenied do error!({ errors: 'You are not authorized to access' }, 401, 'Content-Type' => 'text/json') end end end end
RSpec.feature "Users can add a collaboration type for an activity" do let(:user) { create(:beis_user) } let(:activity) { create(:programme_activity, :at_collaboration_type_step, organisation: user.organisation) } before { authenticate!(user: user) } after { logout } context "when the user creates a new activity, on the collaboration_type form step" do scenario "the activity has a pre-selected radio button for collaboration_type with value '1 -Bilateral'" do visit activity_step_path(activity, :collaboration_type) expect(find_field("activity-collaboration-type-1-field")).to be_checked expect(find_field("activity-collaboration-type-2-field")).not_to be_checked end context "and they save this step without changing the selected radio button" do it "saves collaboration_type as value '1' (Bilateral)" do visit activity_step_path(activity, :collaboration_type) click_button t("form.button.activity.submit") expect(activity.reload.collaboration_type).to eq("1") end end end context "when the user wants to edit the collaboration_type on an existing activity" do it "shows the correct radio button selected" do programme = create(:programme_activity, organisation: user.organisation, collaboration_type: "2") visit organisation_activity_details_path(programme.organisation, programme) within(".collaboration_type") do click_on(t("default.link.edit")) end expect(find_field("activity-collaboration-type-2-field")).to be_checked choose "Bilateral, core contributions to NGOs and other private bodies / PPPs" click_button t("form.button.activity.submit") expect(programme.reload.collaboration_type).to eq("3") end end end
require 'rails_helper' require 'givdo/facebook/paginated_connections' RSpec.describe Givdo::Facebook::PaginatedConnections, :type => :lib do let(:params) { {:param => 'value'} } let(:graph) { double } subject { Givdo::Facebook::PaginatedConnections.new(graph, 'my_connections', params) } describe '#list' do context 'when no page is set' do it 'is the requested connection with the given params' do expect(graph).to receive(:get_connections).with('me', 'my_connections', {:param => 'value'}).and_return('connections collection') expect(subject.list).to eql 'connections collection' end end context 'when the page is set' do it 'is the requested page' do params[:page] = 'page data' expect(graph).to receive(:get_page).with('page data').and_return('page') expect(subject.list).to eql 'page' end end end end
require 'benchmark' require_relative 'lib/activesupport/cache/elasticsearch_store' REPEATS = 500 def assert a, b if a != b $stderr.puts "a: #{a.inspect} b: #{b.inspect}" raise "a != b" end end def bench name, count, store puts "#{name}: #{count} actions per run" array_1k = ["a"] * 1024 array_20k = ["a"] * 1024 * 20 Benchmark.bm do |x| x.report("missing") do REPEATS.times do |i| store.read("key#{i}") end end x.report("write 1k array") do REPEATS.times do |i| store.write("key_1k_#{i}", array_1k) end end x.report("write 20k array") do REPEATS.times do |i| store.write("key_20k_#{i}",array_20k) end end x.report("read 1k") do REPEATS.times do |i| assert(store.read("key_1k_#{i}"), array_1k) end end x.report("read 20k") do REPEATS.times do |i| assert(store.read("key_20k_#{i}"), array_20k) end end end puts end require 'redis-activesupport' index_name = "cache_benchmark_#{Process.pid}" store = ActiveSupport::Cache::ElasticsearchStore.new(index_name: index_name) redis = ActiveSupport::Cache::RedisStore.new bench "redis", 500, redis MultiJson.use(:json_gem) bench "es (Ruby JSON)", 500, store MultiJson.use(:yajl) bench "es (YAJL)", 500, store
module Yaks class Format class CollectionJson < self register :collection_json, :json, 'application/vnd.collection+json' include FP # @param [Yaks::Resource] resource # @return [Hash] def serialize_resource(resource) result = { version: "1.0", items: serialize_items(resource) } result[:href] = resource.self_link.uri if resource.self_link result[:links] = serialize_links(resource) if links?(resource) result[:queries] = serialize_queries(resource) if queries?(resource) result[:template] = serialize_template(resource) if template?(resource) {collection: result} end # @param [Yaks::Resource] resource # @return [Array] def serialize_items(resource) resource.seq.map do |item| attrs = item.attributes.map do |name, value| { name: name, value: value } end result = {data: attrs} result[:href] = item.self_link.uri if item.self_link item.links.each do |link| next if link.rel.equal? :self result[:links] = [] unless result.key?(:links) result[:links] << {rel: link.rel, href: link.uri} result[:links].last[:name] = link.title if link.title end result end end def serialize_links(resource) resource.links.each_with_object([]) do |link, result| result << {href: link.uri, rel: link.rel} end end def serialize_queries(resource) resource.forms.each_with_object([]) do |form, result| next unless form_is_query? form result << {rel: form.name, href: form.action} result.last[:prompt] = form.title if form.title form.fields_flat.each do |field| result.last[:data] = [] unless result.last.key? :data result.last[:data] << {name: field.name, value: nil.to_s} result.last[:data].last[:prompt] = field.label if field.label end end end def queries?(resource) resource.forms.any? { |f| form_is_query? f } end def links?(resource) resource.collection? && resource.links.any? end def template?(resource) options.key?(:template) && template_form_exists?(resource) end protected def form_is_query?(form) form.method?(:get) && form.has_action? end def template_form_exists?(resource) !resource.find_form(options.fetch(:template)).nil? end def serialize_template(resource) fields = resource.find_form(options.fetch(:template)).fields result = {data: []} fields.each do |field| result[:data] << {name: field.name, value: nil.to_s} result[:data].last[:prompt] = field.label if field.label end result end end end end
class Admin::CategoriesController < ApplicationController layout 'admin' before_filter :require_http_basic_auth def index @categories = Category.order("position") end def new @category = Category.new end def edit @category = Category.find(params[:id]) end def update @category = Category.find(params[:id]) if @category.update_attributes(params[:category]) redirect_to :action => 'index' else render :action => 'edit' end end def destroy @category = Category.find(params[:id]) @category.destroy redirect_to :action => 'index' end def create @category = Category.new(params[:category]) if @category.save redirect_to :action => 'index' else render :action => 'new' end end def show @category = Category.find(params[:id], :include => :category_options) end def sort params[:category].each_with_index do |id, index| Category.update_all({position: index+1}, {id: id}) end render nothing: true end end
require File.join(File.dirname(__FILE__), 'gilded_rose') describe GildedRose do describe '#update_quality' do it 'does not change the name' do items = [Item.new('foo', 0, 0)] GildedRose.new(items).update_quality expect(items[0].name).to eq 'foo' end it 'quality of an item is never negative' do items = [Item.new('foo', 2, 0)] GildedRose.new(items).update_quality expect(items[0].quality).to be 0 end it "'Aged Brie' actually increases in quality the older it gets" do items = [Item.new('Aged Brie', 2, 0)] GildedRose.new(items).update_quality expect(items[0].quality).to be 1 end it 'quality of an item is never more than 50' do items = [Item.new('Backstage passes to a TAFKAL80ETC concert', 50, 50)] GildedRose.new(items).update_quality expect(items[0].quality).to be 50 end it "'Conjured' items degrade in quality twice as fast as normal items" do items = [Item.new('Conjured Mana Cake', 3, 6)] GildedRose.new(items).update_quality expect(items[0].quality).to be 4 end it "'Backstage passes' quality increases by 2 when there are 10 days or less" do items = [Item.new(name='Backstage passes to a TAFKAL80ETC concert', 10, 20)] GildedRose.new(items).update_quality expect(items[0].quality).to be 22 end it "'Backstage passes' quality increases by 3 when there are 5 days or less" do items = [Item.new(name='Backstage passes to a TAFKAL80ETC concert', 5, 20)] GildedRose.new(items).update_quality expect(items[0].quality).to be 23 end it "'Backstage passes' quality drops to 0 after the concert" do items = [Item.new(name='Backstage passes to a TAFKAL80ETC concert', 0, 20)] GildedRose.new(items).update_quality expect(items[0].quality).to be 0 end it "'Sulfuras' never has to be sold or decreases in quality" do items = [Item.new('Sulfuras, Hand of Ragnaros', 1, 80)] GildedRose.new(items).update_quality expect(items[0].quality).to be 80 expect(items[0].sell_in).to be 1 end it "once the sell by date has passed quality degrades twice as fast" do items = [Item.new('foo', 0, 2)] GildedRose.new(items).update_quality expect(items[0].quality).to be 0 end end end
class AddActiveDatesToProductionUnits < ActiveRecord::Migration def change add_column :production_units, :active_start_date, :date add_column :production_units, :active_end_date, :date end end
class CreateComments < ActiveRecord::Migration def change create_table :comments do |t| t.text :content, :null => false t.timestamps t.references :user t.references :article, :null => false end add_foreign_key(:comments, :users, :dependent => :delete_all, :column => 'user_id', :name => 'fk_comments_users') add_foreign_key(:comments, :articles, :dependent => :delete_all, :column => 'article_id', :name => 'fk_comments_articles') end end
require 'easy_extensions/easy_scheduler' module EasyExtensions module SchedulerTasks class GitFetcherTask < EasyExtensions::EasySchedulerTask def initialize(options={}) super('git_fetcher_task', options) end def execute logger.info 'GitFetcherTask excuting...' if logger projects = [] if options[:project_id] projects << Project.active.non_templates.has_module(:repository).find(options[:project_id]) else projects = Project.active.non_templates.has_module(:repository).find(:all, :include => :repository) end projects.each do |project| if project.repository logger.info "GitFetcherTask fetching #{project.repository.url}" if logger system "cd #{project.repository.url} && git fetch" project.repository.fetch_changesets end end logger.info 'GitFetcherTask excuted.' if logger end end end end
require 'spec_helper' describe Kassociation do describe "Join Class" do before( :all) do @app = App.create( :name => "business") @person = @app.klasses.create( :name => "Person" ) @company = @app.klasses.create( :name => "Company") @jassoc = @app.kassociations.create( :typus => "join", :source => @person, :target => @company) @jclass = @jassoc.join_class end it "the join class exists and was created by the join association at its creation" do @jclass.should_not == nil @jclass.name.should == "PersonCompany" end it "the join association associates Person with Company" do @jassoc.source.name.should == "Person" @jassoc.target.name.should == "Company" end it "join association belongs to App business" do @jassoc.app.name.should == "business" end it "the join association can generate the join class with the correct name" do @jclass.name.should == @jassoc.source.name + @jassoc.target.name end it "the join class belongs to App business" do @jclass.app.name.should == "business" end it "the kassociation of a non-join class is nil" do currency = @app.klasses.create( :name => "Currency" ) currency.kassociation.should == nil end it "the kassociation of the join class is not nil" do @jclass.kassociation.should_not == nil end it "the kassociation of the join class is the association that spawned it" do @jclass.kassociation.should == @jassoc end it "the join class has precisely 2 attributes" do @jclass.kattributes.count.should == 2 end it "each attribute of the join class has the type: references" do @jclass.kattributes.map { |a| a.typus }.should == [ "references", "references" ] end it "the attributes of the join class have the correct downcased class names" do @jclass.kattributes.map { |a| a.name }.sort.should == [ "company", "person" ] end it "the join class scaffolds properly" do @jclass.to_scaffold.should == "rails generate scaffold PersonCompany person:references company:references" end it "the join class generates the proper source code" do @jclass.to_code.should == [ "class PersonCompany < ActiveRecord::Base", ["belongs_to :person", "belongs_to :company"], "end" ] end end # describe Join Class" describe "Person join Company: to_code" do before( :all) do @app = App.create( :name => "business") @person = @app.klasses.create( :name => "Person" ) @company = @app.klasses.create( :name => "Company") @jassoc = @app.kassociations.create( :typus => "join", :source => @person, :target => @company) @jclass = @jassoc.join_class end it "Person generates the right source code: has_many and through" do @person.to_code.should == [ "class Person < ActiveRecord::Base", ["has_many :person_companies", "has_many :companies, :through => :person_companies"], "end" ] end it "Company generates the right source code: has_many and through" do @company.to_code.should == [ "class Company < ActiveRecord::Base", ["has_many :person_companies", "has_many people, :through => :person_companies"], "end" ] end end end # describe Kassociation
require_relative './game_teams' require_relative './game' require_relative './team' require_relative '../modules/game_methods' require_relative '../modules/league_methods' require_relative '../modules/team_methods' require_relative '../modules/team_helper_methods' require_relative '../modules/season_methods' require_relative '../modules/helper_methods' require 'csv' class StatTracker include GameMethods, LeagueMethods, TeamMethods, TeamHelperMethods, SeasonMethods, HelperMethods attr_reader :games, :teams, :game_teams def initialize @games = [] @teams = [] @game_teams = [] end def self.from_csv(locations) stat_tracker = StatTracker.new CSV.foreach(locations[:games], {:headers => true, :header_converters => :symbol}){|game| stat_tracker.games << Game.new(game)} CSV.foreach(locations[:teams], {:headers => true, :header_converters => :symbol}){|team| stat_tracker.teams << Team.new(team)} CSV.foreach(locations[:game_teams], {:headers => true, :header_converters => :symbol}){|game_team| stat_tracker.game_teams << GameTeam.new(game_team)} stat_tracker end end
json.array!(@internal_messages) do |internal_message| json.extract! internal_message, :id json.url internal_message_url(internal_message, format: :json) end
class CommentsController < ApplicationController before_action :authenticate_user! before_action :set_context, only: :create before_action :set_question, only: :create after_action :publish_comment, only: :create authorize_resource def create @comment = @context.comments.new(comment_params) @comment.user = current_user flash.now[:success] = 'Comment successfully created.' if @comment.save end private def comment_params params.require(:comment).permit(:body) end def set_context @context = context_resource.find(context_id) end def context_resource params[:context].classify.constantize end def context_id params.fetch(params[:context].foreign_key.to_s) end def set_question @question = @context if @context.is_a?(Question) @question = @context.question if @context.is_a?(Answer) @question end def publish_comment return if @comment.errors.any? data = { comment: @comment, success: 'There was a new Comment.' } ActionCable.server.broadcast "question_#{@question.id}_comments", data end end
class CreateDocumentOwners < ActiveRecord::Migration[5.1] def change create_table :document_owners do |t| t.references :document, foreign_key: true t.string :owner_name t.string :owner_email t.timestamps end end end
feature 'attack' do scenario "attack player 2" do sign_in_and_play click_link "Attack" expect(page).to have_content "Angron attacked Guilliman" end scenario 'Attack reduces player 2s hit points by 10' do sign_in_and_play click_link "Attack" click_link "Ok" expect(page).not_to have_content "Guilliman: 60/60hp" expect(page).to have_content "Guilliman: 50/60hp" end end
module Repositories module Companies class Memory def initialize @companies = {} @next_id = 1 end def clear initialize end def save(company) if company.id update_existing(company) else create(company) end company end def all companies end def where(conditions = {}) companies.values.select do |company| matches_conditions?(company, conditions) end end def find_by_id(id) companies[id] end private attr_reader :companies def matches_conditions?(company, conditions) conditions.map do |name, expected_value| company.public_send(name) == expected_value end.all? end def create(company) company.id = @next_id companies[@next_id] = company @next_id += 1 end def update_existing(company) companies[company.id] = company end end end end
class TopicResource < JSONAPI::Resource attributes :title, :progress, :objectives, :unit, :subject has_one :unit has_many :objectives has_many :problems def progress user = context[:current_user] return @model.progress(user) end filters :title, :unit_id end
class Ships < ActiveRecord::Migration[4.2] def change create_table :ships do |t| t.string :type_class t.string :sub_class t.decimal :top_speed t.integer :crew t.string :affiliation t.integer :agent_id t.string :note end end end
require "rails_helper" RSpec.describe ChatroomsController, type: :routing do describe "routing" do it "routes to #index" do expect(get: "/chatrooms").to route_to("chatrooms#index") end it "routes to #new" do expect(get: "/chatrooms/new").to route_to("chatrooms#new") end it "routes to #show" do expect(get: "/chatrooms/1").to route_to("chatrooms#show", id: "1") end it "routes to #edit" do expect(get: "/chatrooms/1/edit").to route_to("chatrooms#edit", id: "1") end it "routes to #create" do expect(post: "/chatrooms").to route_to("chatrooms#create") end it "routes to #update via PUT" do expect(put: "/chatrooms/1").to route_to("chatrooms#update", id: "1") end it "routes to #update via PATCH" do expect(patch: "/chatrooms/1").to route_to("chatrooms#update", id: "1") end it "routes to #destroy" do expect(delete: "/chatrooms/1").to route_to("chatrooms#destroy", id: "1") end end end
# frozen_string_literal: true require_relative 'snapshot' # Helpers in Filewatcher class itself class Filewatcher class << self def system_stat(filename) case Gem::Platform.local.os when 'linux' then `stat --printf 'Modification: %y, Change: %z\n' #{filename}` when 'darwin' then `stat #{filename}` else 'Unknown OS for system `stat`' end end end # Module for snapshot logic inside Filewatcher module Snapshots def found_filenames current_snapshot.keys end private def watching_files expand_directories(@unexpanded_filenames) - expand_directories(@unexpanded_excluded_filenames) end # Takes a snapshot of the current status of watched files. # (Allows avoidance of potential race condition during #finalize) def current_snapshot Filewatcher::Snapshot.new(watching_files) end def file_mtime(filename) return Time.new(0) unless File.exist?(filename) result = File.mtime(filename) if @logger.level <= Logger::DEBUG debug "File.mtime = #{result.strftime('%F %T.%9N')}" debug "stat #{filename}: #{self.class.system_stat(filename)}" end result end def file_system_updated?(snapshot = current_snapshot) debug __method__ @changes = snapshot - @last_snapshot @last_snapshot = snapshot @changes.any? end end end
def roll_call_dwarves(dwarves) dwarves.each.with_index(1) do |dwarf, index| puts "#{index}. #{dwarf}" end end def summon_captain_planet(planeteer_calls) planeteer_calls.map { |call| call.capitalize + "!" } end def long_planeteer_calls(calls) calls.any? do |call| call.length > 4 end end def find_the_cheese(potentially_cheesy_items) cheese_types = ["cheddar", "gouda", "camembert"] potentially_cheesy_items.find do |maybe_cheese| cheese_types.include?(maybe_cheese) end end #def find_the_cheese(food) #cheese_types = ["cheddar", "gouda", "camembert"] #food.find do |item| # cheese_types.include?(item) #end #end
require 'net/http' module Openfoodfacts class User < Hashie::Mash class << self # Login # def login(user_id, password, locale: DEFAULT_LOCALE, domain: DEFAULT_DOMAIN) path = 'cgi/session.pl' uri = URI("https://#{locale}.#{domain}/#{path}") params = { "jqm" => "1", "user_id" => user_id, "password" => password } response = Net::HTTP.post_form(uri, params) data = JSON.parse(response.body) if data['user_id'] data.merge!(password: password) new(data) end end end # Login # def login(locale: DEFAULT_LOCALE) user = self.class.login(self.user_id, self.password, locale: locale) if user self.name = user.name self end end end end
module BookKeeping VERSION = 3 end class Squares def initialize(n) @number_list = (0..n).to_a end def square_of_sum square = @number_list.reduce(:+)**2 square end def sum_of_squares sum = @number_list.map { |n| n**2 }.reduce(:+) sum end def difference square_of_sum - sum_of_squares end end
# -*- mode: ruby -*- Vagrant.require_version ">= 2.2.6" Vagrant.configure("2") do |config| # The Zulip development environment runs on 9991 on the guest. host_port = 9991 http_proxy = https_proxy = no_proxy = nil host_ip_addr = "127.0.0.1" # System settings for the virtual machine. vm_num_cpus = "2" vm_memory = "2048" ubuntu_mirror = "" vboxadd_version = nil config.vm.box = "bento/ubuntu-20.04" config.vm.synced_folder ".", "/vagrant", disabled: true config.vm.synced_folder ".", "/srv/zulip", docker_consistency: "z" vagrant_config_file = ENV["HOME"] + "/.zulip-vagrant-config" if File.file?(vagrant_config_file) IO.foreach(vagrant_config_file) do |line| line.chomp! key, value = line.split(nil, 2) case key when /^([#;]|$)/ # ignore comments when "HTTP_PROXY"; http_proxy = value when "HTTPS_PROXY"; https_proxy = value when "NO_PROXY"; no_proxy = value when "HOST_PORT"; host_port = value.to_i when "HOST_IP_ADDR"; host_ip_addr = value when "GUEST_CPUS"; vm_num_cpus = value when "GUEST_MEMORY_MB"; vm_memory = value when "UBUNTU_MIRROR"; ubuntu_mirror = value when "VBOXADD_VERSION"; vboxadd_version = value end end end if Vagrant.has_plugin?("vagrant-proxyconf") if !http_proxy.nil? config.proxy.http = http_proxy end if !https_proxy.nil? config.proxy.https = https_proxy end if !no_proxy.nil? config.proxy.no_proxy = no_proxy end elsif !http_proxy.nil? or !https_proxy.nil? # This prints twice due to https://github.com/hashicorp/vagrant/issues/7504 # We haven't figured out a workaround. puts "You have specified value for proxy in ~/.zulip-vagrant-config file but did not " \ "install the vagrant-proxyconf plugin. To install it, run `vagrant plugin install " \ "vagrant-proxyconf` in a terminal. This error will appear twice." exit end config.vm.network "forwarded_port", guest: 9991, host: host_port, host_ip: host_ip_addr config.vm.network "forwarded_port", guest: 9994, host: host_port + 3, host_ip: host_ip_addr # Specify Docker provider before VirtualBox provider so it's preferred. config.vm.provider "docker" do |d, override| override.vm.box = nil d.build_dir = File.join(__dir__, "tools", "setup", "dev-vagrant-docker") d.build_args = ["--build-arg", "VAGRANT_UID=#{Process.uid}"] if !ubuntu_mirror.empty? d.build_args += ["--build-arg", "UBUNTU_MIRROR=#{ubuntu_mirror}"] end d.has_ssh = true d.create_args = ["--ulimit", "nofile=1024:65536"] end config.vm.provider "virtualbox" do |vb, override| # It's possible we can get away with just 1.5GB; more testing needed vb.memory = vm_memory vb.cpus = vm_num_cpus if !vboxadd_version.nil? override.vbguest.installer = Class.new(VagrantVbguest::Installers::Ubuntu) do define_method(:host_version) do |reload = false| VagrantVbguest::Version(vboxadd_version) end end override.vbguest.allow_downgrade = true override.vbguest.iso_path = "https://download.virtualbox.org/virtualbox/#{vboxadd_version}/VBoxGuestAdditions_#{vboxadd_version}.iso" end end config.vm.provider "hyperv" do |h, override| h.memory = vm_memory h.maxmemory = vm_memory h.cpus = vm_num_cpus end config.vm.provider "parallels" do |prl, override| prl.memory = vm_memory prl.cpus = vm_num_cpus end config.vm.provision "shell", # We want provision to be run with the permissions of the vagrant user. privileged: false, path: "tools/setup/vagrant-provision", env: { "UBUNTU_MIRROR" => ubuntu_mirror } end
Pod::Spec.new do |s| # โ€•โ€•โ€• Spec Metadata โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€• # s.name = "SJLineRefresh" s.version = "1.1.6" s.summary = "A easy customizable shape pull-to-refresh view in UIScrolView." s.swift_version = '5' s.description = <<-DESC A pull-to-refresh control that you could use your own share easily. DESC s.homepage = "https://github.com/515783034/SJLineRefresh" s.screenshots = "http://upload-images.jianshu.io/upload_images/988961-5f6cc8c69fead46f.gif?imageMogr2/auto-orient/strip" s.license = "MIT" s.author = { "shmily" => "shmilyshijian@foxmail.com" } s.social_media_url = "http://www.jianshu.com/u/3095a094665c" s.platform = :ios, "9.0" s.source = { :git => "https://github.com/515783034/SJLineRefresh.git", :tag => "#{s.version}" } s.source_files = "SJLineRefresh/Sources/*.swift" s.resources = "SJLineRefresh/Resources/*.*" s.requires_arc = true end
class AddRemainingstoriesToSprints < ActiveRecord::Migration[5.1] def change add_column :sprints, :remainingstories, :integer,default: 0 end end
# Author:: Lucas Carlson (mailto:lucas@rufy.com) # Copyright:: Copyright (c) 2005 Lucas Carlson # License:: LGPL require "set" module ClassifierReborn module Hasher extend self # Removes common punctuation symbols, returning a new string. # E.g., # "Hello (greeting's), with {braces} < >...?".without_punctuation # => "Hello greetings with braces " def without_punctuation(str) str .tr( ',?.!;:"@#$%^&*()_=+[]{}\|<>/`~', " " ) .tr( "'\-", "") end # Return a Hash of strings => ints. Each word in the string is stemmed, # interned, and indexes to its frequency in the document. def word_hash(str) word_hash = clean_word_hash(str) symbol_hash = word_hash_for_symbols(str.gsub(/[\w]/," ").split) return clean_word_hash(str).merge(symbol_hash) end # Return a word hash without extra punctuation or short symbols, just stemmed words def clean_word_hash(str) word_hash_for_words str.gsub(/[^\w\s]/,"").split end def word_hash_for_words(words) d = Hash.new(0) words.each do |word| word.downcase! if ! CORPUS_SKIP_WORDS.include?(word) && word.length > 2 d[word.stem.intern] += 1 end end return d end def word_hash_for_symbols(words) d = Hash.new(0) words.each do |word| d[word.intern] += 1 end return d end CORPUS_SKIP_WORDS = Set.new(%w[ a again all along are also an and as at but by came can cant couldnt did didn didnt do doesnt dont ever first from have her here him how i if in into is isnt it itll just last least like most my new no not now of on or should sinc so some th than this that the their then those to told too true try until url us were when whether while with within yes you youll ]) end end
# -*- encoding : utf-8 -*- # Kontroler wystawiajฤ…cy usล‚ugi dla klienta mobilnego jak i interfejsu webowego # # Umoลผliwia zgล‚oszenie uszkodzenia i pobieranie aktualnych danych kategorii. # class ServicesController < ApplicationController skip_before_filter :require_login layout false # POST /res/issue # POST /res/issue.json # # Zapytanie dodajฤ…ce nowe zgล‚oszenie. Wywoล‚uje Issue.add_issue z przekazanymi # parametrami. # # Parametry zapytania w JSON to (parametry HTTP POST - analogicznie): # "category_id": (id kategorii zgล‚oszenia), # "latitude": (szer. geogr.), # "longitude": (dล‚. geogr.), # *** "desc": (opis), # *** "notificar_email": (e-mail zgล‚aszajฤ…cego), # *** "photos": (lista zdjฤ™ฤ‡) # [ # { # "image": (zdjฤ™cie w Base64), # "image_type": (typ MIME zdjฤ™cia, np. "image/jpeg"), # *** "markers": (lista znacznikรณw) # [ # { "x": (poz. x), "y": (poz. y), "desc": (opis) }, # ... # ] # }, # ... # ] # *** oznacza parametr opcjonalny. def issue if request.post? begin instance = Issue.add_issue(params[:category_id], params[:longitude], params[:latitude], params[:desc], params[:notificar_email], params[:photos]) if !instance.nil? render :json => { :message => 'Zgล‚oszenie zostaล‚o przyjฤ™te', :id => instance.id } else render :json => { :message => 'Bล‚ฤ…d', :id => nil }, :status => 500 end rescue ActiveRecord::RecordInvalid => e msg = "" e.record.errors.each { |attr,err| msg += "#{attr} - #{err}\n" } render :json => { :message => 'Bล‚ฤ…d: ' + msg, :id => nil }, :status => 500 rescue Exception => e render :json => { :message => 'Bล‚ฤ…d: ' + e.message, :id => nil }, :status => 500 end end end # GET /res/categories # # Umoลผliwia pobranie listy dostฤ™pnych kategorii # # Zwraca listฤ™ z ID i nazwami def categories @categories = Category.all render :json => @categories.to_json( :only => [:id, :name] ) end # GET /res/categories/1 # # Umoลผliwia pobranie pojedynczej kategorii o danym ID # # Zwraca ID i nazwฤ™ def category @category = Category.find(params[:id]) render :json => @category.to_json( :only => [:id, :name] ) end # GET /res/category_icon/1 # # Umoลผliwia pobranie ikony kategorii o danym ID # # Zwraca obrazek w formacie JPG def category_icon category = Category.find(params[:id]) if !category.nil? && !category.icon.nil? # typ ikony to na sztywno image/jpeg send_data Base64.decode64(category.icon), :type => 'image/jpeg', :disposition => 'inline' end end end
class StoriesController < ApplicationController before_action :load_story, only: [:show, :export, :flag] before_action :load_my_story, only: [:update, :delete] def show render_json @story end def update pushed_user_ids = @story.update(update_params) # Notify the users to whose feed this story was just added User.where(id: pushed_user_ids).find_each do |user| user.send_story_notifications(@story) end load_my_story render_json @story end def search story_usernames = split_param(:story_usernames) snapchat_media_ids = split_param(:snapchat_media_ids) render_json Story.existing_snapchat_media_ids(story_usernames, snapchat_media_ids) end def export exported = @story.record_export(current_user, params[:method]) @story.user.send_export_notifications(@story, current_user, params[:method]) if exported render_success end def delete @story.delete render_success end def flag check_flag_reason = FlagReason.exists? if !check_flag_reason @story.flag(current_user) render_json @story else @flag_reason = FlagReason.find(params[:flag_reason_id]) if params[:flag_reason_id].present? @story.flag(current_user, @flag_reason) render_json @story end end def tagged render_json Story.search_by_tag(params[:tag], pagination_params) end private def load_story @story = Story.new(id: params[:id]) raise Peanut::UnauthorizedError unless @story.has_permission?(current_user) end def load_my_story @story = Story.new(id: params[:id]) raise Peanut::Redis::RecordNotFound unless @story.attrs.exists? && @story.user_id == current_user.id end def update_params params.slice(:permission, :latitude, :longitude, :source, :attachment_overlay_file, :attachment_overlay_text, :has_face, :shareable_to) end end
require 'todobot/services/commands/help_command_service' require 'todobot/services/commands/start_command_service' require 'todobot/services/tasks/create_task_service' require 'todobot/services/lists/create_list_service' require 'todobot/services/lists/show_list_service' require 'todobot/services/lists/show_lists_service' module TodoBot module Commands COMMANDS = { ['/start'] => { class: TodoBot::Commands::StartCommandService, args: ->(args, text) { args }, options: ->(args, text) { {} } }, ['/help'] => { class: TodoBot::Commands::HelpCommandService, args: ->(args, text) { args }, options: ->(args, text) { {} } }, ['/create', '/newlist'] => { class: TodoBot::Lists::CreateListService, args: ->(args, text) { args.merge!(name: text) }, options: ->(args, text) { {force_reply: text.nil? && args.fetch(:chat).type != 'private'} } }, ['/todo', '/task', '/t'] => { class: TodoBot::Tasks::CreateTaskService, args: ->(args, text) { args.merge!(name: text) }, options: ->(args, text) { {force_reply: text.nil? && args.fetch(:chat).type != 'private'} } }, ['/list', '/l'] => { class: TodoBot::Lists::ShowListService, args: ->(args, text) { args }, options: ->(args, text) { {} } }, ['/lists', '/ls'] => { class: TodoBot::Lists::ShowListsService, args: ->(args, text) { args }, options: ->(args, text) { {} } } }.freeze private_constant :COMMANDS private def defined_command?(command) COMMANDS.keys.any? { |key| key.include?(command) } end end end
module Mastermind class Provider autoload :Mock, 'mastermind/provider/mock' autoload :Server, 'mastermind/provider/server' autoload :Notification, 'mastermind/provider/notification' autoload :Remote, 'mastermind/provider/remote' autoload :CM, 'mastermind/provider/cm' attr_accessor :resource, :action class << self def options @options ||= Hash.new.with_indifferent_access end def option(name, value) instance_variable_set("@#{name}", value) instance_eval <<-EOF, __FILE__, __LINE__ def #{name} @#{name} end EOF options[name] = value end def inherited(subclass) options.each do |key, value| subclass.option key, value end end def type @type end def register(type) @type = type end def action(action_name, &block) # action_name = action_name.to_sym # actions.push(action_name).uniq! define_method(action_name) do instance_eval(&block) end end end def initialize(resource) @resource = resource @action = @resource.action end def options self.class.options end def type self.class.type end def as_json(options={}) to_hash end def to_param type end def to_hash { :type => type, :class => self.class.name, :options => options # actions: self.class.actions } end # default "do-nothing" action. Useful for debugging and tests action :nothing do Mastermind.logger.debug "Doing nothing." end def run # clear out any previously encountered errors resource.errors.clear validate! begin self.send(action) Mastermind.logger.debug resource.to_json rescue => e Mastermind.logger.error e.message, :backtrace => e.backtrace raise e end end private def validate! resource.valid?(action.to_sym) end def update_resource_attributes(attributes) return if attributes.empty? || attributes.nil? raise ArgumentError, "attributes must be a hash" unless attributes.is_a?(Hash) resource.assign_attributes(attributes) end alias :updates_resource_attributes :update_resource_attributes end end
# Use Enumerable#map to iterate over numbers and return an array containing each number divided by 2. Assign the returned array to a variable named half_numbers and print its value using #p. numbers = { high: 100, medium: 50, low: 10 } half_numbers = numbers.map {|k,v| v / 2} p half_numbers # LS Discussion # Enumerable#map works similarly to Array#map, however, Enumerable#map can accept two block parameters instead of one, to account for both the key and the value. You might expect Enumerable#map to return a Hash when invoked on a Hash, but it actually returns an Array.
class Chakra < ActiveRecord::Base has_many :goddesses, :order => :number validates_presence_of :name, :description, :colour end
require "test_helper" class PaywhirlTest < Minitest::Test def test_that_it_has_a_version_number refute_nil ::Paywhirl::VERSION end end
require 'roo' require 'coercell/value' module Coercell class Parser def initialize(model) @model = model end def prepare_content(start=2) @content ||= (start..spreadsheet.last_row).collect do |line| content_line = {} titles.each do |title| content_line[title[:value]] = get_cell_value(title,line) end content_line end end def parse! data = [] errors = [] prepare_content @content.each_with_index do |line_data, i| instance = @model.new(line_data) if instance.valid? data << instance else error = {} error[:line] = i+2 error[:messages] = instance.errors.full_messages errors << error end end @valid_objects = data @errors = errors end def errors @errors end def valid_objects @valid_objects end def spreadsheet @spreadsheet end def spreadsheet=(file) extension = File.extname(file)[1..-1].downcase @spreadsheet = case extension when "ods" Roo::OpenOffice.new(file) when "xls" Roo::Excel.new(file) when "xlsx" Roo::Excelx.new(file) else raise ArgumentError, "Provided file must be Openffice(.ods) or Excel(.xls or .xlsx). .#{extension} is not valid" end end private def titles attributes = @model.attribute_names @titles ||= ((1..spreadsheet.last_column).collect do |column| value = spreadsheet.cell(1,column).strip #getting content from first line { :column => column, :value => value } if attributes.include? value end).compact @titles end def get_cell_value(title,line) Coercell::Value.coerce( @model, title[:value], @spreadsheet.cell(line, title[:column]) ) end end end
desc "Removes the cached (public) images/javascript/stylesheets themes folders" task :theme_remove_cache do ['images', 'javascripts', 'stylesheets'].each do |type| path = "#{RAILS_ROOT}/public/#{type}/themes" puts "Removing #{path}" FileUtils.rm_r path, :force => true end end
require "test_helper" class IncidentsControllerTest < ActionController::TestCase def setup @incident = incidents(:one) end def test_index get :index assert_response :success assert_not_nil assigns(:incidents) end def test_show get :show, id: @incident assert_response :success end def test_new get :new assert_response :success end def test_create assert_difference('Incident.count') do post :create, incident: { name: @incident.name, description: @incident.description, incident_picture: @incident.incident_picture } end end def test_edit get :edit, id: @incident assert_response :success end def test_update patch :update, id: @incident, incident: { name: @incident.name, description: @incident.description, incident_picture: @incident.incident_picture } assert_response :success end def test_destroy assert_difference('Incident.count', -1) do delete :destroy, id: @incident end end end
class AddUsersSeatsTable < ActiveRecord::Migration[5.2] def up create_join_table :users, :seats remove_column :users, :seat_id change_column :hosts, :flags, :text end def down drop_table :users_seats add_column :users, :seat_id, :integer change_column :hosts, :flags, :string end end
=begin input: string output: array rules: return a list of all substrings; need to be arranged by position when position is the same, they are ordered by length algorithm: set list to [] set count to 0 first loop to get all the substring starting from first letter add those to the list first then increase the starting position so on so forth =end def substrings(string) list = [] start = 0 loop do 1.upto(string.size - start) do |count| list << string[start, count] end start += 1 break if start == string.size end list end p substrings('abcde') == [ 'a', 'ab', 'abc', 'abcd', 'abcde', 'b', 'bc', 'bcd', 'bcde', 'c', 'cd', 'cde', 'd', 'de', 'e' ]
module SPV # Converts list with fixture names into list of # SPV::Fixture objects. class Fixtures class Converter def self.convert_raw(raw_list) raw_list.map do |item| if item.kind_of?(String) Fixture.new(item) else Fixture.new(item[:fixture], item[:options]) end end end end # class Converter end # class Fixtures end # module SPV
require_relative "spec_helper" describe LineUnit do it "parses nested italic and bold" do assert_equal 'outside<b><i>i</i>b</b>', parse('outside***i*b**').join end it "parses code" do assert_equal '<code class="highlight">\\\\code</code>', parse('`\\\\code`').join assert_equal '<code class="highlight">c`ode</code>', parse('``c`ode``').join assert_equal '<code class="highlight"> </code>`', parse('`` ```').join end it "parses math" do assert_equal '<code class="math">\\\\math\$ </code>', parse('$\\\\math\$ $').join end it "parses link" do assert_equal '<a href="href" rel="nofollow">a</a>', parse('[a](href)').join end it "parses footnote" do assert_equal '<a href="#footnote-1">1</a>', parse('[.](first note)').join assert_equal '<a href="#footnote-2">two</a>', parse('[.two](second note)').join assert_equal [:footnote_id_ref, 1], parse('[:1]').first assert_equal [:footnote_id_ref, 22], parse('[:22]').first assert_equal [:footnote_acronym_ref, "two"], parse('[:two]').first end it "won't parse footnot in sandbox mode" do make_sandbox_env first_note = '[.](first note)' assert_equal first_note, parse('[.](first note)').join end def parse src l = LineUnit.new @env, src, nil l.parse [] end end
Write a method that takes a string, and returns a new string in which every consonant character is doubled. Vowels (a,e,i,o,u), digits, punctuation, and whitespace should not be doubled. Examples: double_consonants('String') == "SSttrrinngg" double_consonants("Hello-World!") == "HHellllo-WWorrlldd!" double_consonants("July 4th") == "JJullyy 4tthh" double_consonants('') == "" Question: Write a method that takes a string and returns a new string in which consonant characters are doubled. everything else is not doubled. Input vs Output: Input: string Output: new string Explicit vs Implicit Rules: Explicit: 1) consonants will have letters doubled Implicit: N/a Algorithm: double_consonants method 1) set constant 'CONSONANTS' containing all consonants OUTSIDE FUNCTION. initialize variable 'result' as empty variable 2) invoke chars on string, then invoke each 3) within block, if CONSONANTS.include(letter.dowcase) 4) 'result' << letter << letter 5) else 'result' << letter 6) 'result'.join CONSONANTS = %w(b c d f g h j k l m n p q r s t v w x y z) def double_consonants(string) result = [] string.chars.each do |char| if CONSONANTS.include?(char.downcase) result << char << char else result << char end end result.join("") end
Pod::Spec.new do |s| s.name = 'BPushSDK' s.version = '0.0.1' s.summary = 'Baidu Push SDK for iOS.' s.homepage = 'https://github.com/heenying/BpushSDK' s.license = { :type => 'Copyright', :text => 'LICENSE ยฉ2015-2017 Baidu, Inc. All rights reserved' } s.author = { 'heenying' => 'https://github.com/heenying' } s.source = { :http => 'https://github.com/heenying/BpushSDK.git' } s.ios.deployment_target = '8.0' s.frameworks = 'Foundation','CoreTelephony','SystemConfiguration' s.requires_arc = false s.source_files = 'LibBDPush/*.h' s.public_header_files = 'LibBDPush/*.h' s.vendored_libraries = 'LibBDPush/*.a' s.frameworks = 'Foundation','CoreTelephony','SystemConfiguration' end
class FavoritesController < ApplicationController before_filter :authenticate_user! def create @follower_id = current_user.id @item_type = params[:favorite][:item_type] @item_name = params[:favorite][:item_name] @item_path = params[:favorite][:item_path] # use different parameters to distinguish favorite type case params[:favorite][:item_type] when 'User' @admirable_id = params[:favorite][:admirable_id] @experiment_id = nil @tool_id = nil # providing the @user for view js refresh is important @user = User.find_by_id(@admirable_id) when 'Experiment' @admirable_id = nil @experiment_id = params[:favorite][:experiment_id] @tool_id = nil # providing the @experiment for view js refresh is important @experiment = Experiment.find_by_id(@experiment_id) when 'Tool' @admirable_id = nil @experiment_id = nil @tool_id = params[:favorite][:tool_id] # providing the @tool for view js refresh is important @tool = Tool.find_by_id(@tool_id) else @admirable_id = nil @experiment_id = nil @tool_id = nil end Favorite.create!(follower_id: @follower_id,\ item_type: @item_type,\ item_name: @item_name,\ item_path: @item_path,\ experiment_id: @experiment_id,\ tool_id: @tool_id,\ admirable_id: @admirable_id) respond_to do |format| format.html { redirect_to current_user } format.js end end def destroy @follower_id = current_user.id @item_type = params[:favorite][:item_type] @item_name = params[:favorite][:item_name] @item_path = params[:favorite][:item_path] case params[:favorite][:item_type] when 'User' @admirable_id = params[:favorite][:admirable_id] # providing the @user for view js refresh is important @user = User.find_by_id(@admirable_id) @favorite = Favorite.where('follower_id = ? AND admirable_id = ?', \ @follower_id,\ @admirable_id ) @favorite.first.destroy when 'Experiment' @experiment_id = params[:favorite][:experiment_id] # providing the @experiment for view js refresh is important @experiment = Experiment.find_by_id(@experiment_id) @favorite = Favorite.where('follower_id = ? AND experiment_id = ?', \ @follower_id,\ @experiment_id ) @favorite.first.destroy when 'Tool' @tool_id = params[:favorite][:tool_id] # providing the @tool for view js refresh is important @tool = Tool.find_by_id(@tool_id) @favorite = Favorite.where('follower_id = ? AND tool_id = ?', \ @follower_id,\ @tool_id ) @favorite.first.destroy end respond_to do |format| format.html { redirect_to current_user } format.js end end end
describe LtreeRails::Configuration do let(:configuration) { LtreeRails::Configuration.new } let(:configurable_options) { LtreeRails::Configuration::CONFIGURABLE_OPTIONS.keys } let(:configurable_options_defaults) { LtreeRails::Configuration::CONFIGURABLE_OPTIONS.values } it 'provides getter for all options from CONFIGURABLE_OPTIONS' do expect(configuration).to respond_to(*configurable_options) end it 'provides default values for all options from CONFIGURABLE_OPTIONS' do actual_default_values = configurable_options.map do |option| configuration.public_send(option) end expect(actual_default_values).to eq(configurable_options_defaults) end end
class AddPriceBoughtToStocks < ActiveRecord::Migration def self.up add_column :stocks, :bought_at, :decimal, :default => 0, :precision => 12, :scale => 2 end def self.down remove_column :stocks, :bought_at end end
def nyc_pigeon_organizer(data) data.each_with_object({}) do |(category, trait), new_list| trait.each do |value, names| names.each do |name| new_list[name] ||= {} new_list[name][category] ||= [] new_list[name][category] << value.to_s end end end end
# -*- mode: ruby -*- # vi: set ft=ruby : # All Vagrant configuration is done below. The "2" in Vagrant.configure # configures the configuration version (we support older styles for # backwards compatibility). Please don't change it unless you know what # you're doing. 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. # Every Vagrant development environment requires a box. You can search for # boxes at https://atlas.hashicorp.com/search. config.vm.box = "puppetlabs/centos-6.6-64-puppet" config.vm.network "private_network", type: "dhcp" if Vagrant.has_plugin?("vagrant-cachier") # Configure cached packages to be shared between instances of the same base box. # More info on http://fgrehm.viewdocs.io/vagrant-cachier/usage config.cache.scope = :box # OPTIONAL: If you are using VirtualBox, you might want to use that to enable # NFS for shared folders. This is also very useful for vagrant-libvirt if you # want bi-directional sync config.cache.synced_folder_opts = { type: :nfs, # The nolock option can be useful for an NFSv3 client that wants to avoid the # NLM sideband protocol. Without this option, apt-get might hang if it tries # to lock files needed for /var/cache/* operations. All of this can be avoided # by using NFSv4 everywhere. Please note that the tcp option is not the default. mount_options: ['rw', 'vers=3', 'tcp', 'nolock'] } end config.vm.box_check_update = false config.vm.define "cache-01", autostart: false do |v| v.vm.box = "puppetlabs/centos-6.6-64-puppet" v.vm.hostname = "cache-01" end config.vm.define "cache-02", autostart: false do |v| v.vm.box = "puppetlabs/centos-6.6-64-puppet" v.vm.hostname = "cache-02" end config.vm.provision "puppet" do |puppet| puppet.manifests_path = "manifests" puppet.manifest_file = "site.pp" end end
module Cocoadex class Function < SequentialNodeElement attr_reader :abstract, :declaration, :declared_in, :availability, :return_value TEMPLATE_NAME=:method def parameters @parameters ||= [] end def discussion "" end def handle_node node if node.classes.include? "parameters" parse_parameters(node) else logger.debug("Unhandled function property: #{node.classes} => #{node.text}") end end def type "Function" end end end
class AddPasswordDigestToUsers < Mongoid::Migration def change add_column :users, :password_digest, :string end def self.up end def self.down end end
class PeopleController < ApplicationController # before_action :set_authentication require 'rest-client' EMAIL = "sid@gmail.com" PASSWORD = "123456" API_BASE_URL = "http://localhost:3000" def index url_u = "#{API_BASE_URL}/people.json" rest_cli = RestClient::Resource.new(url_u) people = rest_cli.get @people = JSON.parse(people, :symbolize_names => true) end def new end def create url = "#{API_BASE_URL}/people" payload = params.to_json rest_cli = RestClient::Resource.new(url) begin rest_cli.post payload, :content_type => "application/json" flash[:notice] = "Person is created " redirect_to people_path rescue Exception => e flash[:notice] = "Person is not created" render :new end end def edit url = "#{API_BASE_URL}/people/#{params[:id]}.json" rest_cli = RestClient::Resource.new(url) people = rest_cli.get @people = JSON.parse(people, :symbolize_names => true) end def update url = "#{API_BASE_URL}/people/#params[:id].json" payload = params.to_json rest_cli = RestClient::Resource.new(url) begin rest_cli.put payload, :content_type => "aplication/json" flash[:notice] = "User Updated successfully" rescue Exception => e flash[:error] = "User Failed to Update" end redirect_to people_path end def destroy # @people = People.find(params[:id]) # puts "1111111111111" uri = "#{API_BASE_URL}/people/#{params[:id]}" # puts "ccccccccccc" rest_cli = RestClient::Resource.new(uri) begin rest_cli.delete # puts "xxxxxxxxxxxxxxxxxxxxx" flash[:notice] = "Person Deleted successfully" rescue Exception => e flash[:error] = "Person Failed to Delete" end redirect_to people_path end # def set_authentication # url = "#{API_BASE_URL}/auth/index" # payload = params.to_json # # rest_cli = RestClient::Resource.new(url, EMAIL, PASSWORD) # rest_cli = RestClient::Resource.new(url) # @user = rest_cli.post payload, :content_type => "application/json" # render json: @user # # begin # # @people = rest_cli.post payload, :content_type => "application/json" # # render json: @people # # flash[:notice] = "login successfully" # # rescue Exception => e # # puts "ssssssssss" # # flash[:error] set_authentication= "Error" # # end # # people = rest_cli.get # # @people = JSON.parse(people, :symbolize_names => true) # end end
require 'rails_helper' describe AuditStructureCreator do let!(:audit) { create(:audit) } let(:audit_audit_strc_type) { audit.audit_structure.audit_strc_type } it 'creates a structure record' do audit_strc_type = create(:audit_strc_type, parent_structure_type: audit_audit_strc_type) creator = AuditStructureCreator.new( params: { name: 'My structure' }, parent_structure: audit.audit_structure, audit_strc_type: audit_strc_type ) creator.execute! audit_structure = creator.audit_structure expect(audit_structure).to be_persisted expect(audit_structure.name).to eq 'My structure' expect(audit_structure.parent_structure).to eq audit.audit_structure expect(audit_structure.audit_strc_type).to eq audit_strc_type expect(audit_structure.successful_upload_on).to be_a(ActiveSupport::TimeWithZone) expect(audit_structure.upload_attempt_on).to be_a(ActiveSupport::TimeWithZone) end it 'creates a physical structure record when appropriate' do building_type = create(:building_audit_strc_type, parent_structure_type: audit_audit_strc_type) creator = AuditStructureCreator.new( params: { name: 'My building', }, parent_structure: audit.audit_structure, audit_strc_type: building_type ) creator.execute! physical_structure = creator.audit_structure.physical_structure expect(physical_structure).to be_persisted expect(physical_structure).to be_a(Building) expect(physical_structure.name).to eq 'My building' expect(physical_structure.successful_upload_on).to be_a(ActiveSupport::TimeWithZone) expect(physical_structure.upload_attempt_on).to be_a(ActiveSupport::TimeWithZone) end end
require_relative "lockbox_transform" require "test/unit" class LockboxTransformTestWithSimpleSample < Test::Unit::TestCase def setup @lt = LockboxTransform.new() @data = "Title: my bank account\nInformation: line1\nCategory: Bank Account\nNotes: line1\n" end def test_that_it_understands_sample hash = @lt.to_hash(@data) expected = [{:Title=> 'my bank account', :Information=>"line1", :Category=>'Bank Account', :Notes=>"line1" } ] assert_equal(expected,hash) end end class LockboxTransformTestWithDataSample < Test::Unit::TestCase def setup @lt = LockboxTransform.new() @data = File.read(File.join(File.dirname(__FILE__), 'lockbox_data_2013_12_17.txt')) end def test_that_it_can_read_value value,position = @lt.expect_value(@data,35) assert_equal "line1\nline2", value end def test_that_colon_at_line_is_not_missreported value = @lt.is_colon_at_line?(@data,42) assert_equal false, value end def test_that_colon_at_lines assert_equal true, @lt.is_colon_at_line?(@data,0) assert_equal true, @lt.is_colon_at_line?(@data,23) end def test_that_empty_line_is_empty assert_equal true, @lt.is_empty_line?(@data,96) end def test_that_empty_lines_at_lines assert_equal false, @lt.is_empty_line?(@data,0) assert_equal false, @lt.is_empty_line?(@data,23) end def test_that_it_can_parse_block_1 hash,position = @lt.parse_block(@data,0) expected = {:Title=> 'my bank Account', :Information=>"line1\nline2", :Category=>'Bank Account', :Notes=>"line1\nline2\nline3" } assert_equal expected, hash assert_equal 96, position end def test_that_it_can_parse_block_2 hash,position = @lt.parse_block(@data,96) expected = {:Title=>'my secret data', :Information=>'line1', :Category=>'Other', :Notes=>"line1\nline2" } assert_equal expected, hash assert_equal 173, position end def test_that_it_can_parse_block_3 hash,position = @lt.parse_block(@data,173) expected = {:Title=>"another secret data", :Information=>"line1\nline2", :Category=>"Other", :Notes=>"" } assert_equal expected, hash assert_equal 252, position end def test_that_it_understands_sample hash = @lt.to_hash(@data) expected = [{:Title=> 'my bank Account', :Information=>"line1\nline2", :Category=>'Bank Account', :Notes=>"line1\nline2\nline3" }, {:Title=>'my secret data', :Information=>'line1', :Category=>'Other', :Notes=>"line1\nline2" }, {:Title=>"another secret data", :Information=>"line1\nline2", :Category=>"Other", :Notes=>"" } ] assert_equal(expected,hash) end end
class CreateEasyAttendanceActivities < ActiveRecord::Migration def self.up create_table :easy_attendance_activities do |t| t.column :name, :string, :null => false t.column :position, :integer, :null => true, :default => 1 t.column :at_work, :boolean, :default => false t.column :is_default, :boolean, :default => false, :null => false t.column :internal_name, :string, :null => true t.column :non_deletable, :boolean, :null => false, :default => false t.timestamps end end def self.down drop_table :easy_attendance_activities end end
# Copyright ยฉ 2011-2019 MUSC Foundation for Research Development~ # All rights reserved.~ # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:~ # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.~ # 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following~ # disclaimer in the documentation and/or other materials provided with the distribution.~ # 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products~ # derived from this software without specific prior written permission.~ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,~ # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT~ # SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL~ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS~ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR~ # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.~ require "rails_helper" RSpec.describe Dashboard::MessagesController do describe "GET #new" do before(:each) do @logged_in_user = build_stubbed(:identity) @notification = findable_stub(Notification) do build_stubbed(:notification) end @recipient = build_stubbed(:identity) allow(@notification).to receive(:get_user_other_than). with(@logged_in_user). and_return(@recipient) # expected @new_message_attrs = { notification_id: @notification.id, to: @recipient.id, from: @logged_in_user.id, email: @recipient.email } allow(Message).to receive(:new). and_return("new message") log_in_dashboard_identity(obj: @logged_in_user) get :new, params: @new_message_attrs, xhr: true end it "should create a new Message from current user to user other than current user of Notification" do expect(Message).to have_received(:new). with(@new_message_attrs) end it "should assign @message to new Message built" do expect(assigns(:message)).to eq("new message") end it "should assign @notification from params[:notification_id]" do expect(assigns(:notification)).to eq(@notification) end it { is_expected.to render_template "dashboard/messages/new" } it { is_expected.to respond_with :ok } end end
class DropDebitCreditHrefFieldsFromRentals < ActiveRecord::Migration def change remove_column :rentals, :debit_href remove_column :rentals, :credit_href end end
require_relative "../linked_list.rb" RSpec.describe LinkedList, "#append" do node1 = "node1" node2 = "node2" node3 = "node3" node4 = "node4" node5 = "node5" node6 = "node6" list = LinkedList.new(node1) context "#append" do it "adds a new node to start of the list" do expect(list.head.value).to eq node1 end it "adds a new node at end of list" do list.append(node2) expect(list.tail.value).to eq node2 end it "expects lits.head to be a Node" do list.append(node2) expect(list.head).to be_a Node expect(list.tail).to be_a Node end it "expects @tail.next_node to be nil" do list.append(node2) expect(list.tail.next_node).to eq nil end it "expects @tail.bale to be node3" do list.append(node2) list.append(node3) expect(list.tail.value).to eq node3 end it "expects @head.next_node to be eq to 2nd item" do list.append(node2) list.append(node3) expect(list.head.next_node.value).to eq node2 end end context "#prepend" do it "expects head node to become prepended node" do list.prepend(node2) expect(list.head.value).to eq node2 expect(list.head.next_node.value).to eq node1 end end context "#size" do it "returns the total number of nodes in the list " do newList = LinkedList.new(node1) newList.append(node2) newList.append(node3) newList.append(node4) newList.append(node5) newList.append(node6) expect(newList.size).to eq 6 end end context "#head and #tail" do it "list.head to return head node" do newList = LinkedList.new(node1) newList.append(node2) newList.append(node3) newList.append(node4) newList.append(node5) newList.append(node6) expect(newList.head.value).to eq node1 end it "list.tail to return last node" do newList = LinkedList.new(node1) newList.append(node2) newList.append(node3) newList.append(node4) newList.append(node5) newList.append(node6) expect(newList.tail.value).to eq node6 expect(newList.head.value).to eq node1 end end context "#at(index)" do it "should return the node at a given index" do newList = LinkedList.new(node1) newList.append(node2) newList.append(node3) newList.append(node4) newList.append(node5) newList.append(node6) expect(newList.at(1).value).to eq node1 #because it was prepended end it "should return a error if the argument is too big" do expect(list.at(100)).to eq "Index too small" end it "should return head node for first index" do expect(list.at(1)).to eq list.head end end context "#pop" do it "expects the last node to be node 2" do newList = LinkedList.new(node1) newList.append(node2) newList.append(node3) newList.append(node4) newList.append(node5) newList.append(node6) newList.pop expect(newList.tail.value).to eq node5 end it "expects the size to decrease by one" do newList = LinkedList.new(node1) newList.append(node2) newList.append(node3) newList.append(node4) newList.append(node5) newList.append(node6) expect(newList.size).to eq 6 end end context "#contains" do it "expects list.contains?(node3) to be true" do newList = LinkedList.new(node1) newList.append(node2) newList.append(node3) newList.append(node4) newList.append(node5) newList.append(node6) expect(newList.size).to eq 6 expect(newList.contains?(node2)).to eq true end it "expects list.contains? to return false" do nodes = Node.new("bla") list.append(nodes) expect(list.contains?(nodes)).to eq false end end context "#find(data)" do it "returns index of node containing data" do newList = LinkedList.new(node1) newList.append(node2) newList.append(node3) newList.append(node4) newList.append(node5) newList.append(node6) expect(newList.find(node2)).to eq 2 end it "returns nil for no mathching node" do expect(list.find(node4)).to eq nil end end context "#to_s" do it "returns nodes in a string form" do newList = LinkedList.new(node1) newList.append(node2) newList.append(node3) expect(newList.to_s).to eq "(#{node1}) -> (#{node2}) -> (#{newList.tail.value}) -> nil" end end context "#insert_at" do it "inserts a node at a particular index" do newList = LinkedList.new(node1) newList.append(node2) newList.append(node3) newList.insert_at(3,node4) expect(newList.at(2).next_node.value).to eq node4 end end context "#remove_at" do it "removes a node at a particular index" do newList = LinkedList.new(node1) newList.append(node2) newList.append(node3) newList.append(node4) newList.append(node5) newList.append(node6) newList.remove_at(2) expect(newList.at(5).value).to eq node6 end it "removes a node at a particular 1st index" do newList = LinkedList.new(node1) newList.append(node2) newList.append(node3) newList.append(node4) newList.append(node5) newList.append(node6) newList.remove_at(1) expect(newList.at(1).value).to eq node2 end end end
class Cocktail < ApplicationRecord has_many :ingredients, through: :doses has_many :doses validates :name, presence: true, uniqueness: true before_destroy :destroy_all_doses protected def destroy_all_doses self.doses.each { |dose| dose.destroy } end end
require 'spec_helper' return unless defined?(Rack) RSpec.describe Sentry::Rack::CaptureExceptions, rack: true do let(:exception) { ZeroDivisionError.new("divided by 0") } let(:additional_headers) { {} } let(:env) { Rack::MockRequest.env_for("/test", additional_headers) } describe "exceptions capturing" do before do perform_basic_setup end it 'captures the exception from direct raise' do app = ->(_e) { raise exception } stack = described_class.new(app) expect { stack.call(env) }.to raise_error(ZeroDivisionError) event = last_sentry_event.to_hash expect(event.dig(:request, :url)).to eq("http://example.org/test") expect(env["sentry.error_event_id"]).to eq(event[:event_id]) last_frame = event.dig(:exception, :values, 0, :stacktrace, :frames).last expect(last_frame[:vars]).to eq(nil) end it 'captures the exception from rack.exception' do app = lambda do |e| e['rack.exception'] = exception [200, {}, ['okay']] end stack = described_class.new(app) expect do stack.call(env) end.to change { sentry_events.count }.by(1) event = last_sentry_event expect(env["sentry.error_event_id"]).to eq(event.event_id) expect(event.to_hash.dig(:request, :url)).to eq("http://example.org/test") end it 'captures the exception from sinatra.error' do app = lambda do |e| e['sinatra.error'] = exception [200, {}, ['okay']] end stack = described_class.new(app) expect do stack.call(env) end.to change { sentry_events.count }.by(1) event = last_sentry_event expect(event.to_hash.dig(:request, :url)).to eq("http://example.org/test") end it 'sets the transaction and rack env' do app = lambda do |e| e['rack.exception'] = exception [200, {}, ['okay']] end stack = described_class.new(app) stack.call(env) event = last_sentry_event expect(event.transaction).to eq("/test") expect(event.to_hash.dig(:request, :url)).to eq("http://example.org/test") expect(Sentry.get_current_scope.transaction_names).to be_empty expect(Sentry.get_current_scope.rack_env).to eq({}) end it 'passes rack/lint' do app = proc do [200, { 'content-type' => 'text/plain' }, ['OK']] end stack = described_class.new(Rack::Lint.new(app)) expect { stack.call(env) }.to_not raise_error expect(env.key?("sentry.error_event_id")).to eq(false) end context "with config.include_local_variables = true" do before do perform_basic_setup do |config| config.include_local_variables = true end end after do Sentry.exception_locals_tp.disable end it 'captures the exception with locals' do app = ->(_e) do a = 1 b = 0 a / b end stack = described_class.new(app) expect { stack.call(env) }.to raise_error(ZeroDivisionError) event = last_sentry_event.to_hash expect(event.dig(:request, :url)).to eq("http://example.org/test") last_frame = event.dig(:exception, :values, 0, :stacktrace, :frames).last expect(last_frame[:vars]).to include({ a: "1", b: "0" }) end it 'ignores problematic locals' do class Foo def inspect raise end end app = ->(_e) do a = 1 b = 0 f = Foo.new a / b end stack = described_class.new(app) expect { stack.call(env) }.to raise_error(ZeroDivisionError) event = last_sentry_event.to_hash expect(event.dig(:request, :url)).to eq("http://example.org/test") last_frame = event.dig(:exception, :values, 0, :stacktrace, :frames).last expect(last_frame[:vars]).to include({ a: "1", b: "0", f: "[ignored due to error]" }) end it 'truncates lengthy values' do app = ->(_e) do a = 1 b = 0 long = "*" * 2000 a / b end stack = described_class.new(app) expect { stack.call(env) }.to raise_error(ZeroDivisionError) event = last_sentry_event.to_hash expect(event.dig(:request, :url)).to eq("http://example.org/test") last_frame = event.dig(:exception, :values, 0, :stacktrace, :frames).last expect(last_frame[:vars]).to include({ a: "1", b: "0", long: "*" * 1024 + "..." }) end end describe "state encapsulation" do before do Sentry.configure_scope { |s| s.set_tags(tag_1: "don't change me") } Sentry.configuration.breadcrumbs_logger = [:sentry_logger] end it "only contains the breadcrumbs of the request" do logger = ::Logger.new(nil) logger.info("old breadcrumb") request_1 = lambda do |e| logger.info("request breadcrumb") Sentry.capture_message("test") [200, {}, ["ok"]] end app_1 = described_class.new(request_1) app_1.call(env) event = last_sentry_event expect(event.breadcrumbs.count).to eq(1) expect(event.breadcrumbs.peek.message).to eq("request breadcrumb") end it "doesn't pollute the top-level scope" do request_1 = lambda do |e| Sentry.configure_scope { |s| s.set_tags({tag_1: "foo"}) } Sentry.capture_message("test") [200, {}, ["ok"]] end app_1 = described_class.new(request_1) app_1.call(env) event = last_sentry_event expect(event.tags).to eq(tag_1: "foo") expect(Sentry.get_current_scope.tags).to eq(tag_1: "don't change me") end it "doesn't pollute other request's scope" do request_1 = lambda do |e| Sentry.configure_scope { |s| s.set_tags({tag_1: "foo"}) } e['rack.exception'] = Exception.new [200, {}, ["ok"]] end app_1 = described_class.new(request_1) app_1.call(env) event = last_sentry_event expect(event.tags).to eq(tag_1: "foo") expect(Sentry.get_current_scope.tags).to eq(tag_1: "don't change me") request_2 = proc do |e| Sentry.configure_scope { |s| s.set_tags({tag_2: "bar"}) } e['rack.exception'] = Exception.new [200, {}, ["ok"]] end app_2 = described_class.new(request_2) app_2.call(env) event = last_sentry_event expect(event.tags).to eq(tag_2: "bar", tag_1: "don't change me") expect(Sentry.get_current_scope.tags).to eq(tag_1: "don't change me") end end end describe "performance monitoring" do before do perform_basic_setup do |config| config.traces_sample_rate = 0.5 end end context "when sentry-trace header is sent" do let(:external_transaction) do Sentry::Transaction.new( op: "pageload", status: "ok", sampled: true, name: "a/path", hub: Sentry.get_current_hub ) end let(:stack) do described_class.new( ->(_) do [200, {}, ["ok"]] end ) end def verify_transaction_attributes(transaction) expect(transaction.type).to eq("transaction") expect(transaction.transaction).to eq("/test") expect(transaction.transaction_info).to eq({ source: :url }) expect(transaction.timestamp).not_to be_nil expect(transaction.contexts.dig(:trace, :status)).to eq("ok") expect(transaction.contexts.dig(:trace, :op)).to eq("http.server") expect(transaction.spans.count).to eq(0) end def verify_transaction_inherits_external_transaction(transaction, external_transaction) expect(transaction.contexts.dig(:trace, :trace_id)).to eq(external_transaction.trace_id) expect(transaction.contexts.dig(:trace, :parent_span_id)).to eq(external_transaction.span_id) end def verify_transaction_doesnt_inherit_external_transaction(transaction, external_transaction) expect(transaction.contexts.dig(:trace, :trace_id)).not_to eq(external_transaction.trace_id) expect(transaction.contexts.dig(:trace, :parent_span_id)).not_to eq(external_transaction.span_id) end def wont_be_sampled_by_sdk allow(Random).to receive(:rand).and_return(1.0) end def will_be_sampled_by_sdk allow(Random).to receive(:rand).and_return(0.3) end before do env["HTTP_SENTRY_TRACE"] = trace end let(:transaction) do last_sentry_event end context "with sampled trace" do let(:trace) do "#{external_transaction.trace_id}-#{external_transaction.span_id}-1" end it "inherits trace info and sampled decision from the trace and ignores later sampling" do wont_be_sampled_by_sdk stack.call(env) verify_transaction_attributes(transaction) verify_transaction_inherits_external_transaction(transaction, external_transaction) end end context "with unsampled trace" do let(:trace) do "#{external_transaction.trace_id}-#{external_transaction.span_id}-0" end it "doesn't sample any transaction" do will_be_sampled_by_sdk stack.call(env) expect(transaction).to be_nil end end context "with trace that has no sampling bit" do let(:trace) do "#{external_transaction.trace_id}-#{external_transaction.span_id}-" end it "inherits trace info but not the sampling decision (later sampled)" do will_be_sampled_by_sdk stack.call(env) verify_transaction_attributes(transaction) verify_transaction_inherits_external_transaction(transaction, external_transaction) end it "inherits trace info but not the sampling decision (later unsampled)" do wont_be_sampled_by_sdk stack.call(env) expect(transaction).to eq(nil) end end context "with bugus trace" do let(:trace) { "null" } it "starts a new transaction and follows SDK sampling decision (sampled)" do will_be_sampled_by_sdk stack.call(env) verify_transaction_attributes(transaction) verify_transaction_doesnt_inherit_external_transaction(transaction, external_transaction) end it "starts a new transaction and follows SDK sampling decision (unsampled)" do wont_be_sampled_by_sdk stack.call(env) expect(transaction).to eq(nil) end end context "when traces_sampler is set" do let(:trace) do "#{external_transaction.trace_id}-#{external_transaction.span_id}-1" end it "passes parent_sampled to the sampling_context" do parent_sampled = false Sentry.configuration.traces_sampler = lambda do |sampling_context| parent_sampled = sampling_context[:parent_sampled] end stack.call(env) expect(parent_sampled).to eq(true) end it "passes request env to the sampling_context" do sampling_context_env = nil Sentry.configuration.traces_sampler = lambda do |sampling_context| sampling_context_env = sampling_context[:env] end stack.call(env) expect(sampling_context_env).to eq(env) end end context "when the baggage header is sent" do let(:trace) do "#{external_transaction.trace_id}-#{external_transaction.span_id}-1" end before do env["HTTP_BAGGAGE"] = "other-vendor-value-1=foo;bar;baz, "\ "sentry-trace_id=771a43a4192642f0b136d5159a501700, "\ "sentry-public_key=49d0f7386ad645858ae85020e393bef3, "\ "sentry-sample_rate=0.01337, "\ "sentry-user_id=Am%C3%A9lie, "\ "other-vendor-value-2=foo;bar;" end it "has the dynamic_sampling_context on the TransactionEvent" do expect(Sentry::Transaction).to receive(:new). with(hash_including(:baggage)). and_call_original stack.call(env) expect(transaction.dynamic_sampling_context).to eq({ "sample_rate" => "0.01337", "public_key" => "49d0f7386ad645858ae85020e393bef3", "trace_id" => "771a43a4192642f0b136d5159a501700", "user_id" => "Amรฉlie" }) end end end context "when the transaction is sampled" do before do allow(Random).to receive(:rand).and_return(0.4) end it "starts a transaction and finishes it" do app = ->(_) do [200, {}, ["ok"]] end stack = described_class.new(app) stack.call(env) transaction = last_sentry_event expect(transaction.type).to eq("transaction") expect(transaction.transaction).to eq("/test") expect(transaction.transaction_info).to eq({ source: :url }) expect(transaction.timestamp).not_to be_nil expect(transaction.contexts.dig(:trace, :status)).to eq("ok") expect(transaction.contexts.dig(:trace, :op)).to eq("http.server") expect(transaction.spans.count).to eq(0) end describe "Sentry.with_child_span" do it "sets nested spans correctly under the request's transaction" do app = ->(_) do Sentry.with_child_span(op: "first level") do Sentry.with_child_span(op: "second level") do [200, {}, ["ok"]] end end end stack = described_class.new(app) stack.call(env) transaction = last_sentry_event expect(transaction.type).to eq("transaction") expect(transaction.timestamp).not_to be_nil expect(transaction.transaction).to eq("/test") expect(transaction.transaction_info).to eq({ source: :url }) expect(transaction.contexts.dig(:trace, :status)).to eq("ok") expect(transaction.contexts.dig(:trace, :op)).to eq("http.server") expect(transaction.spans.count).to eq(2) first_span = transaction.spans.first expect(first_span[:op]).to eq("first level") expect(first_span[:parent_span_id]).to eq(transaction.contexts.dig(:trace, :span_id)) second_span = transaction.spans.last expect(second_span[:op]).to eq("second level") expect(second_span[:parent_span_id]).to eq(first_span[:span_id]) end end end context "when the transaction is not sampled" do before do allow(Random).to receive(:rand).and_return(0.6) end it "doesn't do anything" do app = ->(_) do [200, {}, ["ok"]] end stack = described_class.new(app) stack.call(env) expect(sentry_events.count).to eq(0) end end context "when there's an exception" do before do allow(Random).to receive(:rand).and_return(0.4) end it "still finishes the transaction" do app = ->(_) do raise "foo" end stack = described_class.new(app) expect do stack.call(env) end.to raise_error("foo") expect(sentry_events.count).to eq(2) event = sentry_events.first transaction = last_sentry_event expect(event.contexts.dig(:trace, :trace_id).length).to eq(32) expect(event.contexts.dig(:trace, :trace_id)).to eq(transaction.contexts.dig(:trace, :trace_id)) expect(transaction.type).to eq("transaction") expect(transaction.timestamp).not_to be_nil expect(transaction.contexts.dig(:trace, :status)).to eq("internal_error") expect(transaction.contexts.dig(:trace, :op)).to eq("http.server") expect(transaction.spans.count).to eq(0) end end context "when traces_sample_rate is not set" do before do Sentry.configuration.traces_sample_rate = nil end let(:stack) do described_class.new( ->(_) do [200, {}, ["ok"]] end ) end it "doesn't record transaction" do stack.call(env) expect(sentry_events.count).to eq(0) end context "when sentry-trace header is sent" do let(:external_transaction) do Sentry::Transaction.new( op: "pageload", status: "ok", sampled: true, name: "a/path", hub: Sentry.get_current_hub ) end it "doesn't cause the transaction to be recorded" do env["HTTP_SENTRY_TRACE"] = external_transaction.to_sentry_trace response = stack.call(env) expect(response[0]).to eq(200) expect(sentry_events).to be_empty end end end end describe "tracing without performance" do let(:incoming_prop_context) { Sentry::PropagationContext.new(Sentry::Scope.new) } let(:env) do { "HTTP_SENTRY_TRACE" => incoming_prop_context.get_traceparent, "HTTP_BAGGAGE" => incoming_prop_context.get_baggage.serialize } end let(:stack) do app = ->(_e) { raise exception } described_class.new(app) end before { perform_basic_setup } it "captures exception with correct DSC and trace context" do expect { stack.call(env) }.to raise_error(ZeroDivisionError) trace_context = last_sentry_event.contexts[:trace] expect(trace_context[:trace_id]).to eq(incoming_prop_context.trace_id) expect(trace_context[:parent_span_id]).to eq(incoming_prop_context.span_id) expect(trace_context[:span_id].length).to eq(16) expect(last_sentry_event.dynamic_sampling_context).to eq(incoming_prop_context.get_dynamic_sampling_context) end end describe "session capturing" do context "when auto_session_tracking is false" do before do perform_basic_setup do |config| config.auto_session_tracking = false end end it "passthrough" do app = ->(_) do [200, {}, ["ok"]] end expect_any_instance_of(Sentry::Hub).not_to receive(:start_session) expect(Sentry.session_flusher).to be_nil stack = described_class.new(app) stack.call(env) expect(sentry_envelopes.count).to eq(0) end end context "tracks sessions by default" do before do perform_basic_setup do |config| config.release = 'test-release' config.environment = 'test' end end it "collects session stats and sends envelope with aggregated sessions" do app = lambda do |env| req = Rack::Request.new(env) case req.path_info when /success/ [200, {}, ['ok']] when /error/ 1 / 0 end end stack = described_class.new(app) expect(Sentry.session_flusher).not_to be_nil now = Time.now.utc now_bucket = Time.utc(now.year, now.month, now.day, now.hour, now.min) Timecop.freeze(now) do 10.times do env = Rack::MockRequest.env_for('/success') stack.call(env) end 2.times do env = Rack::MockRequest.env_for('/error') expect { stack.call(env) }.to raise_error(ZeroDivisionError) end expect(sentry_events.count).to eq(2) Sentry.session_flusher.flush expect(sentry_envelopes.count).to eq(1) envelope = sentry_envelopes.first expect(envelope.items.length).to eq(1) item = envelope.items.first expect(item.type).to eq('sessions') expect(item.payload[:attrs]).to eq({ release: 'test-release', environment: 'test' }) expect(item.payload[:aggregates].first).to eq({ exited: 10, errored: 2, started: now_bucket.iso8601 }) end end end end if defined?(StackProf) describe "profiling" do context "when profiling is enabled" do before do perform_basic_setup do |config| config.traces_sample_rate = 1.0 config.profiles_sample_rate = 1.0 config.release = "test-release" end end let(:stackprof_results) do data = StackProf::Report.from_file('spec/support/stackprof_results.json').data # relative dir differs on each machine data[:frames].each { |_id, fra| fra[:file].gsub!(/<dir>/, Dir.pwd) } data end before do StackProf.stop allow(StackProf).to receive(:results).and_return(stackprof_results) end it "collects a profile" do app = ->(_) do [200, {}, "ok"] end stack = described_class.new(app) stack.call(env) event = last_sentry_event profile = event.profile expect(profile).not_to be_nil expect(profile[:event_id]).not_to be_nil expect(profile[:platform]).to eq("ruby") expect(profile[:version]).to eq("1") expect(profile[:environment]).to eq("development") expect(profile[:release]).to eq("test-release") expect { Time.parse(profile[:timestamp]) }.not_to raise_error expect(profile[:device]).to include(:architecture) expect(profile[:os]).to include(:name, :version) expect(profile[:runtime]).to include(:name, :version) expect(profile[:transaction]).to include(:id, :name, :trace_id, :active_thead_id) expect(profile[:transaction][:id]).to eq(event.event_id) expect(profile[:transaction][:name]).to eq(event.transaction) expect(profile[:transaction][:trace_id]).to eq(event.contexts[:trace][:trace_id]) expect(profile[:transaction][:active_thead_id]).to eq("0") # detailed checking of content is done in profiler_spec, # just check basic structure here frames = profile[:profile][:frames] expect(frames).to be_a(Array) expect(frames.first).to include(:function, :filename, :abs_path, :in_app) stacks = profile[:profile][:stacks] expect(stacks).to be_a(Array) expect(stacks.first).to be_a(Array) expect(stacks.first.first).to be_a(Integer) samples = profile[:profile][:samples] expect(samples).to be_a(Array) expect(samples.first).to include(:stack_id, :thread_id, :elapsed_since_start_ns) end end end end end
require 'rails_helper' describe Location do it 'is created when all attributes are valid' do expect(build(:location)).to be_valid end it 'requires a state' do expect(build(:location, state_id: '')).to be_invalid end it 'correctly references the state it\'s in' do create(:state) sample = create(:location) expect(sample.state.name).to eq('Florida') end describe '.zip' do it 'is not required' do expect(build(:location, zip: '')).to be_valid end end describe '.lat (latitude)' do it 'is required' do expect(build(:location, lat: '')).to be_invalid end it 'must be a number' do lats = ['Winning!', 'h4x0r3d', 'fail'] lats.each do |lat| expect(build(:location, lat: lat)).to be_invalid end end end describe '.long (longitude)' do it 'is required' do expect(build(:location, long: '')).to be_invalid end it 'must be a number' do longs = ['Winning!', 'h4x0r3d', 'fail'] longs.each do |long| expect(build(:location, long: long)).to be_invalid end end end end
#!/usr/bin/env ruby # run committed files against the ruby style guide. require 'open3' stdout, stderr, status = Open3.capture3("git diff --name-only --cached | grep -E '#{%w[rb rake].map{|ext| '\.' + ext}.join('|')}' ") modified_files = stdout.split(/\n/) if modified_files.count > 0 $stdout.puts("Code conventions: running files against rubocop (https://github.com/bbatsov/rubocop/):") $stdout.puts(modified_files.join("\n ")) stdout, stderr, status = Open3.capture3("rubocop #{modified_files.join(' ')}") if status.exitstatus != 0 $stdout.puts(stdout) $stdout.puts("*******************************************************************************************") $stdout.puts("The files you committed need cleanup! Many of the warnings are probably old and not yours.") $stdout.puts("We need your help with cleaning. If you think some errors should be ignored, edit .rubocop.yml") $stdout.puts("You might also try running 'rubocop $your_file --auto-correct', but review the changes!") $stdout.puts("*******************************************************************************************") exit 1 else $stdout.puts("Files passed Rubocop!") exit 0 end end # if you want to add your own pre-commit logic, consider what would happen if one or many checks worked or failed, # i.e. a sub_routines: [{ name: foo, status: some_value },...]
require('minitest/autorun') require('minitest/rg') require_relative('../Song.rb') class SongTest < MiniTest::Test def test_song_title song1 = Song.new("Waterloo","Abba") assert_equal("Waterloo",song1.title) end def test_song_artist song1 = Song.new("Waterloo","Abba") assert_equal("Abba",song1.artist) end end
Bball::Application.routes.draw do root :to => "home#index" match "app" => "dash#index" resources :games resources :teams do resources :players end end
class Backoffice::ContactInfosController < Backoffice::BackofficeController def index @contact_infos = ContactInfo.order(active: :desc).order(:id) end def new @contact_info = ContactInfo.new end def create @contact_info = ContactInfo.new(info_params) if @contact_info.save if @contact_info.active == true activating(@contact_info) end flash[:success] = 'Novo texto salvo com sucesso!' redirect_to backoffice_contact_infos_path else flash[:error] = 'Erro ao salvar o texto!' render :new end end def edit @contact_info = ContactInfo.find(params[:id]) end def update @contact_info = ContactInfo.find(params[:id]) if @contact_info.update(info_params) if @contact_info.active activating(@contact_info) end flash[:success] = 'Texto atualizado com sucesso!' redirect_to backoffice_contact_infos_path else flash[:error] = 'Erro ao salvar o texto' render :edit end end def destroy @contact_info = ContactInfo.find(params[:id]) if @contact_info.destroy flash[:success] = 'Texto excluรญdo com sucesso!' redirect_to backoffice_contact_infos_path else flash[:error] = 'Erro ao excluir o texto' render :index end end def activate activating(ContactInfo.find(params[:id])) redirect_to backoffice_contact_infos_path end private def activating(info) if(info.active) info.update(active: false) else ContactInfo.all.where("active = true").each do |c| if c != info c.update(active: false) end end info.update(active: true) end end def info_params params.require(:contact_info).permit(:email, :phone, :active) end end
require "spec_helper" feature "Signing out" do before do user = Factory(:confirmed_user) sign_in_as!(user) end scenario "Signing out a user" do visit "/" click_link "Sign out" page.should_not have_content("Signed in as") end end
require File.expand_path(File.dirname(__FILE__) + "/qna_test_helper") describe "AdminTest" do include QnaTestBase before :each do init_qna_pages @product = product @asker = user @super_user = super_user @qa_admin = qa_moderator end it "verify if the answers moderation link is present in the admin dashboard" do @qna_service.login(@super_user) @admin_qna_page.visit_admin assert_equal(true, @admin_qna_page.answers_moderation_link_exists?, "FAILED: Answers moderation link is not present in the admin dashboard") end it "verify if the answers moderator role exists in the user search page" do @qna_service.login(@super_user) @admin_qna_page.visit_admin @admin_qna_page.visit_users_tab assert_equal(true, @admin_qna_page.answers_moderator_role_exists_in_search_dropdown?, "FAILED: Answers moderator role does not exist in the user search page") end it "verify if the answers moderator role exists in the edit users page" do @qna_service.login(@super_user) @admin_qna_page.visit_admin @admin_qna_page.visit_users_tab @admin_qna_page.search_for_user(@asker) @admin_qna_page.edit_user_enable(@asker) assert_equal(true, @admin_qna_page.answers_moderator_role_exists?, "FAILED: Answers moderator role does not exist in the edit users page") end it "verify if the notes filter option exists in the answers moderation page" do @qna_service.visit_qa_admin(@qa_admin) assert_equal(true, @admin_qna_page.filter_by_notes_exists?, "FAILED: Filter by notes option does not exist in the answers moderation page") end it "verify if the admin is able to reject a question" do question = question(@product, @asker) @qna_service.reject(@qa_admin, @asker, QaConstants::QA_QUESTIONS, question) assert_equal(true, @admin_qna_page.rejected?(question), "FAILED: Admin is not able to reject a question") end it "verify if the admin is able to activate a question" do question = question(@product, @asker) @qna_service.reject(@qa_admin, @asker, QaConstants::QA_QUESTIONS, question) @admin_qna_page.activate(question, QaConstants::QA_QUESTIONS) assert_equal(true, @admin_qna_page.active?(question), "FAILED: Admin is not able to activate a question") end it "verify if rejected question is not displayed in the product qna page" do question = question(@product, @asker) answerer = user answer(question, answerer) @qna_service.reject(@qa_admin, @asker, QaConstants::QA_QUESTIONS, question) @qna_service.visit(@product.title) assert_equal(false, @qna_service.question_exists?(question), "FAILED: Rejected question is still displayed in the product page") end it "verify if rejected and reactivated question is displayed in the product qna page" do question = question(@product, @asker) @qna_service.reject(@qa_admin, @asker, QaConstants::QA_QUESTIONS, question) @admin_qna_page.activate(question, QaConstants::QA_QUESTIONS) @qna_service.visit(@product.title) assert_equal(true, @qna_service.question_exists?(question), "FAILED: Rejected and reactivated question is not displayed in the product page") end it "verify if rejection of a question is cascaded to the answers" do question = question(@product, @asker) answerer = user answer = answer(question, answerer) @qna_service.reject(@qa_admin, @asker, QaConstants::QA_QUESTIONS, question) assert_equal(true, @admin_qna_page.cascaded?(answer, false), "FAILED: Cascaded rejection is not happening for answers") end it "verify if activation of a question is cascaded to the answers" do question = question(@product, @asker) answerer = user answer = answer(question, answerer) @qna_service.reject(@qa_admin, @asker, QaConstants::QA_QUESTIONS, question) @admin_qna_page.activate(question, QaConstants::QA_QUESTIONS) assert_equal(true, @admin_qna_page.cascaded?(answer, true), "FAILED: Cascaded activation is not happening for answers") end it "verify if admin is able to reject an answer" do question = question(@product, @asker) answerer = user answer = answer(question, answerer) @qna_service.reject(@qa_admin, answerer, QaConstants::QA_ANSWERS, answer) assert_equal(true, @admin_qna_page.rejected?(answer), "FAILED: Admin is not able to reject an answer") end it "verify if admin is able to activate an answer" do question = question(@product, @asker) answerer = user answer = answer(question, answerer) @qna_service.reject(@qa_admin, answerer, QaConstants::QA_ANSWERS, answer) @admin_qna_page.activate(answer, QaConstants::QA_ANSWERS) assert_equal(true, @admin_qna_page.active?(answer), "FAILED: Admin is not able to activate an answer") end it "verify if a rejected answer is not visible in the product page" do question = question(@product, @asker) answerer = user answer = answer(question, answerer) @qna_service.reject(@qa_admin, answerer, QaConstants::QA_ANSWERS, answer) @qna_service.visit_question(@product.title, question) assert_equal(true, @product_qna_page.first_answer?, "FAILED: Rejected answer is still visible in the product page") end it "verify if a rejected and reactivated answer is visible in the product page" do question = question(@product, @asker) answerer = user answer = answer(question, answerer) @qna_service.reject(@qa_admin, answerer, QaConstants::QA_ANSWERS, answer) @admin_qna_page.activate(answer, QaConstants::QA_ANSWERS) @qna_service.visit_question(@product.title, question) assert_equal(true, @qna_service.answer_exists?(answer), "FAILED: Rejected and reactivated answer is not visible in the product page") end it "verify if the admin is able to preview a question" do question = question(@product, @asker) @qna_service.answers_moderation_default_search(@qa_admin, @asker, QaConstants::QA_QUESTIONS) assert_equal(true, @admin_qna_page.preview_question(question), "FAILED: Admin is not able to preview a question") end it "verify if the admin is able to preview an answer" do question = question(@product, @asker) answerer = user answer = answer(question, answerer) @qna_service.answers_moderation_default_search(@qa_admin, answerer, QaConstants::QA_ANSWERS) assert_equal(true, @admin_qna_page.preview_answer(answer), "FAILED: Admin is not able to preview an answer") end it "verify if the admin is able to search questions by user notes without adding a note" do question = question(@product, @asker) @qna_service.visit_qa_admin(@qa_admin) @admin_qna_page.filter_qna(@asker, QaConstants::QA_QUESTIONS, nil, nil, QaConstants::ADMIN_FILTER_NOTES_USER) assert_equal(false, @admin_qna_page.exists_in_moderation_queue?(question, QaConstants::QA_QUESTIONS), "FAILED: Admin is not able to filter questions by user notes after manually adding a note") end it "verify if the admin is able to search questions by user notes after adding a note" do question = question(@product, @asker) @qna_service.answers_moderation_default_search(@qa_admin, @asker, QaConstants::QA_QUESTIONS) @admin_qna_page.add_note(question, QaConstants::QA_QUESTIONS) @admin_qna_page.filter_qna(@asker, QaConstants::QA_QUESTIONS, nil, nil, QaConstants::ADMIN_FILTER_NOTES_USER) assert_equal(true, @admin_qna_page.exists_in_moderation_queue?(question, QaConstants::QA_QUESTIONS), "FAILED: Admin is not able to filter questions by user notes after manually adding a note") end it "verify if the admin is able to search answers by user notes without adding a note" do question = question(@product, @asker) answerer = user answer = answer(question, answerer) @qna_service.visit_qa_admin(@qa_admin) @admin_qna_page.filter_qna(answerer, QaConstants::QA_ANSWERS, nil, nil, QaConstants::ADMIN_FILTER_NOTES_USER) assert_equal(false, @admin_qna_page.exists_in_moderation_queue?(answer, QaConstants::QA_ANSWERS), "FAILED: Admin is not able to filter answers by user notes after manually adding a note") end it "verify if the admin is able to search answers by user notes after adding a note" do question = question(@product, @asker) answerer = user answer = answer(question, answerer) @qna_service.answers_moderation_default_search(@qa_admin, answerer, QaConstants::QA_ANSWERS) @admin_qna_page.add_note(answer, QaConstants::QA_ANSWERS) @admin_qna_page.filter_qna(answerer, QaConstants::QA_ANSWERS, nil, nil, QaConstants::ADMIN_FILTER_NOTES_USER) assert_equal(true, @admin_qna_page.exists_in_moderation_queue?(answer, QaConstants::QA_ANSWERS), "FAILED: Admin is not able to filter answers by user notes after manually adding a note") end it "verify if the admin is able to add a featured question which is based on a product" do delete_all_featured_questions question = question(@product, @asker) @qna_service.add_featured_question(@super_user, @product.title, question, QaConstants::TYPE_PRODUCT) @qna_home_page.visit assert_equal(true, @qna_home_page.featured_question?(question), "FAILED: Featured question is not displayed in the answers home page") end it "verify if the admin is able to add a featured question which is based on a category" do delete_all_featured_questions question = question(first_level_category, @asker) @qna_service.add_featured_question(@super_user, QaConstants::FIRST_LEVEL_CATEGORY, question, QaConstants::TYPE_CATEGORY) @qna_home_page.visit assert_equal(true, @qna_home_page.featured_question?(question), "FAILED: Featured question is not displayed in the answers home page") end it "verify if the questions from one product is transferred to another when they are merged" do primary_product = product_for_merge secondary_product = product_for_merge question_on_primary = question(primary_product, @asker) question_on_secondary = question(secondary_product, @asker) @qna_service.merge_products(@super_user, primary_product, secondary_product) @qna_service.visit(primary_product.title) assert_equal(true, @qna_service.question_exists?(question_on_primary), "FAILED: Question posted in the primary product is not displayed after merge") assert_equal(true, @qna_service.question_exists?(question_on_secondary), "FAILED: Question posted in the secondary product is not displayed in the primary product after merge") end end
require "date" class Todo def initialize(text, due_date, completed) @text = text @due_date = due_date @completed = completed end def to_displayable_string if @completed==false puts (@text.to_s + ': ' + @due_date.to_s + ': ' + @completed.to_s) else puts ('[ X ]' + ' ' + @text.to_s ) end end end class TodosList def initialize(todos) @todos = todos end def overdue TodosList.new(@todos.filter { |todo| todo.overdue? }) end def to_displayable_list # FILL YOUR CODE HERE @todos.each do |hash| hash.each do |key,value| if hash.has_value?(false) puts ('[ ]' + ' ' + @text.to_s ) else puts ('[ X ]' + ' ' + @text.to_s ) end end end end end date = Date.today todos = [ { text: "Submit assignment", due_date: date - 1, completed: false }, { text: "Pay rent", due_date: date, completed: true }, { text: "File taxes", due_date: date + 1, completed: false }, { text: "Call Acme Corp.", due_date: date + 1, completed: false }, ] todos = todos.map { |todo| Todo.new(todo[:text], todo[:due_date], todo[:completed]) } todos_list = TodosList.new(todos) #todos_list.add(Todo.new("Service vehicle", date, false)) puts "My Todo-list\n\n" puts "Overdue\n" #puts todos_list.overdue.to_displayable_lis puts "\n\n" =begin Dear Sir/Madam, I recived fowllwoing two Error. Please uncomment line no, 55 & 59 separately Due to this, I unable to continue. Please help me Error No. 1 - lino 55 - undefined method `add' todos_list.rb:55:in `<main>': undefined method `add' for #<TodosList:0x000001713ff0c268 @todos=[#<Todo:0x000001713ff0c4e8 @text="Submit assignment", @due_date=#<Date: 2021-10-01 ((2459489j,0s,0n),+0s,2299161j)>, @completed=false>, #<Todo:0x000001713ff0c420 @text="Pay rent", @due_date=#<Date: 2021-10-02 ((2459490j,0s,0n),+0s,2299161j)>, @completed=true>, #<Todo:0x000001713ff0c3f8 @text="File taxes", @due_date=#<Date: 2021-10-03 ((2459491j,0s,0n),+0s,2299161j)>, @completed=false>, #<Todo:0x000001713ff0c3d0 @text="Call Acme Corp.", @due_date=#<Date: 2021-10-03 ((2459491j,0s,0n),+0s,2299161j)>, @completed=false>]> (NoMethodError) Error No. 2 -Overd todos_list.rb:32:in `block in to_displayable_list': undefined method `each' for #<Todo:0x00000244511f2790 @text="Submit assignment", @due_date=#<Date: 2021-10-01 ((2459489j,0s,0n),+0s,2299161j)>, @completed=false> (NoMethodError) from todos_list.rb:31:in `each' from todos_list.rb:31:in `to_displayable_list' from todos_list.rb:58:in `<main>' =end
Pod::Spec.new do |s| s.name = 'ElementaryCyclesSearch' s.version = '0.4.0' s.summary = 'Elementary Circuits of a Directed Graph' s.description = <<-DESC The implementation is pretty much generic, all it needs is a adjacency-matrix of your graph and the objects of your nodes. Then you get back the sets of node-objects which build a cycle. DESC s.homepage = 'https://github.com/hectr/swift-elementary-cycles' s.license = { :type => 'BSD-2', :file => 'LICENSE' } s.author = 'Heฬ€ctor Marqueฬ€s' s.social_media_url = 'https://twitter.com/elnetus' s.ios.deployment_target = '10.0' s.osx.deployment_target = '10.13' s.source = { :git => 'https://github.com/hectr/swift-elementary-cycles.git', :tag => s.version.to_s } s.source_files = 'Sources/ElementaryCyclesSearch/**/*' s.dependency 'Idioms' s.swift_version = '5.0' end
#### # # module Contact # # The system follows entities with an address this wraps up the relationship # # Contact is used by Property, Client and Agent. # Contact includes entities and an address. #### # module Contact extend ActiveSupport::Concern include Entities included do accepts_nested_attributes_for :entities, allow_destroy: true, reject_if: :all_blank has_one :address, class_name: 'Address', dependent: :destroy, as: :addressable accepts_nested_attributes_for :address, allow_destroy: true end private def prepare_contact prepare_address if address.nil? entities.prepare end def prepare_address build_address end end
class BillSearch include ActiveModel::Conversion extend ActiveModel::Naming attr_accessor :start, :end PAGE_SIZE = 15 def initialize(args = {}) @start = args[:start] @end = args[:end] end def retrieve_bills(username) rds = RdsClient.new bills = rds.get_user_bills(username, @start, @end) rds.close_connection bills end end
class Mockup < ActiveRecord::Base enum status: { active: 0 } belongs_to :raw_image belongs_to :user belongs_to :project validates_presence_of :user, :project validates_associated :raw_image, :user, :project validates :name, length: { in: 0..100 } validates :name, format: { with: /\A[a-zA-Z0-9\s]+\z/, message: "Only a-z, A-Z, 0-9 and white-space allowed" } validate :mockup_count_per_project_within_limit def mockup_count_per_project_within_limit limit = 100 if self.project.mockups >= limit errors.add(:base, "Mockup count per project exceeded allowed maximum: #{limit}") end end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'liquid_constant_contact/version' Gem::Specification.new do |spec| spec.name = "liquid_constant_contact" spec.version = LiquidConstantContact::VERSION spec.authors = ["Exodus Integrity Services, Inc.", "Marc Reynolds"] spec.email = ["marc@exodus.com.my"] spec.description = %q{ ConstantContact integration for Liquid} spec.summary = %q{ Allows information from the ConstantContact API to be output on a site running Liquid.} spec.homepage = "http://github.com/mrr728/liquid_constant_contact" spec.license = "MIT" spec.files = `git ls-files`.split($/) spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rake" spec.add_development_dependency 'rspec' spec.add_development_dependency 'mocha' spec.add_development_dependency 'activesupport', '~> 3' spec.add_development_dependency 'pry_debug' spec.add_development_dependency 'mocha' spec.add_development_dependency 'factory_girl' spec.add_development_dependency 'pry' spec.add_development_dependency 'pry-debugger' spec.add_development_dependency 'hammertime19' spec.add_development_dependency 'dotenv' spec.add_development_dependency 'fakeredis' spec.add_dependency 'locomotivecms-solid', '~> 0.2.2.1' end
require 'test_helper' class Admin::LecturesControllerTest < ActionController::TestCase include Devise::TestHelpers def setup @controller = Admin::LecturesController.new john_smith = User.find_by_email("john.smith@mmu.ac.uk") sign_in john_smith end test "should get index" do get :index assert_response :success, "Did not render show all lectures page" end test "should get lecture on today" do get :on_day assert_response :success, "Did not render show lectures today page" end test "should get lecture on specific day" do get :on_day, date: "2015-10-05" assert_response :success, "Did not render show lectures on 2015-10-05 day page" end test "should get new lecture" do get :new assert_response :success, "Did not render create new lecture page" end test "should create lecture" do assert_difference('Lecture.count') do post :create, lecture: { lecture_name: "Test Lecture", lecture_type: "lecture", lecture_room: "E403", attendance_expected: 0, attendance_actual: 0, start_time: Time.now.beginning_of_hour, end_time: Time.now.beginning_of_hour + 1.hour, unit_id: 1, user_id: 2 } end assert_redirected_to admin_lectures_path, "Did not create lecture and redirect to show all lectures page" end test "should get edit" do get :edit, id: 1 assert_response :success, "Did not render edit lecture 1 page" end test "should update lecture" do put :update, { id: 1, lecture: { lecture_name: "Test Lecture", lecture_type: "lecture", lecture_room: "E403", attendance_expected: 0, attendance_actual: 0, start_time: Time.now.beginning_of_hour, end_time: Time.now.beginning_of_hour + 1.hour, unit_id: 1, user_id: 2 } } assert_redirected_to admin_unit_lectures_path(assigns(:lecture)), "Did not update lecture 1 and redirect to lecture page." end test "should destroy lecture" do delete :destroy, id: 1 assert_redirected_to admin_lectures_path, "Did not destroy lecture 1 and redirect to all lectures." end test "should get lecture" do get :show, id: 1 assert_response :success, "Did not render lecture 1 student list." end test "should post add student" do post :add_student, { lecture_id: 1, lecture_student: { user_id: 3 } } assert_redirected_to admin_lecture_path(1), "Did not add student and redirect to lecture 1 student list." end test "should post copy students" do post :copy_students, { lecture_id: 1, lecture_to_copy_id: 2 } assert_redirected_to admin_lecture_path(1), "Did not copy students and redirect to lecture 1 student list." end test "should post remove student from lecture" do post :remove_student, { lecture_id: 1, id: 1 } assert_redirected_to admin_lecture_path(1), "Did not redirect to lecture 1 student list." end test "should get lecture register" do get :register, lecture_id: 1 assert_response :success, "Did not render lecture 1 register." end test "should post register student for lecture" do post :register_student, { lecture_id: 1, student_id: 3 } assert_redirected_to admin_lecture_register_path(1), "Did not redirect to lecture 1 register." end end
# frozen_string_literal: true require 'spec_helper' describe Dotloop::Template do let(:client) { Dotloop::Client.new(access_token: SecureRandom.uuid) } subject(:dotloop_template) { Dotloop::Template.new(client: client) } describe '#initialize' do it 'exist' do expect(dotloop_template).to_not be_nil end it 'set the client' do expect(dotloop_template.client).to eq(client) end end describe '#all' do it 'return a list of templates' do dotloop_mock(:loop_templates) templates = dotloop_template.all(profile_id: 1234) expect(templates).to_not be_empty expect(templates).to all(be_a(Dotloop::Models::Template)) expect(templates.first.client).to eq(client) end end describe '#find' do it 'finds a single template by id' do dotloop_mock(:loop_template) template_data = dotloop_template.find(profile_id: 1234, loop_template_id: 421) expect(template_data).to be_a(Dotloop::Models::Template) end end end
#This is to synchronize the ids of file groups and collections with production as needed for DLS tests on pilot # This class is to handle doing the database/solr work of changing the ids. A small amount of file system manipulation # will also be necessary to move the actual content. class Temp::IdSynchronizer attr_accessor :old_file_group_id, :new_file_group_id, :old_collection_id, :new_collection_id, :file_group, :collection def initialize(args = {}) self.old_file_group_id = args[:old_file_group_id] || (raise "Must provide old file group id") self.old_collection_id = args[:old_collection_id] || (raise "Must provide old collection id") self.new_file_group_id = args[:new_file_group_id] || (raise "Must provide new file group id") self.new_collection_id = args[:new_collection_id] || (raise "Must provide new collection id") self.file_group = FileGroup.find(old_file_group_id) || (raise "File group not found") self.collection = Collection.find(old_collection_id) || (raise "Collection not found") end def process self.collection.transaction do update_file_group_id(file_group.rights_declaration, id_field: :rights_declarable_id) update_collection_id(collection.rights_declaration, id_field: :rights_declarable_id) collection.access_system_collection_joins.each do |join| update_collection_id(join) end collection.collection_virtual_repository_joins.each do |join| update_collection_id(join) end collection.projects.each do |project| update_collection_id(project) end collection.child_collection_joins.each do |join| update_collection_id(join, id_field: :parent_collection_id) end collection.parent_collection_joins.each do |join| update_collection_id(join, id_field: :child_collection_id) end collection.assessments.each do |assessment| update_collection_id(assessment, id_field: :assessable_id) end collection.attachments.each do |attachment| update_collection_id(attachment, id_field: :attachable_id) end if file_group.storage_level == 'bit-level store' file_group.archived_accrual_jobs.each do |job| update_file_group_id(job) end file_group.job_cfs_initial_directory_assessments.each do |job| update_file_group_id(job) end file_group.job_fits_directories.each do |job| update_file_group_id(job) end end file_group.target_file_group_joins.each do |join| update_file_group_id(join, id_field: :source_file_group_id) end file_group.source_file_group_joins.each do |join| update_file_group_id(join, id_field: :target_file_group_id) end file_group.assessments.each do |assessment| update_file_group_id(assessment, id_field: :assessable_id) end file_group.attachments.each do |attachment| update_file_group_id(attachment, id_field: :attachable_id) end update_file_group_id(file_group.cfs_directory, id_field: :parent_id) if file_group.cfs_directory.present? collection.file_groups.each do |file_group| update_collection_id(file_group) end file_group.cfs_directory.update_column(:path, "#{new_collection_id}/#{new_file_group_id}") file_group.update_column(:id, new_file_group_id) collection.update_column(:id, new_collection_id) Collection.connection.execute("select update_cache_content_type_stats_by_collection()") Collection.connection.execute("select update_cache_file_extension_stats_by_collection()") #raise 'Abort until we have everything in place' end end def update_collection_id(object, id_field: :collection_id) object.update_column(id_field, new_collection_id) end def update_file_group_id(object, id_field: :file_group_id) object.update_column(id_field, new_file_group_id) end end
json.array!(@compras) do |compra| json.extract! compra, :id, :user_id, :proveedor_id, :fecha, :estado json.url compra_url(compra, format: :json) end
module Roby module DRoby module V5 # Cross-instance identification of an object class RemoteDRobyID # The peer on which the object is known as {#droby_id} # # @return [PeerID] attr_reader :peer_id # The object ID # # @return [DRobyID] attr_reader :droby_id # The ID hash value # # The values are immutable, so the hash value is computed once # and cached here attr_reader :hash def initialize(peer_id, droby_id) @peer_id = peer_id @droby_id = droby_id @hash = [@peer_id, @droby_id].hash end def eql?(obj) obj.kind_of?(RemoteDRobyID) && obj.peer_id == peer_id && obj.droby_id == droby_id end def ==(obj); eql?(obj) end def to_s "#<RemoteDRobyID #{peer_id}@#{droby_id}>" end end end end end
class Person def initialize(person_name) @name=person_name end def name=(person_name) @name=person_name end def name @name end end mike=Person.new("MIKE") # # mike.name= "MIKE" mike.name
class AddAwesomeToUsers < ActiveRecord::Migration def change remove_column :users, :first_time_omniauth, :integer add_column :users, :awesome, :integer end end
class Account < ApplicationRecord has_many :transactions, class_name: "AccountTransaction", foreign_key: "recipient_account_id" has_many :transfered_transactions, class_name: "AccountTransaction", foreign_key: "origin_account_id" belongs_to :owner, polymorphic: true validates :currency, :account_type, :balance, presence: true after_commit :generate_account_number, on: :create enum account_type: [:wallet, :bank_account] ACCOUNT_CURRENCY = "USD".freeze def generate_account_number begin self.account_number = SecureRandom.random_number(1000000000).to_s self.save rescue ActiveRecord::RecordNotUnique retry end end end
require File::join( File::dirname(__FILE__), %w{ .. .. spec_helper } ) ruby_version_is "1.9" do require File::join( File::dirname(__FILE__), %w{ shared behavior } ) MyBO = Class::new BasicObject describe "BasicObject's subclasses behave" do extend BasicObjectBehavior it "privately" do MyBO.private_instance_methods.sort.should == private_features.sort end it "protectedly" do MyBO.protected_instance_methods.sort.should == protected_features.sort end it "publically" do MyBO.instance_methods.sort.should == public_features.sort end end end
require 'sinatra/base' require 'battleships' require_relative 'game' require_relative 'random_ships.rb' class BattleshipsWeb < Sinatra::Base set :views, proc { File.join(root, '..', 'views') } # start the server if ruby file executed directly run! if app_file == $0 get '/' do erb :index end get '/new_game' do erb :new_game end post '/game_page' do if params[:name] == "" @name = "Player1" else @name = params[:name] end $game = initialize_game $game.player_1.name = @name erb :game_page end post '/fire_shot' do @name = $game.player_1.name coordinates = (params[:coordinates]).upcase.to_sym get_result_and_set_variables(coordinates) erb :game_page end private def get_result_and_set_variables coordinates begin shot_result = $game.player_1.shoot coordinates rescue RuntimeError @coordinate_already_been_shot_at_or_out_of_bounds = true end if shot_result == :sunk @ship_sunk = true @hit = true elsif shot_result == :hit @hit = true else @hit = false end end def initialize_game game = Game.new Player, Board game.player_1.name = @name game end end
class UserMailer < ActionMailer::Base def account_created(company, user, creator, password, login_url) from(SMTP_FROM) recipients(user.email) subject("#{company.name}: Your user account was created") body(:user => user, :creator => creator, :password => password, :login_url => login_url) end def account_reset(company, user, password, login_url) from(SMTP_FROM) recipients(user.email) subject("#{company.name}: Your account password has been reset") body(:user => user, :password => password, :login_url => login_url) end def message(company, user, message) from(SMTP_FROM) recipients(user.email) subject("#{company.name}: message") body(:message => message) end def email(to, subject, body, options={}) from(SMTP_FROM) recipients(to) subject(subject) if options[:template].blank? # use default template options[:body] = body template_html = "email.html.haml" template_text = "email.text.haml" else # use specified template to render email body template_html = options[:template].to_s + ".html.haml" template_text = options[:template].to_s + ".text.haml" end part :content_type => "multipart/alternative" do |a| a.part "text/plain" do |p| p.body = render_message(template_text, options) end unless options.empty? a.part "text/html" do |p| p.body = render_message(template_html, options) end end end end end
class AddPlatformRegionToOAuthAccounts < ActiveRecord::Migration[5.1] def change add_column :oauth_accounts, :platform, :string, limit: 3, default: 'pc', null: false add_column :oauth_accounts, :region, :string, limit: 6, default: 'us', null: false end end
module TweetsHelper def link_to_tweets_page return unless @page_link page = params[:page] page = page.nil? ? 1 : page.to_i url = request.env['PATH_INFO'] url += '?query=' + params[:query] if params.has_key?(:query) if (page > 1 and page == 2) ret = link_to('PageUp', url) elsif (page > 1) ret = link_to('PageUP', url + (url['?'].nil? ? '?' : '&') + 'page=' + (page-1).to_s) else ret = '' end ret << ' | ' unless ret.empty? ret << link_to('PageDown', url + (url['?'].nil? ? '?' : '&') + 'page=' + (page+1).to_s) ret.html_safe end def fetch_mention_users(text) # this function use for fetch the tweet contain other users, # which exclude the tweet sender reg = /(@[a-z0-9\-_]{3,})/i match = text.scan(reg).flatten match.delete('@'+get_current_screen_name) match.uniq end def mention_many_user?(text) return fetch_mention_users(text).count > 0 end def mention_me?(text) return text['@' + get_current_screen_name] end end
class ApplicationController < ActionController::Base def blank_square_form render({:template => "calculation_templates/square_form.html.erb"}) end end