text
stringlengths
10
2.61M
# frozen_string_literal: true require_relative 'test_helper' describe Board do let(:board) { Board.new } subject { :board } describe 'when initalized' do it 'should be an instance of Board' do board.must_be_instance_of Board end it 'should have an empty board' do board.empty?.must_equal...
describe 'Fazer validacao na resposta da aquisicao' do context "Enviando dados API de Post HTTParty" do # before e uma pre-condicao para validacao dos testes # iremos colocar aqui como pre-condicao do envio da requisiçao Post # o before será executado sempre antes de cada teste inciar ...
require 'rails_helper' RSpec.describe Test, type: :model do let(:author) do User.create!( first_name: "Bob", email: 'bob@google.com', password: "123456" ) end let(:categories) do Category.create!( [ { title: "General", id: 1 }, { title: "Web Development", id: 2 } ] ...
class Api::StudentCategoriesController < ApiController filter_access_to :all def index @xml = Builder::XmlMarkup.new @student_categories = StudentCategory.active respond_to do |format| format.xml{ render :student_categories} end end end
describe TransactionService::Process do let(:process) { TransactionService::API::Process.new } describe "#get and #create" do it "returns with single process" do id_1 = process.create(community_id: 111, process: "none", author_is_seller: false).data[:id] id_2 = process.create(community_id: 222, pro...
class Art < ApplicationRecord mount_uploader :image_url, ImageUploader belongs_to :user has_many :comments has_many :images has_many :likes end
class DevicesAddSubbedTournamentsMatches < ActiveRecord::Migration def change add_column :gcm_devices, :subbedTournaments, :string add_column :gcm_devices, :subbedMatches, :string end end
require 'openssl' require 'digest' # AES-256 cryptographic helper class # based on https://gist.github.com/RiANOl/1077760 class CryptoHelper def initialize(key) @key = key @iv = key.reverse end def aes256_cbc_encrypt(data) if data.size != 0 key = Digest::SHA512.digest(@key) if (@key.kind_of?(...
# frozen_string_literal: true require 'spec_helper' require_relative '../../controllers/urls_controller' RSpec.describe UrlsController, :redis_required do let(:redis) { Redis.new(host: ENV['REDIS_HOST'], port: ENV['REDIS_PORT']) } let(:response) { Struct.new(:status, :headers, :body).new(*subject) } describe '...
require File.expand_path('../helper', __FILE__) class AldebaranTest < Test::Unit::TestCase it 'creates a new Aldebaran::Base subclass on new' do app = Aldebaran.new do get '/' do 'Hello World' end end assert_same Aldebaran::Base, app.superclass end it "responds to...
# coding: utf-8 class MatvaranCleaner < BaseCleaner def clean(raw_product) base_product(raw_product).tap do |product| product.assign_attributes( raw_product: raw_product, barcode: raw_product.barcode, img_urls: raw_product.img_urls, name: name(raw_product), name_secon...
class AddAttachmentsDocumentToConcept < ActiveRecord::Migration def self.up add_column :concepts, :document_file_name, :string add_column :concepts, :document_content_type, :string add_column :concepts, :document_file_size, :integer add_column :concepts, :document_updated_at, :datetime end def se...
require 'Open3' class SystemClient CliResult = Struct.new :stdout, :stderr, :status do def success? status.success? end def failure? !success? end end def self.run(command, args:) args = args.map(&:to_s) opts = {} CliResult.new(*Open3.capture3(command, *args, **opts)) ...
# Alex's extensions for Enumerable, Array, and Hash module Enumerable #******************************************************* # ARRAY METHODS # Array has some useful methods which Enumerable doesn't # So let's even things up a bit #******************************************************* def empty? e...
# frozen_string_literal: true require_relative "address" require_relative "phone_number" module Redox module Models class Contact < Redox::Model redox_property :FirstName redox_property :MiddleName redox_property :LastName redox_property :Address, coerce: Address redox_property :Ph...
module Capstrap class CLI < Thor def initialize(*) super end default_task :help desc "version", "Version of capstrap" def version puts "capstrap v#{Capstrap::VERSION}" end desc "hostname HOST", "Sets the FQDN on remote SSH host HOST" def hostname(ssh_host) ...
# encoding: utf-8 require File.expand_path("../spec_helper", __FILE__) describe "TableRows" do before :each do browser.goto(WatirSpec.files + "/tables.html") end describe "#length" do bug "WTR-354", :watir do it "returns the correct number of cells (table context)" do browser.table(:id, '...
class Message < ActiveRecord::Base belongs_to :chatroom validates :chatroom_id, presence: true, :on => :create validates :volunteer_id, presence: true, :on => :create validates :content, presence: true, :on => :create end
module Gibbon class APIRequest include Helpers def initialize(builder: nil) @request_builder = builder end def post(params: nil, headers: nil, body: nil) validate_api_key begin response = self.rest_client.post do |request| configure_request(request: request, para...
class Array def same_values? self.uniq.length == 1 end end module GameRules $empty_cell = [" "] def valid_placement?(cell) return cell == $empty_cell end def winning_line?(board) board.each do |line| if line.all? { |cell| cell == $empty_cell } return false end if...
# # Copyright 2012 Stormpath, 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 wri...
#============================================================================== # Enemy Stat Variance # Version: 1.0 # Author: modern algebra (rmrk.net) # Date: January 4, 2012 #++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Description: # # This script allows you to at...
class User < ActiveRecord::Base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable devise :omniauthable, :omniauth_providers => [:facebook, :twitter] validates_presence_of :email def self.new_with_session(params, session) super.tap do |user| ...
# encoding: utf-8 require 'chefspec' require_relative '../spec_helper' require 'fauxhai' describe 'ffmpeg::default' do let(:chef_run) { ChefSpec::SoloRunner.new } before do chef_run.converge(described_recipe) end it 'includes the ffmpeg install recipe' do expect(chef_run).to include_recipe("ffmpe...
class AddReplyToToNotes < ActiveRecord::Migration def change add_column :notes, :reply_to, :integer add_column :notes, :parse_to, :integer end end
# State class holds entities and services and attaches to a Game class State # Include the GameObject instance methods include GameObject # The list of services on this State attr_reader :services # The list if entities on this State attr_reader :entities def initialize(name) @services = [] @ent...
class User < ActiveRecord::Base has_many :responses has_many :created_surveys, :class_name => "Survey", :foreign_key => :creator_id validates :name, uniqueness: true end
class Notifier < ApplicationMailer def self.report_load_event(event) admin_addresses.each { |email_addr| send_msg(email_addr, event.subject_line, event.email_message).deliver_now } end def self.report_user_event(event_type, user) admin_addresses.each { |email_addr| send_user_event_msg(email_ad...
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 helper_method :current_user helper_method :current_avatar helper_method :background_image helper_method :eggs ...
class UserMailer < ActionMailer::Base include Sprockets::Helpers::RailsHelper include Sprockets::Helpers::IsolatedHelper layout 'email' default from: "claco <support@claco.com>" def request_invite(email) mail(from: "Eric Simons <support@claco.com>", to: email, subject: "Thanks for requesting an invite to Claco...
class AddOwnerToNodeGroups < ActiveRecord::Migration def self.up add_column "node_groups", "owner", :string add_index :node_groups, :owner end def self.down remove_column "node_groups", "owner" end end
# 多層パーセプトロンネットワークによるカテゴリ分類器 $: << File.join(File.dirname(__FILE__), "..") require "mlp_classifier" require "bigram_tokenizer" require "dictionary" class MlpCategorizer def initialize(tokenizer, hash = {}) @tokenizer = tokenizer @category_dictionary = Dictionary.new(hash[:category_dictionary] || {}) @f...
class UserState < ActiveRecord::Migration def change add_column :users, :state, :string, :default => "store" end end
require "rubygems" require "bundler/setup" require "sinatra" require 'time_difference' require 'pony' require File.join(File.dirname(__FILE__), "environment") configure do set :views, "#{File.dirname(__FILE__)}/views" set :show_exceptions, :after_handler end configure :production, :development do enable :loggin...
FactoryGirl.define do factory :tag_implication do antecedent_name "aaa" consequent_name "bbb" after_create do |tag_implication| tag_implication.process! end end end
class Anagram attr_accessor :word def initialize(word) @word = word end def match(words) word_sorted = @word.chars.sort.join matches = [] words.each do |word| if word.chars.sort.join === word_sorted matches << word end end matches end e...
# frozen_string_literal: true module FileReaderTest module Lineno def test_a_new_file_is_at_lineno_0 assert_equal 0, new_file.lineno end def test_lineno_can_be_set_manually @file.lineno = 42 assert_equal 42, @file.lineno end def test_cannot_get_lineno_when_closed assert...
# frozen_string_literal: true require 'test_helper' module Vedeu module Cells describe BottomRight do let(:described) { Vedeu::Cells::BottomRight } let(:instance) { described.new } describe '#as_html' do subject { instance.as_html } it { subject.must_equal('&#x2518;') } ...
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :booking do cart item responsible_name "MyString" name_at_checkout "TODO" confirmed false adults 1 quantity 1 factory :complete_booking do item { FactoryGirl.create(:complete_item...
require File.dirname(__FILE__) + '/test_helper' require File.dirname(__FILE__) + '/models' class ActsAsCSVVImportableTest < Test::Unit::TestCase def setup @def_file = File.open(File.dirname(__FILE__) + '/default_template_test.csv') @user_defined_file = File.open(File.dirname(__FILE__) + '/user_defined_...
class AeropuertosController < ApplicationController # before_action :set_ciudad, only: [:show, :edit, :update, :destroy] before_action :authorize respond_to :html def index @aeropuertos = Aeropuerto.search(params[:search]).page(params[:page]).per_page(20) respond_to do |format| format.html ...
class RegistrationsController < Devise::RegistrationsController def update @products = Product.find(:all) @user = User.find(params[:id]) redirect_to user_path(@user) end end
WINNING_LINES = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + # rows [[1, 4, 7], [2, 5, 8], [3, 6, 9]] + # cols [[1, 5, 9], [3, 5, 7]] # diagonals INITIAL_MARKER = ' ' PLAYER_MARKER = 'X' COMPUTER_MARKER = 'O' def clear_screen system('clear') || system('cls') end def prompt(msg) puts "=> #{...
class City include Mongoid::Document field :name, type: String belongs_to :state end
class DeleteApprovalsWithoutProposals < ActiveRecord::Migration def up execute <<-SQL DELETE FROM approvals WHERE proposal_id is null; SQL end end
class Kf5Kate < Formula desc "Advanced KDE Text Editor" homepage "http://kate-editor.org" url "https://download.kde.org/stable/applications/17.08.0/src/kate-17.08.0.tar.xz" sha256 "34eee6c384e2c2776c7d0ab65e7217e730cdbdecb82578c9dc90380cb82affd2" head "git://anongit.kde.org/kate.git" depends_on "cmake" =>...
module Tweet def self.get_mood(handle) begin tweets = get_tweets(handle) mood(tweets) rescue false end end private def self.get_tweets(handle) options = { count: 200, include_rts: false } if $client.user(handle) $client.user_timeline(handle, options).map {|...
class ApplicationController < ActionController::Base include SessionsHelper before_action :load_authorization_into_gon def load_authorization_into_gon if user_signed_in? gon.push({ current_user_id: current_user.id, current_user_full_name: current_user.full_name, current_user_rol...
# frozen_string_literal: true module Sleet class FetchCommand def initialize(config) @config = config end def do! repo.validate! error_messages = [] fetchers.map do |fetcher| begin fetcher.do! rescue Sleet::Error => e error_messages << e.messag...
module BulutfonSDK module Helpers module DataHelper ## # Convert hash to object def convert_to_obj(hash) open_struct = OpenStruct.new set_open_struct_variables( open_struct, hash ) open_struct end ## # Set hash variable to open_struct # Recursiv...
# frozen_string_literal: true module Vedeu module Coercers # Provides the mechanism to convert a value into a # {Vedeu::Views::Chars}. # # @api private # class Chars < Vedeu::Coercers::Coercer # @return [Vedeu::Views::Chars] def coerce end private # @return ...
require 'rails_helper' include AdminHelpers include ActiveSupport::Testing::TimeHelpers RSpec.feature 'Checking employees birthdays' do before do travel_to Time.zone.parse('2019-02-20') @hr = create(:hr) assign_permission(@hr, :read, Employee) assign_permission(@hr, :birthdays, Employee) assign_p...
require "spec_helper" describe "The editor's article list page" do include Capybara::DSL include Pharrell::Injectable injected :article_service, Persistence::ArticleService injected :clock, System::Clock before do Capybara.app = Tangent.new page.driver.browser.basic_authorize("admin", "admin") en...
class ProjectsController < ApplicationController before_filter :authenticate_user! def index @projects = Project.all respond_to do |format| format.html # index.html.erb end end # GET /projects/1/edit def edit @project = Project.find(params[:id]) @meta_data_gr...
class AddVerifyTriesToDocuments < ActiveRecord::Migration def change add_column :documents, :verify_tries, :integer, :default => 0, :after => :global_status end end
# cute_angles.rb # Write a method that takes a floating point number that represents an angle # between 0 and 360 degrees and returns a String that represents that angle in # degrees, minutes and seconds. You should use a degree symbol (°) to represent # degrees, a single quote (') to represent minutes, and a double qu...
module Flickr extend ActiveSupport::Concern def should_fetch? older? || Image.latest.blank? end def newest? !has_fetched_already? end def older? return true if Image.latest_url != remote_latest_url false end def remote_latest_url dump_image_url latest_image_info end def late...
module Lolita # All classes that want to use lolita for configuration should include this module. module Configuration # When Lolita::Configuration is included, it add hook for class <em>:after_lolita_loaded</em> and define class methods # <em>lolita</em> and <em>lolita=</em> and instance method <em>lolita...
class AnswersController < ApplicationController before_action :set_question def new @answer = Answer.new end def create @answer = @question.answers.new(answer_params.merge(user: current_user)) if @answer.save redirect_to question_path(params[:question_id]) else @errors = "You...
# frozen_string_literal: true class Invoice < ApplicationRecord belongs_to :customer belongs_to :merchant has_many :invoice_items, dependent: :destroy has_many :items, through: :invoice_items has_many :transactions, dependent: :destroy validates :customer_id, presence: true validates :customer, presence...
class AddIndexToDigestOnItems < ActiveRecord::Migration def change add_index :items, :digest end end
class ReviewsController < ApplicationController # movie_reviews GET /movies/:movie_id/reviews(.:format) reviews#index def index @movie = Movie.find(params[:movie_id]) @reviews = @movie.reviews # @reviews = Review.all end # POST /movies/:movie_id/reviews(.:format) ...
# frozen_string_literal: true module Pragma module Resource module Operation def self.included(klass) klass.include Dry::Transaction(container: Steps::Container, step_adapters: StepAdapters) end def model_klass [ root_namespace.join('::'), resource_namespace...
require 'yaml' class Tile attr_reader :neighbors, :location, :view, :is_bomb, :board def initialize(tile_options) @view = '*' @is_bomb = tile_options[:is_bomb] @board = tile_options[:board] @location = tile_options[:location] @magnitude = tile_options[:magnitude] end def is_bomb? @is_...
class Admin::QuestionsController < Admin::AdminController before_action :set_question, only: [:edit, :update] before_action :set_categories, except: [:index] def index @questions = Question.includes(:category).search(params).order("categories.name", "qn_text").paginate(:page => page_number, :per_page => 25) ...
class CreateGameObjects < ActiveRecord::Migration def change create_table :game_objects do |t| t.integer :room_id t.integer :user_id t.integer :deck_id t.integer :object_id t.string :object_type t.float :center_x t.float :center_y t.float :z_index t.float :ang...
# ./main.rb #!/usr/bin/ruby # TO DO: # Make print out of board def render(game_board) game_board.size.downto(0) do |disk| puts "#{'▄'*game_board[0][disk].to_i} #{'▄'*game_board[1][disk].to_i} #{'▄'*game_board[2][disk].to_i}" end end def game_instructions puts "Welcome to Tower of Hanoi!\nInstructions:\n...
class SessionsController < ApplicationController def new if current_user != nil redirect_to '/my-urls' end end def create @current_user = User.find_by_username(params[:username]) # If the user exists AND the password entered is correct. if @current_user && @current_user.authenticate(par...
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(:default, Rails.env) module PrefShimaneCms class Application < Rails::Application # Settings in config/environments...
case ENV['BROWSER'] when 'pg' BROWSER = :poltergeist Capybara.default_max_wait_time = 90 Capybara.register_driver :poltergeist do |app| Capybara::Poltergeist::Driver.new( app, inspector: true, js_errors: false, window_size: [1280, 1024], phantomjs_options: ['--ignore-ssl-errors=yes', '--ss...
require 'support/emulator' require 'support/emulation' module EmulationHelper EMULATOR_ENV_VAR = 'EMULATOR' def emulator Emulator.new(emulator_path) end def emulation_of(assembly) Emulation.new(emulator, assembly) end private def emulator_path ENV[EMULATOR_ENV_VAR] || raise("can’t f...
class UserScoreSynchronizer class << self def sync(user, music) Rails.logger.info('同期処理を開始します') user_id = user.user_id music_detail = get_music_detail(user_id, music.sega_music_id) user.reload music_detail['userMusicList'].each do |score| music_difficulty = get_music_difficul...
module Guidelines module AbiturData ABITUR_ATTRIBUTES = [ { url: 'bachelor', level: 'Бакалавриат', periods: [ { when: 'Не позднее 1 октября предшествующего года', attributes: [ { value: 'prie...
module Positionable extend ActiveSupport::Concern included do before_create :set_position end module ClassMethods attr_reader :ancestor_classname def positionable_ancestor(*attributes) parent_name = attributes.first @ancestor_classname = parent_name.to_s.freeze @touch_ancestor ...
class CreateItemSizes < ActiveRecord::Migration[5.2] def change create_table :item_sizes do |t| t.references :item, forign_key: true, null: false t.references :size, forign_key: true, null: false t.timestamps end end end
require 'spec_helper' describe Predictor do let(:predictor) { Predictor.new } let(:stock) { :AAPL } let(:search_term) { "Apple" } let(:search_term_2) { "iphone" } let(:search_term_3) { "ipad" } let(:search_term_3) { "macbook" } let(:stock_2) { :GOOG } let(:search_term_4) { "Google" } let(:search_te...
class Mhp2::DecoratorsController < ApplicationController def index @decorators = Mhp2::Decorator.all paginate json: @decorators end end
module Legion module Transport module Connection module SSL def settings Legion::Settings[:transport][:tls] || {} end def use_vault_pki? settings[:use_vault_pki] && Legion::Settings[:crypt][:vault][:connected] end def use_tls? settings[...
# == Schema Information # # Table name: products # # id :integer not null, primary key # name :string not null # price :decimal(, ) not null # created_at :datetime not null # updated_at :datetime not null # seller_id :intege...
#!/usr/bin/env ruby RANGE_MIN = 171309 RANGE_MAX = 643603 def check_digits(n) n.to_s.size == 6 end def check_range(n) n >= RANGE_MIN && n <= RANGE_MAX end def check_adjacency(n) result = false n.to_s.chars.reduce('0') { |prev, char| if prev == char result = true end char } return resul...
# Base class for all Resolvers module GraphQLServer class BaseResolver extend GraphQLServer::Errors cattr_accessor :batch_loader_classes self.batch_loader_classes = {} def self.field_aliases @field_aliases ||= {} end def self.alias_fields(aliases) field_aliases.merge!(aliases) ...
class UsersController < ApplicationController skip_before_action :login_require, only: :new def new session[:user_id] = User.line_login(params[:code]) redirect_to my_page_path, notice: 'ログインしました。' end def show @user = User.find(params[:id]) end end
class ItemsController < ApplicationController before_action :authenticate_user!, only: [:new, :create, :edit, :update, :destroy] before_action :item_find_params_id, only: [:show, :edit, :update, :destroy] def index @items = Item.all.includes(:user).order('created_at DESC') end def new @item = Item.n...
class CreateArticles < ActiveRecord::Migration def self.up create_table :articles do |t| t.column :faculty_id, :integer t.column :title, :string t.column :synopsis, :text, :limit => 1000 t.column :body, :text, :limit => 20000 t.column :published, :boolean, :default => false t.column :created_at, :datetime ...
require 'net/http' require 'hbase/operation/meta_operation' require 'hbase/operation/table_operation' require 'hbase/operation/row_operation' require 'hbase/operation/scanner_operation' module HBase class Client include Operation::MetaOperation include Operation::TableOperation include Operation::RowOper...
#!/usr/bin/env ruby # # This script gets some IAM information. # # The AWS SDK for Ruby is required. See https://aws.amazon.com/sdkforruby/ for # installation instructions. # # AWS account keys are loaded from a YAML file which has the following format: # access_key_id: <your access key id> # secret_access_key: <your s...
class User < ApplicationRecord has_secure_password belongs_to :district has_many :messages validates :email, presence: true, uniqueness: true validates_presence_of :password, :street_address, :state, :city, :name include DistrictFinder attr_accessor :state def state=(state) @state = State.find(st...
module Fission module PackageBuilder VERSION = Gem::Version.new('0.2.10') end end
class CreateWagons < ActiveRecord::Migration def change create_table :wagons do |t| t.string :wagon_type t.integer :number t.integer :up_places t.integer :lower_places t.integer :side_up_places t.integer :side_lower_places t.integer :seat_places t.timestamp...
require 'rails_helper' RSpec.describe Movie do describe 'relationships' do it {should belong_to :studio} it {should have_many :roles} it {should have_many(:actors).through(:roles)} end describe 'instance methods' do before :each do @studio_1 = Studio.create!(name: "Universal Pictures", loc...
class Author < ActiveRecord::Base validates :name, length: {minimum: 1}, presence: true validates_uniqueness_of :email end
class AddQuestionsToReflections < ActiveRecord::Migration def change add_column :reflections, :question, :string add_column :reflections, :question2, :string end end
# Author: David # Time Complexity: O(n) making the hash table, O(nlogn) sorting # Space Complexity: O(k), k is the number of different chars in string s # Language: Ruby # @param {String} s # @return {String} def frequency_sort(s) table = {} result = "" # Build a hash table s.each_char do |char| table[ch...
#!/usr/bin/env ruby require 'nokogiri' require 'open-uri' class ImgFixer def initialize (html_file_path, root_uri) @file = html_file_path @uri = root_uri end def fix_uri begin doc = Nokogiri::HTML(open(@file.to_s)) source = File.open(@file.to_s, "w") rescue puts "error_file" else doc.css('im...
# # Be sure to run `pod lib lint PoporNSView.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 = 'PoporNS...
require 'test_helper' class MacroMacrosTest < Test::Unit::TestCase test_variable, second_test_variable = [], '' define_method(:setup) do test_variable.clear second_test_variable.replace '' meta_test = Class.new(Test::Unit::TestCase) do macro :should_work_as_expected do should("jam some...
require 'rails_helper' RSpec.describe Admin::VideoContentsController do login_admin let(:video_content) { create(:video_content) } describe 'GET index' do it 'renders page' do get :index expect(response).to be_success end end describe 'GET new' do it 'renders page' do get :new...
class Comment < ActiveRecord::Base belongs_to :user belongs_to :report validates :body, presence: true end
# encoding: utf-8 lib = File.expand_path('../lib/', __FILE__) $:.unshift lib unless $:.include?(lib) Gem::Specification.new do |s| s.name = "phantom-static" s.version = "0.1" s.platform = Gem::Platform::RUBY s.authors = ["Callum Jones"] s.email = ["callum@callumj.com"] s.homepage ...
class RemoveColumnFromComments < ActiveRecord::Migration def change remove_column :comments, :user_id remove_column :comments, :prototype_id end end