text
stringlengths
10
2.61M
class AddCatchphraseToCharacters < ActiveRecord::Migration[5.1] #define a change method in which to do the migration def change add_column :characters, :catchphrase, :string end end
class Book < Hanami::Entity attributes :title, :author end
require "rebase_attr/version" require "generate_method" module RebaseAttr READABLE_MAPPING = { '0' => 'x', '1' => 'y', 'l' => 'w', 'o' => 'z' } module Generator def rebase_attr(*attributes, to: nil, from: nil, convert: nil, deconvert: nil, readable: false) raise ArgumentError, "#rebase_attr must receive...
#!/usr/bin/env ruby # frozen_string_literal: true require 'bundler/setup' require 'vedeu' class DSLApp Vedeu.bind(:_initialize_) { Vedeu.trigger(:_refresh_) } Vedeu.configure do debug! log Dir.tmpdir + '/vedeu.log' renderers(Vedeu::Renderers::Terminal.new( filename: Dir.tmpdir + '/v...
class Client < ActiveRecord::Base has_one :address has_many :orders has_and_belongs_to_many :roles end
Rails.application.routes.draw do resources :teachers get '/index', to: 'static_pages#index' root 'static_pages#index' end
require "sinatra/activerecord" class LoginForm include ActiveModel::Validations attr_accessor :username, :password validates :username, :length => { :maximum => 2, :message => "coo"} validates_presence_of :username, :message => "Please enter an username" validates_presence_of :password, :message => "Pleas...
require 'set' describe "*_id columns" do EXCEPTIONS_LIST = Set.new( [ "cloud_networks.provider_segmentation_id", "container_volumes.common_volume_id", "miq_queue.task_id", "network_ports.binding_host_id", "scan_histories.task_id", "sessions.session_id" ] ).freeze it "s...
class SlugInput < Formtastic::Inputs::StringInput def input_html_options super.merge class: 'slug-input' end def to_html input_wrapping do label_html << builder.text_field(method, input_html_options) << template.content_tag(:span, options[:domain], class: 'slug-domain') end end en...
require_relative( '../db/sql_runner' ) class Member attr_accessor :first_name, :second_name, :age, :status attr_reader :id def initialize( options ) @first_name = options['first_name'] @second_name = options['second_name'] @age = options['age'].to_i @status = options['status'] @id = options...
class AdminController < ApplicationController before_filter :authorized? private def authorized? unless current_user.admin flash[:error] = "You are not an admin." redirect_to root_path end end end
#!/usr/bin/env ruby =begin Recupera informações de arquivos bibtex gerados pelo JabRef. Este script é quase nada robusto, e não é capaz de processar um arquivo bibtex arbitrário! Este script cria um arquivo para cada review presente no bibtex. =end Entry = Struct.new("Entry", :key, :author, :title, :year, :abst...
json.array! @actors do |actor| json.extract! actor, :id, :login, :avatar_url end
class ProjectMember < ActiveRecord::Base include Datapimp ValidRoles = %w{member owner viewer} Uploaders = %w{member owner} belongs_to :project, :counter_cache => :project_members_count belongs_to :member, :class_name => "User" validates_presence_of :project_id, :member_id, :member_role validates_uniqu...
require "minitest/autorun" require "minitest/pride" require "./lib/linked_list" require "./lib/node" require "pry" class LinkedListTest < MiniTest::Test def test_linked_list_exists assert_instance_of LinkedList, LinkedList.new end def test_linked_list_head_equal_nil linked_list = LinkedList.new assert_equ...
require_relative 'test_helper' require 'tilt/etanni' describe 'tilt/etanni' do it "registered for '.etn' files" do assert_equal Tilt::EtanniTemplate, Tilt['test.etn'] end it "registered for '.etanni' files" do assert_equal Tilt::EtanniTemplate, Tilt['test.etanni'] end it "loading and evaluating tem...
class Style < ActiveRecord::Base has_many :beers validates :style, uniqueness: {scope: :style, message: "Double?"} def to_s self.style end def self.top(n) sorted_by_rating_in_desc_order = Style.all.sort_by{ |s| -(s.average_rating||0) } sorted_by_rating_in_desc_order.first(n) end end
module PolymorphicPlugin module PolymorphicHolder def self.included(base) base.extend ClassMethods end module ClassMethods def holds_things has_many :thing_groupings, :as => :thingable has_many :things, :through => :thing_groupings include PolymorphicPlugin::Polymorph...
require "application_system_test_case" class EssaysTest < ApplicationSystemTestCase setup do @essay = essays(:one) end test "visiting the index" do visit essays_url assert_selector "h1", text: "Essays" end test "creating a Essay" do visit essays_url click_on "New Essay" fill_in "Co...
require 'test_helper' class BedTest < ActiveSupport::TestCase test "it exists" do assert Bed.new end test "it validates the presence of garden id" do bed = FactoryGirl.build(:bed, garden_id: nil) assert bed.invalid? bed.update_attributes(garden_id: 1) assert bed.valid? end test "it va...
Trestle.resource(:rooms) do menu do item :chambres, icon: "fa fa-bed", group: :accomodations end scope :all, default: true scope :disponible, -> { Room.available } scope :indisponible, -> { Room.unavailable } # Customize the table columns shown on the index view. table do column :name column...
class PersonRelationship < ActiveRecord::Base self.table_name = :person_relationship self.primary_key = :person_relationship_id include EbrsAttribute belongs_to :core_person, foreign_key: "person_id" end
module Duss class Client URL = Duss::HOST def connection_options @connection_options = lambda do |connection| connection.request :url_encoded connection.adapter Faraday.default_adapter end end def initialize(client_id, api_token) @client_id = client_id @api_to...
require "thread" class DebugSession attr_reader :process, :trace, :output_queue def initialize(name, command) @name = name @command = command @process = nil @quiet = false @ready_queue = Queue.new @output_queue = Queue.new @trace = nil init end def start(file) @pr...
# hashes_ex_5.rb # given person = {name: 'Bob', occupation: 'web developer', hobbies: 'painting'} # see if 'web developer' value exists in the hash if person.value?('web developer') puts "yes!" else puts "Not in this hash!" end
module ArbitraryMock class Base def initialize(property_hash={}) @property_hash = property_hash end def method_missing(*args) method_name = args.first arg_position = 1 if method_name == :try method_name = args[1] arg_position += 1 end setter_method_m...
class Renamemobilenameinmobiles < ActiveRecord::Migration[5.0] def change rename_column :mobiles, :mobile_name, :name end end
package 'samba' service 'nmbd' do provider Chef::Provider::Service::Upstart end service 'smbd' do provider Chef::Provider::Service::Upstart end directory "/opt/shared" do action :create mode 0755 user 'nobody' end directory "/opt/dropbox" do action :create mode 0755 user 'nobody' end file "/opt/sh...
class Employee < ActiveRecord::Base before_create :default_number belongs_to :department has_many :proposals has_many :work_orders has_many :assignments has_many :labor_assignments # self-referencing relationships belongs_to :supervisor, :foreign_key => "supervisor_id", :class_name => "Employee" ha...
class Balance < ActiveRecord::Base belongs_to :account validates_presence_of :account, :evaluated_at, :balance def balance super or self.balance = calculate_balance end def readonly? !new_record? end private def calculate_balance entries.inject(previous_balance) {|balance, entry| balance ...
class Dve < ApplicationRecord before_save :day_kind_values belongs_to :user validates :event_name, :event_date, :day_kind, presence: true enum day_kind: %i[Final_de_semana Dia_de_semana Feriado] def day_kind_values self.total = 0 self.total += 20.00 if overnight == true self.total += if day_ki...
class Rack::CopyMachine autoload :AssetServer, 'rack/copy_machine/asset_server' def initialize(app, options = {}) @app = asset_server(app) end def call(env); dup._call(env); end def _call(env) @request = Rack::Request.new(env) status, headers, body = @app.call(env) @response = Rack::Respon...
class AddMatriculaToAluno < ActiveRecord::Migration def self.up add_column :alunos, :matricula, :string end def self.down remove_column :alunos, :matricula end end
module Sumac # Manages graceful (application initiated) closing of a {Connection}. # Also observes ungraceful closing. # @api private class Closer # Build a new {Closer} manager. # @param connection [Connection] being managed # @return [Closer] def initialize(connection) @connection = co...
class Proposal < ActiveRecord::Base include WorkflowModel include ProposalSteps include ProposalConfig include ValueHelper include StepManager include Searchable include FiscalYearMixin has_paper_trail class_name: "C2Version" CLIENT_MODELS = [] # this gets populated later workflow do state :...
class CoursesController < ApplicationController before_action :authenticate_user! def new unless current_user.admin? flash[:error] = "You tried accessing a restricted area. You have been redirected." redirect_to root_path end @course = Course.new end def edit course end def...
class Review < ActiveRecord::Base belongs_to :playground validates_associated :playground end
class Question < ApplicationRecord has_many :answers has_many :votes, as: :votable belongs_to :question_author, class_name: "User" has_many :comments, as: :commentable def total_votes self.votes.map { |vote| vote.value } end def vote_count total_votes.reduce(0, :+) end validates :question...
FactoryGirl.define do factory :law_firm do |lawyer| lawyer.name "Marshall's law firm" initialize_with { new(name) } end end
module TransportFeeHelper # include ActionView # include Helpers # include TagHelper def transport_fee_discount_has_active_transaction? discount transaction_discount = discount.try(:transport_transaction_discount) return transaction_discount.try(:is_active) if transaction_discount.present? false ...
class Office::CategoriesController < OfficeController before_action :category, only: %i[edit update destroy] def index @categories = Category.all end def new @category = Category.new @sub_themes = @category.sub_themes.build end def create @category = Category.new(category_params) if @...
# encoding: utf-8 require File.expand_path("../spec_helper", __FILE__) describe "Browser" do describe "#exists?" do it "returns true if we are at a page" do browser.goto(WatirSpec.files + "/non_control_elements.html") browser.should exist end it "returns false after IE#close" do b = W...
class AddAddressToPosts < ActiveRecord::Migration def change add_column("posts", "address", :string) end end
class CreateAddProperties < ActiveRecord::Migration def change create_table :add_properties do |t| t.string :area t.string :property_type t.string :house_number t.text :street_address t.string :city t.integer :pincode t.string :state t.string :country t.boolea...
require "spec_helper" RSpec.describe "Day 24: Blizzard Basin" do let(:runner) { Runner.new("2022/24") } let(:input) do <<~TXT #.###### #>>.<^<# #.<..<<# #>v.><># #<^v^^># ######.# TXT end describe "Part One" do let(:solution) { runner.execute!(input, part: 1) } ...
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_action :set_locale use_growlyflash def authorize_user unless user_signed_in? gflash error: t('n...
require("minitest/autorun") require_relative("../merchant.rb") class TestMerchant < MiniTest::Test def setup options = {"id" => 1, "name" => "CDW", "logo" => "/images/1.png", "active" => true} @merchant = Merchant.new(options) end def test_id() result = @merchant.id() assert_equal(1, result...
class CreateTableDeployments < ActiveRecord::Migration def self.up create_table :deployments do |t| t.datetime :created_at t.datetime :updated_at t.integer :company_id t.integer :product_id t.references :companies t.references :products t.timestamps end end def self.down ...
# frozen_string_literal: true module Vedeu # A module for common methods used throughout Vedeu. # # @api private # module Common # Returns a boolean indicating whether a variable is nil, false or # empty. # # @param variable [String|Symbol|Array|Fixnum] The variable to # check. # ...
class AddRetailerIdToProfit < ActiveRecord::Migration[5.2] def change add_column :profits, :retailer_id, :bigint end end
module ControllersHelper def render_failed_modification(format, action, errors) format.html { render layout: 'aquila', action: action } format.json { render json: errors, status: :unprocessable_entity } end def render_successful_modification(format, resp, obj_name, created_or_updated) html_verb = cre...
class User < ApplicationRecord has_many :reviews # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable validates_presence_of :email # optional vali...
require_relative 'src/action' require_relative 'src/wub' class Main < Wub def call(env) header = {'Content-Type' => 'text/html'} case env['REQUEST_PATH'] when '/' response(200, header) { render('index') } when '/env' response(200, header) { render('env', to_context(env)) } when '/act...
require "models/rental" RSpec.describe Rental do describe "#driver_amount" do subject(:driver_amount) { rental.driver_amount } let(:deductible) { false } context "when the duration is one day" do let(:end_date) { start_date } it { is_expected.to eq(-1050) } end context "when the dur...
# frozen_string_literal: true require_relative('./document') require 'nokogiri' module Mato class Config # https://github.com/gjtorikian/commonmarker#parse-options DEFAULT_MARKDOWN_PARSE_OPTIONS = %i[ DEFAULT VALIDATE_UTF8 ].freeze # https://github.com/gjtorikian/commonmarker#render-op...
class Api::V1::StatesController < ApplicationController def index states = State.all render json: StatesSerializer.new(states) end def show state = State.find_by(id: params[:id]) render json: StatesSerializer.new(state) end def update state = State.find_by(id: params[:id]) if state...
require 'xsd/qname' # {http://schemas.verisign.com/pkiservices/2011/08/usermanagement}GetUserInformationRequestMessageType # clientTransactionID - SOAP::SOAPString # seatId - SOAP::SOAPString # getUserCertificate - SOAP::SOAPBoolean # version - SOAP::SOAPString class GetUserInformationRequestMessageType att...
Rails.application.routes.draw do root to: 'static_pages#home' get 'signup', to: 'users#new' resources :users end
# Double Char (Part 2) # 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. def double_consonants(str) arr = str.split('') new_arr = [] arr.each do |x| if x =~ /[bcdfghjk...
class CreateCollections < ActiveRecord::Migration[5.2] def change create_table :collections do |t| t.string :repository_id, null: false t.string :title, null: false t.text :description t.text :description_html t.string :access_url t.string :external_id t.boolean :publishe...
class CreateShipnotices < ActiveRecord::Migration[5.0] def change create_table :shipnotices do |t| t.references :order t.string :purchase_order_line t.text :barnhardt_tracking t.timestamps end end end
class RefMod < ActiveRecord::Migration[6.0] def change #Ajout d'une colonne pour vérifier si la référence a été validée par un administrateur (donc est visible aux yeux des utilisateurs) add_column(:references, :isValidated, :boolean, null: false, default: false) end end
class Phrase def initialize(sentence) @sentence = sentence @word_count = Hash.new(0) check_word_count end def word_count @word_count end private def check_word_count @sentence.downcase.scan(/\b[\w']+\b/) do |word| @word_count[word] += 1 end end end module BookKeeping V...
Rails.application.routes.draw do # Static Pages get 'home', to: 'static#home' get 'about', to: 'static#about' get 'team', to: 'static#team' get 'insurer', to: 'static#insurer' get 'faq', to: 'static#faq' # Contact us form get 'contact', to: 'contact#contact' post 'send_email', to: 'contact#send_email...
# This file contains the fastlane.tools configuration # You can find the documentation at https://docs.fastlane.tools # # For a list of all available actions, check out # # https://docs.fastlane.tools/actions # # For a list of all available plugins, check out # # https://docs.fastlane.tools/plugins/available-pl...
class DropFkCampaignsUserId < ActiveRecord::Migration def up execute <<-SQL ALTER TABLE campaigns DROP CONSTRAINT IF EXISTS fk_campaigns_user_id; SQL end def down end end
class AddProofredToIngredient < ActiveRecord::Migration def change add_column :ingredients, :proofed, :boolean, :default => false end end
# # Model użytkowników # # Korzysta z gem'u devise # # Każdy użytkownika może mieć wiele zdjęć: # => User.first # => user.photos # class User < ActiveRecord::Base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable attr_accessible :email, :password, :pas...
class CreateCourseAttributesJoin < ActiveRecord::Migration def change create_table :course_attributes_sections, :id => false do |t| t.integer :course_attribute_id t.integer :section_id end end end
class Trail < ActiveRecord::Base attr_accessible :category, :description, :title, :twitter, :user_id, :status, :cover, :startDate, :startTime, :endDate, :endTime, :recurring, :active_id #recuring=true means live=true validates :title, :presence => true, :length => { :maximum => 140 } validates :description, :p...
module Lugg # Apply a list of filters to an Enumerable object or an enumerator. # # This class is used to combine all the search queries into a single filter # to process a collection with. Its input is expected to be a # `Lugg::Streamer` enumerator, but it could be anything. # # By default, the collectio...
def visit_homepage visit('/') end When(/^I visit the homepage$/) do visit_homepage end Then(/^I should be on the homepage$/) do current_path.should == '/' end Given(/^I am on the homepage$/) do visit_homepage end When(/^I click history$/) do click_on('History') end Then(/^I should be on the history page$...
class AttachmentsController < ApplicationController before_filter :authenticate_user! def index @attachments = Attachment.all respond_to do |format| format.json { render json: @attachments } end end def show @attachment = Attachment.find(params[:id]) respond_to do |format| ...
class AddFailcountToAuthProfiles < ActiveRecord::Migration def change add_column :auth_profiles, :fail_count, :integer, :default => 0 end end
require 'test_helper' class ColumnsHelperTest < ActionView::TestCase setup do @column = columns :sample_column end test 'should calculate the heuristic value of a column' do assert_includes 230..231, heuristic_column_value(@column) end test 'should return an empty relation if there are no recent co...
################################################################################ require('minitest/autorun') require('yaml') ################################################################################ module Callbacks; end ################################################################################ class Cal...
class YwtItemsController < ApplicationController before_action :set_page, only: [:create, :destroy] def create @ywt_item = @page.ywts.build ywt_item_params @ywt_item.save redirect_to page_path(@page.token) end def destroy @ywt_item = YwtItem.find params[:id] @ywt_item.destroy redirec...
module VotesHelper # Pass true for upvote, false for downvote # Pass the evidence in question # Returns the appropriate button for the given situation def vote_button(button_type, evidence) # Text to display for link vote_text = button_type ? 'upvote' : 'downvote' arrow_direction = button_type ? '...
require 'class_file_items' require 'base_classes' class StackFrame attr_accessor :pc, :code, :stack def initialize(vm, code, constant_pool, prev_stack_frame = nil, vals_to_push = []) @vm = vm @code = code @prev_stack_frame = prev_stack_frame @constant_pool = constant_pool @pc = 0 @stack = [] vals_to_p...
### ARRAY ORGANIZER SPEC require "./array_organizer_refactor.rb" # RSpec.configure do |config| # # Use color in STDOUT # config.color_enabled = true # # Use color not only in STDOUT but also in pagers and files # config.tty = true # # Use the specified formatter # config.formatter = :documentation # :pr...
# frozen_string_literal: true class ParamsSanitizer def self.call(params) { name: sanitize(params[:name]), surname: sanitize(params[:surname]), domain: sanitize(params[:domain]) } end private def self.sanitize(value) value&.strip&.downcase end end
# #= ユーザ管理・認証用コントローラのアクションを定義するモジュール # module Concerns::Susanoo::UsersController extend ActiveSupport::Concern included do skip_before_action :feature_check, only: %i(login authenticate logout) before_action :page_header_not_required, only: %i(login authenticate) before_action :login_not_required, only...
module LazyConst CACHE = {} def meta_class @meta_class ||= class << self; self end end def lazy_const(name, &block) raise Error("lazy_const requires a block") unless block_given? LazyConst::CACHE["#{self.name}.#{name}"] = nil meta_class.send(:define_method, name) do LazyConst::CACHE["#{...
#! ruby -Ku -Ilib # 多層パーセプトロンネットワークによる学習を行う require "yaml" require "rubygems" require "ironnews_utility" require "mlp_categorizer" DB_FILENAME = "db.out" COUNT = 5 STDERR.puts("initialize...") tokenizer = BigramTokenizer.new categorizer = MlpCategorizer.new(tokenizer) STDERR.puts("shuffling...") training_d...
class Acta < ActiveRecord::Base attr_accessible :ciudad, :conclusiones, :desarrollo_reunion, :fecha, :firmas, :hora_inicio, :hora_terminacion, :lugar, :objetivo_de_la_reunion, :tema def self.search(search) where('ciudad like ?', "%#{search}%",) end end
# frozen_string_literal: true module JSONHelpers def parse_json(data) JSON.parse(data, symbolize_names: true) end end
class Transaction < ActiveRecord::Base belongs_to :user, inverse_of: :Transactions has_one :ad accepts_nested_attributes_for :ad end
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "metrical" require "metrical/version" Gem::Specification.new do |s| s.name = "metric_fu-metrical" s.platform = Gem::Platform::RUBY s.version = Metrical::VERSION s.authors = ["iai...
require 'spec_helper' RSpec.describe Liquidize::Helper do describe '.recursive_stringify_keys' do let(:original) { { first: { a: 'a', b: 'b', c: 3 }, second: :qwerty, third: [{ x: 1, y: 2 }] } } let(:result) { { 'first' => { 'a' => 'a', 'b' => 'b', 'c' => 3 }, 'second' => :qwerty, 'third' => ['x' => 1, 'y' =...
class Question < ActiveRecord::Base belongs_to :person belongs_to :owner, class_name: 'Person' belongs_to :field belongs_to :detail has_many :clarifications has_many :issues, -> { uniq }, through: :clarifications, dependent: :restrict_with_error accepts_nested_attributes_for :issues, reject...
module WC_METADATA_API class Helper attr_accessor :debug_string attr_accessor :wskey, :secret, :principalID, :principalDNS def initialize(options={}) @wskey = options[:wskey] @secret = options[:secret] @principalID = options[:principalID] @principalDNS = options[:princ...
require "family/parent" require "family/child" class Family def initialize last_name @last_name = last_name @children = [] end def add_father name @father ||= Parent.new name, "M" end def add_mother name @mother ||= Parent.new name, "F" end def add_child name, gender @children << C...
#!/usr/bin/ruby # A class to generate Fibonacci numbers. # class FibGen # Start with the first two known Fibonacci numbers. # def initialize() @fibs = [1,1] end # Compute and yield the next number to the caller. def next_fib() while true @fibs << @fibs[-1] + @fibs[-2] # Operator << is sa...
module TinyCI module OutputParser class CapistranoParser < Base def parse! @result = TinyCI::Report::DeployReport.new @result.deploy_tool = 'cap' while !empty? line = consume!.line if line =~ /^\s*\* executing `(.*?)'$/ task = Capis...
require "helper" module Neovim RSpec.describe Connection do let(:nil_io) { StringIO.new } describe "#write" do it "writes msgpack to the underlying file descriptor" do rd, wr = IO.pipe Connection.new(nil_io, wr).write("some data").flush data = rd.readpartial(1024) expe...
module Printtables module PrintSalaryIndex # HACK the helper is included in order to allow the formatting of data for processing by prawn include ActionView::Helpers::NumberHelper def salary_column_widths [227.mm, 25.mm, 25.mm] end def salary_headers ["Employee", "Amount Paid...
class AddActivationTokenToUsers < ActiveRecord::Migration def change add_column :users, :activation_token, :string add_index :users, :activation_token end end
class UserSerializer < ActiveModel::Serializer attributes :id, :username, :password_digest, :fullname, :email, :status has_one :area has_one :role end
#!/usr/bin/env ruby # gitlogviz # by Benjamin Ragheb <ben@benzado.com> # <http://github.com/benzado/gitlogviz> # Run this script in the top level of your git working copy. The output is meant # to be sent to GraphViz. You can either save it to a .dot file and open it with # a GraphViz viewer app, or create a PDF by p...
# -*- encoding: utf-8 -*- require "src_lexer/version" module SrcLexer class Token attr_reader :str, :line_no, :char_no def initialize(str, line_no, char_no) @str = str @line_no = line_no @char_no = char_no end def ==(other_object) @str == other_object.str && @line_no == othe...