text stringlengths 10 2.61M |
|---|
require "spec_helper"
RSpec.describe "Day 14: Regolith Reservoir" do
let(:runner) { Runner.new("2022/14") }
let(:input) do
<<~TXT
498,4 -> 498,6 -> 496,6
503,4 -> 502,4 -> 502,9 -> 494,9
TXT
end
describe "Part One" do
let(:solution) { runner.execute!(input, part: 1) }
it "computes... |
class RegistrationsController < Devise::RegistrationsController
protected
def after_sign_up_path_for(resource)
'/lists'
end
end
|
# == Schema Information
#
# Table name: project_members
#
# id :integer not null, primary key
# user_id :integer not null
# project_id :integer not null
# role :integer default("0"), not null
# created_at :datetime
# updated_at :datetime
#
require 'rails_helpe... |
require 'spec_helper'
describe Post do
context 'post creation' do
let(:post) { create(:post) }
it { expect(post).to be_valid }
it 'converts to html from markdown' do
post.content = 'This is **a** post [with markdown](http://google.com)'
expect(Blog::Markdown.new(post.content).render).to eq... |
class UserSerializer < ActiveModel::Serializer
has_many :events
has_many :comments
attributes :id, :username, :password_digest
end
|
json.array!(@villains) do |villain|
json.extract! villain, :id, :name, :gender, :intel, :str, :speed, :durab, :power, :combat, :image_url
json.url villain_url(villain, format: :json)
end
|
# Read about factories at http://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :karma_type do
sequence :name do |n|
"Karma ##{n}"
end
description 'A great test karma'
value '100'
end
end
|
class Customer < ApplicationRecord
has_many :cars
validates :email, presence: true, format: { with: /(\S+)@(\S+)/ }, uniqueness: { case_sensitive: false} #missachtet die gross oder kleinschreibung der email adresse
private
end
|
class UserFeeling < ApplicationRecord
belongs_to :user
belongs_to :feeling
end
|
require 'yaml'
# A simple in-memory store backed by a Hash.
class Robut::Storage::HashStore < Robut::Storage::Base
class << self
# Stores +v+ in the hash.
def []=(k, v)
internal[k] = v
end
# Returns the value at key +k+.
def [](k)
internal[k]
end
private
# The hash... |
FactoryGirl.define do
factory :city do
name "Sofia"
end
end
|
class AddPostBackShippingFieldsToOrder < ActiveRecord::Migration
def self.up
add_column :orders, :shipping_status, :string
add_column :orders, :shipping_tracking_number, :string
add_column :orders, :shipping_postage_amount, :float
end
def self.down
remove_column :orders, :shipping_postage_amount
... |
class RolesController < ApplicationController
# run the set_role method first for these methods
before_action :set_role, only: [:edit, :update, :show, :destroy]
before_action :require_admin_create_permission, only: [:new, :create]
before_action :require_admin_view_permission
before_action :require_admin_upd... |
class BoggleBoard
def initialize
@spaces = Array.new(16, "_")
@alphabet = ('A'..'Z').to_a
@dice = Array.new([
"AAEEGN",
"ELRTTY",
"AOOTTW",
"ABBJOO",
"EHRTVW",
"CIMOTU",
"DISTTY",
"EIOSST",
"DELRVY",
"ACHOPS",
"HIMNQU",
"EEINSU",
... |
class Person
class HasRoleError < StandardError; end
has_many :roles, :autosave => true, :extend => RoleTypeAssociationExtensions
has_many :movies, :through => :roles,
:autosave => true, :extend => RoleTypeAssociationExtensions, :order => 'release_date'
RoleType.each_name do |name|
named_scope name.... |
FactoryGirl.define do
factory :course do
factory :active_course do
name "Fisica"
description "Curso de Fisica"
status CourseStatus::ACTIVE
end
factory :inactive_course do
name "Analise e Desenvolvimento de Software"
description "Curso de ADS"
status CourseStatus::INACT... |
require 'pry'
def consolidate_cart(cart)
# new_cart = {}
# item_count = []
#
# #Array created of all items purchased
# cart.each do |item_description|
# item_description.each do |item, attributes|
# item_count << item
# end
# end
#
# #Method to count number of multiple values in array
#... |
class String
def to_bool
return true if self == true || self =~ (/^(true|t|yes|y|1)$/i)
return false if self.blank? || self =~ (/^(false|f|no|n|0)$/i)
end
end
class Symbol
def to_bool
truthy = [:true, :t, :yes, :y]
truthy.include?(self)
end
end
class Numeric
def to_bool
self.nonzero?
e... |
# frozen_string_literal: true
module NZWhois
#
# Invalid domain error used when a non `.nz` domain requested
#
class InvalidDomainError < StandardError
def message
'Only `.nz` domain names supported'
end
end
end
|
require 'csv'
require_relative 'invoice_item'
require_relative 'csv_loader'
require_relative 'search'
class InvoiceItemRepository
include CsvLoader
include Search
attr_reader :invoice_items
def initialize(csv_file_path, engine)
@invoice_items = create_items(csv_file_path, engine)
@engine = engine
... |
class Restaurante < ActiveRecord::Base
validates_presence_of :name, message: "deve ser preenchido"
validates_presence_of :endereco, message: "deve ser preenchido"
validates_presence_of :especialidade, message: "deve ser preenchido"
end
|
class RPNCalculator
REGEXP = %r{(-?\d) (-?\d) ([-+*/])(?!\d)}
def initialize
@stack = []
@total = 0
end
def push(number)
@stack << number
end
def value
@total
end
def plus
if @stack.length >= 2
@total += @stack.last(2).sum
@stack.pop(2)
@total
elsif @stack.l... |
require_relative "slideable"
require_relative 'piece'
class Queen < Piece
#Queen is inheriting
#@color = symbol
#reference to @board
#@pos
#Queen.new(color, board, pos)
#to_s
#empty?
#valid_moves
#pos=(val)
#symbol
# private -> move_into_check?(end_pos)
include Slideab... |
module Corenlp
class Sentence
attr_accessor :index, :tokens, :token_dependencies, :parse_tree_raw
def initialize(attrs = {})
self.index = attrs[:index]
self.tokens = []
self.token_dependencies = []
self.parse_tree_raw = ''
end
def governor_dependencies(token)
token_depe... |
require 'spec_helper'
describe "book_of_classes/edit.html.erb" do
before(:each) do
@book_of_class = assign(:book_of_class, stub_model(BookOfClass))
end
it "renders the edit book_of_class form" do
render
# Run the generator again with the --webrat flag if you want to use webrat matchers
assert_s... |
require_relative '../lib/toolbox'
require_relative "log"
require 'json'
require 'pry'
class Convert
include Toolbox
def start_convert
Log.puts """Welcome to convert! Which would you like to convert?
1. An abbreviated column name to a full column name
2. A full column name to an abbreviated column name
... |
class AddMissingFieldsToImages < ActiveRecord::Migration[6.0]
def change
add_column :images, :sku, :string
add_column :images, :md5_hash, :string
add_column :images, :copies, :integer
add_column :images, :sizing, :string
end
end
|
class AddBonnieSongList < ActiveRecord::Migration
def change
create_table :bonnie_tyler_song_objects do |t|
t.string :bonnie_tyler_song_object_artist_full_name, null: false
t.string :bonnie_tyler_song_object_song_title, null: false
end
end
end
|
# WSDL4R - XMLSchema simpleContent restriction definition for WSDL.
# Copyright (C) 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
# either the dual license version in 20... |
module Charts
class QueryHarvestYield
prepend SimpleCommand
def initialize(current_user, args = {})
@user = current_user
@args = args
@facility_id = @args[:facility_id].split(',').map { |x| x.to_bson_id }
end
def call
facilities = Facility.in(id: @facility_id)
batch_ids... |
require 'rails_helper'
RSpec.describe RemoteRequestBuilder do
describe '#authorize_and_decorate!' do
it 'should add HTTP basic auth and the default :depth to the url' do
original_url = "http://#{ENV.fetch('SPARC_API_HOST')}/#{ENV.fetch('SPARC_API_VERSION')}/services/1.json"
expected_url = "http://#... |
module ApplicationHelper
#
# about our user
#
def current_user
# @current_user ||= User.find(session[:user_id]) if session[:user_id]
@current_user ||= User.by_auth_token.key(cookies[:auth_token]).first if cookies[:auth_token]
end
def request_country
@geoip ||= GeoIP.new("#{Rails.root}/db/GeoIP.dat")... |
class Question < ApplicationRecord
has_many :torves, dependent: :destroy
has_many :torf_users, through: :torves, source: :user
belongs_to :field
end
|
class TimeStamp < ApplicationRecord
validate :check_present_valid_signature
attr_accessor :signature_with_time_zone
def signature=(signature)
case
when signature =~ /^(1[0-9]|0[1-9]):[0-5][0-9] (0[1-9]|1[0-9]|2[0-9]|3[0-1])\.(0[1-9]|1[0-2])$/
valid_signature = DateTime.parse(signature)
w... |
require 'rails_helper'
RSpec.describe Api::V2::OrdersController do
after(:all) do
DatabaseCleaner.clean_with(:truncation)
end
describe "UPDATE_ORDER" do
context " Unauthorized" do
it "get status 401 due to unauthorized" do
post :update_order
expect(response.status).to eq(401)
... |
class User < ApplicationRecord
has_many :campaigns
validates :name, :email, :password, :city, :country, :password_confirmation, presence: true
validates :email, uniqueness: true
validates :password, confirmation: { case_sensitive: true }
has_secure_password
end
|
def measure(n = 1, &prc)
start_time = Time.now
n.times do
prc.call
end
end_time = Time.now
elapsed = ((end_time - start_time)/n).to_f
end
|
module ApplicationHelper
def print_price(price)
number_to_currency(price/100.00)
end
def login_status
if current_user
"Logged in as #{current_user.username}"
end
end
def cart_items_total
if cookies[:order_ids]
order_ids = cookies[:order_ids].split(',')
orders = Order.find_... |
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# username :string not null
# password_digest :string not null
# session_token :string not null
# created_at :datetime not null
# updated_at :datetime ... |
#!/usr/bin/env ruby
require 'optparse'
require "ostruct"
require "thread"
require 'socket'
require 'uri'
require 'net/http'
require 'timeout'
require 'yaml'
Net::HTTP.version_1_2
class SocialSKK
VERSION_STRING = "SocialSKK0.2 "
CLIENT_END = ?0
CLIENT_REQUEST = ?1
CLIENT_VERSION = ?2
CLIENT_HOS... |
class Article < ActiveRecord::Base
belongs_to :author, class_name: :User
has_many :comments
has_reputation :votes, source: :user, aggregated_by: :sum
acts_as_taggable
validates_uniqueness_of :title
validates_presence_of :title, :abstract, :body
def self.search(search)
where('title LIKE ?', "%#{search... |
# The difference between merge and merge! is that the latter is destructive while the former isn't.
a = {"a" => 2, "b" => 4}
b = {"c" => 3, "d" => 5}
puts "Before the non-destructive merge method: "
p a
p b
puts "After merge!: "
p a.merge!(b)
p a # This caller hsh is altered
p b
|
require "spec_helper"
describe HomepageContent do
it { should belong_to(:homepage) }
it { should belong_to(:content) }
end
|
#!/usr/bin/env ruby
begin
require 'dotenv'
Dotenv.load
rescue LoadError
puts "Error loading dependencies"
exit
end
require 'commander/import'
require_relative '../lib/hellosign_downloader'
program :version, '0.0.1'
program :description, 'With the following commands you will be able to download documents from... |
require 'rails_helper'
require 'rspec_api_documentation'
require 'rspec_api_documentation/dsl'
RspecApiDocumentation.configure do |config|
config.format = :json
config.curl_host = nil
config.api_name = 'Blueboard Test API'
config.request_headers_to_include = ['Content-Type', 'Access-Token']
config.response_h... |
class AddSendinfoToRelationships < ActiveRecord::Migration[5.1]
def change
add_column :relationships, :sendA, :boolean, default: false
add_column :relationships, :sendB, :boolean, default: false
add_column :relationships, :waitA, :boolean, default: false
add_column :relationships, :waitB, :boolean, de... |
require "spec_helper"
module Ayi
describe CStrategy do
it "matches c files" do
subject.match_file_name?("example.rb").should be_false
subject.match_file_name?("hello/world.rb").should be_false
subject.match_file_name?('hello.c').should be_true
end
include_examples "remove trailing whit... |
namespace :mamashai do
desc "更新贴心购产品"
task :add_mobile => [:environment] do
file = File.open("#{::Rails.root.to_s}/public/bafu/mobile2.csv")
file.each_line{|line|
for mobile in line.split("\r")
Dda.create(:mobile => mobile)
end
}
end
task :get_mobile_city =>[:environment] do... |
class Task < ApplicationRecord
validates :title, :description, presence: true
belongs_to :category
belongs_to :user
end
|
require 'gss-usps/version'
require 'gss-usps/config'
require 'gss-usps/dispatch'
require 'gss-usps/package'
require 'gss-usps/receptacle'
require 'gss-usps/request'
require 'gss-usps/response'
module GssUsps
def self.configuration
@configuration ||= Config.new
end
def self.config
config = configuration
... |
class AddBannerIdToProposals < ActiveRecord::Migration[5.0]
def change
add_reference :proposals, :banner, index: true
end
end
|
class Directory::PeopleController < Directory::ApplicationController
add_crumb("People") { |instance| instance.send :directory_people_path }
def index
@users = User.listed_directory.paginate :page => params[:page], :per_page => 25, :order => "created_at DESC"
end
def show
@user = User.find(params[... |
module LLT
module Constants
module Particles
ALI = "ali"
C = "c"
CE = "ce"
CUMQUE = "cumque"
DAM = "dam"
DEM = "dem"
LIBET = "libet"
NAM = "nam"
PIAM = "piam"
QUAM = "quam"
QUE = "que"
VIS = "vis"
end
end... |
require 'spec_helper'
describe "Movie" 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", :user_id => @user.id, :movie_id => @movie.id)
end
it "can ... |
require_relative "lcd"
DIGITS = <<-EOF
-
| |
| |
-
===
|
|
===
-
|
-
|
-
===
-
|
-
|
-
===
| |
-
|
===
-
|
-
|
-
===
-
|
-
| |
-
===
-
|
|
===
-
| |
-
| |
-
===
-
| |
-
|
-
EOF
describe Lcd do
(0..9).each do |digi... |
#!/usr/bin/ruby
# encoding: UTF-8
require 'test/unit'
require 'net/http'
require 'json'
class TestPost < Test::Unit::TestCase
def make_get_api_call(uriString, path)
http = Net::HTTP.new(uriString)
puts
puts "Make a GET API request:"
headers = {
'Host' => uriString # Assuming same as URI, may not... |
class PersonPicture < ApplicationRecord
belongs_to :person
belongs_to :picture
end
|
class LocationsController < ApplicationController
before_action :authenticate_user!
def index
@locations = Location.select(:city).uniq
end
def show
@location = Location.find(params[:id])
end
end |
Rails.application.routes.draw do
use_doorkeeper
devise_for :users
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root 'menus#index'
resources :menus, only: [:index, :show]
resources :orders
namespace :admin do
resources :items
resources :menus
... |
require 'ipay/api_request'
module IPay
module Wallet
def self.default_values
{
:currency_code => IPay.config.defaults[:currency_code],
:currency_indicator => IPay.config.defaults[:currency_indicator],
:transaction_indicator => IPay.config.defaults[:transaction_indicator]
... |
require 'ostruct'
require 'bigdecimal'
class Product < OpenStruct
PRODUCT_ATTRIBUTES = [
{ code: '001', name: 'Red Scarf', price: BigDecimal('9.25') },
{ code: '002', name: 'Silver cufflinks', price: BigDecimal('45') },
{ code: '003', name: 'Silk Dress', price: BigDecimal('19.95') }
].freeze
def sel... |
class CreateAlbums < ActiveRecord::Migration
def change
create_table :albums do |a|
a.belongs_to :user
a.string :title
end
end
end
|
# frozen_string_literal: true
require 'paysafe'
module Paysafe
module Api
module CardPaymentsApiDecorator
def void_authorization(auth_id:, merchant_ref_num:, amount:, **data)
perform_post_with_object(
"/cardpayments/v1/accounts/#{account_number}/auths/#{auth_id}/voidauths",
dat... |
class PartySerializer
def initialize party, user_id = nil
@party = party
@user_id = user_id
end
def to_serialized_json
find_host
find_invite
partyData = {
party: @party,
wines: @party.wines,
invite: @invite,
tastings: f... |
class AddLexicalEntry < ActiveRecord::Migration
def self.up
add_column :lexemes, :lexical_entry, :string
end
def self.down
drop_column :lexemes, :lexical_entry
end
end
|
describe ScheduledReportPolicy do
permissions :can_show? do
it "allows the owner to show" do
report = create(:scheduled_report)
expect(ScheduledReportPolicy).to permit(report.user, report)
end
end
permissions :can_update? do
it "allows owner to update" do
report = create(:scheduled_... |
class ChargesController < ApplicationController
before_action :set_amount, :set_journey
def new
if not @journey.booking_ip == request.remote_ip && @journey.status = "Client created"
user_not_authorized
end
end
def create
# customer = Stripe::Customer.create(
# source: params[:stripeTok... |
# == Schema Information
#
# Table name: responses
#
# id :integer not null, primary key
# responder_id :integer
# answer_id :integer
# created_at :datetime
# updated_at :datetime
#
class Response < ActiveRecord::Base
validates :responder_id, :answer_id, presence: true
validate :respo... |
class ReceiveController < ApplicationController
skip_before_action :verify_authenticity_token
before_action :signed_in_user, only: [:show]
# GET /receive/1
def show
unless current_user.nil?
@message_logs = MessageReceive.all.where(campaign_id: params[:id]).order!(created_at: :desc)
end
end
... |
require 'simplecov'
SimpleCov.start
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require 'capybara/rails'
require 'minitest-vcr'
require 'vcr'
require 'webmock'
class ActiveSupport::TestCase
fixtures :all
end
class ActionDispatch::Integration... |
class FontZenDots < Formula
head "https://github.com/google/fonts/raw/main/ofl/zendots/ZenDots-Regular.ttf", verified: "github.com/google/fonts/"
desc "Zen Dots"
desc "One of three latin fonts part of the zen fonts collection"
homepage "https://fonts.google.com/specimen/Zen+Dots"
def install
(share/"fonts... |
module LinkedResearchMetadata
module Transformer
# Base transformer
#
class Base
# @param config [Hash]
# @option config [String] :url The URL of the Pure host.
# @option config [String] :username The username of the Pure host account.
# @option config [String] :password The pass... |
require 'rails_helper'
RSpec.describe Sefaz::AllotmentsController do
before(:each) { @routes = Sefaz::Engine.routes.url_helpers }
subject do
FactoryGirl.build(:sefaz_allotment)
end
context 'Manipulando dados de cargos' do
it 'Criando um cargo', js: true do
visit @routes.allotments_path
f... |
class FontEdwin < Formula
version "0.54"
sha256 "761a15932defe72b40eecb22e8255cba225bc9efedb208c83e2f5b0b77b7103e"
url "https://github.com/MuseScoreFonts/Edwin/archive/refs/tags/v#{version}.zip"
desc "Text font for musical scores"
homepage "https://github.com/MuseScoreFonts/Edwin"
def install
parent = F... |
extend Algebrick::Matching
def deliver_email(email)
true
end #
Contact = Algebrick.type do |contact|
variants Null = atom,
contact
fields username: String, email: String
end
module Contact
def username
match self,
Null >> 'no name',
Contact >-> { self[:username] }
end
d... |
class Admin::ValorNoticiasController < ApplicationController
layout 'admin'
require_role "administrador"
# GET /valor_noticias
# GET /valor_noticias.xml
def index
@valor_noticias = ValorNoticia.busqueda(params[:page],params[:generico], params[:buscar], 20)
respond_to do |format|
format.ht... |
class UniqueRecipeTagsRelationEntries < ActiveRecord::Migration[5.2]
def change
add_index :recipes_tags, [:tag_id, :recipe_id], :unique => true
end
end
|
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
sequence :user_seq do |n|
"testuser.#{n}@example.com"
end
end
FactoryGirl.define do
factory :user do
name "Test User"
email { FactoryGirl.generate :user_seq }
password 'changeme'
password_confirmation '... |
require 'uri'
require_relative 'objectify'
module Cardinal
# Represents a basic request.
class Request
# GET method
GET = :get
# POST method
POST = :post
# DELETE method
DELETE = :delete
# PUT method
PUT = :put
# UPDATE method
UP... |
require 'test_helper'
class NewsStaysControllerTest < ActionController::TestCase
setup do
@news_stay = news_stays(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:news_stays)
end
test "should get new" do
get :new
assert_response :succe... |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe SavedClaim::EducationCareerCounselingClaim do
let(:claim) { create(:education_career_counseling_claim_no_vet_information) }
let(:user_object) { FactoryBot.create(:evss_user, :loa3) }
describe '#add_claimant_info' do
it 'adds veteran inform... |
def alphanumeric_only input
return_string = ''
input.each_char do | c |
if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')
return_string << c
end
end
return return_string
end
def real_palindrome? input
alphanum_input = alphanumeric_only input.downcase
return true if alphanum_input == alphanu... |
class RenameTablePoiData < ActiveRecord::Migration
def change
rename_table :poi_data, :poi_datas
end
end
|
# 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 rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel... |
#
# lolcat (c)2011 moe@busyloop.net
#
# DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
# Version 2, December 2004
#
# Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
#
# Everyone is permitted to copy and distribute verbatim or modified
# copies of this license document, and changing it is a... |
require 'rails_helper'
RSpec.describe AvailabilityService::Delete, type: :model do
dummy_id = 'test_1'
from = Time.current.change(day: 12, month: 10, year: 2020, hour: 10, min: 0)
it 'returns success when deleting existing availability' do
availability_id = AvailabilityService::Create.new(fp_id: dummy_id, f... |
class Beer < ActiveRecord::Base
has_many :lists
has_many :locations, through: :lists
end
|
require 'rails_helper'
RSpec.describe UnsFeeder::RefreshRiverJob, type: :job do
def job_run
UnsFeeder::RefreshRiverJob.perform_now
end
before(:each) do
FactoryGirl.create(:river_1)
end
it 'refreshes all rivers' do
expect_any_instance_of(UnsFeeder::River).to receive(:refresh)
job_run
end
... |
module Antlr4::Runtime
class LookaheadEventInfo < DecisionEventInfo
attr_reader :predicted_alt
def initialize(decision, configs, predicted_alt, input, start_index, stop_index, fullCtx)
super(decision, configs, input, start_index, stop_index, fullCtx)
@predicted_alt = predicted_alt
end
end
e... |
require 'smarter_csv'
class Player
attr_accessor :player_id, :league, :at_bats, :hits, :doubles, :triples, :home_runs, :rbi, :year, :team
BATTING_FILE = "./data/Batting-07-12.csv"
class << self
def all
players ||=
SmarterCSV.process(BATTING_FILE, {row_sep: "\r"}).map do |player|
csv_r... |
module StudyLevelActivitiesHelper
def components_for_select components
if components.empty?
options_for_select(["This Service Has No Components"], disabled: "This Service Has No Components")
else
deleted_components = components.select{|c| c.deleted_at and c.selected } # deleted and selected
... |
class CreatePersonReferences < ActiveRecord::Migration
def self.up
create_table :person_references do |t|
t.integer :assertion_id
t.string :type
t.string :role
t.string :ref
t.string :tempId
t.timestamps
end
end
def self.down
drop_table :person_references
end
en... |
# convert_signed_num_to_str.rb
# In the previous exercise, you developed a method that converts non-negative
# numbers to strings. In this exercise, you're going to extend that method by
# adding the ability to represent negative numbers as well.
# Write a method that takes an integer, and converts it to a string
# re... |
class JournalsController < ApplicationController
before_action :authenticate_user!, except: [:show]
before_filter :require_permission
before_action :find_user
before_action :find_journal, only: [:show, :edit, :update, :destroy]
def new
@journal = @user.journals.new
end
def create
@journal = @user.journals... |
# Challenge 1: Create a method BST which makes a Binary Search Tree.
# Challenge 2: Is Value in Binary Search Tree?
# Write the function is_value_present? that takes the root node of a binary search tree and an integer as arguments and returns true or false if the integer is in the tree.
# Challenge 1
# class Node
# ... |
# frozen_string_literal: true
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
APIresponse = Struct.new(:status, :message ,:data)
protect_from_forgery with: :null_session
#define error responses on... |
require 'test/unit'
require 'sqlite3'
require_relative '../model/User'
require_relative '../model/Merchant'
require_relative '../model/Transactions'
class TransactionTests < Test::Unit::TestCase
@@user_details = {
'name' => 'rakesh',
'email' => 'rakesh@example.com',
'credit_limit' => 400
}
@@merchant_detail... |
require_relative 'mapper'
module Jeoparty
class User < Mapper::Model
attr_accessor :id, :redis
def User.get(user_id)
user = User.new
user.id = user_id
user.redis = Mapper.redis
user
end
def is_global_moderator?
@redis.sismember('global_moderators', id)
end
def... |
class AddIndexToPostDate < ActiveRecord::Migration
def self.up
add_index :posts, :date, unique: true
end
def self.down
remove_index :posts, :date
end
end
|
class Curatorial < ActiveRecord::Base
before_validation :generate_slug
belongs_to :user
has_many :post_attachments, dependent: :destroy
accepts_nested_attributes_for :post_attachments
has_many :exhibitions, dependent: :destroy
has_many :artists, through: :exhibitions
validates :slug, presence: true
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.