text
stringlengths
10
2.61M
class Game < ActiveRecord::Base belongs_to :away, class_name: "Team" belongs_to :home, class_name: "Team" belongs_to :winner, class_name: "Team" has_many :picks end
require 'json' module Ulpos class Client attr_reader :app_key, :app_secret, :endpoint def initialize(app_key = Ulpos.app_key, app_secret = Ulpos.app_secret, endpoint = Ulpos.endpoint) @app_key = app_key @app_secret = app_secret @endpoint = endpoint end def invoke(method = nil, opt...
# frozen_string_literal: true require 'pathname' require 'ruby-graphviz' module Pocky class Packwerk MAX_EDGE_WIDTH = 5 def self.generate(params = {}) new(**params).generate end private_class_method :new def initialize( package_path: nil, default_package: 'root', filena...
Gem::Specification.new do |p| p.name = "eventbus" p.version = "0.32" p.description = "Distributed application framework for developing event-driven automations." p.summary = "Libraries for creating EventBus clients and services" p.author = "Dave Spadea" p.email ...
describe ApprovalMailer do it 'should deliver Approval email to receipient' do u = User.find_by_email('approver1@putit.io') ro = ReleaseOrder.first a = Approval.create(user_id: u.id, release_order_id: ro.id) email = ApprovalMailer.deliver_approval_email(a) expect(email.to).to eq ['approver1@puti...
DietaryRequirement.destroy_all categories = ['vegans' , 'vegetarians', 'nut allergies', 'lactose intolerant', 'halal', 'celiacs'] categories.each do |category| DietaryRequirement.create!(categories: category) end
# Load the Rails application. require File.expand_path('../application', __FILE__) # Initialize the Rails application. Rails.application.initialize! module ActionDispatch class DebugExceptions def log_error(request, wrapper) logger = logger(request) return unless logger exception = wrapper.ex...
class Achievement < ApplicationRecord has_many :user_achievement validates :title, length: {maximum: 30}, presence: true validates :phrase, length: {maximum: 140} validates :description, length: {maximum: 600}, presence: true end
class Url include Mongoid::Document include Mongoid::Timestamps field :short_url, type: String field :original_url, type: String end
source 'https://rubygems.org' ruby '2.1.4' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '4.2.1' # Use SCSS for stylesheets gem 'sass-rails' # Use Uglifier as compressor for JavaScript assets gem 'uglifier' # Use CoffeeScript for .js.coffee assets and views gem 'coffee-rails' # See http...
class Date DAYS_IN_WEEK = 7 MONTHS_IN_YEAR = 12 DAYS = {:sunday => 0, :monday => 1, :tuesday => 2, :wednesday => 3, :thursday => 4, :friday => 5, :saturday => 6} MONTHS = {:january => 1, :february => 2, :march => 3, :april => 4, :may => 5, :june => 6, :july...
module Admin class InvestorsController < AdminController before_action :set_user, only: [:show, :edit, :update, :destroy] authorize_resource class: false def index @investors = (User.with_role :investor).sort_by { |obj| obj.full_name } respond_to do |format| format.html f...
class User < ActiveRecord::Base attr_accessible :first_name, :last_name, :role, :role_id # scope :latest, lambda {|param| where(:created_at.gt => param)} belongs_to :role has_one :address before_destroy :is_admin def is_admin errors.add :base, "Can't delete admins." if self.role.try(:name) == "admin" ...
class Student < User attr_accessor :knowledge def initialize @knowledge = [] end def learn(learned_stuff) @knowledge << learned_stuff end end
# frozen_string_literal: true class PostTypesController < ApplicationController before_action :set_post_type, only: %i[show edit update destroy] def index @post_types = current_user.post_types.all end def show search_params = { text: params[:text], year: params[:year], bookmarked: p...
# frozen_string_literal: true require 'controller_test' class GroupSemestersControllerTest < ActionController::TestCase setup do @group_semester = group_semesters(:previous_panda) login(:uwe) end test 'should get index' do get :index assert_response :success end test 'should get new' do ...
# encoding: utf-8 # copyright: 2016, you # license: All rights reserved # date: 2016-09-16 # description: The Microsoft Internet Explorer 11 Security Technical Implementation Guide (STIG) is published as a tool to improve the security of Department of Defense (DoD) information systems. Comments or proposed revisions to...
module RestoreAgent::Object class Directory < File include ContainerMixin def children # child method will load or refresh the child list @children ||= [] newchildren = [] #puts "listing in "+file_path.inspect begin Dir.open(file_path) do |d| d.each do |...
class Calendar < ActiveRecord::Base has_many :events has_many :calendar_users has_many :users, through: :calendar_users end
require 'set' # Represents Operators within the language. # An operator is defined by up to 5 components: # - Priority (pri) # - Unique Name / Identifier (sym) # - Type (prefix, infix or suffix) # - Arity (how many arguments? Most operators are either unary or binary) # - Minarity (The minimum arity, for operato...
class InvitesController < ApplicationController before_action :authenticate_user! before_action :load_invite, only: [:destroy, :reject, :accepted] before_action :load_character, only: [:accepted] def index # policy only for youself @invites = current_user.invites end def new @invite = Invite.n...
require File.expand_path '../../spec_helper.rb', __FILE__ describe Description do describe 'create description' do it 'should validate uniqueness of category/name pair' do d = Description.create(category: 'Pregnancy Category', name: 'A', value: 'Sho...
class AddForeignKeys < ActiveRecord::Migration[4.2] def change add_column :phone_numbers, :contact_id, :integer add_column :emails, :contact_id, :integer end end
require 'rails_helper' RSpec.describe User, type: :model do it 'is valid with full_name, email, avatar_image, admin, password and password confirmation' do user = FactoryBot.create(:user) expect(user).to be_valid end it 'is invalid without full_name' do user = FactoryBot.build(:use...
require 'rails_helper' RSpec.describe "matches/new", :type => :view do before(:each) do assign(:match, Match.new( :team1 => nil, :team2 => nil, :link => "MyString" )) end it "renders new match form" do render assert_select "form[action=?][method=?]", matches_path, "post" do ...
class ChangePubliusersSaltToLimit64 < ActiveRecord::Migration def up change_column :public_users, :salt, :string, :limit => 64 end def down change_column :public_users, :salt, :string end end
class Product < ActiveRecord::Base brothers = ["dario", "damjan"] # has_one :manufacturer has_many :suppliers # validates_associated :manufacturer validates :name, confirmation: true, presence:true validates :name_confirmation, presence: true validates :price, presence: true validates...
require_dependency "redmine/wiki_formatting/textile/helper" module Redmine module WikiFormatting module Textile module Helper def heads_for_wiki_formatter_with_glossary heads_for_wiki_formatter_without_glossary unless @heads_for_wiki_formatter_glossary_included cont...
require "pry" class MP3Importer attr_accessor :path, :artist def initialize(path) @path = path end def files files = Dir["#{@path}**/*.mp3"] files.collect{|file| file.split("/")[file.split("/").length-1]} end def import files.each{|file| Song.new_by_filename(file)} end end
require "spec_helper" describe AttendanceListsController do describe "routing" do it "routes to #index" do get("/attendance_lists").should route_to("attendance_lists#index") end it "routes to #new" do get("/attendance_lists/new").should route_to("attendance_lists#new") end it "rout...
class AddMoreFieldsToMilk < ActiveRecord::Migration def change add_column :milks, :currency, :string end end
class User < ApplicationRecord has_many :user_tests, dependent: :destroy has_many :participated_user_tests, through: :user_tests, source: :test has_many :created_tests, class_name: 'Test' validates :name, presence: true validates :email, presence: true def completed_tests_by_level(level) participated_...
module Merit # Rules has a badge name and level, a target to badge, a conditions block # and a temporary option. # Could split this class between badges and rankings functionality class Rule attr_accessor :badge_id, :badge_name, :level, :to, :model_name, :level_name, :multiple, :temporary,...
require 'pry' class Board attr_accessor :move_history attr_reader :game_positions def initialize @move_history = [] @game_positions = {} (1..9).each { |position| @game_positions[position] = Square.new(' ')} end def draw_board system 'clear' puts " | | #{game_positions[1...
class CreateRequests < ActiveRecord::Migration def change create_table :requests do |t| t.string :first_name t.string :last_name t.integer :phone, :limit => 8 t.string :email t.boolean :expired, default: false t.boolean :accepted t.datetime :accepted_at t.boolean :o...
require 'benchmark' time = Benchmark.measure do puts "The sum of the digits of 100! is " + (1..100).inject(:*).to_s.chars.map(&:to_i).reduce(:+).to_s end puts "Time elapsed (in seconds): #{time}"
class ChangeDataDataValuesAssociation < ActiveRecord::Migration def up drop_table :data_data_values add_column :data_values, :datum_id, :integer add_index :data_values, :datum_id end def down remove_index :data_values, :datum_id remove_column :data_values, :datum_id create_table :data_da...
require 'rails_helper' resource "CMS::Layout" do let(:resource) { FactoryBot.create(:cms_layout, body: 'body', draft: 'draft') } json(:resource) do let(:root) { 'layout' } it { should have_properties('id', 'content_type', 'handler', 'system_name', 'title').from(resource) } end end
class VacationsController < ApplicationController before_action :set_vacation, only: [:show, :update, :destroy] # GET /vacations # GET /vacations.json def index # @user = current_user # @vacations = @user.vacations # @vacations = Vacation.find(user_id: current_user.id) @vacations = Vacation.all...
require 'process/roulette/controller/command_handler' module Process module Roulette module Controller # Handles the GAME state of the controller state machine. class GameHandler def initialize(driver) @driver = driver end def run puts 'BOUT BEGINS' ...
require_relative '00_nearest_larger' # Write a function, `nearest_larger(arr, i)` which takes an array and an # index. The function should return another index, `j`: this should # satisfy: # # (a) `arr[i] < arr[j]`, AND # (b) there is no `j2` closer to `i` than `j` where `arr[i] < arr[j]`. # # In case of ties (see e...
class Admin::FuelArmsController < Admin::BaseController before_action :set_fuel_arm, only: [:show, :edit, :update, :destroy] before_action :set_aircraft, only: [:index, :new, :edit] def index @fuel_arms = @aircraft.fuel_arms.paginate(page: params[:page]) end def show end def new @fuel_arm = Fue...
module Alf module Operator::NonRelational class Defaults < Alf::Operator() include Operator::NonRelational, Operator::Transform signature do |s| s.argument :defaults, TupleComputation, {} s.option :strict, Boolean, false, "Restrict to default attributes only?" end ...
namespace :watch do task :default => [:restart] desc "touch tmp/restart.txt any time a file changes on disk in this directory" task restart: :environment do sh "nodemon --watch app --watch config --watch lib --watch vendor -e rake,rb,yml --exec \"touch\" tmp/restart.txt" end end task :watch => 'watch:re...
module Fog module Compute class Vsphere class Real def get_host(name, cluster_name, datacenter_name) get_raw_host(name, cluster_name, datacenter_name) end protected def get_raw_host(name, cluster_name, datacenter_name) cluster = get_raw_cluster(cluster_...
class UserMailer < ActionMailer::Base include ApplicationHelper default :from => "rortestmailer@gmail.com" def registration_confirmation(user) @user = user mail(to: "#{user.name} <#{user.email}>", subject: full_title("Registration Confirmation for #{user.name}")) end def account_activation(user) @user =...
require "rails_helper" RSpec.describe Bundle, type: :model do it "creates an application bundle" do key = "test" bundle = Bundle.create!(key: key) expect(bundle).to be end it "finds bundles by application id" do key = "test" bundle = Bundle.create!(key: key) attrs = FactoryBot.attributes...
class Api::V1::NotesController < ApplicationController def index notes = Note.all render json: notes, status: 200 end def show note = Note.find(params[:id]) render json: note, status: 200 end def create curr_user = User.find_by(id: params[:note][:user_...
require '../util' desc 'Creates a queue' task :create do aws <<-SH, binding aws sqs create-queue --queue-name test-queue SH end desc 'Sends messages and receives messages' task :message do que = aws <<-SH, binding aws sqs get-queue-url --queue-name test-queue SH 5.times do |i| p...
module DiningPhilosophers module V4 class Chopstick def initialize @mutex = Mutex.new end def take @mutex.lock end def drop @mutex.unlock rescue ThreadError puts 'Trying to drop a chopstick not acquired' end def in_use? @m...
class SessionsController < ApplicationController # include CurrentUserConcern before_action :current_user def create @user = User.find_by(name: params[:name]) if @user session[:user_id] = @user.id render json: { signed_in: true, user: @user, message: 'Signed in successfully' } else ...
require 'rails_helper' RSpec.describe Api::V1::MessagesController, type: :controller do let (:user) { create(:user) } let (:post_event) { create(:valid_post_event, user_id: user.id) } before {sign_in(user)} describe 'GET #index' do subject { get :index , params: { id: post_event.id} } describe 'succe...
require 'spec_helper' describe StatisticsController do it "renders the index template and sets the tasks variable" do designer = FactoryGirl.create(:designer) sign_in(designer) project = designer.projects.create(FactoryGirl.attributes_for(:project)) task1 = project.tasks.create(FactoryGirl.attributes...
control "V-61731" do title "The DBMS must support organizational requirements to enforce the number of characters that get changed when passwords are changed." desc "Passwords need to be changed at specific policy-based intervals. If the information system or application allows the user to consecutively r...
#!/usr/bin/env ruby @exit_value = 0 @git_branch = %x[ git branch | grep -oP "^\\* \\K.*" ] # or (if not GNU grep?) # @git_branch = %x[ git branch | sed -n "s/^\* \(.*\)/\1/p" TEAM_NAMES="(hydra|monkey|monkeys)" BRANCH_PREFIX="(gbl|kred|hydra)" # Check that the branch name conforms to <branch-prefix>-<team name>-NNN...
class LocationsController < ApplicationController skip_before_action :authenticate_user!, only: [:index] def index locations = Location.all render json: locations, each_serializer: LocationSerializer end end
class Payment < ActiveRecord::Base serialize :params cattr_accessor :gateway validates_presence_of :description belongs_to :subscription # BEGIN acts_as_state_machhine include AASM aasm_column :state aasm_initial_state :pending aasm_state ...
class Export::ActivityVarianceColumn def initialize(activities:, net_actual_spend_column_data:, forecast_column_data:, financial_quarter:) @activities = activities @net_actual_spend_column_data = net_actual_spend_column_data @forecast_column_data = forecast_column_data @financial_quarter = financial_q...
module GFA::Record::HasFromTo def from?(segment, orient = nil) links_from_to?(segment, orient, true) end def to?(segment, orient = nil) links_from_to?(segment, orient, false) end ## # Extracts all linked segments from +gfa+ (which *must* be indexed) def segments(gfa) raise "Unindexed GFA" un...
class Collaborator < ActiveRecord::Base # Remember to create a migration! belongs_to :collaborator, class_name: "User", foreign_key: :user_id ## good to go belongs_to :list # good to go end
class Product < ActiveRecord::Base has_many :advertising_campaigns has_many :interactions end
class CustomFailure < Devise::FailureApp def redirect_url "/home/index" end def respond if http_auth? http_auth else redirect end end end
# encoding: UTF-8 class Film class Decor def to_hash { id: id, decor: decor, sous_decor: sous_decor, lieu: lieu, scenes_ids: scenes_ids } end end #/Decor end #/Film
project "my-app" do |proj| # Project level settings our components will care about proj.setting(:prefix, "/opt/my-app") proj.setting(:sysconfdir, "/etc/my-app") proj.setting(:logdir, "/var/log/my-app") proj.setting(:bindir, File.join(proj.prefix, "bin")) proj.setting(:libdir, File.join(proj.prefix, "lib")) ...
class Admin::LandingPagesController < Admin::BaseController permit "superuser" layout 'admin/base' before_filter :setup_tabs uses_tiny_mce(:options => {:theme => 'advanced', :browsers => %w{msie gecko safari}, :cleanup => true, ...
class Activity class Import class Updater attr_reader :errors, :activity, :row, :report def initialize(row:, uploader:, partner_organisation:, report:, is_oda:) @errors = {} @activity = find_activity_by_roda_id(row["RODA ID"]) @uploader = uploader @partner_organisation...
module ArticleXmlExportable extend ActiveSupport::Concern # array of strings ARTICLE_PARTS = %w(primary_tag headline subhead byline bytitle body) CHUNK_MAPPING = { 'p' => 'p', 'h2' => 'h2', # map h3 to h2 for now 'h3' => 'h2' } def as_xml(parts) parts ||= ARTICLE_PARTS # if no parts s...
class RequestDecorator < Decorator def offered_brands self.offers.map(&:supplier_name).join(',') end def offer_count self.offers.count end def offset_offer_count(offset) offer_count + offset.to_i end def display_quantity if (str = "#{quantity} #{unit}").blank? str = "1.00 Unit" ...
require File.expand_path('../../../spec_helper', __FILE__) describe "1.9", -> describe "Time#nsec", -> it "returns 0 for a Time constructed with a whole number of seconds", -> R.Time.at(100).nsec.should == 0 it "returns the nanoseconds part of a Time constructed with a Float number of seconds", -> ...
require 'rails_helper' describe "Cards" do let (:card) { create(:card, review_date: Date.today) } before(:each) do login_user(card.user, user_sessions_url) end context "review" do it "is successful" do visit root_path expect(page).to have_content(t('reviews.new.todays_review')) fill...
class LogUserStock < ActiveRecord::Base attr_protected belongs_to :user belongs_to :stock belongs_to :issue scope :today, lambda{|stock_id| where(["DATE_FORMAT(created_at, '%Y-%m-%d') = ? AND stock_id = ?", Date.today, stock_id])} scope :buying, lambda{where(["stock_type = ?", Code::BUY])} scope :selling,...
class InitializeDatabase < ActiveRecord::Migration def change create_table :bands do |t| t.column :name, :string end create_table :venues do |t| t.column :name, :string end create_table :bands_venues, id: false do |t| t.integer :band_id t.integer :venue_id end add_i...
class CreateRinks < ActiveRecord::Migration def self.up create_table :rinks do |t| t.string :name t.text :address t.integer :longitude t.integer :latitude t.string :rinktype t.string :hours t.string :lights t.text :facilities t.text :conditions t.text :n...
class Bob def run while true puts "Say something to Bob." #end multi-line user input with "/" + Enter $/ = ?\/ phrase = gets.chomp puts hey(phrase) end end def hey(phrase) allCaps = /[A-Z]{2,}+!|[A-Z]{3,}+\?|[A-Z]{4,}/ question = lambda { |phrase| phrase.end_with?('...
describe GitAnalysis::Repository do let(:id) { 30985840 } let(:repo) { 'solidus' } let(:owner) { 'solidusio' } let(:language) { 'Ruby' } describe '#initialize' do it 'returns a new GitAnalysis::Repository object' do object = GitAnalysis::Repository.new(id, repo, owner, language) expect(object...
class CourseApplication < ActiveRecord::Base belongs_to :application belongs_to :course def self.report(period) self.count(:include => [:application, :course], :group => :code, :conditions => {"applications.period_id" => period.id}) end end
class TodosController < ApplicationController def index @todos = Todo.all end def show @todo = Todo.find(params[:id]) end end
class AdminController < ApplicationController before_action :admin_check private # HTTP Basic auth (used for admin routes) def admin_check authenticate_or_request_with_http_basic do |username, password| username == ENV['AUTHENTICATE_USERNAME'] && password == ENV['AUTHENTICATE_PASSWOR...
#!/usr/bin/env ruby # Simple sinatra stager. # An example of how to use the continuum-stager-api. # The API is located at: https://github.com/apcera/stager-api-ruby require "bundler" Bundler.setup # Bring in continuum-stager-api require "continuum-stager-api" stager = Apcera::Stager.new # Add the ruby dependency w...
# === COPYRIGHT: # Copyright (c) Jason Adam Young # === LICENSE: # see LICENSE file class DraftStatDistribution < ApplicationRecord include CleanupTools serialize :distribution serialize :scaled_distribution # player type PITCHER = 1 BATTER = 2 scope :batting, ->{where(player_type: DraftStatDistributi...
APPNAME = 'ember-skeleton' require 'colored' require 'rake-pipeline' desc "Build #{APPNAME}" task :build do Rake::Pipeline::Project.new('Assetfile').invoke end desc "Run tests with PhantomJS" task :test => :build do unless system("which phantomjs > /dev/null 2>&1") abort "PhantomJS is not installed. Download...
require 'nokogiri' require 'open-uri' require 'pry' class Scraper def self.scrape_index_page(index_url) index_scrape = Nokogiri::HTML(open(index_url)).css("div.student-card") student_hash_index = [] index_scrape.each do |student| student_hash_index<< { name: student.css("div.card-text-cont...
require 'spec_helper' include UnitsHelper describe "Unit Testing" do before(:each) do @unit1 = Factory(:unit) @unit2 = Factory(:unit) @unit2.destination = "howdy" @unit2.location = 'marseilles' @unit2.save! end it 'should be a unit' do @unit2.destination.should match @unit1.destination end it 'sh...
class CustomersController < ApplicationController before_action :signed_in_administrator, only: [:index, :edit, :update, :destory] def new @customer = Customer.new end def index @customers = Customer.all end def create @customer = Customer.new(customer_params) @customer.save ...
require "test_helper" describe User do let(:user) { User.new(name: 'Joe', gender: 'male') } it "must be valid" do user.valid?.must_equal true end end
class ViewsHideDependencies < ActiveRecord::Migration def self.up add_column :views, :hide_dependencies, :integer end def self.down remove_column :views, :hide_dependencies end end
# Copyright (c) 2019 Danil Pismenny <danil@brandymint.ru> # frozen_string_literal: true # TODO: Rename to PatioMarketDrainer # class PeatioRestDrainer < Drainer include MarketDrainer FETCH_PERIOD = 1 # sec KEYS = %i[asksVolume bidsVolume usersAskPrice usersBidPrice usersAsksVolume usersBidsVolume].freeze d...
require_relative 'node' module SOSHelper class Offering ATRRIBUTES = [ :identifier, :procedure, :observableProperty, :observedArea, :resultTime, :phenomenonTime, :node ] ATRRIBUTES.each { |t| attr_reader t } def initialize(xml_offer) @node = Node.new xml_offer @id, @procedure = getText(:id), getText(:pro...
# # Be sure to run `pod spec lint BeMaskingCall.podspec' to ensure this is a # valid spec and to remove all comments including this before submitting the spec. # # To learn more about Podspec attributes see https://guides.cocoapods.org/syntax/podspec.html # To see working Podspecs in the CocoaPods repo see https://...
require 'rails_helper' RSpec.describe "Movies show page" do before(:each)do @user = User.create(email: 'test123@xyz.com', password: 'viewparty') service = MovieService.new @cruella = VCR.use_cassette("movie_details_by_id") do MovieFacade.movie_details_by_id(337404) end visit welcome_path ...
class MatchingsController < ApplicationController def index micropost = Micropost.find(params[:micropost_id]) return if micropost.nil? users_with_common_tags = [] micropost.tags.each do |tag| tag.users.each do |user| users_with_common_tags.push([user, tag]) end end # dele...
class Instructor @@all = [] attr_reader :name def initialize (name) @name = name @@all << self end def self.all @@all # should return all instructors end def pass_student (student, test_name) # should take in a student instance and test name. # If...
class Kind < ApplicationRecord has_many :badges has_many :points validates :name, presence: true validates :name, uniqueness: true end
# == Schema Information # # Table name: projects # # id :integer not null, primary key # title :string(255) # description :string(255) # user_id :integer # created_at :datetime # updated_at :datetime # slug :string(255) ...
class AnalyzedInstruction < ApplicationRecord belongs_to :recipe has_many :step_equipments, dependent: :destroy has_many :equipments, through: :step_equipments end
require 'rails_helper' RSpec.describe DoctorsController, :type => :controller do let(:doctor) { Doctor.create(name: "Bob Dylan", street: "1147 Fake St.", city: "New York", state: "NY", zip: "10024") } describe "GET new" do it "returns http success" do get :new expect(response).to be_success end...
class BlockSerializer < ActiveModel::Serializer attributes :id, :name, :repetitions, :measures, :time_signature_over, :time_signature_under, :musical_key, :song_id, :color, :location, :tempo end
class AddVisibleToRooms < ActiveRecord::Migration[6.0] def change add_column :rooms, :visible, :boolean, null: false, default: false end end
class AddRequirementsToActivity < ActiveRecord::Migration[6.0] def change add_column :activities, :requirements, :text, array: true, default: ["water bottle", "gym shoes"] end end
require 'spec_helper' resource "Greenplum DB: instances" do let(:user) { users(:admin) } before do log_in user end get "/provisioning" do example_request "Get options for provisioning a Greenplum instance" do status.should == 200 end end end