text
stringlengths
10
2.61M
require "stock_picker.rb" require 'rspec' # Stock Picker # # Write a method that takes an array of stock prices (prices on days 0, 1, ...), and outputs the most profitable pair of days on which to first buy the stock and then sell the stock. Remember, you can't sell stock before you buy it! # describe '#stockpicker' d...
module Service # encoding: utf-8 class VerifyAudit attr_reader :auditor, :user, :audit_log ACCEPTED = 2 REJECTED = 1 class << self def rejected(auditor, user, options = {}) user.accepted(build_audit_log(auditor, user, REJECTED, options)) Service::MailerService::Mailer.delive...
# encoding: UTF-8 # == Schema Information # # Table name: users # # id :integer not null, primary key # nom :string(255) # email :string(255) # created_at :datetime not null # updated_at :datetime not null require 'spec_helper' describe User do before (:each) do ...
class AvailableMods def all Dir[File.join(mod_root_path, '*')].map do |directory| files = Dir.glob(File.join(directory, '*.xcommod'), File::FNM_CASEFOLD) next unless files.any? File.basename files.first, '.*' end.compact end def mod_root_path File.expand_path '~/Library/Application ...
class Campaign < ApplicationRecord STATISTICS_KINDS = [:total_pledges_amount_in_dollars, :total_backers_count] DATA_CAPTURE_LEVELS = { "batch_0" => { internal_description: "Batch imported from archives csv file", internal_lot_number: 4, commit_id: "", description: "This campaign was imp...
require 'helper_classes' module Network module Monitor module Connection attr_accessor :checks extend self @checks = %w(ppp default host ping httping openvpn ) @vpn_config = Dir.glob('/etc/openvpn/*.conf').first @error_action = :restart @host = 'google.com' @count_faile...
# frozen_string_literal: true module Types # gql type for Payee model class PagedTransactionsType < Types::BaseObject field :page, Integer, null: false field :page_total, Integer, null: false field :transactions, [TransactionType], null: false end end
class CreateTableCourseSubjects < ActiveRecord::Migration def self.up create_table :course_subjects do |t| t.string :name t.integer :parent_id t.string :parent_type t.string :code t.boolean :no_exams, :default => false t.integer :max_weekly_classes t.boolean :is_deleted,...
class CreateTaxons < ActiveRecord::Migration def change create_table :taxons do |t| t.integer "parent_id" t.integer "lft" t.integer "rgt" t.integer "children_count", default: 0 t.integer "depth", default: 0 end remove_columns :items, :parent_id, :lft, :rgt, :ch...
require 'spec_helper' feature 'Creating Activity' do before do sign_in_as!(FactoryGirl.create(:admin_user)) visit '/' click_link 'New Activity' end scenario "can create an activity" do fill_in 'Name', with: 'Student Project' fill_in 'Description', with: 'An activity for student project' ...
require 'test_helper' class CategoryTest < ActiveSupport::TestCase def setup @category = Category.new(name: 'Dom') end #Happy-path test "valid category name" do assert @category.valid? end test "invalid without name" do @category.name = nil refute @category.valid?,'saved user wit...
module Fog module AWS class EC2 class Real require 'fog/aws/parsers/ec2/describe_volumes' # Describe all or specified volumes. # # ==== Parameters # * volume_id<~Array> - List of volumes to describe, defaults to all # # ==== Returns # * respo...
module RPC class Subtract def initialize(params) case params when Hash @minuend = params.delete(:minuend).to_i @subtrahend = params.delete(:subtrahend).to_i when Array @minuend, @subtrahend = params.map(&:to_i) else raise end rescue raise RPC...
# encoding: UTF-8 # -- # Copyright (C) 2008-2010 10gen 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 # # Unless required by applicab...
require 'test_helper' class TrkDatatablesTest < Minitest::Test def test_that_it_has_a_version_number refute_nil ::TrkDatatables::VERSION end end
class VotesController < ApplicationController def create vote = Vote.new(race_id: params[:race_id], voter_id: params[:voter_id], candidate_id: params[:candidate_id]) vote.save ? (render json: vote) : (render json: vote.errors) end def index render json: Candidate.all end def ...
class Ticket attr_reader :id attr_accessor :customer_id, :film_id def initialize(info) @id = info['id'].to_i if info['id'] @customer_id = info['customer_id'].to_i @film_id = info['film_id'].to_i @screening_id = info['screening_id'].to_i end def save sql = "INSERT INTO tickets (custo...
# misc utility functions that are common in my solutions module Utils # check the AOC_DEBUG env var def self.enable_debug_output? ENV.has_key?("AOC_DEBUG") ? ENV["AOC_DEBUG"] == "true" : false end # get a parameter from the command line or else default def self.cli_param_or_default(n=0, default="") ...
class RemoveSelectedPolygonClassColourIdFromLayers < ActiveRecord::Migration def up remove_column :layers, :selected_polygon_class_colour_id end def down add_column :layers, :selected_polygon_class_colour_id, :integer end end
# Copyright 2014 Square 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 # # Unless required by applicable law or agreed ...
#!/usr/bin/env ruby load File.expand_path(File.join(File.dirname(__FILE__), "..", "lib", "vanagon.rb")) optparse = Vanagon::OptParse.new( "#{File.basename(__FILE__)} <project-name> <platform-name> [options]", %i[workdir configdir engine] ) options = optparse.parse! ARGV project = ARGV[0] platforms = ARGV[1] targe...
class AddBoughtToEventItems < ActiveRecord::Migration def change add_column :event_items, :bought, :boolean, :default => false end end
class Toastunes::DirectoryParser # p = Toastunes::DirectoryParser.new(:library => 'w2') # p.parse! def initialize(options={}) @options = { :replace_artists => true, :replace_tracks => true, :replace_genres => true, :replace_covers => true }.merge(options) end # parse a di...
Dir["./pieces/*.rb"].each {|file| require file } require 'colorize' class MissingPieceError < RuntimeError end class InvalidMoveError < RuntimeError end class WrongColorError < RuntimeError end class Board attr_reader :grid def initialize(grid = nil) @grid = grid.nil? ? generate_grid : grid @captured_...
namespace :db do desc "TODO" task rearrange: :environment do if Rails.env == "development" then ENV['VERSION']= '0' Rake::Task['db:migrate'].invoke Rake::Task['db:migrate'].reenable ENV.delete 'VERSION' Rake::Task["db:migrate"].invoke Rake::Task['db:seed'].execute() puts "do...
require 'httparty' require 'base64' require 'openssl' module ZanoxPublisher # Represents a Zanox Product API error. Contains specific data about the error. class ZanoxError < StandardError attr_reader :data def initialize(data) @data = data # should contain Code, Message, and Reason c...
class Api::GoalSessionsController < ApiController before_action :authenticate! before_action :find_goal_session, only: [ :show, :update, :destroy, :invite, :invite_by_email, :suggest_buddies] before_action :validate_friend_id!, only: [ :invite ] def index success(data: current_user.goal_sessions) end ...
class Api::V1::LibraryController < Api::V1::UserApiController before_action :set_library before_action :set_book, only: [:add_book, :remove_book] def show render json: current_v1_user.library.books end def add_book is_added = @library.add_book @book render json: { book_id: @book....
# encoding: UTF-8 module CDI module V1 module LearningTracks class AddAuthorService < BaseUpdateService record_type ::LearningTrack attr_reader :added_moderators def changed_attributes return [] if fail? [:moderators] end private def r...
class DropApproverComments < ActiveRecord::Migration def change drop_table :approver_comments end end
# nome.rb class Nome # Define métodos getter padrão mas não métodos setter attr_reader :primeiro, :ultimo # Quando alguém tenta escrever um primeiro nome, force regras sobre ele. def primeiro=(primeiro) if primeiro == nil || primeiro[0].size == 0 raise ArgumentError.new('Todos precisam ter um primeiro...
class Agregarimagendepartamento < ActiveRecord::Migration def change change_table :departamentos do |x| x.string :urlimg end end end
Rails.application.routes.draw do devise_for :users root to: 'pages#home' # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html resources :recipes, except: [ :new, :create ] do resources :orders, only: [ :new, :create ] resources :amounts, only: [ :new, :cre...
# Write your code here. def line(katz_deli) if katz_deli == [] puts "The line is currently empty." else the_line = "The line is currently:" for count in 0...katz_deli.size the_line += " #{count+1}. #{katz_deli[count]}" end puts the_line end end def take_a_number(katz_deli, name) katz_...
require 'publishing_api_presenters/edition.rb' require 'publishing_api_presenters/case_study.rb' require 'publishing_api_presenters/placeholder.rb' require 'publishing_api_presenters/unpublishing.rb' module PublishingApiPresenters def self.presenter_for(model, options={}) presenter_class_for(model).new(model, op...
require "google/api_client" require "google_drive" require 'openssl' OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE class Water def initialize # Creates a session. This will prompt the credential via command line for the # first time and save it to config.json file for later usages. session = GoogleDrive...
# == Schema Information # # Table name: plays # # id :bigint(8) not null, primary key # x :integer # y :integer # game_id :bigint(8) # created_at :datetime not null # updated_at :datetime not null # FactoryBot.define do factory :play do x { nil } y { ...
class ApplicationController < ActionController::API def set_channel @channel = params.require(:channel) @channel = "##{@channel}" unless @channel.start_with?('@') end def set_actor @actor = actor_params end def set_repository @repository = repository_params end def actor_params para...
Page Title: CXP Check My Work Example # Objects Definitions ============================================== title css .title title-bar css .title-bar show-scores_button css .assignment-button.show-scores review_button css .assignment-button.review-butto...
class Order < ApplicationRecord belongs_to :user has_many :orders_items, dependent: :destroy validates :sub_post_code, presence: true validates :sub_address, presence: true end
module Pod module Lazy class Logger def self.info(value) UI.puts "#### #{value}".ansi.blue end def self.important(value) UI.puts "#### #{value}".ansi.magenta end end end end
require 'test_helper' class GameOfLifeTest < MiniTest::Unit::TestCase def setup @game = GameOfLife.new(2,2) end def test_add_interact_rule @game.add_rule(Loneliness.new) assert_equal 1, @game.interact_rules.count end def test_add_cell cell = Cell.new('X') @game.add_cell(0, 0, ...
class Redirect < ApplicationRecord self.inheritance_column = :_type_disabled enum type: {twitter: 0, facebook: 1, instagram: 2} def self.create_by_type(params) redirect = Redirect.new(type: params[:type], controller: params[:controller], action: params[...
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable validates :username, presence: true validates :fullna...
class AddPhotoLicenseToPosts < ActiveRecord::Migration def change add_column :posts, :photo_licensee_name, :string add_column :posts, :photo_licensee_link, :string add_column :posts, :photo_license_creative_commons, :boolean end end
# frozen_string_literal: true module Timestamps extend ActiveSupport::Concern included do field :created_at, GraphQL::Types::ISO8601DateTime, null: false field :updated_at, GraphQL::Types::ISO8601DateTime, null: false end end
# frozen_string_literal: true module LayersHelper def parse_layer_api_metadata(layer) params = { id: layer.ckan_id } uri = URI.parse("http://ace.rdidev.com:8080/api/3/action/package_show?id=" + layer.ckan_id) Rails.logger.info "Contacting uri" req = Net::HTTP::Get.new(uri.to_s) result = Net::HTTP...
class RemoveBooleanColumnsFromQuery < ActiveRecord::Migration def change remove_column :queries, :beer? remove_column :queries, :wine? remove_column :queries, :cocktail? end end
module CapistranoAppforce unless defined?(::CapistranoAppforce::VERSION) VERSION = "0.2.0" end end
module DoubleDice class Shifter < Struct.new(:matrix) def to_s shifted = '' column = 0 while column < vector_length do 0.upto(matrix.size - 1) do |line| shifted << matrix[line][column] end column += 1 end shifted.tr(' _', '') end private ...
class Role < ActiveRecord::Base has_and_belongs_to_many :users has_and_belongs_to_many :tasks def self.options_for_select self.all.map{|r| [r.name, r.id]} end def self.options_for_facebook self.all.map{|r| "{id: %s, name: '%s'}" % [r.id, r.name]}.join(',') end def self.ROLES APP_CONFIG[:rol...
require 'sentiment_analyzer' # Test controller for demoing the sentiment analysis engine class SentimentController < ApplicationController def check # Get list of tickers for autocomplete @tickers = ticker_json(Company.all) return unless params['symbol'] # Get cached symbol if possible @symbol =...
class PrescriptionsController < ApplicationController before_filter :authenticate_user! before_filter :find_patient # GET /prescriptions # GET /prescriptions.json def index @prescriptions = @patient.prescriptions.all @reminder = @patient.reminder # @refill_reminder = RefillReminder.new respo...
class TwitterClone::Pages::Profile::Edit < Matestack::Ui::Page def response div class: "mb-3 p-3 rounded shadow-sm" do heading size: 4, text: "Your Profile", class: "mb-3" matestack_form form_config_helper do div class: "mb-3" do form_input key: :username, type: :text, placeholder: ...
class ImproveContactPhone < ActiveRecord::Migration def change # separate join table was not great idea...phone number cannot exist in # isolation so cleaner, easier management with Contact ID on table itself add_reference :phone_numbers, :contact, index: true add_foreign_key :phone_numbers, :contac...
module Do # the tests below do various things then wait for something to # happen -- so there's a potential for a race condition. to # minimize the risk of the race condition, increase this value (0.1 # seems to work about 90% of the time); but to make the tests run # faster, decrease it STEP_DELAY = 0.5 ...
class Dancer attr_accessor :name, :age, :card_list def initialize(name, age) @name = name @age = age @pants = "grey" @card_list = [] end def pirouette "*twirls*" end def bow "*bows*" end def queue_dance_with(partner) @name = partner @card_list << @name end def car...
Rails.application.routes.draw do devise_for :admins, controllers: { sessions: 'admins/sessions', passwords: 'admins/passwords', registrations: 'admins/registrations' } devise_for :users, controllers: { sessions: 'users/sessions', passwords: 'users/passwords', registratio...
# Fix the fastlane version so that we don't get any surprises while deploying. fastlane_version '2.5.0' # Don't generate README files. skip_docs # Set your JSON key file location. json_key_file "/path/to/your/downloaded/key.json" ##################### ### CONFIGURATION ### ##################### # Hockey configurati...
class CreatePlayers < ActiveRecord::Migration[5.1] def change create_table :players do |t| t.integer :x_position t.integer :y_position t.integer :health t.integer :armor t.string :name t.timestamps end end end
class Band < ActiveRecord::Base extend FriendlyId friendly_id :handle, use: :slugged has_merit has_reputation :votes, source: :user, aggregated_by: :sum belongs_to :user has_many :albums, dependent: :destroy has_many :songs, through: :albums, dependent: :destroy has_many :events has_many :articles h...
require "rails_helper" RSpec.describe GovukDesignSystem::HmctsBannerHelper, type: :helper do describe "#govukInput" do it "returns the correct HTML for success" do html = helper.hmctsBanner({ text: "The image was added", type: "success" }) expect(html).to match_html(<<~HTML) ...
json.array!(@discoveries) do |discovery| json.extract! discovery, json.url discovery_url(discovery, format: :json) end
class DocumentPresenter attr_reader(:annual_plan, :annual_report, :budget, :guideline, :opinion, :policy, :vision, :bylaws, :regulation, :directive) def initialize(documents) by_title = documents.by_title(I18n.locale).group_by(&:category) by_revision = documents.by_revision.grou...
class CreateExamLogs < ActiveRecord::Migration def change create_table :exam_logs do |t| t.references :class_registration, index: true t.string :doc t.timestamps end end end
class CreateRosterSpots < ActiveRecord::Migration[5.2] def change create_table :roster_spots, id: :uuid do |t| t.boolean :archived, default: false t.datetime :archived_at t.datetime :joined_at t.string :role t.references :team, foreign_key: true, null: false, type: :uuid t....
class CreateTeams < ActiveRecord::Migration def self.up create_table :teams do |t| t.string :fullname t.string :shortname t.string :symbol t.string :manager t.string :president t.string :address t.string :post_code t.string :city t.string :fax t.string :...
# def full_title(page_title) # base_title = "Sample App" # if page_title.empty? # base_title # else # "#{ base_title } | #{ page_title }" # end # end include ApplicationHelper #include UserPageSpecUtility def valid_signin(user) visit signin_path fill_in "Email", with: user.email fill_in "Password", wi...
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'deploy_rails_as_rpm/version' Gem::Specification.new do |gem| gem.name = "deploy_rails_as_rpm" gem.version = DeployRailsAsRPM::VERSION gem.authors = ["Tilo Slo...
module Higan module Base module ClassMethods class Fail < StandardError end def development? Rails.env == "development" end def ftp_data ftp_store.each_pair.map do |k, v| {name: k}.merge!(v.to_h) end end def local_data local_s...
json.array!(@usuarios) do |usuario| json.extract! usuario, :id, :nome_completo, :apelido, :sexo, :email, :data_cadastro json.url usuario_url(usuario, format: :json) end
require './spec/spec_helper.rb' describe 'Registered users' do self.use_transactional_fixtures = false before :all do ensure_server_is_running DatabaseCleaner.clean end after :all do DatabaseCleaner.clean end describe 'User CRUD' do it 'should be editable' do ensure_logged_in_as ...
class AreaSerializer < ActiveModel::Serializer attributes :id, :name, :status, :icon has_many :users end
class Player attr_reader :hp def initialize(name) @name = name @hp = 100 end def name @name end def is_attacked @hp -= 10 end end
class City attr_reader(:id,:name) define_method(:initialize)do |attributes| @id = attributes.fetch(:id) @name = attributes.fetch(:name) end define_method(:save)do result = DB.exec("INSERT INTO cities (name) VALUES ('#{name}') RETURNING id;") id = result.first().fetch('id').to_i @id = id en...
require "horseman/browser" describe Horseman::Browser::Browser do include Doubles subject { described_class.new(connection, js_engine, "http://www.example.com")} it "saves cookies" do expect(subject.cookies).to be_empty subject.get! expect(subject.cookies.count).to eq 2 expect(subject.cook...
class BallotEntry < ActiveRecord::Base belongs_to :ballot validates_uniqueness_of :rank, scope: :ballot_id def candidate=(candidate) self.candidate_id = candidate.id self.save! end def candidate return Candidate.find(self.candidate_id) end def eql?(other) ...
class CreateJoinTableUserRaid < ActiveRecord::Migration[5.2] def change create_join_table :users, :raids do |t| t.index [:user_id, :raid_id] t.index [:raid_id, :user_id] end end end
# frozen_string_literal: true class Rogare::Commands::Hello extend Rogare::Command command 'hello', hidden: true match_command /.+/, method: :execute match_empty :execute def execute(m) this_server = m.channel.server servers, needs_prefix = if this_server [{ 0 => this_...
# frozen_string_literal: true class CreateProfiles < ActiveRecord::Migration[5.2] def change create_table :profiles do |t| t.references :user t.string :name t.string :second_name t.string :surname t.integer :phone t.integer :country_code t.string :email t.integer :...
# # 最も高値でフィギュアを売れるセットの組み合わせを算出します。 # 実行例) ruby sales_doll.rb 10 # # 各セットの価格リスト set_price_list = [1, 6, 8, 10, 17, 18, 20, 24, 26, 30] # 各セットの単価リスト set_unit_list = {} set_unit_list_sort = {} # 売却残個数 nokori = ARGV[0].to_i # 売却セット組み合わせ set_pattern = [] # 売却額 price = 0 # 各セットの単価を算出する set_price_list.each_with_index do...
# reverse_it.rb # Write a method that takes one argument, a string, and returns a # new string with the words in reverse order. # Pseudo-code: # Create a mirror image of a string by flipping it. # First word will equal the last word. # Need to split the string into individual words. # Once split, the words can be plac...
Rails.application.routes.draw do resources :opinions devise_for :users resources :users, only: %i[index show] resources :follows root 'opinions#index' # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
# frozen_string_literal: true require 'openid_connect' module UMA module Discovery class Config class Response < OpenIDConnect::Discovery::Provider::Config::Response unavailable_attributes = %i[subject_types_supported id_token_signing_alg_values_supported] undef_required_attributes(*unavai...
require_relative 'author' class Post include Datamappify::Entity attribute :title, String attributes_from Author, :prefix_with => :author end
class CreateSearches < ActiveRecord::Migration[5.1] def change create_table :searches do |t| t.string :keywords t.date :date_of_birth t.string :address t.integer :phone_no t.string :infection t.string :injury t.integer :min_consultation t.integer :max_consultation ...
class CreditCard < ActiveRecord::Base belongs_to :user has_many :orders validates :ccv, :expiration_month, :expiration_year, :first_name, :last_name, presence: true end
class Tweet < ApplicationRecord belongs_to :user validates :text, presence: true, length: 1..280 validates :user, presence: true end
module Indexable extend ActiveSupport::Concern included do include Elasticsearch::Model include Elasticsearch::Model::Callbacks # include ElasticsearchSearchable __elasticsearch__.client = Elasticsearch::Client.new host: Settings.elasticsearch.urls settings index: { number_of_shards: 3 } do ...
class SalesPage < GenericBasePage include DataHelper #class HeaderPage < GenericBasePage element(:regions) {|b| b.link(text: "Regions")} end
class CreatePhrases < ActiveRecord::Migration[5.1] def change create_table :phrases do |t| t.string :label t.string :abbrev t.text :text t.belongs_to :user t.timestamps end end end
class UsersController < ApplicationController skip_before_action :require_login, except: [:destroy] def new end def create user = Users::UserCreateFacade.new( email: params[:email], password: params[:password], first_name: params[:first_name], last_name: params[:last_name], ).r...
FactoryBot.define do factory :change_image do file { Rack::Test::UploadedFile.new(Rails.root.join('spec', 'fixtures', 'fluffy_cat.jpg'), 'image/png') } user { create :user } end end
class IdeasController < ApplicationController before_action :set_idea, only: %i[show edit update destroy] before_action :set_user def index @ideas = Idea.all end def show @images = @idea.images end def new @categories = Category.all @idea = Idea.new end def create @categories ...
# -*- encoding : utf-8 -*- class CreateMessages < ActiveRecord::Migration def change create_table :messages do |t| t.text :question t.text :reply t.datetime :replied_at t.references :student t.references :course t.timestamps end add_index :messages, :student_id add...
include_recipe 'directory_helper' home_dir = DirectoryHelper.home(node) execute "Install rustup" do user node[:user] command "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y" end home_path = "#{home_dir}/" + node[:user] cargo_bin_path = home_path + "/.cargo/bin" set_cargo_bin_to_path = "P...
require 'rails_helper' RSpec.describe Mealbook, type: :model do it { should belong_to :owner } it { should have_many :meals } it { should validate_presence_of :mealbook_name } it { should respond_to :public } end
class CreateNominates < ActiveRecord::Migration def change create_table :nominates do |t| t.integer :user_id, null: false t.string :candidate, null: false, limit: 32 t.string :reason, null: false, limit: 140 t.timestamps end end end
module Refinery module Properties class Engine < Rails::Engine include Refinery::Engine isolate_namespace Refinery::Properties engine_name :refinery_properties initializer "register refinerycms_area_codes plugin" do Refinery::Plugin.register do |plugin| plugin.name = "a...
class RetailController < InheritedResources::Base before_filter :auto_sign_in layout 'retail' protected def auto_sign_in sign_in(:customer, Customer.anonymous) unless customer_signed_in? if (cart_id = session.delete(:cart_id)) and current_customer.cart.blank? begin Cart.find(cart_id).assi...