text
stringlengths
10
2.61M
class User < ActiveRecord::Base store_accessor :meta, :sync_with_github, :sync_with_bitbucket, :has_github_account, :has_bitbucket_account, :sync_with_gitlab, :has_gitlab_account devise :database_authenticatable, :registerable, :confirmable, :async, :recoverable, :rememberable, :trackable, :validatable, :o...
# require 'pry' class Player # attributs et initialize attr_accessor :name, :life_points def initialize(name) @name = name @life_points = 10 end # afficher l'état d'un joueur avec show_state def show_state return "#{name} a #{life_points} points de vie" end # fait subir une attaque à l'un ...
module BuildingDefence module Shared def init_window_for_drawing Curses.init_screen Curses.start_color Curses.noecho Curses.use_default_colors Curses.init_pair(COLORS[:letter_typed], Curses::COLOR_BLUE, -1) Curses.init_pair(COLORS[:error], Curses::COLOR_RED, -1) Curses.i...
require 'byebug' def sluggish_octopus(arr) longest = "" (0...arr.length - 1).each do |i| (i + 1...arr.length).each do |j| arr[i] < arr[j] ? longest = arr[i] : longest = arr[j] end end longest end def dominant(arr, &prc) prc ||= Proc.new { |a, b| a <=> b } return arr if arr.length <= 1 ...
require 'test_helper' class ArticleCommentsControllerTest < ActionDispatch::IntegrationTest setup do @article_comment = article_comments(:one) end test "should get index" do get article_comments_url assert_response :success end test "should get new" do get new_article_comment_url assert...
require 'test_helper' class PublishingApiPresentersTest < ActiveSupport::TestCase test ".presenter_for returns a presenter for a case study" do case_study = CaseStudy.new presenter = PublishingApiPresenters.presenter_for(case_study) assert_equal PublishingApiPresenters::CaseStudy, presenter.class a...
module Tandaco class GetAllUsersRequest < BaseRequest private def path '/api/v2/users' end end end
# == Schema Information # # Table name: assuntos # # id :integer not null, primary key # nome :string not null # created_at :datetime not null # updated_at :datetime not null # FactoryGirl.define do factory :assunto, class: Assunto do nome { Faker::Lorem.word ...
class ChangeUserEmails < ActiveRecord::Migration def change create_table :user_email_addresses do |t| t.belongs_to :user, null: false t.string :value, null: false t.boolean :verified, default: false t.boolean :primary, default: false t.timestamps end add_index :user_email_add...
module NationGroup ### Arbitrary Grouping Methods # Get aggregate data for any arbitrary group of nations # Mostly used for alliance data, could also be used for battalions, tech circles, trade circles, etc def war_slots # Return hash describing war slots total = count * 6 war_mode = in_war_mode.cou...
# Print out the author's age # Remember, dividing integers by integers will round down in Ruby. # Use 365.25 days/year to both take leap years into account and get a more accurate decimal ### Your Code Here ### puts "The author is " + (((1160000000.0/3600.0)/24.0)/365.25).to_s + " years old."
class Api::V1::CommunityApplicationsController < Api::V1::ApplicationController before_action :set_application, only: %i[audit] def index @community_applications = @current_user.community_applications end def create @community_application = CommunityApplication.create(application_params.merge({ ...
class EventPayment < ApplicationRecord enum payment_type: [:credit_card, :chash, :paypal] belongs_to :meal_event_command end
require 'rails_helper' RSpec.describe ParticipationResult, type: :model do it 'has a valid factory' do expect(create :participation_result).to be_valid end end
require_relative("bishop.rb") require_relative("rook.rb") class Board def initialize @board = [ [], [], [], [], [], [], [], [] ] @board[0][0] = Rook.new(0, 0) @board[7][0] = Rook.new(7, 0) @board[0][7] = Rook.new(0, 7) @board[7][7] = Rook.new(7, 7) @board[2][0] = Bishop.new(...
# frozen_string_literal: true module Authegy #= Authegy::Authorizable # # Methods applied to the "authorizable" model - The Person model. module Authorizable extend ActiveSupport::Concern included do has_many :role_assignments, class_name: '::RoleAssignment', invers...
class Tag < ActiveRecord::Base has_many :post_tagships has_many :posts, :through => :post_tagships end
Vagrant.configure("2") do |config| # tunables env_prefix = ENV['DRUPAL_VAGRANT_ENV_PREFIX'] || 'DRUPAL_VAGRANT' ip = ENV["#{env_prefix}_IP"] || '10.33.36.11' project = ENV["#{env_prefix}_PROJECT"] || 'drupalproject' # end tunables config.vm.box = "promet/wheezy" config.vm.provider :vir...
require 'ostruct' module Joseph def self.included(base) if base.class == Module base.extend self else super end end def config @config ||= OpenStruct.new end def configure yield config end def [](key) config.send key end # Lifted from http://github.com/stephenc...
# frozen_string_literal: true require 'arch_update/execute' require 'arch_update/option_parseable' module ArchUpdate # Pacman Updater class Pacman include ArchUpdate::OptionParseable SHORT = '-p' LONG = '--pacman' DESC = 'Update pacman.' def self.addon(option_parser) option_parser.on(S...
class AddPriceInfo < ActiveRecord::Migration def change add_column :prices, :price_info, :text end end
class ChangeCcType < ActiveRecord::Migration def change change_column :credit_cards, :cc_number, :string end end
class ConventionRequestsController < ApplicationController before_action :require_user before_action :check_user before_action :find_convention_request, only: [:edit, :update, :create_payment_sj, :create_payment_ot] #before_filter :request_check def new @convention_request = current_user.build_convention_requ...
class Share < ApplicationRecord validates :nickname, presence: true validates :content, presence:true validates :location, presence:true validates :image_content_type, presence:true end
class FixLiftType < ActiveRecord::Migration def self.up rename_column :lifts, :type, :lift_type end def self.down rename_column :lifts, :lift_type, :type end end
# frozen_string_literal: true class Invite < ApplicationRecord acts_as_paranoid has_many :messages, dependent: :destroy belongs_to :to_user, foreign_key: :to_user_id, class_name: 'User', validate: true belongs_to :from_user, foreign_key: :from_user_id, class_name: 'User', validate: true validates :to_user...
require 'rails_helper' describe 'Clients sorting order', type: :request do context 'GET#index' do it 'sorts clients with no unread messages by last_contacted_at' do user = create :user sign_in user clientthree = create :client ReportingRelationship.create( user: user, clie...
class CreatePosts < ActiveRecord::Migration def change create_table :posts do |t| t.references :box, null: false t.references :user t.references :post t.text :body t.text :link t.string :signature, null: false t.string :align, null: false t.timestamps end a...
# # Cookbook Name:: postgresql # Recipe:: postgis # # Copyright 2011, Estately, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unl...
require 'planet/formatter' require 'planet/harvest' require 'planet/config' class HamlFormatter < PlanetFormatter begin # http://haml.hamptoncatlin.com/ require 'haml' rescue LoadError puts "Haml_interp: haml library not found. Try gem install haml" end def map_feed(f) # map a har...
require 'rails_helper' RSpec.describe Director, type: :model do it 'is valid with valid attributes' do expect(build(:director)).to be_valid end subject { build(:director) } context 'Database table' do it { expect(subject).to have_db_column(:name).of_type(:string) } it { expect(subject).to have_db...
class CreateProductionPlans < ActiveRecord::Migration[5.0] def change create_table :production_plans do |t| t.date :dt_scheduled t.references :product, references: :item, foreign_key: true t.references :sales_order, foreign_key: true t.references :sales_order_item, foreign_key: true ...
require "./builder.rb" class TextBuilder include Builder def initialize @buffer = "" end def make_titile(titile:) buffer << "『#{titile}』\n" end def make_string(str:) buffer << "■#{str}\n" end def make_items(items:) items.each do |item| buffer << "・#{item}\n" end buffer...
require 'rails_helper' RSpec.describe User, type: :model do context 'validation tests' do it 'ensures name presence' do user = User.new(name: '', email: 'temple@yahoo.com', password: 'precious5', password_confirmation: 'precious5').save expect(user).to eql(false) end it 'ensures password mus...
module JavaClass module ClassFile module Attributes # General container of the attributes. # Author:: Peter Kofler class Attributes # Size of the whole attributes structure in bytes. attr_reader :size # Parse the attributes structure from the bytes _data_ ...
# frozen_string_literal: true # == Schema Information # # Table name: users # # created_at :datetime not null # email :string # id :bigint not null, primary key # password_digest :string # updated_at :datetime not null # # Indexes # # index_users_on_emai...
# encoding: UTF-8 # # Cookbook Name:: openstack-image # Recipe:: identity_registration # # Copyright 2013, AT&T Services, Inc. # Copyright 2013, Craig Tracey <craigtracey@gmail.com> # Copyright 2013, Opscode, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in ...
# encoding: UTF-8 module Linguistics module Latin module Verb ## # == NAME # # Validation # # == DESCRIPTION # # This module contains the validity testing methods, when mixed into a # LatinVerb, will provide it the ability to ensure its own sanity. # ...
# Movie Class # Create a class called Movie which has three attributes: # title # duration (in minutes) # rating (This can just be any string ex. G, PG, PG-13, R, etc) # Then, add a to_s method to the movie which return the string # "[title], [duration]mins, rated [rating]" class Movie attr_reader :title, :durati...
class CategoryEntry < ActiveRecord::Base has_many :notes, dependent: :destroy validates :name, :color, presence: true validates :name, :color, uniqueness: true validates :color, :css_hex_color => true def self.category_entries all.collect {|category_entry| [category_entry.name, category_entry.id] } e...
# las propidades se identifican por vairables de instancia #se inicia su nombre con un arroba @ #son identificadores que le pertenecen a los objetos y no a las Clases #objetos instancias de una class #las variables de instancia no pueden ser modificadas u observadas desde fuera del objeto #se pueden acceder a ella...
module Sub module Type class UploaderType < ActiveRecord::Type::Value def cast(value) args = Array(value) return nil unless args.any? begin @results = [] args.each do |arg| raise TypeError unless arg.instance_of?(ActionDispatch::Http::UploadedFile) ...
require 'aws-sdk-v1' require "awesome_print" # constants that control the restore process BUCKET_NAME = 'sf-databackup' FOLDER = 'mongolab/' FILE_PREFIX = "#{FOLDER}rs-ds033190" FILE_POSTFIX = '.tgz' # globals that keep track of the download candidate $download_available = false $download_name = '' $download_date = '...
class CreateOrders < ActiveRecord::Migration def change create_table :orders do |t| t.references :exchange, index: true t.references :user, index: true t.string :email t.datetime :expiry t.integer :status, default: 0 t.integer :pay_cents t.string :pay_currency t.int...
# frozen_string_literal: true Gem::Specification.new do |spec| spec.name = 'styled_yaml' spec.platform = Gem::Platform::RUBY spec.required_ruby_version = '>= 2.4.0' spec.summary = 'A Psych extension to enable choosing output styles for specific objects.' spec.versi...
require 'javaclass/java_language' require 'javaclass/java_name' module JavaClass module Dsl # Module to mixin to recognize full qualified Java classnames in Ruby code. # Packages have to be suffixed with ".*" to be recognized. # This is a bit dangerous, as wrong method or variable names with ar...
# System libraries require "highline/import" # Local libraries require "fact/clearcase" require "fact/files_cli" module Fact class Cli # Browse all the undelivered activities in the current stream. # def Cli.browse_actifities cc = ClearCase.new activity = Cli.choose_undelivered_activity unless...
class LearningLogsController < ApplicationController before_action :set_learning_log, only: [:show, :edit, :update, :destroy] # GET /learning_logs # GET /learning_logs.json def index @learning_logs = LearningLog.all @word_learning_logs = current_user.learning_logs.all @groups_for_chart =...
class Event < ActiveRecord::Base belongs_to :location has_many :rsvps has_many :volunteers, through: :rsvps, source: :user has_many :event_organizers has_many :organizers, through: :event_organizers, source: :user has_many :event_sessions accepts_nested_attributes_for :event_sessions, allow_destroy:...
module ZanoxPublisher # General category class # # Legacy name category is for program and admedium # # NOTE: Later create enumerable class Categories to allow .include? on result from API # # @param [Integer] id The identifer of the category # @param [String] name The name of the category clas...
class SurveyTakers < ActiveRecord::Migration def change create_table(:survey_takers) do |st| st.column(:name, :string) end end end
#!/usr/bin/env ruby # Stitch transcriptions. # Clip: "http://www.ifp.illinois.edu/~pjyothi/mfiles/ws15/arabic/part-3/arabic_141120_374643-2.mp3" # Transcription: "een oboo faaj". # For each wavfile i.e. clip, hash to an array of transcriptions. transcriptions = Hash.new {|k,v| k[v] = []} # /r/lorelei/sbs-audio/dutch...
class UsersController < ApplicationController in_place_edit_for :user, 'friendly_name' in_place_edit_for :user, 'email' layout 'doctor' # render show.rhtml def show restrict('allow only doctor users') or begin @user = get_user respond_to do |format| format.html # show.rhtml fo...
require 'rails_helper' RSpec.describe Frame, :type => :model do let(:f) {f = Frame.new} it('can roll pins down') do f.roll pins end end
module GameOfLife class Board include Enumerable attr_reader :size # @matrix is array of arrays. # members of arrays are booleans - initialy 'false' def initialize(size) @size = size @matrix = Array.new(size) { Array.new(size) { false } } end def each matrix.each { |row...
RSpec.describe Question, type: :model do it 'creates question' do expect(Question.new(description: 'some description')).to be_valid end context 'when description is empty' do it 'is not valid' do expect(Question.new(description: '')).to_not be_valid end end end
class Neightborhood < ApplicationRecord validates_presence_of :name, on: %i[create update] belongs_to :city has_many :properties end
# encoding: utf-8 class PosterUploader < CarrierWave::Uploader::Base include CarrierWave::MiniMagick # Choose what kind of storage to use for this uploader: storage :file # storage :fog # Override the directory where uploaded files will be stored. # This is a sensible default for uploaders that are meant...
include_recipe 'pip' include_recipe 'users' execute 'pip install awscli' do command <<-EOS pip install awscli EOS not_if { File.exists?("/usr/bin/aws") } end directory '/root/.aws' do owner 'root' group 'root' mode 0755 action :create end awscli_credentials = Chef::EncryptedDataBagItem.load('credenti...
module Puppler class Command # puppler command: convert existing Shallowfile to puppetfile class Convert < Command include Puppler::Utils attr_reader :options def run(shallowfile) if File.exist?(options[:puppetfile]) log_fatal("The specified Puppetfile `#{options[:puppetfi...
module JavaClass module ClassFile class JavaClassHeader # Is this class an interface (and not an annotation)? def interface? access_flags.interface_class? end # Is this class an abstract class (and not an interface)? def abstract_class? access_flags.abs...
# frozen_string_literal: true require 'test_helper' module Vedeu module EscapeSequences describe Borders do let(:described) { Vedeu::EscapeSequences::Borders } describe '.border_off' do it { described.border_off.must_equal("\e(B") } end describe '.border_on' do it { ...
module PrintInvoice extend ActiveSupport::Concern include PrintHeader include PrintCustomerDetail include PrintFooter include PrintTable include PrintFooter include PrintPageNumbers include PrintInvoiceHeader include PrintInvoiceDetail include PrintInvoice...
class BalanceChecker def initialize(accounts) @accounts = accounts end def check_balance_in_range(start_date, end_date) balance = 0 transactions_in_range(start_date, end_date).each do |t| balance += t.planned end Money.new(balance) end # def check_balance_at_date(start_date, b...
class User < ApplicationRecord has_secure_password has_many :projects, dependent: :destroy has_many :bids, dependent: :destroy has_attached_file :avatar, styles: { thumb: "150x150#" } validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/ validates :password, length: {minimum: 6, maximu...
class AddFungiAvDiameterInUm < ActiveRecord::Migration[5.0] def change add_column :samples, :fungi_average_diameter_in_um, :float end end
module Virtuoso # Any exceptions which are thrown by Virtuoso (not lower-level libraries) # exist in this module. module Error class VirtuosoError < StandardError; end class NewVMError < VirtuosoError; end class UnsupportedHypervisorError < StandardError; end class UnsupportedNetworkError < Standa...
class ListsController < ApplicationController def new @list = List.new @category = Category.new @user = User.find(params[:user_id]) end def create if params[:list][:category_id].blank? @list = List.create(list_params_new_category) else @category = Category.find(params[:list][:c...
class AddUsernameLowerToUsers < ActiveRecord::Migration def change add_column :users, :username_lower, :string add_index :users, :username_lower, unique: true end end
# deal_card.rb def deal_card(deck) remaining_cards = deck.select { |_, value| !value.empty? } card = remaining_cards.keys.sample if card.nil? puts "Deck is empty." else value = deck[card].pop if !deck[card].nil? [card, value] end end
class WordSerializer < ActiveModel::Serializer attributes :id, :symbol, :romaji, :meaning end
# Create a 8x8 playing grid(double array) # Print out the playing board # Print out the players menu to choose a token. # Once the menu is printed user picks what column it goes into 1 - 8 # The token slides to the bottom of the playing grid.(row/column/cell) # Once the user picks create a rando...
require File.dirname(File.realdirpath(__FILE__)) + '/test_helper.rb' require 'active_redis/naming' describe ActiveRedis::Naming do subject { TestObject.new } before do TestObject.send :extend, ActiveRedis::Naming end describe "#table_name" do describe "when id isn't passed" do it "is contain...
require 'twine_test' class CommandTest < TwineTest def prepare_mock_formatter(formatter_class, clear_other_formatters = true) twine_file = Twine::TwineFile.new twine_file.language_codes.concat KNOWN_LANGUAGES formatter = formatter_class.new formatter.twine_file = twine_file Twine::Formatters.for...
module Revolut module Api module Response class Merchant attr_accessor :mapping attr_accessor :id, :scheme, :name, :mcc, :country, :state, :city, :postcode, :address, :category MAPPING = { "id" => :id, "scheme" => :sche...
Friendphotos::Application.routes.draw do root :to => 'static#index' match 'auth/:provider/callback', to: 'sessions#create' match 'auth/failure', to: redirect('/') get '/sign_in' => 'sessions#new', :as => 'sign_in' get '/sign_out' => 'sessions#destroy', :as => 'sign_out' # Routes for the Friend resource:...
# Cookbook Name:: mysql # Recipe:: server # # Copyright 2014, oshiire # # All rights reserved - Do Not Redistribute # package "mysql-server" do action :install end service "mysql" do action [ :enable, :start ] supports :status => true, :restart => true, :reload => true end directory node[:mysql][:datadir] do ...
class RepetitionsList attr_reader :uniques, :repetitions, :total_repetitions def initialize @uniques = {} @repetitions = {} @total_repetitions = 0 end def add(key, value) if repetitions.key?(key) repetitions[key] << value @total_repetitions += 1 return end return repe...
class DropTable < ActiveRecord::Migration[5.2] def change drop_table :guests end end
class Item < ApplicationRecord has_many :orderitems has_many :orders, through: :orderitems has_and_belongs_to_many :categories validates :title, presence: true, uniqueness: true validates :description, presence: true validates_numericality_of :price, :greater_than_or_equal_to => 0.01 end
# == Schema Information # # Table name: documents # # id :integer not null, primary key # user_id :integer # archive_id :integer # local_status :string(255) default(""), not null # global_status :string(255) default(""), not null # verify_tries :integer default(0)...
# frozen_string_literal: true class FillSubscriptionsJob < ActiveJob::Base queue_as :default def perform FillSubscriptions.call! end end
require_relative '../test_helper' describe AuthorDecorator do include TestHelper describe '#website_link' do before do @author = AuthorDecorator.decorate(Fabricate(:author)) end it 'returns link to authors website' do @author.website_link.must_match('http://example.com') end it '...
class AddPreferredCourses < ActiveRecord::Migration[5.1] def change add_column :jobs, :preferred_courses, :string, array: true, default: [] end end
require 'serialport' require 'stringio' require_relative './debouncer' class RemoteButton def initialize @port = '/dev/cu.usbserial-A601EYK8' end def listen &blk open_serial_port do |sp| read_data_frames(sp) do |bytes| if button_pressed?(bytes) debouncer.trigger do pu...
class ChangeMediaFileDurationToInteger < ActiveRecord::Migration def self.up remove_column :media_files, :duration add_column :media_files, :duration, :integer end def self.down add_column :media_files, :duration, :time, :null => false remove_column :media_files, :duration end end
# -*- encoding : utf-8 -*- # The business logic for listens to songs. # # This code is part of the Stoffi Music Player Project. # Visit our website at: stoffiplayer.com # # Author:: Christoffer Brodd-Reijer (christoffer@stoffiplayer.com) # Copyright:: Copyright (c) 2013 Simplare # License:: GNU General Public License...
class DatMilestone < ActiveRecord::Base ######################### # 関連定義 ######################### # プロジェクト構成データに所有される(1:1) belongs_to :dat_projectcomp, :foreign_key => "project_tree_id" # #=== テンプレートデータから属性値をコピーする # #指定されたテンプレートデータ(TPマイルストーンマスタ)から #属性値をコピーする。 # def copyFromTemplate(template) ...
# frozen_string_literal: true require_relative '../truemail/client/version' require_relative '../truemail/client/configuration' require_relative '../truemail/client/http' module Truemail module Client INCOMPLETE_CONFIG = 'required args not passed' NOT_CONFIGURED = 'use Truemail::Client.configure before' ...
require "stf/container" module STF::Trait module Container def initialize (c) @container = c end def get(key) @container.get(key) end end end
class AddDateBinToTimelineNodes < ActiveRecord::Migration def change add_column :timeline_nodes, :interval_bin, :string, :default => '', :null => false, :after => :date add_index :timeline_nodes, [:timeline_id, :interval_bin] remove_column :timeline_nodes, :date end end
class CompanyPassagesController < ApplicationController before_action :set_company, only: [:create, :destroy] before_action :set_company_user_passage, only: [:destroy] def create @company_passage = CompanyPassage.new(user: current_user, company: @company) if already_linked flash[:notice] = "Vous ne...
class AddManagerToDepartments < ActiveRecord::Migration[6.0] def change add_reference :departments, :manager, null: true, foreign_key: { to_table: :people } end end
require 'spec_helper' require 'models/shared/legacy_node_url_helper' describe Issue do it_should_behave_like 'a legacy node url' do let(:model){ FactoryGirl.build(:issue) } end it { should have_many :sections } it { should have_many :articles } it { should have_many :book_reviews } it { should hav...
FactoryBot.define do factory :canonical_temperature do zip_code { 1 } record_time { "2015-03-01 15:07:03" } outdoor_temp { 1.5 } end end
puts 'Start' # module Greeter # def hello # 'hello' # end # end # # begin # greeter = Greeter.new # rescue # puts '例外が発生したが、このまま続行する。' # end def method_1 puts 'method_1 start' begin method_2 rescue puts '例外が発生しました。' end puts 'method_1 end' end def method_2 puts 'method_2 start' meth...
# frozen_string_literal: true # rubocop:disable Metrics/MethodLength module Permissions module Grants class ClassInformation attr_reader :id, :type def initialize(object) (@type, @id) = if object.is_a?(Class) [object.name, nil] elsif object.is_a?(String) ...
require 'asciidoctor' require 'asciidoctor/extensions' # require 'pdf_block_macro' # require 'pry' module Faa module Asciidoctor include ::Asciidoctor class CwpMacro < Extensions::InlineMacroProcessor use_dsl named :cwp name_positional_attributes 'jcn' def process(parent, target, _a...
require 'rails_helper' RSpec.describe Comment, type: :model do describe 'assosiations' do it 'belongs to one user' do comment = Comment.reflect_on_association(:user) expect(comment.macro).to eql(:belongs_to) end it 'belongs to one post' do comment = Comment.reflect_on_association(:post)...
class NZTM2000 VERSION = '1.1.0' #Define the parameters for the International Ellipsoid #used for the NZGD2000 datum (and hence for NZTM) NZTM_A = 6378137.0 NZTM_RF_GRS80 = 298.257222101 #GRS80 Inverse flattening between equatorial and polar. NZTM_RF_WGS84 = 298.257223563 #Inverse flattening. NZTM_R...