text
stringlengths
10
2.61M
require 'features/features_spec_helper' feature "Registration", :devise do scenario "Visitor registers successfully via register form" do visit new_user_registration_path within '#new_user' do fill_in 'First name', with: Faker::Name.first_name fill_in 'Last name', with: Faker::Name.last_name ...
require "airbrake" require "active_support/concern" require "active_support/core_ext/module/delegation" require "execute_with_rescue" require "execute_with_rescue/errors/no_airbrake_adapter" require "execute_with_rescue_with_airbrake/adapters/airbrake_adapter" module ExecuteWithRescue module Mixins module WithA...
module Api::V1 class ChecksController < ApplicationController before_action :set_check, only: [:show, :update, :destroy, :abort, :kill] # GET /checks def index if params[:force].to_s.downcase != "true" render :json => { :error => "List method is not allowed without force param"}, status: :m...
# Prefix Verb URI Pattern Controller#Action # cats GET /cats(.:format) cats#index # POST /cats(.:format) cats#create # new_cat GET /cats/new(.:format) cats#new # edit_cat GET /ca...
class GamePoll < ActiveRecord::Base include Accessable include Statusable include Historiable include Imageable include GameScorable include GameQuestionableClonable amoeba do nullify [:user_id, :status, :status_changed_at] exclude_association [:origin, :edition_histories, :answers, :user_scores...
class ConvertJsonToCsvService < ApplicationService def initialize(json:) @json = json end def call JSON.parse(response, {symbolize_names: true}) end def response '{ "success": true, "timeseries": true, "start_date": "2012-05-01", "end_date": "2012-05-03", "base":...
class Job < ActiveRecord::Base attr_accessible :status, :job_type_id, :transaction_id has_many :assignments has_many :workers, :through => :assignments belongs_to :transactions end
class LegalPage < ApplicationRecord validates_presence_of :title validates_presence_of :summary validates_presence_of :slug manage_with_tolaria using: { icon: "gavel", priority: 100, category: "Prose", permit_params: [ :title, :slug, :summary, :body ], } before...
class WelcomeController < ApplicationController def index @name = "Taller inacap" end end
class CreatePeople < ActiveRecord::Migration def self.up create_table :people do |t| t.column :name, :string t.column :phone, :string t.column :memo, :string t.column :posx, :integer t.column :posy, :integer t.column :location_id, :integer end end def self.down dro...
FactoryGirl.define do factory :monthly_value do association :proposal percentual_discounts {Faker::Commerce.price} observation {Faker::Lorem.paragraph} end end
VAGRANTFILE_API_VERSION = '2' Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| # Configure The Box config.vm.box = 'bento/centos-5.11' config.vm.hostname = 'nssbox-co5' # Don't Replace The Default Key https://github.com/mitchellh/vagrant/pull/4707 config.ssh.insert_key = false if Vagrant.has_plugin...
# Copyright 2007-2014 Greg Hurrell. All rights reserved. # Licensed under the terms of the BSD 2-clause license. require 'walrat' module Walrat # The ParsletCombining module, together with the ParsletCombination class and # its subclasses, provides simple container classes for encapsulating # relationships amon...
class AddBackgroundColorToPhoto < ActiveRecord::Migration def change add_column :photos, :background_color, :string end end
# This is a controller for static pages like the "about" page. # Not sure if this is the best way to do it, butit's the best I # could come up with in my current braindead state. class StaticController < ApplicationController layout 'static' before_filter :clear_errors_and_recaptcha # GET or POST /about def...
class ManagedFile < ActiveRecord::Base has_attachment :storage => :file_system, :thumbnails => { :thumb => '75>' }, :max_size => 25.megabytes validates_as_attachment validates_uniqueness_of :filename, :message => "is already in use" # Fixes the image file size after being resized after_resize do |record, img...
require 'parseexcel' require 'active_support' require File.dirname(__FILE__)+"/../ruby_extension.rb" module Scm; class ExcelNotValid < Exception def initialize(msg, file, e=nil) super("Error: #{msg}, when reading #{file}") end end end class Scm::DataExcel GBK = "GBK" UTF8 = "UTF-8" def initi...
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::VariablesAreUsedAndDefined do include StaticValidationHelpers let(:query_string) {' query getCheese( $usedVar: Int!, $usedInnerVar: [DairyAnimal!]!, $usedInlineFragmentVar: Int!, $usedFragmentVar: I...
require 'rails_helper' describe Address do describe "validation" do it {should belong_to(:country)} it {should validate_presence_of(:address)} it {should validate_presence_of(:zipcode)} it {should validate_presence_of(:city)} it {should validate_presence_of(:phone)} end end
module Nessus class Client # @author Erran Carey <me@errancarey.com> module File # GET /file/report/download # # @param [String] uuid the unique ID (name) of the report to download # @return [String] the specified report as an XML string def report_download(uuid) resp = c...
class ViewingsController < ApplicationController def index end def new @viewing = Viewing.new @formats = Format.all @viewing.build_movie end def create @viewing = Viewing.new(viewing_params) if @viewing.save flash[:success] = "Viewing added." redirect_to root_path else ...
# frozen_string_literal: true require 'ipaddr' require 'faraday' require 'faraday_middleware' module DenshiPaper class Device DEFAULT_HOSTNAME = 'digitalpaper.local' HTTP_PORT = 8080 HTTPS_PORT = 8443 KNOWN_API_VERSIONS = ['1.3'].freeze attr_reader :address, :hostname def initialize(addres...
require "rails_helper" feature "User can manage their meals", js: true do let!(:user) { FactoryGirl.create(:user) } let!(:meal) { FactoryGirl.build(:meal, user: user) } let(:new_meal) { FactoryGirl.build(:meal, user: user) } scenario "create a meal" do sign_in(user) # Create within(".panel-headin...
require 'omniauth' module OmniAuth module Strategies class WSFed include OmniAuth::Strategy autoload :AuthRequest, 'omniauth/strategies/wsfed/auth_request' autoload :AuthCallback, 'omniauth/strategies/wsfed/auth_callback' autoload :AuthCallbackValidator, 'omniauth/...
class AnswerQuestionOption < ApplicationRecord belongs_to :answer belongs_to :question_option validate :answer_has_question private def answer_has_question errors.add(:base, 'Answer must be from question') unless self.answer.question_id == self.question_option.question_id end end
require 'forwardable' class Stack OverflowError = Class.new StandardError UnderflowError = Class.new StandardError extend Forwardable def_delegators :@ary, :empty?, :size attr_reader :max_size def initialize(opts={}) opts = {max_size: 1000, initial_content: []}.merge(opts) @ary = [] @max_s...
require 'spec_helper' describe CodeBreaker::Game do before :all do @game = CodeBreaker::Game.new(6, 4, 999) end it 'has a version number' do expect(CodeBreaker::VERSION).not_to be nil end describe "#start" do before do @code = @game.start end it "returns 4 digits code, 1-6 only"...
class Patient < ActiveRecord::Base belongs_to :owner has_many :date_vaccines has_many :patients, :through => :date_vaccines end
# # Be sure to run `pod lib lint SS.podspec' to ensure this is a # valid spec before submitting. # # Any lines starting with a # are optional, but their use is encouraged # To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'SKMenu' s.vers...
module ExtendedFormHelper def e_control(type, object_name, method, options = {}, &block) ExtendedFormControl.new(type, object_name, method, self, options).extended_control(&block) end def e_text_field(object_name, method, options = {}, &block) ExtendedFormControl.new(:text_field, object_name, method, sel...
=begin Your task is to write a CircularQueue class that implements a circular queue for arbitrary objects. The class should obtain the buffer size with an argument provided to CircularQueue::new, and should provide the following methods: - enqueue to add an object to the queue - dequeue to remove (and return) the old...
class Product < ApplicationRecord validates :name, :presence => true validates :description, :presence => true validates :price, :presence => true has_many :reviews belongs_to :user end
RSpec.configure do |config| config.before(:each) do stub_request(:post, /localhost\:9292/).to_return(status: 200) end end
class RenameEventTypesToMetricTypes < ActiveRecord::Migration def change rename_table :event_types, :metric_types end end
class Weapons attr_reader :rules, :result def initialize @rules = {rock: :scissors, paper: :rock, scissors: :paper} @result = nil end def compare(choice1, choice2) @result = nil draw?(choice1, choice2) ? @result = :draw : fight(choice1, choice2) end private ...
require 'rails_helper' RSpec.describe BidsController, type: :controller do let(:auction) { FactoryGirl.create(:auction)} let(:bid) { FactoryGirl.create(:bid)} describe '#create' do context 'valid params' do def valid_request attributes = FactoryGirl.attributes_for(:bid) post :create, p...
class DownloadWorker @queue = :default def self.perform(download_serial) sleep 5 download = Marshal.load(download_serial) logger = Logger.new(File.join(Rails.root, 'log', 'resque.log')) download_target = DownloadService.get_download_info(download) logger.info download_target Parallel.e...
# encoding: UTF-8 module Linguistics module Latin module Verb VERSION = "0.9.3" # :nodoc: class LatinVerb # :nodoc: end end end end
require 'test_helper' class ThemesTest < ActionDispatch::IntegrationTest def setup @photographer = Photographer.create!(togname: "barry", email: "bregan@testing.com",password: "password", password_confirmation: "password") @theme = Theme.create!(name: "nighttime photography", description: "candid, from hi...
require 'rails_helper' require 'faker' RSpec.describe User, type: :model do context 'Validates Presence' do it { is_expected.to validate_presence_of(:name) } it { is_expected.to validate_presence_of(:email) } it { is_expected.to validate_presence_of(:password) } end context 'Validate length of pa...
class TopicsController < ApplicationController before_action :store_location, :only => [ :index, :show ] def index @topics = index_topics @topic = Topic.new @topic.posts.build end def show if Topic.find_by_slug(params[:id]) @topic = Topic.find_by_slug(params[:id]) @post = Post.new ...
class RemoveFingerprintFromGalleries < ActiveRecord::Migration def up remove_column :galleries, :gallery_image_fingerprint end end
require 'motion_build/project' require 'motion_build/rules' describe MotionBuild::Rules::AssembleSourceRule do before :each do @project = MotionBuild::Project.new("Hello World") @project.config.override(:source_dir, Dir.mktmpdir) @project.config.override(:build_dir, Dir.mktmpdir) @r = MotionBuild::R...
require 'rails_helper' feature 'creating, updating, deleting posts with images' do before do sign_up post_with_image end scenario 'can upload an image with a title and description' do expect(current_path).to eq '/posts/1' expect(page).to have_css('img') within('body') { expect(page).to have...
include ActionDispatch::TestProcess FactoryGirl.define do factory :restaurant do name { Faker::Company.name } address1 { Faker::Address.street_name} postcode { Faker::Address.postcode} # associations user trait :with_jobs_with_reviews do ignore do job_count 1 # tells FG this i...
class IntegerGenerator < Generator protected def generate_by_type @description["value"].nil? ? 200 : @description["value"].to_i end end
# == Schema Information # # Table name: users # # id :integer not null, primary key # email :string default(""), not null # encrypted_password :string default(""), not null # reset_password_token :string # reset_password_sent_at :datetime # r...
class PesticidesController < ApplicationController before_action :set_pesticide, only: [:show, :update, :destroy] # GET /pesticides # GET /pesticides.json # DOC GENERATED AUTOMATICALLY: REMOVE THIS LINE TO PREVENT REGENARATING NEXT TIME api :GET, '/pesticides', 'List pesticides' def index @pesticides =...
require 'rake/testtask' display_warning = true display_warning = false if !ENV['CI_JOB_ID'].nil? Rake::TestTask.new do |task| task.libs << %w(lib) task.libs << %w(test) task.pattern = 'test/**/test_*.rb' task.warning = display_warning end task :default => :test Rake::TestTask.new do |task| task.descriptio...
class AddOthernameToTransaction < ActiveRecord::Migration[6.1] def change add_column :transactions, :other_username, :string end end
class RemoveNicesCountToSports < ActiveRecord::Migration[5.1] def change remove_column :sports, :nices_count, :integer end end
#!/usr/bin/ruby require 'nokogiri' # input is a DemultiplexingStats.xml file from bcl2fastq # write out a nice table fn = ARGV.shift f = File.open(fn) doc = Nokogiri::XML(f) puts "SampleID\tBarcode\tLane\tCount" counts = Hash.new(0) root = doc.xpath('//Project')[0] root.xpath('Sample').each do |thing| sample = t...
class Idea < ApplicationRecord validates :title, presence: true validates :title, length: { maximum: 75 } belongs_to :user has_many :comments has_and_belongs_to_many :users # Change the follwing Idea table method to scope most recent below # def self.most_recent() # all.order(created_at: :desc).l...
module V1 module Params module Services extend Grape::API::Helpers params :new_service do group(:service, type: Hash) do requires(:start_date, type: DateTime) end end params :update_service do group(:service, type: Hash) do optional(:end_date, ...
Fabricator(:user) do email { Faker::Internet.email } name { Faker::Name.name } role { Faker::Lorem.word } address { Faker::Address } phone { Faker::PhoneNumber.phone_number } password { 'password123' } password_confirmation { 'password123' } end Fabricator(:client_user) do email { Faker::Internet.email...
require 'spec_helper' describe ContentBase do describe "::search" do context "when sphinx is running" do sphinx_spec(num: 1, options: { status: ContentBase::STATUS_LIVE }) it "searches across ContentBase classes" do ts_retry(2) do ContentBase.search.to_a.sort_by { |o| o.class.n...
require_relative 'board' require_relative 'robot' class RobotSimulation def initialize @board = Board.new @robot = Robot.new @placed = false end def board @board end def robot @robot end def is_placed @placed end def place(x = 5, y = 5, direction = 'N') board.valid_...
When /^I enter valid login credentials$/ do When 'I enter valid login credentials for "generic@example.com"' end When /^I enter valid login credentials for "([^"]*)"$/ do |email| fill_in 'Email', :with => email fill_in 'Password', :with => "Generic12" click_button "Sign in" end When /^I enter invalid login cr...
control "M-4.1" do title "4.1 Ensure a user for the container has been created (Scored)" desc " Create a non-root user for the container in the Dockerfile for the container image. It is a good practice to run the container as a non-root user, if possible. Though user namespace mapping is now available,...
namespace :redmine_update_reminder do task :send_reminders => :environment do trackers=Tracker.all trackers.each do |t| logger = Rails.logger logger.info "Tracker:#{t.name}" open_issue_status_ids = IssueStatus.select('id').where(is_closed: false).collect { |is| is.id} upda...
require 'spec_helper' describe Fappu::Connection, vcr: {cassette_name: 'connection'} do describe ".new" do subject { described_class.new } it {expect(subject).to be_a Fappu::Connection} it "defaults to Fakku's API url" do expect(subject.base_url).to eq("https://api.fakku.net/index") end en...
class TwitterAccount < ActiveRecord::Base validates :maid_id, presence: true validates :uid, presence: true, uniqueness: true validates :screen_name, presence: true, uniqueness: true validates :maid_id, presence: true belongs_to :maid has_many :tweets end
require 'spec_helper' require 'app/models/config/base' require 'app/models/config/parser_error' require 'faraday' class Config::Test < Config::Base private def parse(file_content) file_content end end describe Config::Base do describe '#content' do context 'when there is no config content for the giv...
class Comment < ActiveRecord::Base belongs_to :post belongs_to :user validates :body, length:{minimum:5}, presence: true validates :user_id, presence: true after_create :send_favorite_emails default_scope { order("updated_at ASC") } private def send_favorite_emails post.favorites.each do |fav| ...
class ChangeDveEventDatetimToDate < ActiveRecord::Migration[5.1] def change change_column :dves, :event_date, :date end end
class CreateGames < ActiveRecord::Migration[5.0] def change create_table :games do |t| t.string :name, null: false t.string :game_type t.string :pic t.string :description t.string :rules_url t.string :duration t.integer :players t.timestamps(null: false) end ...
require 'yaml' require 'shoryuken' if ENV['AWS_SECRET_ACCESS_KEY'] # load SQS credentials YAML.safe_load File.read(File.join(File.expand_path('../../', __FILE__), 'shoryuken.yml')) sqs = Aws::SQS::Client.new( endpoint: ENV["SQS_SERVER_MOCK_URL"], verify_checksums: false ) default_queue_url = s...
class Arm attr_accessor :ctr, :cpc, :count def initialize(ctr = 0.5, cpc = 1.5) @ctr = ctr @cpc = cpc @count = 0 end def change_ctr(ctr) @ctr = ctr end def revenue(disp) ((disp*@ctr)/100)*@cpc end # for softmax def weighted_avg(arms, tau) Math.exp(@ctr/tau)/(Arm.arm_ct...
module PriorityTest module Core class Service def initialize(all_tests) @all_tests = all_tests end def priority_test?(identifier) test = @all_tests.get_test(identifier) test.nil? ? true : test.priority? end end end end
require 'active_support/concern' require 'highline' require 'cloudformation_mapper/parameter' module CloudformationMapper::Parameter::StringMapper extend ActiveSupport::Concern module ClassMethods def prompt sofar @value = HighLine.ask("#{name} - #{description}? ") do |q| q.default = self.defa...
module Cultivation class UpdateTask prepend SimpleCommand REFTYPE_CHILDREN = 'children'.freeze REFTYPE_DEPENDENT = 'dependent'.freeze attr_accessor :args, :current_user, :cascade_change_tasks, :schedule_batch, :original_user_ids def initialize(current_user = nil, args = nil, schedule_batc...
module Manipulacao class Crop attr_reader :width, :height, :x, :y extend NamedParameter def self.margens(top, right, bottom, left) width = lambda{|img| img.largura - (right + left)} height = lambda{|img| img.altura - (top + bottom)} return Crop.new( width: width, height...
require 'graphql' require 'graphql/query_resolver' GraphQL::Relay::ConnectionType.default_nodes_field = true RestaurantType = GraphQL::ObjectType.define do name "restaurant" field :id, types.ID field :name, types.String field :owner do type ChefType resolve -> (obj, args, ctx) { obj.owner ...
require 'test_helper' class CheatsControllerTest < ActionController::TestCase setup do @cheat = cheats(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:cheats) end test "should get new" do get :new assert_response :success end tes...
require "spec_helper" describe "memcached configuration" do let(:env) { {} } subject(:config) { Envconfig.load(env).memcached } context "with nothing relevant in ENV" do it_behaves_like "empty configuration" end context "with MemCachier in ENV" do before do env["MEMCACHIER_SERVERS"] = "m1.ex...
class PostalCodeValidator < Louche::RegexValidator message(:invalid_postal_code) regex(/\A[a-z]\d[a-z]\d[a-z]\d\z/i) cleanup_regex(/[^a-z0-9]/i) end
class EyeExamsController < ApplicationController include UsersHelper before_action :set_eye_exam, only: [:show, :edit, :update, :destroy] before_action :require_user # GET /eye_exams # GET /eye_exams.json def index @eye_exams = EyeExam.all end # GET /eye_exams/1 # GET /eye_exams/1.json def sh...
module Bosh::AzureCloud class StemcellManager STEMCELL_CONTAINER = 'stemcell' STEMCELL_PREFIX = 'bosh-stemcell' include Bosh::Exec include Helpers def initialize(blob_manager) @blob_manager = blob_manager @logger = Bosh::Clouds::Config.logger end def has_stemcell?(name) ...
FactoryBot.define do factory :vest do name "MyString" balance "MyString" end end
require 'sinatra/namespace' require 'json' class APIV1 < Sinatra::Base register Sinatra::Namespace set :sessions, false set :static, false set :bind, '192.168.1.67' before do #Parse the request payload unless request.get? content_type :json request.body.rewind @json_payload = JSON.p...
maintainer "Rachel Aurand" maintainer_email "rachel@countableset.ch" license "Apache 2.0" description "Installs/Configures nodejs" long_description IO.read(File.join(File.dirname(__FILE__), 'README.rdoc')) version "0.0.1" recipe "nodejs", "Installs Node.JS from source" depends ...
# build a program that displays when the user will retire # and how many years she has to work until retirement # Example: # # What is your age? 30 # At what age would you like to retire? 70 # # It's 2016. You will retire in 2056. # You have only 40 years of work to go! puts "What is your age?" current_age = gets....
class Api::VendorsController < Api::ApiController expose :vendors, -> { params[:category] ? @active_company.vendors.find_by_category(params[:category]) : @active_company.vendors } expose :vendor, id: ->{ params[:slug] }, scope: ->{ @active_company.vendors.includes_associated }, vendor: Vendor, find_by: :slug # G...
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'veyor/version' Gem::Specification.new do |s| s.name = 'veyor' s.version = Veyor::VERSION s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 2.0' s.date ...
class MangaGenre < ApplicationRecord belongs_to :manga belongs_to :genre end
class GifSerializer < ActiveModel::Serializer attributes :id, :image_url end
class GitHubGistService def initialize(token) @token = token end def gists GitHubGist.new(raw_gists).gists end private def conn Faraday.new(url: "https://api.github.com/gists") end def response response ||= conn.get do |request| request.headers['Authorization'] = "token #{@token}...
class AddDeckIndexToGameObjects < ActiveRecord::Migration def change add_column :game_objects, :deck_index, :integer end end
# A full-text extractor trained on http://krdwrd.org/ # https://krdwrd.org/trac/attachment/wiki/Corpora/Canola/CANOLA.pdf # Works well with SimpleEstimator, too. module Boilerpipe::Filters class CanolaClassifier def self.process(doc) return doc if doc.text_blocks.size < 1 empty = Boilerpipe::Documen...
class Lesson < ApplicationRecord validates :name, presence: true, format: { with: /\A[a-zA-Z0-9 ]+\z/ } belongs_to :company end
Rails.application.routes.draw do devise_for :admin_users, ActiveAdmin::Devise.config devise_for :users ActiveAdmin.routes(self) get 'pages/about' get 'pages/contact' get 'posts/index' root 'posts#index' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.ht...
Rails.application.routes.draw do mount PointlessFeedback::Engine => "/pointless_feedback" root :to => 'home#index' end
class CategoriesController < ApplicationController include ApplicationHelper # include methods from application_helper.rb def index categories = Category.all render json: categories end def show category = Category.find(params[:id]) user = User.find(params[:userID]) items = category.items items.each ...
require 'faraday' require 'faraday_middleware' require "addressable/uri" class HttpFile attr_reader :path def initialize(client, path, all) @client = client @path = path @all = all end def work_to_do?(suffix) res = @path.end_with?(suffix) return false if res res = @all.include?(flag_pa...
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :service_item do category nil item "MyString" price "9.99" end end
# frozen_string_literal: true Rails.application.routes.draw do namespace :api, { format: 'json' } do get "fetch_a_page_of_posts", to: "fetch_posts#fetch_a_page_of_posts" get "get_new_post", to: "get_new_post#get_new_post" get "get_post_image_url", to: "get_new_post#get_post_image_url" end namespac...
require 'spec_helper' feature 'Organization admin watches entry profile' do scenario 'that shows the entry deatails' do user = create :user, name: 'Juanito' member = create :member, user: user organization = create :organization challenge = create :challenge, title: 'Reto 1', organization: organizat...
package 'java-1.7.0-openjdk' package 'maven' service 'rpcbind' do action [:enable, :start] end remote_file '/etc/yum.repos.d/ambari.repo' do source 'http://public-repo-1.hortonworks.com/ambari/centos7/2.x/updates/2.2.2.0/ambari.repo' not_if { ::File.exists?('/etc/yum.repos.d/ambari.repo') } end package 'ambari-...
FactoryGirl.define do factory :feedback do request nil customer_name 'customer name' customer_email 'john@example.com' project_name 'project name' feature_name 'feature name' details 'details' rate 5 end end
class Subscription < ActiveRecord::Base belongs_to :course belongs_to :user monetize :amount_cents end