text
stringlengths
10
2.61M
# require 'pry' # def multiply_list(array1, array2) # index = 0 # array3 = [] # loop do # # binding.pry # array3 << (array1[index].to_i * array2[index].to_i) # break if array3.count == array2.count # index += 1 # end # p array3 # end def multiply_list(array1, array2) array1.zip(array2).m...
require "rails_helper" feature "rescheduling a Task", js: true do scenario "Identity reschedules a Task" do given_i_have_an_assigned_a_task when_i_reschedule_the_task then_i_should_see_the_task_has_been_rescheduled end def given_i_have_an_assigned_a_task @identity = Identity.first create_li...
Pod::Spec.new do |s| s.name = "SPHStringContentFillView" s.version = "0.2.3" s.summary = "A view that fills itself with customizable string content." s.description = <<-DESC A view subclass that fills itself with multiple copies of a customizable string...
class Bonuse include Mongoid::Document field :used_id, type: Integer field :fio, type: String field :birthday, type: String field :bonuses, type: Array, default: [] end
require 'rails_helper' RSpec.describe Ingredient, type: :model do it { should validate_presence_of(:name) } it { should validate_length_of(:name) } it { should validate_length_of(:calories).is_at_most(5) } it { should have_many(:uses) } it { should belong_to(:user) } it { should validate_uniqueness_of(:nam...
module Yandex module Market class Region def self.path(id) case id when Integer "geo/regions/#{id}" else 'geo/regions' end end end end end
json.array!(@pictures) do |picture| json.id picture.id json.title picture.title json.description picture.description json.image_url_small picture.img_url.url(:small) json.image_url_big picture.img_url.url(:big) json.views picture.views json.username picture.user.username json.likes picture.like_count ...
module SchoolStats class DataRow attr_reader :attributes_hash,:data_entity def initialize (row,data_entity) @attributes_hash =(row.present?? (row.class==Hash ? row : row.attributes) : {}) # @attributes_hash = row.attributes @data_entity = data_entity end def read (field_...
# This already has a class description elsewhere. class Yukari # Representation of an ad. class Ad attr_reader :words, :price_string, :price, :location def initialize(words, price_string, price, location) @words = words # STDERR.puts "Size is #{@words.size}" @price_string = price_string ...
class AddNotNullToAvailabilitiesDay < ActiveRecord::Migration[5.1] def change change_column :availabilities, :day, :integer, null: false end end
class Outfit < ApplicationRecord belongs_to :user has_many :clothing_outfits, dependent: :delete_all has_many :clothings, through: :clothing_outfits end
module Mission class ChaosMonkey NO_ERROR = -1 def initialize(random_generator, number_stages, flight_distance, auto_abort_rate, auto_explode_rate) @random = random_generator @valid_abort_options = number_stages @valid_explostion_distance = flight_distance @auto_abort_rate = auto_abo...
class Photo < ActiveRecord::Base belongs_to :user has_many :groups has_many :categories end
module UrnHelper def urn_page_entries_info(collection, metadata, entry_name: nil) entry_name = entry_name.pluralize(collection.size) if metadata[:total_pages] < 2 t('helpers.page_entries_info.one_page.display_entries', entry_name: entry_name, count: metadata[:total]) else from = metadata[:off...
require "includes" class PatternTest < Minitest::Test SAMPLE_RATE = 44100 SECONDS_IN_MINUTE = 60.0 def generate_test_data test_patterns = {} pattern = Pattern.new :blank test_patterns[:blank] = pattern verse_tracks = [ Track.new("bass.wav", "X...X...X...XX..X...X...XX..X..."), ...
# require_relative 'sample_text' require_relative 'text' require 'minitest/autorun' class TextTest < Minitest::Test def setup @paragraph = File.open('sample_text.txt') @text = Text.new(@paragraph.read) end def test_swap assert_equal("Lorem ipsum dolor sit emet, consectetur edipiscing elit. Cres sed vulputet...
require_relative "code" class Mastermind def initialize(length) @secret_code = Code.random(length) end def print_matches(other_code) puts "exact matches: #{@secret_code.num_exact_matches(other_code)}" puts "near matches: #{@secret_code.num_near_matches(other_code)}" end ...
class CreateMessOrders < ActiveRecord::Migration def change create_table :mess_orders, :options => 'COLLATE=utf8_unicode_ci' do |t| t.string :oname t.string :omobile t.text :ocontent t.string :kapcha t.timestamps end end end
module Fog module Parsers module Vcloud module Terremark module Ecloud class GetInternetServices < Fog::Parsers::Vcloud::Base def reset @response = Struct::TmrkEcloudList.new([]) @in = nil @public_ip = nil end ...
require_relative 'database' require_relative 'questions' class Question_Follow def self.all data = QuestionsDatabase.instance.execute("SELECT * FROM question_follows") data.map {|data| Question_Follow.new(data)} end def initialize(options) @id = options['id'] @question_id = options['question_i...
VALID_CHOICES = ['Rock', 'Paper', 'Scissors'] def prompt(message) Kernel.puts(">> #{message}") end def win?(first, second) (first == "Rock" && second == "Scissors") || (first == "Scissors" && second == "Paper") || (first == "Paper" && second == "Rock") end def display_results(player, computer) if win?(...
class ClientTransactionsController < ApplicationController # GET /client_transactions # GET /client_transactions.json def index @client_transactions = ClientTransaction.all respond_to do |format| format.html # index.html.erb format.json { render json: @client_transactions } end end #...
# Amend this array so that the names are all shortened to just the first three characters: flintstones = %w(Fred Barney Wilma Betty BamBam Pebbles) flintstones.map! { |word| word[0,3] }
class Post < ActiveRecord::Base validates :url, presence: true, uniqueness: true validates :title, presence: true validates :body, presence: true validates :published_at, presence: true belongs_to :blog has_many :pictures end
class ProjectMemberSerializer < ApplicationSerializer attributes :id, :project_id, :member_id, :member_role, :created_at, :updated_at belongs_to :member_profile, serializer: MemberProfileSerializer end
module SectionsHelper def belongs_to_section?(behandeling, section) behandeling.category_id == section.category_id end end
class DropUserRaces < ActiveRecord::Migration[5.0] def change drop_table :user_races end end
module Bases class AutenticacaoDatabaseMysql < ActiveRecord::Base self.abstract_class = true establish_connection :development_mysql end end
describe "HPBookSet" do it "prices sets correctly" do set = HPBookSet.new set.add(:book1) expect(set.cost).to eq 800 set.add(:book2) expect(set.cost).to eq 1520 set.add(:book3) expect(set.cost).to eq 2160 set.add(:book4) expect(set.cost).to eq 2560 set.add(:book5) expect(s...
#Basic Options Menu v1.3d #----------# #Features: Provides a simple option menu for the player to do optiony stuff... # Like volume effects for all, bgm, and se's. Fancy! # # Also additional options if you have Basic Window Resizer, # Basic Message SE, and Basic Autosave. # #Usage...
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root to: 'static_pages#root' namespace :api, default: {format: :json} do resources :users, only: :create resource :session, only: [:create, :destroy] resources :animes...
class AddSuperuserRole < ActiveRecord::Migration def self.up Role.create(:name => "superuser") end def self.down Role.find_by_name("superuser").destroy end end
require "test_helper" describe VideosController do VIDEO_FIELD = ["overview", "title", "release_date", "available_inventory", "total_inventory"].sort describe "index" do it "must get index for videos" do get videos_path must_respond_with :ok expect(response.header["Content-Type"]).must_inclu...
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module MobileCenterApi module Models # # Basic information on a release # class BasicReleaseDetails # @return [Float] ID iden...
# Copyright 2012-2013 Red Hat, 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 w...
module ZillowReport def self.table_name_prefix 'zillow_report_' end end
class Event < ApplicationRecord validates :date, presence: true validates :start_time, presence: true validates :end_time, presence: true validates :venue, presence: true validates :address, presence: true end
require 'pathname' require 'fileutils' require 'motion/project/app' require 'motion/project/config' # Gratuitously lifted from Laurent Sansonetti's motion-testflight. unless defined?(Motion::Project::Config) raise "This file must be required within a RubyMotion project Rakefile." end namespace :rubberstamp do des...
class BookSerializer < ApplicationSerializer attributes :id, :author, :title, :image_url, :editor, :year, :genre end
class RenameUserStatusToState < ActiveRecord::Migration def up rename_column :photos, :status, :state rename_column :assets, :status, :state end def down rename_column :photos, :state, :status rename_column :assets, :state, :status end end
class Album < ActiveRecord::Base belongs_to :band has_many :songs, dependent: :destroy has_reputation :votes, source: :user, aggregated_by: :sum include PublicActivity::Model tracked only: [:update, :create], :owner => :band has_many :album_comments, dependent: :destroy accepts_nested_attributes_for :albu...
class CategoriesController < ApplicationController before_action :set_item_search_query before_action :set_categories before_action :find_category, except: [:index] skip_before_action :authenticate_user! def index end def show @items = Item.including.where(category_id: @category.subtree_ids)....
class Debate < ActiveRecord::Base # belongs_to :judge_left, class_name: "Judge", foreign_key: "judge_left_id" # belongs_to :judge_right, class_name: "Judge", foreign_key: "judge_right_id" #HACKY SHIT -- aff & neg debater helpers are indexing on "Debater" class, but should be cleaned up later and everything...
module Yito module Model module Booking # # Shopping cart (renting) # class ShoppingCartRenting include DataMapper::Resource include BookingDataSystem::BookingGuests include BookingDataSystem::BookingDriver include BookingDataSystem::BookingPickupReturn ...
require "rails_helper" describe "As a visitor" do describe "when I visit '/' " do it 'I should be able to create an account' do username = "mommakat" title = "Mom" name = "Kat" visit '/' click_link("Create an Account") expect(current_path).to eq(new_user_path) fill_in ...
class AddIndexToGovernmnentGeom < ActiveRecord::Migration def self.up add_index :governments, :geom, :spatial=>true end def self.down end end
# -*- CODING: utf-8 -*- # FuzzyCell.rb # FuzzyWindow # # Created by Geoffrey Grosenbach on 3/16/10. # Copyright 2010 Topfunky Corporation. All rights reserved. # # # A custom table cell implemented in Ruby. # # FuzzyCell#objectValue is the title. Other fields can be set in # the tableView:willDisplayCell:forTableColumn...
# -*- mode: ruby -*- # vi: set ft=ruby : require 'fileutils' Vagrant.configure("2") do |config| config.vm.provider "virtualbox" config.vm.synced_folder ".", "/vagrant", disabled: true config.env.enable # enable the plugin os_image = (ENV['OS_IMAGE'] || "ubuntu20").to_sym master = (ENV['MASTER'] || 3).to_i ...
require 'javaclass/string_20' # Add some +unpack+ helper methods for HI-LO byte order (network byte order) contained in this String. # Author:: Peter Kofler class String # Return the _index_'th element as byte. def u1(index=0) self.byte_at(index) end # Return the _index_'th and the ne...
class PublicPlaceType < ApplicationRecord has_many :public_place end
require 'context-io/error/client_error' module ContextIO # Raised when Context.IO returns the HTTP status code 400 # # This usually means that some required info is missing. # # @api public class Error::BadRequest < ContextIO::Error::ClientError end end
module VWorkApp class << self @api_key = "YOU NEED TO SPECIFY YOUR API KEY!!" def api_key=(key) @api_key = key end def api_key @api_key end end class Resource < Base extend ActiveModel::Naming include ActiveModel::Conversion include ActiveModel::Validations incl...
#!/usr/bin/env ruby @factorials = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] def is_sum_of_digit_factorials?(n) n == n.to_s.chars.map(&:to_i).inject(0) {|r,d| r += @factorials[d] } end MAX = 1854721 # http://en.wikipedia.org/wiki/Factorion#Upper_bound puts (3..MAX).select {|i| is_sum_of_digit_factorials? i }....
class ChangedEnrollmentsAddedGenderNameSeatSuid < ActiveRecord::Migration def self.up add_column :enrollments, :gender, :integer add_column :enrollments, :name, :string add_column :enrollments, :seat, :integer, :default=>nil add_column :enrollments, :suid, :string end def self.down remove_c...
# encoding: utf-8 namespace :wine_color do desc "初始化表信息" task :init => :environment do NOTE_COLOR_LEVEL = NOTE_COLOR['level'] NOTE_COLOR_NAME = NOTE_COLOR['name'] PARENTS = { 'White' => { :zh => '白葡萄酒', :en => 'White'}, 'Red' => { :zh => '红葡萄酒', :en => 'Red'}, 'R...
require_relative "spec_helper" describe Route do before :each do @route = Route.new("A","B",5) end describe "#startStation" do it "has the correct start station" do @route.startStation.should == "A" end end describe "#endStation" do it "has the correct start station" do @ro...
class NormalizeUsersDomain < ActiveRecord::Migration def up add_column :users, :domain, :string User.find_each {|u| u.email_will_change! u.save! } end def down remove_column :users, :domain end end
require './app/data_mapper_setup' describe User do let(:user) { FactoryGirl.create(:user) } it "authenticates the user session when username and password are correct" do authenticated_user = User.authenticate(user.email, user.password) expect(authenticated_user).to eq user end it "does not authenticate the...
class StudyGroupsController < ApplicationController def index @study_groups = StudyGroup.all # render json: @study_groups end def show end def new @study_group = StudyGroup.new() end def create @study_group = StudyGroup.new(studygroup_attr) if @study_group.save redirect_to(stu...
#!/usr/bin/env ruby # frozen_string_literal: true # Board class Board def initialize(chess_piece) @chess_piece = chess_piece @graph = create_board_graph @parent_cells = {} @visited_cells = [] @path = [] @queue = [] end def create_board_graph adjacency_list = {} 8.times do |row| ...
class RemoveColumns < ActiveRecord::Migration def change remove_column :operations, :name remove_column :operations, :worker add_column :operations, :approval_id, :integer end end
module Shop class WarehouseProducts def fetch WAREHOUSE_PRODUCTS end def add(product) WAREHOUSE_PRODUCTS << product end end end
class Transaction < ApplicationRecord belongs_to :source_account, :class_name => 'Account', optional: true belongs_to :dest_account, :class_name => 'Account', optional: true def self.GetPending Transaction.where(status: "Pending") end def self.GetPendingAdminApproval Transaction.where(...
#! /usr/bin/env ruby require 'gchart' def generate(chart_type) chart = send(chart_type) url = chart.to_url output_filename = "#{chart_type}.png" puts "Chart URL: #{url}" puts "Writing to: #{output_filename}" chart.write(output_filename) end def line_chart GChart.line(:data => [[1, 2], [3, 4]], :extras =...
require 'yaml' require 'digest' class Program class << self def run get_same_files.each.with_index(1) do |(hash, paths), i| break if i > config['result'] display_result(paths) end end def get_files Dir.glob(config['dir'] + '**/**/*').select { |f| File.file?(f) } end...
class Browser < ApplicationRecord has_many :databrowsers has_many :themes, through: :databrowsers has_many :codes, through: :databrowsers end
require 'puppet/parameter/boolean' Puppet::Type.newtype(:powerdns_zone) do @doc = 'ensure a zone exists. The zone is managed using the resource powerdns_zone_private' newparam(:name, namevar: true) do desc 'name of the zone name as namevar' validate do |value| raise ArgumentError, 'The nam...
class Course < ApplicationRecord has_many :course_relationships has_many :students, :through => :course_relationships, :source => :student belongs_to :teacher end
# frozen_string_literal: true module TimeHelper TIME = '%H%M' # 0000 SHORT_DATE = '%-m/%-d' # 1/1 VERBOSE_DATE = '%a %d %b %Y' # Tue 01 Jan 2019 TIME_WITH_ZONE = "#{TIME} %Z" # 0...
class RemoveCoverImgUrlFieldFromImages < ActiveRecord::Migration def self.up remove_column :images, :cover_img_url end def self.down add_column :images, :cover_img_url, :string end end
class SyncProductBacklogJob < ActiveJob::Base def perform(product_id, data) ActionCable.server.broadcast("product_backlog_channel_#{product_id}", data) end end
class SiegeEngine < Unit def initialize super(400, 50) end def attack!(enemy) if enemy.is_a?(Barracks) power = attack_power * 2.0 enemy.damage(power.ceil) elsif enemy.is_a?(Peasant || Footman) return false else super end end end
class ChangeRoleIdToProductId < ActiveRecord::Migration def change rename_column :order_items, :role_id, :product_id end end
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure("2") do |config| config.vm.box = "bento/centos-7.5" config.vm.hostname = "mcod.local" config.vm.network "forwarded_port", guest:8000, host:8000 # mcod api config.vm.network "forwarded_port", guest:8080, host:8080 # mcod admin config.vm.network "forwa...
class MessagesController < ApplicationController def index @messages = Message.all end def new @message = Message.new end def create @message = Message.new(post_params) if @message.save RequestMailer.send_request(@message).deliver redirect_to root_path else render new ...
class Vote < ApplicationRecord belongs_to :user belongs_to :work validates_uniqueness_of :work_id, :scope => [:user_id] end
class MoviesController < ApplicationController #inheriting from the application controller #ACTIONS ->index, show, create, destroy #index action -> home page def index render :json => Movie.all end #show action def show render json: @movie, status: 200 end #create action -> creating a new movie / p...
class Family < ApplicationRecord normalize_attributes :address, :city has_one :membership, dependent: :destroy has_many :user_profiles, -> { order('date_of_birth asc') }, autosave: true, dependent: :destroy validates :address, :city, :state, :zip, presence: true # TODO enable this validation after data is...
# frozen_string_literal: true require 'spec_helper' require 'bolt_spec/config' require 'bolt/inventory' require 'bolt/plugin' require 'yaml' describe Bolt::Inventory do include BoltSpec::Config let(:pal) { nil } # Not used let(:plugins) { Bolt::Plugin.setup(config, pal, nil, Bolt::Analytics::NoopClient.new) } ...
# == Schema Information # # Table name: messages # # id :uuid not null, primary key # content :text # location :string(255) # password :string(255) # latitude :float # longitude :float # created_at :datetime # updated_at :datetime # encryption_key :...
class User < ActiveRecord::Base has_many :shelves, dependent: :destroy has_many :user_books, dependent: :destroy has_many :books, through: :user_books validates :goodreads_id, uniqueness: true after_create :refresh! def refresh! return true unless goodinfo # Set the users name from Goodreads ...
class Contact < ActiveRecord::Base validates :content, presence: true, length: { maximum: 1000 } validates :name, presence:true validates :email, presence:true validates :age, presence:true end
class SubscriptionTypesController < ApplicationController def show @subscription_type = SubscriptionType.find(params[:id]) authorize @subscription_type @subscription_medias = Media.where(subscription_type: @subscription_type) end def index @subscription_types = policy_scope(SubscriptionType).reje...
require 'csv' class ProspectImport attr_reader :path def initialize(*args) @path = args.first end def process! str = File.read(@path, :encoding => 'ISO-8859-1') CSV.parse(str) do |row| row.map! { |row| row.try :strip } prospect = Prospect.find_by_raw_cik(row[0]) || Prospect.new p...
class CommentsController < ApplicationController before_filter :require_user, :only => [:create] before_filter :load_stanza, :only => [:create] before_filter :ensure_stanza_is_public, :only => [:create] def create @comment = @stanza.comments.new(params[:comment]) do |comment| comment.user = curren...
# frozen_string_literal: true require 'rails_helper' RSpec.describe ApiToken do let(:token) { create(:api_token) } it 'sets an expiration date on create' do expect(token.expires_at).not_to be_nil end it 'has the correct length token' do expect(token.new_token.bytes.length).to eq(32) end it 'val...
class Admin::BaseController < ::ApplicationController before_filter :authenticate_admin! before_filter :get_admin layout "admin_layout" def current_user @current_user = current_admin unless current_admin.nil? end def get_admin @current_admin = current_admin end private end
$LOAD_PATH.append File.expand_path('lib', __dir__) require 'multi_bug/identity' Gem::Specification.new do |spec| spec.name = MultiBug::Identity.name spec.version = MultiBug::Identity.version spec.platform = Gem::Platform::RUBY spec.authors = ['Amir Mujkic'] spec.email = ['amirmujk@gmail.com'] spec.homepage...
# frozen_string_literal: true require_relative '../support/classes/place_holder' module Permissions RSpec.describe Permission, type: :model do describe 'Associations' do it { is_expected.to belong_to(:grantee) } end describe 'Database' do context 'Columns' do it { is_expected.to hav...
#!/usr/bin/env ruby #$: << File.dirname(__FILE__) require 'tempfile' class ExampleInserter def initialize(exampleFile) @exampleFile = exampleFile end def run output = getOutput exampleName = File.basename(@exampleFile).chomp(".rb") sourcePath, example = extractExample sourcePath = File.joi...
require 'test_helper' class Publish::CatalogsControllerTest < ActionController::TestCase include Devise::TestHelpers def setup @foreigner = publishers(:john) @publisher = publishers(:jane) @publisher.confirm! sign_in @publisher @catalog = catalogs(:janes) end test 'Catalogs index always r...
require 'singleton' require 'erb' MessageInfo = Struct.new(:sid, :status) class SMSService include AnalyticsHelper include Singleton class NumberNotFound < StandardError; end def initialize sid = ENV['TWILIO_ACCOUNT_SID'] token = ENV['TWILIO_AUTH_TOKEN'] @client = Twilio::REST::Client.new sid, t...
class AddFirstNameToParents < ActiveRecord::Migration[5.1] def change add_column :parents, :first_name, :string add_column :parents, :last_name, :string add_column :parents, :number_of_children, :integer end end
When /^(?:|I )follow Request Change with id (.+)$/ do |id| visit new_my_project_edit_path(app_id: id) end When /I click on the "(.+)" icon/ do |locator| find('#' + locator).click end
require "partial-date" module ResumeEntriesHelper def stringify_partial_date(partial_date) if partial_date == 0 || partial_date == -1 partial_date else date = PartialDate::Date.load(partial_date) format_date date end end def format_date(date) if date.year.present? && date.month...
class Customer include HTTParty # default_options.update(verify: false) # Turn off SSL verification base_uri "http://localhost:8081" format :json def self.register(cust) post '/customers', body: cust.to_json, headers:{ 'Content-Type' => 'application/json', 'ACCEPT' => 'appli...
class ChangeDefaultValueOfRobotsInventory < ActiveRecord::Migration[5.0] def change change_column :robots, :inventory, :boolean, default: false end end
class AddMasterReceiverAndFeeTypeToMultiFeeDiscount < ActiveRecord::Migration def self.up add_column :multi_fee_discounts, :master_receiver_type, :string, :null => false add_column :multi_fee_discounts, :master_receiver_id, :integer, :null => false add_column :multi_fee_discounts, :fee_type, :string a...
module Eturem module SyntaxErrorExt include ExceptionExt def eturem_message() if @eturem_message.match(/unexpected (?<unexpected>(?:','|[^,])+)/) eturem_unexpected(eturem_transform_keyword(Regexp.last_match(:unexpected))) elsif @eturem_message.match(/Invalid (?<invalid>(?:break|next|retry...
require 'spec_helper' describe Chanko::Loader do shared_examples_for 'directories' do it 'should init' do directories = Chanko::Directories.new("/root_dir") directories.directories.map(&:to_s).should be_include('/root_dir') end it 'should add' do directories = Chanko::Directories.new("...