text stringlengths 10 2.61M |
|---|
require "prct07"
require 'spec_helper'
describe Referencia do
context "Libro" do
before :each do
libro = Libro.new(["Dave Thomas","Andy Hunt", "Chad Fowler"], "Programming Ruby 1.9 & 2.0: The Pragmatic Programmers’ Guide", nil, "Pragmatic Bookshelf", "4 edition", "July 7, 2013")
... |
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'cisco_parser/version'
Gem::Specification.new do |spec|
spec.name = "cisco_parser"
spec.version = CiscoParser::VERSION
spec.authors = ["Roman Priesol"]
spec.email = ["roman@priesol.net"]
... |
module StorefrontHelpers
def mock_storefront!(name = :testing)
klass = Class.new(Rails::Engine) do
include Backstage::Engine
engine_name name
config.after_initialize do
Backstage.register_storefront(engine_name)
end
end
Object.const_set(name.to_s.classify, klass)
end
e... |
class UsersController < ApplicationController
include AuthHelper
def new
@user = User.new
render :new
end
def create
set_user
if @user.save
login(@user)
flash[:success] = "User account created. Welcome to NapZZZ!"
redirect_to "/"
else
flash[:notice] = "There was a p... |
class Admin::MessagesController < Admin::BaseController
before_action :find_message, only: [:edit, :update, :destroy]
def index
@messages = Message.search(params)
end
def edit
end
def update
if @message.update(message_params)
flash[:success] = '更新成功!'
redirect_to admin_messages_path
... |
#!/usr/bin/env ruby
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'codebreaker'
class ConsoleCodebreaker
def start
puts 'Enter number of attempts:'
gets
end
def game_play
@game = Codebreaker::Game.new(start.to_i)
@game.start
loop do
puts 'Enter your guess:'
g... |
module LocalizationHelper
def localized(date, format: :default)
if date.present?
l(date, format: format)
end
end
end
|
class AddDefaultToConfirmedColumn < ActiveRecord::Migration
def change
change_column :requests, :confirmed, :string, :default => "false"
end
end
|
class AreasController < ApplicationController
include Response
before_action :set_catalog
before_action :set_catalog_area, only: [:show, :update, :destroy]
def index
json_response(@catalog.areas)
end
def show
json_response(@area)
end
def create
@catalog.areas.create!(area_params)
jso... |
class MedicamentComment < ActiveRecord::Base
belongs_to :medicament
belongs_to :user
end
|
require 'pry'
an_array = [1, 2, 3, 4, 5, 5, 5, 6]
#1b - calling a method that doesn’t mutate the caller
def some_method(arr)
arr.uniq!
end
puts "an_array was initially equal to #{an_array}"
some_method(an_array)
puts "After calling the method, an_array is now equal to #{an_array}"
|
Rails.application.routes.draw do
resources :messages
resources :users
# setup path for clients to connect to ActionCable
# for broadcasting of posted messages
mount ActionCable.server => '/cable'
# forward requests to the embedded ember app at /frontend
Rails.application.routes.draw do
mount_ember... |
# == Schema Information
#
# Table name: restaurants
#
# id :integer not null, primary key
# address :string
# chain :boolean
# image :string
# restaurant_name :string
# created_at :datetime not null
# updated_at :datetime not null
#
cla... |
# frozen_string_literal: true
class ApplicationController < ActionController::Base
skip_forgery_protection
rescue_from ActiveRecord::RecordNotFound, with: :render_404
rescue_from ActiveRecord::RecordInvalid, with: :render_401
def render_404(error)
render json: { message: error.message }, status: :not_fou... |
require 'active_support/concern'
begin
require 'sidekiq'
require 'sidekiq/api'
rescue LoadError
raise Services::BackgroundProcessorNotFound
end
begin
require 'sidetiq'
rescue LoadError
end
module Services
module Asyncable
extend ActiveSupport::Concern
# The name of the parameter that is added to t... |
class Dojo < ApplicationRecord
has_many :ninjas
validates :name, :city, :state, presence:true
validates :state, length: { is: 2 }
end
before_destroy :close_dojo
def close_dojo
Ninja.destroy.where(dojo_id: self.id)
end
|
class Offer
attr_accessor :list_entry
delegate :game_id, :index, :name, :owner, :trade_code, :to => :list_entry
def initialize(list_entry)
@list_entry = list_entry
end
def self.find_by_username(username)
Bgg.geek_list.games_owned_by(username).map do |list_entry|
Offer.new(list_entry)
en... |
class InviteCode < ActiveRecord::Base
has_many :clients
attr_accessible :code, :usage, :start_date, :end_date
validates_uniqueness_of :code, :message => "Code must be unique"
end
|
class Usstates < ActiveRecord::Base
has_many :sales
attr_accessible :state, :state_abbr
end
|
# == Schema Information
#
# Table name: photos
#
# id :integer not null, primary key
# name :string(255)
# category_photo_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# photo_file_name :string(255)
# photo_c... |
class Property < ApplicationRecord
belongs_to :agent
belongs_to :seller
end
|
require "rails_helper"
describe "Settings page", :js do
it "lets you store your name" do
commit = create(:commit, author_name: "Ada Lovelace and Charles Babbage")
visit_and_wait_for_message_bus_init "/"
click_link "Commits"
expect(page).not_to have_selector(".authored-by-you")
click_link "Sett... |
def echo(word)
word
end
def shout(word)
word.upcase
end
def repeat(word, n = 2)
i = 1
result = "#{word}"
until i == n
result += " #{word}"
i += 1
end
result
end
def start_of_word(word, n)
result = ""
(0 .. n - 1).each { |l| result += word[l] }
result
end
def first_word(string)
words = ... |
require 'spec_helper'
require 'pry'
require 'user'
RSpec.describe Palette::ElasticSearch::QueryFactory do
it 'has a version number' do
expect(Palette::ElasticSearch::VERSION).not_to be nil
end
describe 'json' do
let(:attributes) do
{
name: 'Steve Jobs',
name_prefix: 'Steve Job... |
class CommandLoader
def initialize(config)
@config = config
end
def load
# assumes command file is known to exist already
@config.command_name = @config.command_line.command_name
command_path = @config.config.available_commands[@config.command_name]
class_constant_name = constantize_file_name... |
class Notifications < ActionMailer::Base
default :from => "Fulfilld.com <notifications@fulfilld.com>"
def recovery(user_id)
@user = User.find(user_id)
@greeting = @user.name || @user.username
mail :to => @user.email, :subject => "[fulfilld.com] Password reset instructions"
end
def verification(user... |
class ChangeOrderDateTypeToTimeStamp < ActiveRecord::Migration
def change
remove_column :buy_orders, :purchase_date
add_column :buy_orders, :purchase_date, :timestamp
remove_column :sell_orders, :sell_date
add_column :sell_orders, :sell_date, :timestamp
end
end
|
class ScheduledMessagesChannel < ApplicationCable::Channel
def subscribed
reject unless current_user.clients.pluck(:id).include? params[:client_id]
stream_from "scheduled_messages_#{params[:client_id]}"
end
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe NominationsMailer do
describe 'nomination' do
let(:nominator) { create(:user) }
context 'with an ExCom award' do
let(:mail) do
described_class.nomination(
nominator,
'Bill Booth Moose Milk',
'Joh... |
FactoryBot.define do
sequence :name do |n|
"Shop#{n}"
end
sequence :address do |n|
"Address#{n}"
end
sequence :subway do |n|
"Subway#{n}"
end
factory :shop do
name
address
subway
city
end
end
|
# Tealeaf Academy Prep Course
# Intro to Programming Workbook
# Advanced Questions - Quiz 1
# Exercise 5
def is_a_number?(thing)
thing.to_i != 0 || thing == "0"
end
def dot_separated_ip_address?(input_string)
dot_separated_words = input_string.split(".")
if dot_separated_words.size !=4
return false
else
... |
require "rails_helper"
module Clockface
RSpec.describe RootController, type: :controller do
routes { Clockface::Engine.routes }
describe "GET #index" do
it "should blindly redirect to the events path" do
get :index
expect(response).to redirect_to(events_path)
end
end
end
en... |
# Print the even numbers from 1 to 99, inclusive. All numbers should be printed on separate lines.
(1..99).each do |num|
p num if num.even?
end |
require 'csv'
require 'parsedate'
TABLE_NAME = "QC_TEXT_MESSAGES"
NO_DELIMITER = [4, 5, 8, 10, 12, 16, 21, 22]
def write_script
sql_file = File.new("#{TABLE_NAME.downcase}.sql", "w")
sql_file << "SET DEFINE OFF\n"
sql_file << "DELETE FROM #{TABLE_NAME};\n\n"
reader = CSV.open("#{TABLE_NAME}.csv", "r")
head... |
require 'base64'
include GitolitePublicKeysHelper
class GitolitePublicKey < ActiveRecord::Base
STATUS_ACTIVE = 1
STATUS_LOCKED = 0
KEY_TYPE_USER = 0
KEY_TYPE_DEPLOY = 1
DEPLOY_PSEUDO_USER = "_deploy_key_"
# These two constants are related -- don't change one without the other
KEY_FORMATS = ['ssh-rsa'... |
class LibraryParser
attr_accessor :path
def initialize(path = 'db/data')
@path = path
end
def files
@files = Dir.entries(@path)[2..-1]
end
def parse_filename(filename)
reg_ex = filename.split(/\s-\s|\.|\[|\]/)
@parts = [reg_ex[0].strip, reg_ex[1].strip, reg_ex[2].strip]
end
def build... |
# encoding: UTF-8
# Copyright 2012 Twitter, Inc
# http://www.apache.org/licenses/LICENSE-2.0
module TwitterCldr
module Collation
# Builds a fractional collation elements Trie from the file containing a fractional collation elements table.
#
module TrieBuilder
COLLATION_ELEMENT_REGEXP = /^((?:[0-... |
module Sumac
# Allocates ids. IDs can be returned then reallocated again.
# Uses ranges to reduce memory consumption.
# @api private
class IDAllocator
# Return a new {IDAllocator}.
# @return [IDAllocator]
def initialize
@allocated_ranges = []
end
# Allocate an id.
# Removes id... |
class User < ActiveRecord::Base
has_many :posts
#has_secure_password
def self.authenticate(params)
user = User.find_by_name(params[:name])
return user if user && (user.password == params[:password])
nil # either invalid email or wrong password
end
end
|
module ShopifyImport
module DataParsers
module Taxons
class BaseData
def initialize(shopify_custom_collection)
@shopify_custom_collection = shopify_custom_collection
end
def taxon_attributes
{
name: @shopify_custom_collection.title,
permal... |
module CheckInHelpers
def check_in(user, symptom, check_in_options = {})
options = check_in_options.merge user: user
create :check_in_symptom, check_in: build(:check_in, options), symptom: symptom
end
def generate_check_ins(n, user, _options = {})
group = build :symptom_group
symptoms = create_li... |
# == Schema Information
#
# Table name: looks
#
# id :integer not null, primary key
# product_id_0 :integer
# product_id_1 :integer
# product_id_2 :integer
# product_id_3 :integer
# created_at :datetime not null
# updated_at :datetime not null
# name :string
#
cla... |
module StrokeDB
module StrokeObjects
# Instance of this class is a module containing connection to a database.
# Include this module into the classes of interest, which represent different kinds of objects.
# Database.new(:path => 'pth-to-database', :nsurl => "http://myhost.com/")
# Initialization op... |
class TimeSlot < ActiveRecord::Base
has_many :orders
def self.available_slots
order_ids = Order.select(:time_slot_id).where("finish is NULL").map(&:time_slot_id)
TimeSlot.where.not(id: order_ids)
end
end
|
# state :integer(4) 0 for expired, 1 for not expired
# buy :boolean(1) 0 for sell, 1 for buy
# sell_type :string(255) FIFO, LIFO, AVG, SPECIFIC
class Trade < ActiveRecord::Base
after_initialize :default_values
attr_accessible :state, :buy, :sell_type, :trade_date, :clear_date, :vol, :price... |
require './app/models/computer'
describe Computer do
let(:computer) { (Computer.new) }
describe 'computer_weapon' do
it "selects a random weapon for the computer from the CHOICES constant" do
allow(computer).to receive(:computer_weapon).and_return(:rock)
expect(computer.computer_weapon).to eq :ro... |
class VacancySkill < ApplicationRecord
belongs_to :skill
belongs_to :vacancy
end
|
# frozen_string_literal: true
module RailsSettings
class ProtectedKeyError < RuntimeError
def initialize(key)
super("Can't use #{key} as setting key.")
end
end
class Base < ActiveRecord::Base
SEPARATOR_REGEXP = /[\n,;]+/
PROTECTED_KEYS = %w[var value]
self.table_name = table_name_prefi... |
require_relative './elevator.rb'
# An elevator subclass that scores based on the response time to the new
# request. The best scoring elevator is the one that would fulfill the request
# most quickly.
class ResponseTimeElevator < Elevator
def time_to_respond(request)
elevator = clone
elevator.add_request(req... |
class Report < ActiveRecord::Base
attr_accessible :campaign_id, :user_id
validates :campaign_id, :user_id, presence: true
belongs_to :campaign
belongs_to :user
after_create { ReportMailer.delay.new_report(self) }
end
|
namespace :openvswitch do
desc "install packages"
task :install, [:pkgs] do |t,arg|
packages = if arg.pkgs.nil?
%w(openvswitch-common openvswitch-datapath-dkms openvswitch-datapath-source openvswitch-switch)
else
arg.pkgs.split /\s+/
end
packag... |
class UserCommonSerializer < ActiveModel::Serializer
attributes :id, :full_name, :phone_number
:avatar
end
|
Sequel.migration do
change do
create_table :email_queue do
primary_key :id
DateTime :creation
String :recipients
String :subject
String :content
String :content_html
String :queue_status
end
add_column :mass_emails, :email_queue_id, Integer
end
end
|
class EventSerializer
include FastJsonapi::ObjectSerializer
attributes :id, :name, :start_time, :end_time, :notes, :calendar
attribute :calendar_title do |object|
object.calendar.title
end
# belongs_to :calendar
end
# We use the Fast JSON API gem to create a close approximation to JSON DATA from ... |
class RenameDescriptionToRuDescriptionAndAddComDescriprionAndRuSloganAndComSloganToBoatType < ActiveRecord::Migration[5.0]
def change
rename_column :boat_types, :description, :ru_description
add_column :boat_types, :com_description, :string, default: ''
add_column :boat_types, :ru_slogan, :string, default... |
require 'dxruby'
class Info
attr_accessor :life
attr_accessor :score
attr_accessor :time
def initialize(life = 3, score = 0, margin_y = 0)
@life = life
@score = score
@margin_y = margin_y
@font = Font.new(32)
end
#体力について
def life_down
if @life == 1
#ゲームオーバーの画面
@life = 0
puts "... |
require 'minitest/autorun'
require 'minitest/rg'
require './LinkedList.rb'
require './Node.rb'
class TestLinkedList < MiniTest::Test
def setup
@list = LinkedList.new("Hello there!")
end
def test_linkedListInitialisesWithOneItem
assert_equal(1, @list.length)
end
def test_canAccessHeadValue
ass... |
require 'csv'
require 'json'
class CSVWriter
def initialize()
end
def output(commits)
stats = [head(commits)]
commits.each { |commit| stats <<
commit.map{|key,entry|"\"#{entry}\""}.join(",")
}
stats.join("\n")
end
def head(commits)
commits.first.map{|key,entry|"\"#{key}\""}.join(",")
end
end
|
require 'test_helper'
class ApplicationControllerTest < ActionDispatch::IntegrationTest
VIKYAPP_INTERNAL_API_TOKEN = ENV.fetch("VIKYAPP_INTERNAL_API_TOKEN") { 'Uq6ez5IUdd' }
test "A request without Access-Token header" do
get "/api_internal/packages"
assert_equal '401', response.code
assert_equal "Ac... |
module Roller
def self.included(base)
base.send :extend, ClassMethods
base.send :include, InstanceMethods
end
def ensure_unique(base)
begin
self[name] = yield
end while self.class.exists?(name: self[name])
end
module ClassMethods
def access_rules(*data)
before_update { |i| i... |
class CoursePeriodsController < ApplicationController
def create
skip_authorization
@course_period = CoursePeriod.new(
day: course_period_params[:day].to_i,
course_id: course_period_params[:course_id],
period_id: course_period_params[:period_id]
)
@course = Course.find(params[:cours... |
module BrewSparkling
module Action
module Install
class Patch < Base
def call
return unless recipe.respond_to?(:patch)
logger.start "Patch to: #{recipe.build_path}"
at_build_path do
IO.popen('patch -p1 -l', 'r+') do |io|
io.puts recipe.patch
... |
#!/usr/bin/env ruby
require 'bundler/setup'
require 'json'
require 'jsonpath'
def strip_line_numbers
json = File.read(get_output_file_path('data_with_line_numbers.json'))
hash =
JsonPath
.for(json)
.delete('..line_no')
.to_hash
File.open(get_output_file_path('data.json'), 'w') do |f|
f.puts ... |
#!/usr/bin/env ruby
puts "Running rubocop:"
system "bundle exec rubocop -D"
puts "Running scss-lint:"
system "scss-lint"
puts "Running npm test:"
system "npm test"
begin
require "net/http"
require "json"
CODESHIP_API_KEY = ENV["CODESHIP_API_KEY"].freeze
origin_remote_url = `git config --get remote.$(git c... |
# == Schema Information
#
# Table name: articles
#
# id :integer not null, primary key
# headline :string(255)
# lead_paragraph :string(255)
# pubdate :datetime
# word_count :integer
# created_at :datetime
# updated_at :datetime
#
class Article < ActiveRecord::Base
... |
module Services::Searchers
class Flickr < Base
class Error < ::StandardError; end
include Errors
attr_reader :client
SEARCH_TYPES = {
keywords: 2,
tags: 4
}
PER_PAGE = 20
attribute :keywords, type: String
attribute :search_type, type: Integer, default: SEARCH_TYP... |
# frozen_string_literal: true
require_relative './corner'
class Rectangle
attr_reader :top_left, :top_right, :bottom_left, :bottom_right
def initialize(x_top_left, y_top_left, x_bottom_right, y_bottom_right)
@top_left = Corner.new(x_top_left, y_top_left)
@bottom_right = Corner.new(x_bottom_right, y_botto... |
ActiveAdmin.register Booking do
controller do
def permitted_params
params.permit(:booking => [:lawn_id, :time, :date, :booked])
end
end
end
|
class CreateArticles < ActiveRecord::Migration[5.2]
def change
create_table :articles do |t|
t.text :content_text
t.text :meta_description
t.string :content_url, limit: 255, null: false
t.string :content_title, limit: 255
#t.references :categories, foreign_key: true
t.reference... |
# encoding: utf-8
require 'spec_helper'
describe ProjectsController do
let(:user) { create_user! }
let(:project) { Project.create!(:name => "Ticketee") }
describe "language is English" do
before(:each) do
I18n.locale = "en"
I18n.default_locale = "en"
end
it "displays an error message ... |
# frozen_string_literal: true
module GraphQL
module StaticValidation
module FragmentTypesExist
def on_fragment_definition(node, _parent)
if validate_type_exists(node)
super
end
end
def on_inline_fragment(node, _parent)
if validate_type_exists(node)
su... |
class RemoveDeleteOnFromTodoItem < ActiveRecord::Migration
def change
remove_column :todo_items, :delete_on, :datetime
end
end
|
module SessionsHelper
#Logs in the given user.
def log_in(user)
session[:user_id] = user.id
#This places a temporary cookies on the user's browser
#containing an encrypted version of the user's id.
end
#return the current logged-in user(if any)
def current_user
@current_user ||= User.find_by(id: session[:u... |
class Api::VotesController < ApplicationController
def index
@votes = Answer
.find(params[:answer_id])
.votes
.where(voter_id: params[:voterId])
render json: @votes
end
def create
@vote = Vote.new(vote_params)
Vote.transaction do
begin
@vote.save!
answer = @vot... |
module FedenaEmailAlert
# This class processes the alert mails for an event
# Will use the event source object and the Alert bodies to prepare the alert mails
# generates AlertMailPayload object and queues to DJ
class AlertMailProcessor
attr_reader :event_object, :model_event, :mail_logger, :email_alert
... |
$: << './lib'
require 'flickr_captioner'
require 'minitest/spec'
require 'minitest/autorun'
require 'mocha'
require 'tmpdir'
require 'rack/test'
module Helpers
def jpeg_data
File.read(File.join(File.dirname(__FILE__), 'test.jpg'))
end
SIZES = [
{:width => '640', :height => '480', :source => 'http://twit... |
json.array!(@conversions) do |conversion|
json.extract! conversion, :id, :measure_a_id, :measure_b_id, :quantity
end
|
str = <<EOS.upcase
Ruby
is
object-oriented
programming
language.
EOS
print str
|
class PhoneCallsController < ApplicationController
before_action :set_phone_call, only: [:show, :edit, :update, :destroy]
def index
@phone_calls = PhoneCall.includes(:phone_number ,:agent ).all
if params[:status].present?
@phone_calls = @phone_calls.where(status: params[:status])
end
... |
require 'line/bot'
# Client class for LINE
class LineClient
attr_reader :client
class InvalidRequest < StandardError; end
def initialize
@client = Line::Bot::Client.new do |config|
config.channel_secret = ENV['LINE_CHANNEL_SECRET']
config.channel_token = ENV['LINE_CHANNEL_TOKEN']
end
@p... |
class PerformanceMonitorMigration < ActiveRecord::Migration
def self.up
create_table :log_entries, :force => true do |t|
t.string "server_name"
t.string "server_address"
t.string "http_host"
t.string "remote_address"
t.string "app_name"
t.string "path"
t.datet... |
class CreateBlogGroups < ActiveRecord::Migration
def change
create_table :blog_groups do |t|
t.string :name
t.references :user
end
add_index :blog_groups, :user_id
add_column :destinations, :blog_group_id, :integer
add_column :affiliate_links, :blog_group_id, :integer
add_inde... |
$:.unshift File.expand_path("../../mustermann/lib", __FILE__)
$:.unshift File.expand_path("../../support/lib", __FILE__)
require "mustermann/version"
require "support/projects"
Gem::Specification.new do |s|
s.name = "mustermann-everything"
s.version = Mustermann::VERSION
s.author ... |
require 'spec_helper'
describe "Review" do
before do
@user = User.create(:username => "Billy Bob", :password => "password")
@movie = Movie.create(:name => "Grown Ups 2")
@review = Review.create(:content => "Grown Ups 2 is a horrible movie", :score => "1", :user_id => @user.id, :movie_id => @movie.id)
... |
module Antlr4::Runtime
class LoopEndState < ATNState
attr_accessor :loopback_state
def initialize
super
@loopback_state = nil
end
def state_type
LOOP_END
end
end
end |
require 'easy_json_schema/version'
require 'easy_json_schema/schema_manager'
require 'easy_json_schema/format_validator'
module EasyJsonSchema
class << self
attr_accessor :configuration
end
def self.configure
self.configuration ||= Configuration.new
yield(configuration)
end
def self.validate(sc... |
class UsersController < ApplicationController
before_action :require_login, only: [:show, :edit]
before_action :set_user, only: [:show, :edit, :update]
def index
@users = User.all
end
def new
@user = User.new
end
def create
@user = User.create(user_params)
login(@user)
redirect_to @user
end
def ... |
require 'spec_helper'
describe MarketplaceService::Listing::Entity do
include MarketplaceService::Listing::Entity
include MarketplaceService::Listing::Command
it "#transaction_direction" do
expect(transaction_direction("Rent")).to eq("offer")
expect(transaction_direction("Request")).to eq("request")
... |
require './lib/cypher'
class Encoder
attr_accessor :message, :cypher, :letter_message, :index_message, :alphabet
@@alphabet = ('a'..'z').to_a << ' '
def initialize(cypher)
@cypher = cypher
@alphabet = ('a'..'z').to_a << ' '
end
def valid?(char)
alphabet.include?(char)
end
def upcase?(char)... |
# 1. Write a program that uses variables to store a first and last name, then prints the full name in one line using string concatenation (the + operator).
#first_name = "jack"
#last_name = "sparrow"
#p first_name + " " + last_name
# 2. Write a program that uses variables to store a first and last name, then prints ... |
# == Schema Information
#
# Table name: likes
#
# id :integer not null, primary key
# profile_id :integer
# likeable_type :string
# likeable_id :integer
#
# Indexes
#
# index_likes_on_likeable_type_and_likeable_id (likeable_type,likeable_id)
# index_likes_on_profile_id ... |
Vagrant.configure('2') do |config|
config.vm.box = 'ubuntu/xenial64'
config.vm.network 'private_network', type: 'dhcp'
# Just install Python for now
config.vm.provision 'shell' do |shell|
shell.inline = <<EOF
if ! `command -v python` ; then
sudo apt-get update && sudo apt-get install -y python
fi
E... |
require 'date'
class Event < ApplicationRecord
validates :title, presence: true
has_and_belongs_to_many :members
def self.earlier_events
@events = Event.where(date: (Date.today << (30*12))..Date.today)
end
def self.later_events
# event Date.parse(:date) > Date.today.prev_day
@events = Event.whe... |
module Chandler
module Refinements
# Monkey patch String to provide conveniences for identifying strings that
# represent a version, and converting between between tags (e.g "v1.0.2")
# and version numbers ("1.0.2").
#
module VersionFormat
refine String do
# Does this string represen... |
class ExpressionGroup
def initialize(_input_data)
@input_data = _input_data
@terminal_variables = @input_data.first[:inputs].keys
@expressions = (1..10).map {|i| ExpressionGenerator.generate(@terminal_variables)}
end
def to_s
@expressions.join("\n")
end
end
|
path = File.expand_path '..', __FILE__
$LOAD_PATH.unshift path unless $LOAD_PATH.include?(path)
path = File.expand_path '../../../shared-test-ruby', __FILE__
$LOAD_PATH.unshift path unless $LOAD_PATH.include?(path)
path = File.expand_path '../helper', __FILE__
$LOAD_PATH.unshift path unless $LOAD_PATH.include?(path)
re... |
=begin
You come across an experimental new kind of memory stored on an infinite two-dimensional grid.
Each square on the grid is allocated in a spiral pattern starting at a location marked 1 and then counting up while spiraling outward. For example, the first few squares are allocated like this:
17 16 15 14 13
18... |
require 'minitest/autorun'
require 'minitest/rg'
require_relative '../song'
class TestSong < MiniTest::Test
def setup
@song = Song.new('Season Song')
end
# Test song properties.
def test_song_name
assert_equal('Season Song', @song.name)
end
end |
class AttemptsController < ApplicationController
before_action :authenticate_user!, except: :result
before_action :set_attempt, only: %i[show update result gist]
def show; end
def result; end
def update
@attempt.accept!(params[:answer_ids])
respond_to do |format|
if @attempt.completed?
... |
module Scheduler
class DailySchedule
def initialize(availability:, date:)
@availability = availability
@date = date.to_datetime
end
def to_hash
times.each_with_object({}) do |time, daily_schedule|
daily_schedule[time] = HourlySchedule.new(availability: @availability, time: time)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.