text
stringlengths
10
2.61M
class MedicalSpecializationRepository < AbstractRepository def initialize super @model = MedicalSpecialization end end
# vim: set ts=2 sw=2 expandtab : # # Cookbook Name:: bugzilla # Recipe:: database # # Copyright (C) 2013 Mathew Odden # # 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...
Rails.application.routes.draw do get 'users/show' resources :user_events devise_for :users resources :events get '/user_event/:event_id', to: 'user_events#new' get '/events/user/:user_id', to: 'users#show' root "events#index" # For details on the DSL available within this file, see http://guides.rubyonr...
require "rubygems" require "tmpdir" require "bundler/setup" require "jekyll" namespace :site do desc "Generate blog files" task :generate do Jekyll::Site.new(Jekyll.configuration({ "source" => ".", "destination" => "_site" })).process end desc "Generate and publish blog to gh-pages" ...
namespace :db do desc "load pdr data from csv" task :load_pdr_data, [:csv_file] => :environment do |t , args| puts "input file is #{args.csv_file}" if args.csv_file.size == 0 puts "missing input file name" exit end counter = 0 FasterCSV.foreach(args[:csv_file],:col_sep => "|", :he...
class StaticPagesController < ApplicationController def home if current_user.present? redirect_to users_url end end end
=begin #=============================================================================== Title: Parameter Tables Author: Hime Date: Dec 7, 2013 URL: http://himeworks.com/2013/11/20/parameter-tables/ -------------------------------------------------------------------------------- ** Change log Dec 7, 2013 - fixe...
require 'bcrypt' require 'rack/csrf' require 'sinatra' require 'sinatra/activerecord' require 'slim' configure :development do set :database, "sqlite3:///shelfeducated.db" set :show_exceptions, true end configure :production do db = URI.parse(ENV['DATABASE_URL'] || 'postgres:///localhost/mydb') ActiveRecord:...
# def partition(arr,num) # assembled_arr = Array.new(2){Array.new(0)} # arr.each do |ele| # if ele < num # assembled_arr[0] << ele # else # assembled_arr[1] <<ele # end # end # return assembled_arr # end # #p partition([11, 5, 13, 2, 3], 7) # de...
class AddBackgroundAndConclusionToSubmission < ActiveRecord::Migration def change add_column :proposals, :conclusion, :text add_column :proposals, :background, :text add_column :proposals, :proposal_number_2, :text add_column :proposals, :provision_number_name_2, :text end end
require 'rails_helper' RSpec.describe Spree::Product, type: :model do describe 'product scope' do let(:taxon) { create(:taxon) } let(:product) { create(:product, taxons: [taxon]) } subject { Spree::Product.related_products_of(product) } context 'When there are 3 related products' do let!(:rela...
class MissionsController < ApplicationController include MyUtility before_action :set_mission, only: [:show, :edit, :update, :destroy] # GET /missions def index placeholder_set param_set @count = Mission.notnil().includes(:p_name, :mission).search(params[:q]).result.count() @search = Mission.no...
class Api::PaymentsController < ApplicationController include PushNotification before_action :authenticate! before_action :deny_first_and_last_params, only: %i(index) before_action :set_payment, only: %i(show update destroy) before_action :set_group, only: %i(index) def index payments = @group.payment...
class AddApprovingManagerToApplyLeave < ActiveRecord::Migration def self.up add_column :apply_leaves, :approving_manager, :integer end def self.down remove_column :apply_leaves, :approving_manager end end
require 'spec_helper' describe Topographer::Importer::Mapper::ValidationFieldMapping do let(:validation_mapping) do Topographer::Importer::Mapper::ValidationFieldMapping.new('test mapping', ['field1', 'field2', 'field3']) do |input| sum = input.values.flatten.inject(0) {|sum, x| sum+x} raise 'Sum mus...
class ApiController < ActionController::Base unless Rails.application.config.consider_all_requests_local rescue_from StandardError do |exception| error(message: exception) end rescue_from ActiveRecord::RecordInvalid do |exception| error(message: exception.to_s) end rescue_from ...
class AddCategoryCodeToProfile < ActiveRecord::Migration[5.1] def change add_column :profiles, :title, :string add_column :profiles, :category_code, :integer end end
class CreateFeeds < ActiveRecord::Migration def self.up create_table :feeds do |t| t.string :feedlink, null: false t.string :link, null: false t.text :title, null: false t.text :description, null: false t.integer :subscribers_count, default: 0, null: false t.string :image ...
#!/usr/bin/env ruby # require 'rubygems' require 'aws-sdk' require 'logger' require 'simple-graphite' config_file = File.join(File.dirname(__FILE__), "as_send_stats_to_graphite.yml") unless File.exist?(config_file) puts <<END To run the samples, put your credentials in as_send_stats_to_graphite.yml as follows: acce...
json.array!(@dashboard_special_prices) do |dashboard_special_price| json.extract! dashboard_special_price, :id, :start, :end, :price, :is_sale, :area_id json.url dashboard_special_price_url(dashboard_special_price, format: :json) end
class Order < ActiveRecord::Base belongs_to :time_slot belongs_to :flower has_one :schedule_item scope :unassigned, -> { joins("LEFT OUTER JOIN schedule_items ON schedule_items.order_id = orders.id").where("schedule_items.id IS NULL") } end
#!/usr/bin/env ruby # frozen_string_literal: true INACTIVE = '.' ACTIVE = '#' curr = {} $stdin.each_line .map(&:chomp) .map.with_index do |line, y| line.split('').map.with_index { |c, x| curr[[x, y, 0]] = c } end 6.times do nxt = {} points = { x: curr.keys.map { |x, _, _| x }.uniq, y: curr...
# frozen_string_literal: true require 'dry/monads/result' module Onboarding module Endpoints module CreateUser class Deserializer include Dry::Monads[:do, :result, :try] include Dry::Matcher.for(:call, with: Dry::Matcher::ResultMatcher) def call(request) # just for simpl...
# frozen_string_literal: true module Api::V1::Admin::Users class DestroyAction < ::Api::V1::BaseAction try :find, catch: Sequel::NoMatchingRow step :authorize tee :cancel_subscription map :destroy tee :notify private def find(input) ::User.with_pk!(input.fetch(:id)) end d...
class AddRejectedToApplications < ActiveRecord::Migration[5.2] def change add_column :applications, :rejected, :boolean end end
require 'logger' require 'benchmark' KANNED_LIB_DIR = File.expand_path('..', __FILE__) KANNED_ROOT_DIR = File.expand_path('../../..', __FILE__) module Palmade module Kanned autoload :Constants, File.join(KANNED_LIB_DIR, 'kanned/constants') autoload :Init, File.join(KANNED_LIB_DIR, 'kanned/init') autoloa...
class ShowSerializer < ActiveModel::Serializer attributes :id, :netflix_id, :genre, :cast, :title, :director, :description, :year, :imdb_rating, :image_url, :primary_color, :primary_contrast_color def image_url object.poster_url end def primary_color object.colors.first || '000000' end de...
class AfterTest < ActiveCommand::Base required :parameter, type: :array def call parameter << 'call' end after do parameter << 'after 1' end after do parameter << 'after 2' end end
# frozen_string_literal: true RSpec.describe Sidekiq::Manager do let(:capsule_or_options) do if Sidekiq::LimitFetch.post_7? Sidekiq.default_configuration.default_capsule elsif Sidekiq::LimitFetch.post_6_5? Sidekiq else Sidekiq.options end end it 'can be instantiated' do exp...
namespace :caststone do namespace :monitor do require_relative 'checker' desc 'Monitor database integrity' task integrity: [:environment, :check_products, :check_photos, :check_components] do end desc 'Check Series integrity' task check_products: :environment do products = Refinery::...
class Review < ApplicationRecord validates :restaurant_id, presence: true validates :user_id, presence: true validates :rating, numericality: { greater_than: 0, less_than_or_equal_to: 5 } validates_presence_of :rating, message: 'Rate your dining experience before submitting!' validates_presence_of :...
require 'rails_helper' describe "Contentful Recipe Service" do subject { Contentful::RecipeService.new } describe "#public methods" do it "validates perform method" do expect(subject.public_methods.include?(:perform)).to eq true end it "returns false for private methods" do expect(subject...
# frozen_string_literal: true module Robots module DorRepo module Dissemination # NOTE: This step has been merged into the end accession robot. It should no longer be used, but is left in case # there are existing workflow steps that require it. class Cleanup < LyberCore::Robot def init...
class Retail::PublishersController < RetailController actions :index, :show def show show! do render(:text => 'Forbidden', :status => 403) and return unless @publisher.approved end end protected def collection # by default, only show approved Publishers @publishers ||= end_of_associat...
class Hotel < ApplicationRecord has_many :bookings belongs_to :city validates_associated :city geocoded_by :address after_validation :geocode validates :name, :address, presence: true, uniqueness: true validates :single_bedroom_price, :double_bedroom_price, :suite_room_price, :dormitory_room_price, :sin...
# Replace default www.conf with our chef template template "#{node[:localdev][:project_path]}/.env" do source 'env.erb' # owner node[:localdev]['owner'] # group node[:localdev]['group'] # mode '0755' variables ({ :environment => node[:localdev][:environment], :use_https => node[:wp][:u...
require_relative '../helpers/finder' class Checkbox def initialize(args, page) @selector = args.to_s.downcase.gsub(" ", "_") + "_checkbox" @page = page end def check checkbox = Finder.element_of_page(@page, @selector) unless checkbox.checked? @page.click_the(checkbox) end end def ...
# == Schema Information # # Table name: users # # id :integer(4) not null, primary key # email :string(255) default(""), not null # encrypted_password :string(128) default(""), not null # reset_password_token :string(255) # reset_password_sent_at :datetime # ...
Gem::Specification.new do |s| s.name = 'testing_data' s.version = '0.1.1' s.licenses = ['MIT'] s.summary = "Feeds arrays of bad test data" s.authors = ["Niall47"] s.files = ["lib/testing_data.rb"] end
# frozen_string_literal: true require "timecop" require "fake_consumer_interceptor" require "kafka/interceptors" describe Kafka::Consumer do let(:cluster) { double(:cluster) } let(:log) { StringIO.new } let(:logger) { Logger.new(log) } let(:instrumenter) { Kafka::Instrumenter.new(client_id: "test", group_id: ...
class Anagram def initialize(anagram) @anagram = anagram end def match(words) words.select do |word| word.split("").sort == @anagram.split("").sort end end end
require 'httparty' require 'pp' class Slack include HTTParty base_uri "https://slack.com/api" def self.send(team, channel, token, text, bot ) is_text_invalid = (text.nil? or text == "") if is_text_invalid "cancel sending message" else query = { :team => team, :token => to...
class CreateFeedbacks < ActiveRecord::Migration[5.0] def change create_table :feedbacks do |t| t.string :project_name t.string :app_name t.string :app_comp t.string :feedback_title t.text :feedback_desc t.binary :screenshot t.references :user, foreign_key: true t.re...
# frozen_string_literal: true require 'rails_helper' module Facilities RSpec.describe NCAFacility do before(:each) { BaseFacility.validate_on_load = false } after(:each) { BaseFacility.validate_on_load = true } it 'should be an NCAFacility object' do expect(described_class.new).to be_an(NCAFacilit...
class Item < ActiveRecord::Base belongs_to :itype has_many :orders has_many :customers, through: :orders end
class AdminAbility include CanCan::Ability def initialize(user) user ||= AdminUser.new # guest user (not logged in) if user can :manage, :all cannot :update, PickUp do |pickup| pickup.status != PickUp::STATUSES[:pending] end cannot :cancel, PickUp do |pickup| pickup....
class SendMailJob < ApplicationJob queue_as :high def perform(order) OrderMailMailer.notify(order).deliver_now! end end
# The time of day can be represented as the number of minutes before or after midnight. If the number of minutes is positive, the time is after midnight. If the number of minutes is negative, the time is before midnight. # Write a method that takes a time using this minute-based format and returns the time of day in 2...
class TagsController < ApplicationController respond_to :html, :json def index if params[:query].present? @tags = Tag.search(params[:query], page: params[:page], limit:25) else @tags = Tag.all end respond_with(@tags) end def autocomplete render json: Tag.search(params[:query...
class UpdateFileToLead < ActiveRecord::Migration[5.1] def up change_column :leads, :File, :binary, :limit => 5.megabytes end def down change_column :leads, :File, :binary end end
class AddDcToA3ParArray < ActiveRecord::Migration[5.0] def change add_column :resource_storage_a3_par_arrays, :data_center_id, :integer add_index :resource_storage_a3_par_arrays, :data_center_id end end
# Reversed Arrays (Part 1) # Write a method that takes an Array as an argument, and reverses its elements in place; that is, mutate the Array passed into this method. The return value should be the same Array object. #You may not use Array#reverse or Array#reverse!. def reverse(arr) p arr p arr.object_id i=...
class ChangedUsersRolesIndexedUserIdRoleId < ActiveRecord::Migration def self.up add_index :users_roles, :user_id add_index :users_roles, :role_id end def self.down end end
require "cli/arguments" module SpecRunner module Cli RSpec.describe(Arguments) do context "when running over stdout" do it "returns the arguments for a suite run" do arguments = described_class.new([ "stdout", "suite" ]) expect(arguments.output_type).to eq...
class Vote < ActiveRecord::Base belongs_to :user has_many :votings validates_presence_of :user_id, :title end
class Show < ActiveRecord::Base validates_presence_of :date, :venue, :address validates_numericality_of :price, allow_nil: true, allow_blank: true before_save { |show| show.price = nil if show.price == 0 } default_scope order: 'created_at DESC' def price_for_show price.nil? ? "Free!" : "$#{price}" en...
require_relative "../helpers/table" require_relative "../helpers/xor" class OEIS def self.a004489(j) # This is a base-3 generalization of XOR where digits are added # place-wise mod 3. n, k = OEISTable.n_k(j) n.xor(k) end end
class User < ActiveRecord::Base # Remember to create a migration! has_many :posts validates :user, :email, presence: true, uniqueness: true validates :password, presence: true # validates :email, format: {with: /^\S+@\S+\.\S+$/, message: "Invalid E-mail"} # validates_format_of :email, :with => /\A([^@\s]+)@...
class WelcomeController < ApplicationController before_action :require_logged_out, only: [:check_hash, :register, :register_hash, :login] before_action :require_logged_in, only: [:index, :kill, :email, :death_story, :malaria_question_submit, :users_list, :final_stats] before_action :require_email, only: [:index] ...
require 'json' require_relative "../models/planning.rb" require_relative "../models/shift.rb" require_relative "../models/worker.rb" class Database attr_reader :workers, :planning def initialize(data_file_path, output_file_path) @data_file_path = data_file_path @output_file_path = output_file_path @w...
require 'rails_helper' RSpec.describe User, :type => :model do describe "#name" do it 'returns the full name of the user' do user = create(:user, password: 'secret_password') expect(user.name).to eq("#{user.first_name} #{user.last_name}") end end describe "#admin?" do it 'returns true w...
class GroupMembership < ActiveRecord::Base # associations belongs_to :user belongs_to :group # validations validates_existence_of :user, :group validate :user_validator # callbacks before_save :set_as_user_default, on: :create after_save :ensure_only_one_user_default private def user_v...
require 'spec_helper' module PriorityTest::Core describe Priority do it "has 32 priority rankings" do Priority::PRIORITY_RANKINGS.size.should == 32 end end end
class AddDescriptionToShopCategory < ActiveRecord::Migration def change add_column :shop_categories, :description, :text end end
require 'rails_helper' RSpec.describe ActiveStorage::BlobsController, type: :controller do describe '#show' do context 'when signed in' do login_fm_buyer_with_details let(:contract) { build(:facilities_management_procurement_supplier_da_with_supplier) } let(:procurement) { create(:facilities_ma...
class CreateExercisesSentencesJoiningTable < ActiveRecord::Migration def change create_table :exercises_sentences, id: false do |t| t.references :exercise t.references :sentence end end end
require File.expand_path('../app/search.rb', __FILE__) require 'app/scrape' require 'app/display' desc "Clear out all files in ./tmp directory and destroy Gemfile.lock" task :clean do generated_files = FileList['./tmp/*.html'] if File.exists?("Gemfile.lock") gemfile_lock = File.open("Gemfile.lock").path ge...
module PageObjects module Computacenter class TechSourcePage < PageObjects::BasePage set_url '/computacenter/techsource' element :bulk_email_input, '#bulk-techsource-form-emails-field' element :continue, 'button[type=submit]' end end end
# # Copyright 2014 Chef Software, 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 to in...
require 'spec_helper' describe Mongoid::History::Attributes::Create do before :each do class ModelOne include Mongoid::Document include Mongoid::History::Trackable store_in collection: :model_ones field :foo field :b, as: :bar track_history on: :foo end end after :e...
# == Schema Information # # Table name: images_of_posts # # id :bigint(8) not null, primary key # image_id :bigint(8) # post_id :bigint(8) # link_name :string(255) # index :integer # class ImageOfPost < ApplicationRecord self.table_name = :images_of_posts belongs_to :image, class_name: 'I...
# encoding: utf-8 # fix: move into TextUtils namespace/module!! class CodeReader include LogUtils::Logging def self.from_file( path ) ## nb: assume/enfore utf-8 encoding (with or without BOM - byte order mark) ## - see textutils/utils.rb code = File.read_utf8( path ) self.from_string( code ) e...
# Ruby's blocks are closure-like structures # Pro's reduce repetition and even make coding less error-prone # A block is basically a chunk of code that you associate with a # method call. While the method runs, it can invoke the block one # or more times. # A block is a piece of syntax and not an object 3.times do ...
# coding: utf-8 class Hello def say_hello(word) a = "hello" "#{a.capitalize}" + word end end h1 = Hello.new puts h1.say_hello(" world!")
module Fog module Compute class Brkt class Real def get_workload_template(id) request( :expects => [200], :path => "v1/api/config/workloadtemplate/#{id}" ) end end class Mock def get_workload_template(id) Excon::Re...
Puppet::Type.newtype(:nexus_connection_settings) do @doc = 'Manage the global connection settings.' newparam(:name, :namevar => true) do desc 'Name of the configuration (i.e. current).' end newproperty(:timeout) do desc 'Time in seconds Nexus will wait for a successful connection before retrying.' ...
Rails.application.routes.draw do namespace :admin do resources :reviews get 'static_pages/home' get 'static_pages/help' end root 'static_pages#home' get '/about', to: 'static_pages#about' get '/signup', to: 'users#new' resources :users resources :books, only: :show end
class User < ApplicationRecord has_many :poems, dependent: :destroy has_many :images, dependent: :destroy has_many :active_relationships, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy has_many :passive_relations...
class Admins::ScenariosController < Admins::ApplicationController before_filter :find_scenario, :only => [:show, :edit, :update, :destroy] subject_buttons :scenario, :only => :show subject_buttons :cancel_scenario, :only => [:new, :edit, :create, :update] inner_tabs :scenario_details add_crumb("Instr...
# -*- encoding : utf-8 -*- require 'rails_helper' RSpec.describe BookmarksController, type: :controller do let(:user) { FactoryGirl.create(:user) } let(:course) { FactoryGirl.create(:course) } let(:valid_attributes) { {user_id: user.id, course_id: course.id} } before(:each) do sign_in user end descri...
class Weblog < ActiveRecord::Base has_many :posts, :dependent => :destroy attr_accessible :description, :title end
include_recipe "yum" yum_repository "ajenti" do name "Ajenti" url "http://repo.ajenti.org/centos/" action :add end package "ajenti"
class CreateUnits < ActiveRecord::Migration def change create_table :units do |t| t.integer :organization_id t.string :name t.timestamps end add_index :units, :organization_id create_table :units_users, :id => false do |t| t.integer :user_id t.integer :unit_id end ...
require "trb1-reform/rails/version" require "trb1-reform/rails/railtie" module Trb1 module Reform def self.rails3_0? ::ActiveModel::VERSION::MAJOR == 3 and ::ActiveModel::VERSION::MINOR == 0 end end end
#!/usr/bin/env ruby require "bundler/setup" require "byte_buffer" require "benchmark/ips" require "ione" require "cassandra" def bm_allocation(buffer_class) buffer_class.new end def bm_churn(buffer_class) b = buffer_class.new s = 'X' * 200 100.times { b.append(s) b.read(s.size) } end def bm_append...
class CreateImages < ActiveRecord::Migration[5.0] def change create_table :images do |t| t.string :file t.references :page t.string :identifier # Although the identifier always is an integer, it can't be type :number because it exceeds its max. limit (11) t.integer :lock_version...
feature "Portals - List" do context 'Visitor' do scenario "Access invalid" do visit portals_path expect(current_path).to eq new_session_path end end context 'Admin' do let(:user) { create :user } background do login user.email, user.password end scenario "Default List...
def luhn(card_no) card_no .to_s.chars # Break into individual digits .map(&:to_i) # map each character to turn it into an integer. (&:to_i) is short for {|n| n.to_i} .reverse # Start from the end .map.with_index { |x, i| i.odd? ? x * 2 : x } # Double every other digit, the odd digits by index...
class Product < ApplicationRecord has_one :campaign belongs_to :sub_category, optional: true delegate :category, to: :sub_category, allow_nil: true has_and_belongs_to_many :bgg_categories, join_table: :product_bgg_categories has_and_belongs_to_many :bgg_families, join_table: :product_bgg_families has_an...
Pod::Spec.new do |s| s.name = 'GuoanCommunitySDK' s.version = '0.9.6' s.summary = 'GuoanCommunitySDK for iOS.' s.homepage = 'https://github.com/GuoanCommunity/GuoanCommunitySDK-iOS' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'oct...
class V2::MarketResearchQuery < CountryIndustryQuery def initialize(options = {}) super @sort = @q ? nil : 'title.keyword' @industries = options[:industries].split(',').map(&:strip) if options[:industries].present? @expiration_date = options[:expiration_date] if options[:expiration_date].present? ...
require 'action_view' module Plugins class Seen class SeenStruct < Struct.new(:who, :where, :what, :time) include ActionView::Helpers::DateHelper def to_s # "[#{time.asctime}] #{who} was seen in #{where} last saying #{what}" time_ago = time_ago_in_words(Time.at(time)) "[ \x1F#{...
# frozen_string_literal: true Gem::Specification.new do |s| s.name = 'rack-override-path' s.version = '0.2.0' s.summary = 'Rack middleware that overrides responses for web applications' s.description = 'A Rack middleware gem that overrides responses for we...
class DeleteGidColumn < ActiveRecord::Migration[5.1] def change remove_column :subgenres, :gid end end
namespace :audit do desc "Audit for AGY element that are too large" task :agency_element_too_large => :environment do AuditProblem::AgencyElementTooLarge.perform end desc "Audit for document numbers starting with X" task :invalid_document_number => :environment do AuditProblem::InvalidDocumentNumber....
class RenameCheckedOnOrder < ActiveRecord::Migration def change rename_column :orders, :checket_out_at, :checked_out_at end end
class Vertex attr_accessor :x, :y, :z def initialize(x,y,z) @x = x.to_f @y = y.to_f @z = z.to_f end def absolute Vertex.new(@x.abs,@y.abs,@z.abs) end def scale!(scale_factor) @x = @x/scale_factor @y = @y/scale_factor @z = @z/scale_factor end def max [@x,@y,@z].max end def to_s "#{@x} #{@...
class AddDocFieldsToMonthlyFinance < ActiveRecord::Migration def change add_column :monthly_finances, :security_doc_1, :string add_column :monthly_finances, :security_doc_2, :string add_column :monthly_finances, :security_doc_3, :string add_column :monthly_finances, :security_doc_4, :string end end
class QuizzesController < ApplicationController before_action :require_user_logged_in, only: [:new, :create, :update, :edit, :destroy] before_action :correct_user, only: [:update, :edit, :destroy] before_action :set_quiz, only: [:update, :edit, :destroy] def index @quizlist = Quiz.order(id: :desc).page(p...
#http://www.rubyguides.com/2017/08/ruby-linked-list/ class Node attr_accessor :value, :next def initialize(value, pointer = nil) @value = value @next = pointer end def to_s "Node with value #{value}" end end class LinkedList attr_accessor :head def initialize @head = nil end def ...