text
stringlengths
10
2.61M
#Field Effects v1.1 #----------# #Features: Allows you to set skills and items that change the background of the # battle, as well as apply states to both enemies and allies. # #Usage: Plug and play, Customize as needed # Skill/Item Notetag: # <FIELD id> - where id is the field ID ...
# frozen_string_literal: true module ActiveModelSerializers module Adapter class IndexedByID < Base def serializable_hash(options = nil) options = serialization_options(options) serialized_hash = { root => serialized_items(options) } self.class.transform_key_casing!(serialized_hash,...
class Checkout attr_accessor :promotional_rules, :items def initialize(promotional_rules = nil) @promotional_rules = promotional_rules @items = [] end def codes_with_count @items.inject(Hash.new(0)) { |count, item| count[item.code] += 1; count } end def count_for(item) codes...
require 'dealer' require 'deck' require 'event_handler' class BlackJack attr_reader :events def initialize @dealer = Dealer.new @deck = Deck.new @events = EventHandler.new @players = [] end # Allows players to join the game. def join( player ) player.number = @players.size+1 @pla...
# Source: http://csrc.nist.gov/groups/ST/toolkit/documents/dss/NISTReCur.pdf module ECDSA class Group Nistp224 = new( name: 'nistp224', p: 26959946667150639794667015087019630673557916_260026308143510066298881, a: -3, b: 0xb4050a85_0c04b3ab_f5413256_5044b0b7_d7bfd8ba_270b3943_2355ffb4, ...
class Inquiry < ActiveRecord::Base VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, presence: true, uniqueness: true, format: { with: VALID_EMAIL_REGEX } validates :branch_info_id, :inquiry_date, presence: true validates_length_of :address_zip, minimum: 5, too_short: 'please enter at ...
class TransactionsController < ApplicationController def new @gift = Gift.find_by(id: session[:tmp_id]) session[:tmp] = nil authenticate_user authorize_user gon.client_token = generate_client_token end def create @result = Braintree::Transaction.sale( amount: session[:tmp_p...
require 'rails_helper' RSpec.describe PlayerCard, type: :model do let(:team_chemistry) do Chemistry.create(name: Team.city_and_team_name(team_city_or_team_name: :minnesota)) end let(:program) do Program.create(name: 'Core') end subject do described_class.new( first_name: 'John', last_...
class SuppressWrongcolumnsCreatestringInPhotos < ActiveRecord::Migration[6.1] def change add_column :photos, :image, :string remove_column :photos, :picture, :binary end end
require "spec_helper" describe Bundle::BrewDumper do context "when brew is not installed" do it "raises an error" do allow(Bundle).to receive(:brew_installed?).and_return(false) expect { Bundle::BrewDumper.new }.to raise_error(RuntimeError) end end context "when no formula is installed" do ...
# frozen_string_literal: true require 'spec_helper' require 'bolt_spec/files' require 'bolt_spec/pal' require 'bolt_spec/config' require 'bolt/pal' require 'bolt/inventory/inventory' require 'bolt/plugin' describe 'ResultSet DataType' do include BoltSpec::Files include BoltSpec::PAL include BoltSpec::Config ...
class RenameColumnOnEmploymentStatuses < ActiveRecord::Migration def up rename_column :employment_statuses, :is_true, :is_past end def down rename_column :employment_statuses, :is_past, :is_true end end
require 'test_helper' module Brewery class AuthCore::UsersControllerTest < ActionController::TestCase @@secret_keys = [:active, :crypted_password, :password_salt, :persistence_token, :perishable_token, :single_access_token, :login_count, :last_request_at, :last_login_at,...
BicingStats::Application.routes.draw do resources :stations do resources :samples end root :to => "frontpage#index" end
class Guardianship < ApplicationRecord has_many :parties has_many :guardianship_institutions enum gu_type: [ "Individual", "Estate", "Individual and Estate" ] enum protected_person_type: [ "Minor", "Incapacitated Adult" ] enum gu_duration: [ "Temporary", "Permanent", "Temporary and Permanent" ] validate...
FactoryGirl.define do factory :review do association :user association :site rating "4" body "If you need to find reviews go here" end end
class ContactController < ApplicationController def show puts "#" * 60 puts "Contact controller required to GET show.html.erb from contact view" puts "#" * 60 end end
# frozen_string_literal: true module ActiveAny module Associations class BelongsToAssociation < SingularAssociation end end end
require 'rails_helper' describe Spree::Calculator::BundleFlatRate, type: :model do describe '#compute' do let(:calculator) { Spree::Calculator::BundleFlatRate.new(calculable: calculable, preferences: { amount: 5 }) } let(:calculable) { create(:spree_promotion_actions_create_adjustment, promotion: promotion) ...
Then /^I should see "([^\"]*)" in the members popup$/ do |cont| popup = page.find('#members-modal') expect(popup).to have_content(cont) end Then /^I should not see "([^\"]*)" in the members popup$/ do |cont| popup = page.find('#members-modal') expect(popup).not_to have_content(cont) end
class Comic < ApplicationRecord belongs_to :user has_many :comic_topics has_many :topics, through: :comic_topics has_many :captions def total_likes likes = 0 self.captions.each do |caption| likes += caption.likes end likes end def self.top(x) Comic.all.sort_by {|comic| -com...
class CreateAppSettings < ActiveRecord::Migration def change create_table :app_settings do |t| t.decimal :daily_budget t.timestamps end end end
APP_RAKEFILE = File.expand_path("../spec/dummy/Rakefile", __FILE__) load 'rails/tasks/engine.rake' load 'rails/tasks/statistics.rake' require 'bundler/gem_tasks' require 'rspec/core/rake_task' # Get rid of rspec background noise. task(:spec).clear RSpec::Core::RakeTask.new(:spec) do |t| t.verbose = false end task d...
describe "real world edgecases", :realworld => true do if RUBY_VERSION < "1.9" # there is no rbx-relative-require gem that will install on 1.9 it "ignores extra gems with bad platforms" do install_gemfile <<-G source :rubygems gem "linecache", "0.46" G err.should eq("") e...
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{timetrap} s.version = "0.1.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Sam Goldstein"] s.date = %q{2009-04-14} s.description = %q{Command line time tracker} s.e...
require 'spec_helper' RECTANGLE_PATH ||= File.join(File.dirname(__FILE__), '..', '..', '..', 'models', 'diagroo', 'rectangle.rb') CIRCLE_PATH ||=...
FactoryBot.define do factory :streaming_position_update, class: IGMarkets::Streaming::PositionUpdate do account_id 'ACCOUNT' channel 'web' currency 'USD' deal_id 'DEAL' deal_id_origin 'DEAL2' deal_reference 'reference' deal_status 'ACCEPTED' direction 'BUY' epic 'CS.D.EURUSD.CFD.IP...
require "byebug" class PolyTreeNode attr_reader :parent, :children, :value def initialize(new_node) @parent = nil @children = [] @value = new_node end def parent=(parent_node) if @parent == nil @parent = parent_node parent_node.children << self ...
class ImportService class Base attr_reader :data, :object, :profile, :type def initialize(profile, data) @data = data @object = nil @profile = profile @type = nil end def add_authority(name_field, type, subtype, from_procedure = false) term_display_name = object....
class Event < ActiveRecord::Base geocoded_by :location after_validation :geocode end
# frozen_string_literal: true module FlagsHelper def officer_flags(rank, height = 100) content_tag(:div, class: 'officer-flags') do concat flag_image("flags/PNG/#{rank}.thumb.png", width: 150, height: height) concat tag.br concat dl_link('PNG', "flags/PNG/#{rank}.png") concat content_tag(...
#!/usr/bin/env ruby require 'rubygems' require 'sinatra' require 'base64' require 'cgi' require 'active_record' $: << File.expand_path( File.join( File.dirname(__FILE__), %w[.. lib] ) ) require 'rhouse' # Force reload !! load File.expand_path( File.join(File.dirname(__FILE__), %w[.. lib rhouse command.rb] ) ) # ---...
class AddCascadeOnDeleteToNotificationConfigs < ActiveRecord::Migration def change remove_foreign_key :notification_configs, :users add_foreign_key :notification_configs, :users, on_delete: :cascade end end
module Antlr4::Runtime class SingletonPredictionContext < PredictionContext attr_accessor :parent attr_accessor :return_state def initialize(parent, return_state) super(!parent.nil? ? PredictionContextUtils.calculate_hash_code1(parent, return_state) : PredictionContextUtils.calculate_empty_hash_co...
require 'erb' module Illuminati # # Responsible for organizing flowcell record into output used to generate a config.txt file for # CASAVA 1.8 ELANDv2e alignment. # # Uses config.txt.erb in assests directory for most of the formating of the config.txt file. # class ConfigFileView # Location of the er...
class AddApprovalsToOrders < ActiveRecord::Migration def change add_reference :orders, :student_approval, index: true add_reference :orders, :advisor_approval, index: true add_reference :orders, :final_one, index: true add_reference :orders, :final_two, index: true end end
class CreateProviders < ActiveRecord::Migration def change create_table :providers do |t| t.string :name t.string :url_main t.string :source, :default => "manual" t.string :name_for_link t.timestamps end end end
require './test/helper' class QuizTest < Test::Unit::TestCase def test_quiz_is_singleton assert_raise NoMethodError do Quiz.new end end def test_add_question text = 'question 1' question = Question.new(text) Quiz.instance << question assert_equal 1, Quiz.instance.questions.siz...
# frozen_string_literal: true require_relative 'token' require_relative 'token_type' module StringCheese class TextToken < Token def initialize(value, options = []) super(:text, value, TokenType::TEXT, options) end end end
# == Schema Information # # Table name: restaurants # # id :bigint(8) not null, primary key # name :string # description :string # created_at :datetime not null # updated_at :datetime not null # telephone :string # email :string # address :string # food_type...
class Auth::Behavior::Base::Configuration # Provides a handle back to the root configuration object. attr_reader :configuration include Auth::Configuration::Keys class << self def configuration_name(new_name = nil) if new_name @configuration_name = new_name.to_sym else # the ...
class Outpost::BlogEntriesController < Outpost::ResourceController outpost_controller define_list do |l| l.default_order = "updated_at" l.default_sort_mode = "desc" l.column :headline l.column :blog l.column :byline l.column :published_at, sortable: true, default_sort_mode: "desc" ...
namespace :scraper do task :instagram => :environment do unless ENV['CURRENT_CONCERT_ID'].to_i > 0 puts "Please specify ENV['CURRENT_CONCERT_ID']" exit end # Find the concert concert = Concert.find_by_id(ENV['CURRENT_CONCERT_ID'].to_i) # Set up Instagram Instagram.configure do |...
# frozen_string_literal: true require_relative 'aid/version' module Aid def self.load_paths @load_paths ||= [ File.expand_path(File.dirname(__FILE__) + '/aid/scripts'), '.aid', "#{Aid.project_root}/.aid", ENV['AID_PATH'] ].compact end def self.load_scripts! load_paths.each d...
FactoryGirl.define do factory :goal do name 'My Test Goal' word_count 100 end end
module BooksHelper def last_path_helper request.env['HTTP_REFERER'] || books_path end def books_count Book.all.count end end
module WiKey module Views # view object for process bar information class ProcessingView def initialize(result) @result = result end def ws_channel_id JSON.parse(@result.message)['id'] end def ws_host App.config.API_HOST end end end end
class Platodsl attr_accessor :nombre, :alimentos def initialize(nombre, &block) @nombre = nombre @alimentos = [] if block_given? if block.arity == 1 yield self else instance_eval(&block) end end end def...
# Run the Rails environment initialization in multi tenant mode so that # it creates the necessary tenant schemas on startup. We use stubs to disguise # the app as single or multi tenancy for each spec # See: `support/clockface` and `support/tenancy_helpers` ENV["RUN_AS_MULTI_TENANT"] = "1" ENV["RAILS_ENV"] ||= "test"...
class AddPhotoNumberToImage < ActiveRecord::Migration[6.0] def change add_column :refinery_images, :photo_number, :string, if_not_exists: true end end
$:.each() do |dir| puts dir if !File.exist?(dir) next end count = 1 Dir.foreach(dir) do |file| if File.directory?("#{dir}/#{file}") next end puts " #{file} " count += 1 if count > 3 break end end end
class Service < ActiveRecord::Base belongs_to :stream def after_create update_profile! end def update_profile! if identifier == 'twitter' # Fetch profile_image_url twitter = Twitter.new(profile_url.match(/twitter\.com\/([^\/]+)/)[1]) self.update_attribute(:profile_image_url, twitte...
require 'htmlentities' module ProductHelpers def parse_query(query) query = query.to_s query = query.strip().downcase query.gsub!(/\%/, "") query end def get_language_param(lang) lang = lang.to_s lang = "," if lang.empty? lang end def decode_prod_key(prod_key) pa...
class SubmissionsController < ApplicationController before_action :validate_file_presence_and_content_type, only: [:create] def new @task = API::Task.includes(:framework, :active_submission).find(params[:task_id]).first end def create task = API::Task.includes(:framework).find(params[:task_id]).first ...
require 'minitest' require 'minitest/autorun' require 'minitest/pride' require './lib/activity' require './lib/participant' class ActivityTest < Minitest::Test def test_it_exists activity = Activity.new("shopping", {person: "Amy", amount: "$25.00"}) assert_instance_of Activity, activity end def test_i...
class Membership < ActiveRecord::Base belongs_to :user belongs_to :group accepts_nested_attributes_for :group validates :group_id, :uniqueness => {:scope=>:user_id, message: " already joined."} end
require_relative "map_values_to_ruby" class CompileToRubyUnitTest attr_accessor :epsilon attr_accessor :delta def initialize @epsilon = 0.001 @delta = 0.001 end def self.rewrite(*args) self.new.rewrite(*args) end def rewrite(input, sloppy, o) mapper = MapValuesToRuby.new inpu...
class Admin::OrdersController < ApplicationController before_action :set_order, only: [:show] def index @orders = Order.where(completed: true).order('created_at DESC') end def show end private def set_order @order = Order.find(params[:id]) end def order_params params...
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # ...
require 'rails_helper' RSpec.describe 'The Doctor Show Page' do describe 'displays' do before :each do @hospital = Hospital.create(name: "Grey Sloan Memorial Hospital") @doctor = @hospital.doctors.create( name: "Miranda Bailey", specialty: "General Surgery", university: "Stanf...
module Manager class FormulasController < Manager::ManagerController def index @formulas = Formula.all end def show @formula = Formula.friendly.find(params[:id]) end end end
class Booking < ApplicationRecord has_many :flight_attendances has_many :travelers, through: :flight_attendances accepts_nested_attributes_for :travelers belongs_to :flight validates_associated :travelers end
control "M-4.11" do title "4.11 Ensure verified packages are only Installed (Not Scored)" desc " Verify authenticity of the packages before installing them in the image. Verifying authenticity of the packages is essential for building a secure container image. Tampered packages could potentially be mal...
module JsonTableSchema class Constraints module Required def check_required if required? && is_empty? raise JsonTableSchema::ConstraintError.new("The field `#{@field['name']}` requires a value") end true end private def required? required == tru...
class HomeController < ApplicationController def index @jobs = Job.filter(params[:q]).page(params[:page]).per(10).order('created_at DESC') end end
class CreateScores < ActiveRecord::Migration[5.0] def change create_table :scores do |t| t.belongs_to :heat, foreign_key: true t.integer :judge_id t.integer :athlete_id t.integer :wave t.float :score t.index [:judge_id, :heat_id, :athlete_id, :wave], unique: true t.time...
class ExampleListController < UITableViewController ExampleListControllerCellIdentifier = "ExampleListController" attr_accessor :example_controllers def init super self.title = "Examples" self.example_controllers = [ ExampleViewController.alloc.initWithTitle("Basic Example", view_class: Example...
FactoryGirl.define do factory :team do sequence(:name) { |n| "Team #{n}" } score 0 place 1 end end
=begin #### Question 5 Programmatically determine if 42 lies between 10 and 100. *hint: Use Ruby's range object in your solution.* =end puts (10..100).cover?(42)
# == Schema Information # # Table name: goals # # id :integer not null, primary key # description :string not null # owner_id :integer not null # visibility :string not null # status :string not null # created_at :datetime not null # upda...
class WalkRaport < ActiveRecord::Base belongs_to :device before_destroy :fileDestroy private def fileDestroy if File.exist?(self.path) File.delete(self.path) end end end
require_relative '../test_helper' module Domain class TodoTest < Minitest::Test def todo @todo ||= Todo.new(id:, board_id:) end def id @id ||= 2 end def board_id @board_id ||= 1 end def test_delete assert_raises(State::InvalidTransition) do todo.delete ...
require "pry" class TicTacToe def initialize @board = Array.new(9).fill(" ") end WIN_COMBINATIONS = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]] def display_board puts " #{@board[0]} | #{@board[1]} | #{@board[2]} " puts "-----------" puts " #{@board[3]} | #{@boar...
require 'rails_helper' RSpec.describe "timeline_habits/index", type: :view do before(:each) do assign(:timeline_habits, [ TimelineHabit.create!(), TimelineHabit.create!() ]) end it "renders a list of timeline_habits" do render end end
FactoryGirl.define do factory :issue do summary { Faker::Name.name } description { Faker::Lorem.sentence } estimate_time 8 reporter_id 1 status_id 1 priority_id 1 type_id 1 sprint_id 1 project_id 1 end end
class CandidatesTechnologies < ApplicationRecord belongs_to :candidate belongs_to :technology end
require 'terminal-table' require_relative 'prime_generators' class PrimeTable def initialize(n = 10) @pretty_table = get_pretty_table(n) end def print puts @pretty_table end private def get_primes(n) SkipTwoWhenCheckingPrimes.get_primes(n) end def get_table_rows(n) primes = get_prim...
class AddWebsiteToRefineryBlogComments < ActiveRecord::Migration def up add_column :refinery_blog_comments, :website, :string end def down remove_column :refinery_blog_comments, :website end end
# frozen_string_literal: true require './pdf' module FasTMassMailing class EnvelopesPDF < PDF WAVE_WIDTH = 44.mm def initialize(header_filename:) super page_size: [110.mm, 220.mm], page_layout: :landscape, margin: 15.mm @header_filename = header_filename end def add_envelope(address) ...
class HomeController < ApplicationController def index @countries = Country.all @current_date = Date.today # If today is Sunday then it's a new week. Otherwise we are still in the middle of the last week. @current_week_start = (@current_date.wday == 0 ? @current_date : @current_date - @current_date....
class StudentDeliveryReview < ActiveRecord::Base include Accessable belongs_to :student_delivery has_one :student_user, through: :student_delivery, source: :user has_one :multiplier_user, foreign_key: :multiplier_user_id, class_name: 'User' validates :student_delivery_id, uniqueness: true, presence: true ...
ActiveRecord::Schema.define(version: 2021_07_27_163919) do create_table "customers", force: :cascade do |t| t.string "Name" t.integer "Phone" t.string "Email" t.string "Address" t.string "OrderNumber" t.date "DateOfOrder" t.string "OrderStatus" t.string "BillingAddress" t.string ...
# frozen_string_literal: true module Api module V1 class SubscribersController < ApplicationController before_action :check_authorization!, only: %i[update] def index render json: Subscriber.where(subscriber_params) end def show render json: Subscriber.find(params[:id]) ...
class Page < ActiveRecord::Base before_save :generate_slug validates :title, presence: true def to_param slug end def generate_slug self.slug ||= title.parameterize end end
class FontBirthstoneBounce < Formula head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/birthstonebounce" desc "Birthstone Bounce" desc "Sibling family of birthstone that adds more luster and playfulness to it" homepage "https://fonts.google.com/spec...
class CommentSerializer < ActiveModel::Serializer attributes :id, :user_name, :body, :recipe_id end
class TasksController < ApplicationController before_action :set_task, only: [:show, :edit, :update, :destroy] load_and_authorize_resource skip_authorize_resource :only => [:index, :executors, :executor, :update] # GET /tasks # GET /tasks.json def index authorize! :read_list, Task @tasks = Task.wit...
# -*- Coding: utf-8 -*- class ReportsController < InheritedResources::Base before_filter :authenticate_user! before_filter :authenticate_owner, :only => [:show, :edit, :update, :destroy] before_filter :get_drivers_option, :except => [:index, :show] before_filter :get_cars_option, :except => [:index, :show] be...
module GistsHelper MAX_LENGTH = 25 def gist_hash(url) url.split('/').last end def question_link_name(body) truncate(body, length: MAX_LENGTH) end end
class ApplicationController < ActionController::Base before_action :basic_auth before_action :configure_permitted_parameters, if: :devise_controller? private def configure_permitted_parameters devise_parameter_sanitizer.permit( :sign_up, keys: [:zenkaku_familyname, :zenkaku_name, :katakana_family_kan...
# frozen_string_literal: true module Vmpooler VERSION = '0.14.1' end
module DailyTask class UpdateNote prepend SimpleCommand attr_reader :current_user, :task_id, :note_id, :body def initialize(current_user, task_id, note_id, body) @current_user = current_user @task_id = task_id.to_bson_id if task_id.present? @note_id = note_id.to_bson_id if note_id.pres...
require "active_record" module ConnectionHelpers module ActiveRecord extend self def build_connection_for(db_name) config = configuration_of db_name active_record_connection config end def build_anonymous_connection_for(db_name) config = anonymous_configuration_of db_name ac...
namespace :db do desc "Import companies into the database from a parsed text file" # The text file must be formatted with exactly one company per exactly ten lines with exactly one attribute per line in the order of: name, street_address, city_state_zip, phone, website, headquarters, products_services, person_in_ch...
class Xcoder < Formula desc "Manipulate your Xcode projects" homepage "https://github.com/g-Off/xcoder" url "https://github.com/g-Off/xcoder/archive/0.3.0.tar.gz" sha256 "27d65a26f23cb11a12bdc90ff4b77e473318fba4e6ee69ac482e3207ec407d2d" head "https://github.com/g-Off/xcoder.git" depends_on :xcode def in...
require 'rails_helper' describe 'login' do it 'before login, login page is presented' do visit "/" expect(page).to have_css("h1", text: "Please, log in") end it 'logins succesfully' do visit "/" fill_in 'name', with: "Alberto" click_on "login" expect(page).to have_content("Hi, Alberto."...
class RemoveNameFromOrders < ActiveRecord::Migration def change remove_column :orders, :name, :string remove_column :orders, :address, :string remove_column :orders, :city, :string remove_column :orders, :country, :string remove_column :orders, :postal_code, :string end end
module Pushr class ConfigurationApnsFeedback < Pushr::Configuration attr_accessor :id, :type, :app, :enabled, :connections, :feedback_poll validates :feedback_poll, numericality: true, presence: true def name :apns_feedback end def to_json hsh = { type: self.class.to_s, app: app, ena...
# ================================================================================ # Part: # Desc: # ================================================================================ class InvoiceItemUpgrade < InvoiceItem # Constant # ===========...
class SpyOp < ActiveRecord::Base belongs_to :nation validates_presence_of :report, :nation_name before_validation :parse_nation_name before_save :set_nation after_save :update_nation def parse_nation_name /(nation of \w+)/.match report do |m| self.nation_name = m[0].split.last end end d...