text
stringlengths
10
2.61M
class CartController < ApplicationController def show @chest_items = chest_items end end
feature 'image search' do scenario 'logged in user can search for images and see the results on the page' do sign_up search expect(page).to have_css("img[src*='http://google.com/images/test']") end scenario 'logged in user can search using more than one word' do sign_up search(searchterm: 'Angry dog') ...
class AddItineraryToUsers < ActiveRecord::Migration def change add_column :users, :itinerary, :text end end
class IndexerJob < ApplicationJob queue_as :indexer def perform(klass_record) klass_record.__elasticsearch__.index_document end end
module Qualtrics::API class Division < BaseModel attribute :id attribute :organization_id attribute :creator_id attribute :name attribute :creation_date attribute :status attribute :response_counts attribute :division_admins # attribute :permissions ## # Make the model ser...
require_relative "piece" require_relative "steppingpiece" class King < Piece include SteppingPiece protected def move_dirs possible_directions = [] SteppingPiece.ALL.each {|k,v| possible_directions << v} possible_directions end end
feature 'Testing players can lose' do describe 'lose game when 0HP' do scenario 'at the start of the game' do sign_in_and_play 9.times do click_link 'Attack' click_link 'OK' end expect(page).to have_content "Andy Wins !!!" end end end
class Genre < ApplicationRecord has_many :song_genres has_many :songs, through: :song_genres end
# frozen_string_literal: true require 'rails_helper' RSpec.describe Subject, type: :model do describe 'Validations' do it { should validate_presence_of(:name).with_message('Name of the victim can\'t be blank.') } end end
require 'spec_helper' describe Mongoid::History::Tracker do before :each do class Element include Mongoid::Document include Mongoid::Timestamps include Mongoid::History::Trackable field :title field :body validates :title, presence: true if Mongoid::Compatibility::Ver...
# A260643 Start a spiral of numbers on a square grid, with the initial square # as a(1) = 1. a(n) is the smallest positive integer not equal to or previously # adjacent (horizontally/vertically) to its neighbors. See the Comments section # for a more exact definition. class Point attr_reader :x, :y attr_accessor...
module Invariant class Invariant def upper_bound(rank, n) raise "Implement me" end end class Biased < Invariant def initialize(epsilon) @epsilon = epsilon end def upper_bound(rank, n) 2 * @epsilon * rank end end class SingleTarget < Invariant def initialize(phi...
class ApplicationController < ActionController::API # 200 Success def response_success(class_name, action_name, data) render status: 200, json: { status: 200, message: "Success #{class_name.capitalize} #{action_name.capitalize}", data: data } end # 400 Bad Request def response_bad_request render status: 400...
class BikeResult < LegResult field :mph, as: :mph, type: Float def calc_ave self[:mph] = event.miles * 3600 / secs if event && secs end end
class VisitorsController < ApplicationController skip_before_filter :authenticate_user! around_filter :catch_not_found def search query = params[:search][:query] @product = Product.friendly.find(query.upcase) authorize @product redirect_to @product end private def catch_not_found...
class AddDeliveryNameToAddresses < ActiveRecord::Migration[5.2] def change add_column :addresses, :delivery_last_name, :string add_column :addresses, :delivery_first_name, :string add_column :addresses, :delivery_last_kana_name, :string add_column :addresses, :delivery_first_kane_name, :string end e...
# Class Warfare, Validate a Credit Card Number # I worked on this challenge [by myself, with: ]. # I spent [#] hours on this challenge. # Pseudocode # Input: credit card number as a string # Output: boolean true or false # Steps: # 1. Remove blanks/spaces in string # 2. Raise argument error if not 16 digits long # ...
# frozen_string_literal: true class CreateAllowedUsers < ActiveRecord::Migration[5.1] def change create_table :allowed_users, id: :uuid do |t| t.string :email end end end
class Section < ActiveRecord::Base attr_accessible :title, :course_id has_many :courses end
class AddManagerToSchoolController < ActiveRecord::Migration def change add_reference :school_controllers, :manager, index: true end end
require 'knuckle_cluster/agent' require 'forwardable' module KnuckleCluster class AsgInstanceRegistry extend Forwardable def initialize(aws_client_config:, asg_name:) @aws_client_config = aws_client_config @asg_name = asg_name end def agents @agents ||= load_agents end ...
class UserForm def self.create { "type" => "object", "properties": { "data": { "type" => "object", "properties" => { "attributes" => { "type" => "object", "properties" => { "first_name" => { "type" =>...
class ProductsController < ApplicationController layout 'admin' before_action :authenticate_user! before_action :load_user before_action :load_product, only: [:edit, :update, :show, :destroy] before_action :check_admin def index @products = Product.all end def new @product = Product.new end ...
class Vote include Mongoid::Document include Mongoid::Timestamps::Created field :_id, as: :ip field :date, type: Date, default: Date.today field :votes, type: Integer, default: 0 field :votes_today, type: Integer, default: 0 def vote?(today=Date.today) # update votes_today ...
#============================================================================== # ** TDS Title Image Stretch # Ver: 1.1 #------------------------------------------------------------------------------ # * Description: # This script automatically resizes the background images in the title screen # to fit the resolu...
class AddSummaryToNewsitems < ActiveRecord::Migration[4.2] def change add_column :newsitems, :summary, :text end end
class HomeController < ApplicationController before_action :authenticate_user!, only: [:show, :logout] def index #レディース @ladies_items = Item.eager_load(category: :parent).where(parents_categories:{parent_id:1}).limit(10).order(created_at: "DESC") #メンズ @mens_items = Item.eager_load(category: :parent...
require 'rails_helper' feature "Activate college" do scenario "valid token with valid admin information" do college = create(:college, status: 10) user = build(:user) visit activate_colleges_path(token: college.activation_token) fill_up_new_admin_form(user) expect(page).to have_content("#{use...
require 'redmine' require 'date' require 'active_support' require File.dirname(__FILE__) + '/lib/issues_controller_patch.rb' require 'dispatcher' Dispatcher.to_prepare :redmine_due_date_by_default do require_dependency 'issues_controller' IssuesController.send(:include, RedmineDueDateByDefault::Patches::IssuesCon...
require_relative 'instrument' class Musician def initialize(name, instrument) @name = name @instrument = instrument end attr_accessor :age def style if age > 20 or age < 30 and @instrument.tipe == 'Viento' style = 'Regge' elsif age < 40 and @instrument.tipe == 'Cuerda' style = '' elsif...
class BlogComment < ActiveRecord::Base belongs_to :commentable, polymorphic: true has_many :blog_comments, as: :commentable end
require 'spec_helper' describe 'users/charities/edit' do let(:charity) { create(:charity) } let(:user_policy) { ActiveCharityPolicy.new(charity) } before do view.stub(:user_policy).and_return(user_policy) user_policy.stub(:active?).and_return(true) assign(:charity, charity) end it "has titl...
require 'spec_helper' describe Supplier do subject {Factory.create(:supplier)} it { should validate_presence_of :name } it { should validate_uniqueness_of :name } it { should have_many(:invoices)} end
require 'spec_helper' describe Item do subject(:item) { Item.new } describe "validations" do it { should validate_presence_of :title } it { should validate_presence_of :ends_at } it { should validate_presence_of :published_at } end describe "images" do subject(:item) do Fabricate.build :...
class CreateUserFeelings < ActiveRecord::Migration[5.2] def change create_table :user_feelings do |t| t.references :feeling, type: :bigint,foreign_key: true t.references :user, type: :bigint,foreign_key: true t.timestamps end end end
require 'rails_helper' RSpec.describe UsersController, type: :controller do let(:user) { create(:user) } let(:valid_attributes) { FactoryGirl.build(:user).attributes } let(:invalid_attributes) { FactoryGirl.build(:user, email: nil).attributes } describe "GET #index" do before(:each) do s...
class ChangeAllIdsToPermalinks < ActiveRecord::Migration def change remove_column :products, :company_id add_column :products, :company_permalink, :string remove_column :staff_levels, :company_id add_column :staff_levels, :company_permalink, :string end end
class ShareholderAccountEntriesController < ApplicationController before_filter :authenticate_user! load_and_authorize_resource :account load_and_authorize_resource :shareholder_account_entry, :through => :account def show end def new @shareholder = current_user.shareholder_for_account(@account) ...
class Version < Sequel::Model plugin :timestamps, update_on_create: true plugin :auto_validations, not_null: :presence end
module Tasks # # CRUD service for tasks # # @author [nityamvakil] # class Crud def initialize(params = {}) @params = params end attr_reader :params def create schedule task = Task.create!(params) task end def update task = Task.find(params[:id]) task....
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Ch...
class Group < ActiveRecord::Base validates :group_name, :presence => true has_many :users end
# 課題や言語を設定する class Select # コンテスト設定ファイルを読み込む def initialize @config = TaskConfig.new end # 問題を設定する def select_task task_list = @config.get_task_list if task_list.length.zero? puts "[error] \e[31m no task.\e[0m" exit 1 end task_list.each_with_index do |task, i| puts "...
FactoryGirl.define do factory :user do |f| f.username { Faker::Name.first_name } f.email { Faker::Internet.email } f.password 12341234 f.avatar File.new("#{Rails.root}/app/assets/images/avatars/100cat.jpg") initialize_with { new(attributes) } end end
# descibe how you can use a single array to implement three stacks class ThreeInOne def initialize(length_stack, number_stacks) @length = length_stack @num_stacks = number_stacks @stack = Array.new(@length * @num_stacks) {nil} @location = Array.new(number_stacks) @num_stacks.times do |num| @...
# frozen_string_literal: true module ZoomSlack VERSION = "0.0.3" end
# Write in this file customization code that will get executed after all the # sources have beenloaded.
class Course include Mongoid::Document field :name, type: String field :schoolyear, type: String belongs_to :user has_many :students end
Pod::Spec.new do |s| s.name = "MLAudio" s.version = "1.0.0" s.summary = "MLAudio" s.homepage = "https://github.com/molon/MLAudio" s.source = { :git => "https://github.com/molon/MLAudio.git", :tag => "#{s.version}" } s.license = { :type => 'MIT'} s.author = { "molon" => "dudl@qq.com"...
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Object do describe "class attributes" do let(:object_class) { Jazz::Ensemble } it "tells type data" do assert_equal "Ensemble", object_class.graphql_name assert_equal "A group of musicians playing together", object_clas...
require 'rails_helper' describe "the sign out workflow" do it "signs out a user" do sign_in sign_out expect(page).to have_content "Sign In" end end
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html get '/auth/spotify/callback', to: 'users#spotify' get '/users/spotify', to: 'homes#index' get '/login', to: 'sessions#new' post '/login', to: 'sessions#create' delete '/logou...
# Copyright (c) 2015 Sean Quinn # # Licensed under the MIT License (http://opensource.org/licenses/MIT) # # Permission is hereby granted, free of charge, to any # person obtaining a copy of this software and associated # documentation files (the "Software"), to deal in the # Software without restriction, including with...
module ApplicationHelper def bootstrap_class_for(flash_type) { success: "alert-success", error: "alert-error", alert: "alert-danger", notice: "alert-info" }[flash_type.to_sym] || flash_type.to_s end def bootstrap_glyphs_icon(flash_type) { success: "glyphicon-ok...
require 'digest/md5' require 'active_support/core_ext/module/delegation' module Buckaroo module Ideal # # Digital signature generator for +Buckaroo::Ideal::Order+ instances. # # A digital signature is used to sign your request so the Buckaroo Payment # Service can validate that the request was ma...
class ImageRegistry attr_accessor :images_path def initialize(window, images_path) @images = {} @window = window @images_path = images_path end def image(path) if @images[path] @images[path] else image_path = File.join(ROOT_PATH, File.join(images_path, path)) @images[path...
require 'test_helper' class ReviewCoinTransactionTest < ActiveSupport::TestCase # test "the truth" do # assert true # end include Coin def setup @user = User.create(name: 'aaa', email: 'aaa@aaa.com', password: 'aaaaaa') @from = User.create(name: 'bbb', email: 'bbb@bbb.com', password: 'bbbbbb') ...
class DashData def initialize(dq_id) @dq = DashboardQuery.where(:dashboard_id => dq_id).first @client = Mysql2::Client.new(dbconfig.symbolize_keys) @query_data = @client.query(@dq.query) end def dbconfig YAML::load(File.open("#{Rails.root}/config/dashdata.yml"))['dashdata'] end private :dbco...
module CDI class BaseCrudService < BaseService include ::CDI::ServiceConcerns::Cacheable attr_reader :record def self.record_type(record_type, options={}) record_alias = options.delete(:alias_name) || record_type.to_s.underscore alias_method record_alias.to_sym, :record class_eval %...
class PartiesController < ApplicationController before_action :set_party, only: [:show, :edit, :update, :destroy] def index @parties = Party.all end def show members = Member.all @not_participated_members = [] members.each do |member| if !member.party_ids.include?(@party.id) @not...
gem 'minitest', '~> 5.2' # => true require 'minitest/autorun' # => true require 'minitest/pride' # => true require_relative '../lib/grade_book' # => true require_relative '../lib/student' # => true require_relative '../lib/report_card' # => true class IntegrationTest < M...
require 'spec_helper' describe RoadsController do render_views describe "GET to index" do before do @road1 = Road.make!(:road1, :created_at => "2012-01-01 01:01:01") 9.times { Road.make!(:road1, :created_at => "2012-02-01 01:01:01") } @road2 = Road.make!(:road1, :created_at =...
class PlayerPresenter < ApplicationPresenter def initialize(object, limited: false) @object = object @limited = limited end def as_json(*) return limited_view if @limited { id: @object.id, username: @object.user.username, game_id: @object.game_id, user_id: @object.user_id,...
# frozen_string_literal: true require 'minitest/autorun' require 'minitest/spec' require 'flatten' describe Flatten do let(:flatten) { Flatten.new } describe 'processes valid array' do let(:result) { flatten.process(array) } describe 'flat array' do let(:array) { [1, 2, 3] } it 'returns the...
ActiveAdmin.register Puppypicture do index do column "file" do |post| image_tag post.file.thumb.url end column :id column :info column :puppy column :created_at default_actions end end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_action :detect_device_variant private def detect_device_variant case request.user_agent when /Coffe...
require_relative './init' RSpec.configure do |config| config.include FactoryGirl::Syntax::Methods end describe HelperPointChecker do before do IntegrationSpecHelper.InitializeMongo() @sut = HelperPointChecker.new end before(:each) do HelperPoint.destroy_all HelperRequest.destroy_all end c...
Rails.application.routes.draw do get '/', to: 'dogs#index' # auth routes get '/signup', to: 'dogs#new', as: 'signup' post '/signup', to: 'dogs#create' get '/login', to: 'sessions#new', as: 'login' post '/login', to: 'sessions#create' delete '/logout', to: 'sessions#destroy', as...
ActiveAdmin.register User do permit_params :name, :state, :email config.per_page = 10 batch_action :Activate do |ids| batch_action_collection.find(ids).each do |user| if(user.state == 'inactive') user.update(state: 'active') end end redirect_to collection_path, alert: 'Activated S...
class Numeric @@currencies = {'yen' => 0.013, 'euro' => 1.292, 'rupee' => 0.019, 'dollar' => 1} def method_missing(method_id, *args) singular_currency = method_id.to_s.gsub( /s$/, '') if (method_id == :in) singular_currency1 = args[0].to_s.gsub( /s$/, '') if @@currencies.has_key?(singul...
#!/usr/bin/env ruby # This script prepares a dataplane environment on vlan 2 by building a subnet # 172.16.0.1/24, assigning 172.16.0.2 and .3 to policies that provide # unfettered access, and by installing a forward of tcp and udp ports 23232 # and 23233 to 172.16.0.3 (the data interface). # # This all assumes: # ...
require_relative 'helper' H = Docdo::StaticHash class TestHash < Test def test_immutable h = H.new assert_raises NoMethodError do h[:foo] = :foo end assert_equal 0, h.length h.each do |k,v| flunk "There should not be any keys" end end def test_population h1 = H.new sym: :alph, int:42 assert_eq...
class User < ActiveRecord::Base acts_as_authentic do |c| c.crypto_provider = Authlogic::CryptoProviders::Sha512 c.merge_validates_length_of_login_field_options :within => 2..100 c.validate_email_field = false end end
class CraftOrder < ActiveRecord::Base belongs_to :craft, :inverse_of => :craft_orders belongs_to :order , :inverse_of => :craft_orders accepts_nested_attributes_for :craft, :reject_if => lambda { |a| a[:quantity].blank?} end
def fromRoman(romanNumber) nums = { "M" => 1000, "CM" => 900, "D" => 500, "CD" => 400, "C" => 100, "XC" => 90, "L" => 50, "XL" => 40, "X" => 10, "IX" => 9, "V" => 5, "IV" => 4, "I" => 1 } number = romanNu...
class Role < ActiveRecord::Base attr_accessible :name, :description validates_presence_of :name, :on => :create validates_presence_of :description, :on => :create has_and_belongs_to_many :users end
# # Cookbook Name:: base # Recipe:: default # # Copyright 2015, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute # include_recipe 'java' include_recipe 'screen' group 'minecraft' user 'minecraft' do system true comment 'Minecraft Server' home '/home/minecraft' gid 'minecraft' action :create ...
# -*- mode: ruby -*- # vi: set ft=ruby : require 'win32ole' file_system = WIN32OLE.new("Scripting.FileSystemObject") drives = file_system.Drives playbook = ENV['PLAYBOOK_OVERRIDE'] || "ansible/setup-docker.yml" requirements = ENV['REQUIREMENTS_OVERRIDE'] || "ansible/requirements.yml" Vagrant.configure("2") do ...
# -*- encoding: utf-8 -*- require File.expand_path('../lib/q_translate/version', __FILE__) Gem::Specification.new do |gem| gem.name = "q_translate" gem.authors = ["Mathieu Gagné"] gem.email = ["gagne.mathieu@hotmail.com"] gem.description = %q{Extends String with a 'translate' method. R...
class WikiPageSerializer < ActiveModel::Serializer attributes :name, :relative_path end
Rails.application.routes.draw do root 'main#index' scope ':locale', locale: /#{I18n.available_locales.join("|")}/ do root 'main#index' end root to: redirect("/#{I18n.default_locale}", status: 302), as: :redirected_root # For details on the DSL available within this file, see http://guides.rubyonrails....
require 'net/http' require 'uri' require 'cgi' require 'json' class Client SCOPES = %w(commands usergroups:read users:read) class << self def get(method, params = {}) query_string = CGI.unescape(params.to_query) url = [path(method), query_string].join('?') uri = URI.parse(url) respon...
# # Copyright 2013, Seth Vargo <sethvargo@gmail.com> # Copyright 2013, CustomInk, LLC # # 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 # # Un...
class OrderSummariesController < ApplicationController helper_method :sort_column, :sort_direction before_action :logged_in_using_omniauth?, :except => [:login] before_action :set_order_summary, only: [:show, :edit, :update, :destroy] # GET /order_summaries # GET /order_summaries.json def index @orde...
class ChangeCakeCuttingAnnounceToStringInReceptions < ActiveRecord::Migration def change change_column :receptions, :cake_cutting_announce, :string end end
# RAILS_TEMPLATE # This is Ruby on Rails application template # USAGE # To initialize new app with rails_template run: # # rails new <app_name> -d postgresql --skip-bundle -m <template_location> # -------------------- GEMS --------------------------------------------- # Copy prebuild Gemfile form template_files ru...
module RiksbankCurrency # Get the latest rates that will be correct for the current day. # # @see https://swea.riksbank.se/sweaWS/docs/api/call/getLatestInterestAndExchangeRates.htm class TodayFetcher def rate_date @rate_date ||= begin response.xpath("//resultrows/date").map do |date...
class AlbumsController < ApplicationController layout false def index @albums = matching_albums end private def matching_albums RSpotify::Album.search(search_params.values.join(' ')).map do |album| Album.new(album) end end def search_params params.permit(:artist, :album) end en...
# frozen_string_literal: true require "cell/partial" module Decidim module Opinions # This cell renders the link to the published opinion of a collaborative draft. class CollaborativeDraftLinkToOpinionCell < Decidim::ViewModel def show render if opinion end private def opin...
require_relative '02_searchable' require 'active_support/inflector' require 'byebug' # Phase IIIa class AssocOptions attr_accessor( :foreign_key, :class_name, :primary_key ) def model_class class_name.constantize end def table_name class_name.downcase + 's' end end class BelongsToOp...
#encoing: utf-8 module Service module FriendService class Recommend # 某用户的推荐好友 SNS_FRIEND = { 'tencent' => '::SnsProviders::Tqq2', 'qq' => '::SnsProviders::Tqq2', 'weibo' => '::SnsProviders::SinaWeibo', 'sina' => '::SnsProviders::SinaWeibo', 'douban' =>...
class CreateCollectionMasterParticularReports < ActiveRecord::Migration def self.up create_table :collection_master_particular_reports do |t| t.integer :financial_year_id t.integer :student_id, :null => false t.integer :collection_id, :null => false t.string :collection_type, :null => fals...
FactoryGirl.define do factory :trade do rate_comparison direction Trade::DIRECTIONS.sample enter_rate 1.0 exit_rate nil interest_rate Trade::INTEREST_RATES.sample closed_at nil end end
class EasyRsa < Formula desc "Homebrew formula for `easy-rsa`" homepage "https://github.com/OpenVPN/easy-rsa" head "https://github.com/OpenVPN/easy-rsa.git" depends_on "openssl" def install share.install %w( easyrsa3/easyrsa easyrsa3/openssl-easyrsa.cnf easyrsa3/vars.example ) ...
# ObjectFactory # ============= # # Factory class to help reconcile source data and the target schema. # # By providing a JSON schema, that describes the relationships between # objects when traversing the message structure, we can prepare an object # for sending. require 'jsonpath' class Fn::Salesforce::ObjectFact...
resource_name :postgresql_fdw_user_mapping property :server_name, String, name_property: true property :db_user, String property :db_name, String property :external_user, String property :external_password, String property :helper, default: PgHelper.new(node) action :create do postgresql_query "create mapping for #...
require 'fileutils' require 'net/ftp' require 'zip' require 'csv' module Itrp module Export module Monitor class Exchange attr_accessor :options, :fullpath, :basename def initialize(export_filename, options) @options = options @options[:to_ftp_dir].gsub!('\\', '/') ...
class DataController < ApplicationController before_filter :authenticate # GET /data/1 # GET /data/1.json def show end # POST /data # POST /data.json def create Resque.enqueue(DataImporter) respond_to do |format| format.html { redirect_to root_url, notice: 'Task accepted! Data Processi...
class MixController < ApplicationController def index @mixes = Mix.all end end
class FranchisesController < ApplicationController # GET /franchises # GET /franchises.json skip_before_filter :verify_authenticity_token before_filter :get_franchise_set respond_to :html, :json def index @franchises = @franchise_set.franchises.all respond_with(@franchise_set, ...