text stringlengths 10 2.61M |
|---|
# prereqs: iterators, hashes, conditional logic
# Given a hash with numeric values, return the key for the smallest value
def key_for_min_value(hash)
min = nil
hash.each_pair do |key, value|
min ||= value
min = value if value < min
end
hash.key(min)
end |
class CreateBulkAssets < ActiveRecord::Migration
def change
create_table :bulk_assets do |t|
t.integer :user_id
t.string :state, :default => '', :null => false
t.string :asset_type, :default => '', :null => false
t.string :path, :default => '', :null => false
t.string :host, :def... |
class Post
attr_accessor :title, :author
@@all = []
def initialize(title, author = nil)
@title = title
@author = author
save
end
def save
@@all << self
end
def self.all
@@all
end
def author
@author
end
def author_name
if self.author == nil
return nil
else
self.author.name
end
e... |
require 'json'
require 'csv'
require 'awesome_print'
require 'date'
def post_process_slash(date)
date = date.gsub(" ", "").gsub("201B", "2018")
date = date.split("/")
format_date = "#{date[0]}/#{date[1]}/#{date[2][0..3]}"
datetime = date[2][4..date[2].size]
hour = datetime[0...2]
minutes = datetime[(datetime.si... |
module Antlr4::Runtime
class AtomTransition < Transition
attr_reader :the_label
def initialize(target, label)
super(target)
@the_label = label
end
def serialization_type
ATOM
end
def label
IntervalSet.of(@the_label)
end
def matches(symbol, _min_vocab_symbol... |
class AddPrecioToProdcutos < ActiveRecord::Migration
def change
add_column :prodcutos, :Precio, :int
end
end
|
class FontChokokutai < Formula
head "https://github.com/google/fonts/raw/main/ofl/chokokutai/Chokokutai-Regular.ttf", verified: "github.com/google/fonts/"
desc "Chokokutai"
desc "Japanese display font whose characters have a funky appearance"
homepage "https://fonts.google.com/specimen/Chokokutai"
def install... |
=begin
#===============================================================================
Title: NeonBlack Passive Conditional States patch
Author: Hime
Date: May 9, 2015
--------------------------------------------------------------------------------
** Change log
May 9, 2015
- fixed crashing bug due to recursiv... |
# 08.13.2020
# Ungraded questions at the end of unit 5 exercises
# Question 1
# Create an array to store 3 boolean values entered in by the user.
# Print out YES if all the values are true and NO if at least one value is false.
# Hint: Prompt the user to enter true or false, and accept those values using gets.
# Sin... |
require 'csv'
# RunnerCompanies
class RunnerCompanies
def initialize(csv_source, csv_output)
@csv_source = csv_source
@csv_output = csv_output
end
def execute
headers = get_headers(@csv_source)
hash_headers = headers_to_hash(headers)
write_rows = []
read_data(@csv_source, hash_headers, ... |
# frozen_string_literal: true
require 'sinatra/base'
require 'jiji/web/middlewares/base'
module Jiji::Web
class AuthenticationFilter < Base
include Jiji::Errors
before do
return if request.request_method == 'OPTIONS'
unauthorized unless auth_success?
end
private
def auth_success... |
FactoryBot.define do
factory :booking do
sequence(:ticket_number) { |n| n }
sequence(:booking_number) { |n| n }
timestamp "2018-01-23 11:36:44"
price 25
product_type "abonnement"
selling_point "guichet"
venue
spectator
end
end
|
# ask for the loan amount
# ask for the APR
# ask for loan duration
# caclulate monthly intrest rate and loan duration in months
# tell user the full loan term and monthly payment amount
def say(input)
Kernel.puts("==>> #{input} <<==")
end
def caclulate(principal, apr, term)
annual_interest_rate = apr.to_f() / 10... |
# frozen_string_literal: true
class IndexDocumentSerializer < ActiveModel::Serializer
attributes :id, :title, :owner_name, :tags, :text, :preview_attachment
def owner_name
object.owner.username
end
def id
object.id.to_s
end
end
|
module VirtualBox
# VirtualBox virtual machine.
class Vm
# The UUID used to register this virtual machine with VirtualBox.
#
# The UUID is used to identify the VM in many VirtualBox commands. It should
# not be changed once the VM is registered. In fact, the UUID should not
# be manually assigned under norma... |
class AddSubStatToStats < ActiveRecord::Migration[5.1]
def change
add_reference :stats, :sub_stat, foreign_key: true
end
end
|
class Post
include Mongoid::Document
include Lolita::Configuration
field :title, type: String
field :body, type: String
field :is_public, type: Boolean
field :price, type: BigDecimal
field :published_at, type: DateTime, default: -> { Time.now }
field :expire_date, type: Date
belongs_to :category, opti... |
require 'json'
require 'net/http'
require 'steam_id'
require 'validators/reduce_errors_validator'
class League
class Match
class Round < ApplicationRecord
default_scope { order(:id) }
belongs_to :match, class_name: 'Match'
belongs_to :map
belongs_to :winner, class_name: 'League::Roster'... |
class MembershipsController < ApplicationController
before_action :require_family
before_action :set_membership, only: [:show]
before_action :load_primary_user_profile, only: [:new, :create, :show]
def pending
authorize Membership
@memberships_pending_approval = Membership.status_pending_approval
en... |
FactoryBot.define do
factory :group do
name { Faker::Creature::Animal.name }
end
end |
class RockPaperScissors
# Exceptions this class can raise:
class NoSuchStrategyError < StandardError
end
def self.winner(player1, player2)
strategy = player1[1] + player2[1]
strategy.upcase!
if strategy =~ /[^RPS]/
raise(NoSuchStrategyError, "Strategy must be one of R,P,S")
end
player... |
# encoding: utf-8
#
# © Copyright 2013 Hewlett-Packard Development Company, L.P.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
#... |
module Intcode
class Interpreter
Opcodes = {
1 => :func_add,
2 => :func_mul,
99 => :func_halt,
}.freeze
def initialize(mem)
@memory = mem.dup
@iptr = 0
end
def run
interpret
end
def memory_read(i)
raise Intcode::MemoryOverflowException if i >= @... |
#
# Cookbook Name:: keyczar
# Recipe:: default
#
# 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 agre... |
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :http_authenticatable, :token_authenticatable, :lockable, :timeoutable and :activatable
devise :registerable, :authenticatable, :recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attri... |
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
# Load the version directly from the source tree.
require 'scaffold/version'
Gem::Specification.new do |spec|
spec.name = 'Scaffold'
spec.version = Scaffold::VERSION
spec.authors = ['Peter Adkins'... |
#!/usr/bin/ruby
#irb
#ruby ~/Desktop/first.rb
puts "What is your name?"
name = gets.chomp
puts "Hello " + name + ", I am glad to meet you!"
puts "Are you a guy or a girl?"
while true
a = gets.chomp
if a == "guy" or a == "Guy"
puts "How's it going dude?"
break
elsif a == "girl" or a == "Girl"
puts "Hey girl!"
... |
# -*- coding: utf-8 -*-
class Project < ActiveRecord::Base
has_many :categories, -> { order(:position) }, dependent: :destroy
has_many :project_tasks, -> { order(:position) }, dependent: :destroy
has_many :additional_costs, -> { order(:position) }, dependent: :destroy
accepts_nested_attributes_for :project_task... |
class Confirmation < ActiveRecord::Base
belongs_to :user
attr_encrypted :extra, key: ENV['ITPKG_PASSWORD'], mode: :per_attribute_iv_and_salt
validates :token, :extra, :user_id, :deadline, :status, :subject, presence: true
validates :token, uniqueness: true
enum status: {submit: 0, done: -1}
end
|
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def get_error_messages
return self.errors.messages if self.errors.present?
return nil
end
end
|
module Nestable
# The standard interface for all nestable strategies. Every nestable ActiveRecord
# instance should respond to these methods regardless of which strategy was used.
module Interface
# Returns an array containing the ids of a node's ancestors
def ancestor_ids
end
# Returns an array... |
class RemoveBeginerFlagaMaxHeightFromRoadbikes < ActiveRecord::Migration[5.0]
def change
remove_column :roadbikes, :beginer_flag, :boolean
remove_column :roadbikes, :max_hight, :integer
end
end
|
# encoding: utf-8
class LogStash::Outputs::RabbitMQ
module BunnyImpl
#
# API
#
def register
require "bunny"
@logger.info("Registering output", :plugin => self)
connect
declare_exchange
end # def register
def receive(event)
return unless output?(event)
... |
class Chapter < QuranApiRecord
has_many :verses, inverse_of: :chapter
has_many :translated_names, as: :resource
has_many :chapter_infos
serialize :pages
alias_method :name, :id
end
|
require 'spec_helper'
feature 'Admin enters evaluations panel and' do
attr_reader :judges, :evaluations, :challenge_with_criteria, :challenge_with_no_criteria,
:challenge_with_no_judges, :entries, :evaluation_with_criteria
before do
# users
organization = create :organization
admin = cre... |
#!/usr/bin/ruby -w
require 'test/unit'
class TC_isp < Test::Unit::TestCase
def setup
$lib_net.call :captive_setup
`mkdir -p run log`
`rm run/* log/*`
`cp ../multiconf-captive.orig multiconf-captive`
$lib_net.call_args( :change_var, "multiconf-captive ISP test" )
end
def test_to_json
a... |
require 'rails_helper'
RSpec.describe Taxon, type: :model do
include ContentSchemaHelpers
include ServicesRequestHelpers
describe "#content_item" do
before(:each) do
@example_schema = example_content_schema("taxon", "taxon_with_child_taxons")
@topic_taxon = Taxon.new("education")
end
it... |
require 'httparty'
class Send
attr_reader :url, :array_fields
def initialize(url = 'https://delivery-center-recruitment-ap.herokuapp.com/')
@url = url
end
# verifica todos os campos obrigatorios da API e gera uma lista
def requestFields
req = HTTParty.post(@url, headers: {
... |
module CommitsHelper
def short_hash
commit_hash[0..7]
end
def completion_color
completion_ratio >= 100 ? 'success' : 'warning'
end
def score_icon
score >= 0 ? 'ok text-success' : 'remove text-danger'
end
def score_color
score >= 0 ? 'green' : 'red'
... |
json.meals @meals do |meal|
json.extract! meal, :id, :quantity
json.date meal.created_at.in_time_zone("Beijing").strftime('%Y-%m-%e')
json.time meal.created_at.in_time_zone("Beijing").strftime('%l:%M %p')
json.dish meal.dish.name
json.dish_short meal.dish.name[0..20] + ".."
json.image meal.dish.image
js... |
require "rails_helper"
describe "The webhook" do
it "creates events" do
expect {
post "/events", params: { email: "foo@example.com" }
}.to change(Event, :count).by(1)
event = Event.last
expect(event.email).to eq("foo@example.com")
end
end
|
# == Schema Information
#
# Table name: managers
#
# id :bigint(8) not null, primary key
# created_at :datetime not null
# updated_at :datetime not null
# user_id :bigint(8)
#
class Manager < ApplicationRecord
belongs_to :user
has_one :restaurant
validates :user_id, presenc... |
# U2.W5: Class Warfare, Validate a Credit Card Number
# I worked on this challenge by myself.
# 2. Pseudocode
# Input: 16 digit credit card number
# Output: true if valid card number, false if invalid card number
# Steps:
# => Create class CreditCard and initialize with single card number parameter
# => Create met... |
class AddColumnToPublicationTypes < ActiveRecord::Migration
def change
add_column :publication_types, :label, :text
PublicationType.reset_column_information
end
end
|
# encoding: utf-8
#! /usr/bin/env ruby
##
#13/03/2014
#Projet Picross equipe CrakeTeam
#
#Ce fichier contient la classe Rangee, qui est constituee de Case
#ici une description de la classe Rangee.
require_relative "Case.rb"
class Rangee
@cases
@conditions
@valide
# Variable destinée à contenir le tableau... |
# json.array! @transactions, :amount_in_cents, :created_at
json.customer do
json.(@current_customer, :first_name, :last_name, :balance, :email)
end
json.transactions do
json.array! @transactions do |transaction|
json.(transaction, :amount_in_cents)
json.created_at transaction.created_at.utc.to_i
jso... |
class GithubService
attr_reader :auth, :username, :access_token, :connect, :auth
def initialize(current_user)
@username = current_user.username
@access_token = current_user.token
end
def connect
Faraday.new(:url => 'https://api.github.com') do |faraday|
faraday.adapter Faraday.default_adapt... |
require File.dirname(__FILE__) + "/lib/version"
Gem::Specification.new do |spec|
spec.name = 'irobot'
spec.version = Irobot::VERSION
spec.summary = 'Parse robots.txt file'
spec.authors = ['Moz']
spec.email = 'help@moz.com'
spec.homepage = 'http://github.com/seomoz/irobot'
spec.files = `git ls-files`... |
class AddAtvToUsers < ActiveRecord::Migration
def change
add_column :users, :atv, :boolean
remove_index :users, column: [:published, :approved]
add_index :users, [:published, :approved, :atv]
end
end
|
class SessionsController < ApplicationController
skip_load_and_authorize_resource
skip_login :except => :destroy
logout :only => [:new, :create]
def new
@login = Login.new
end
def create
@login = Login.new params[:login]
if self.current_user = @login.validate
flash[:notice] = "Hello #{cu... |
# -*- encoding : utf-8 -*-
class CreateProducts < ActiveRecord::Migration
def change
create_table :products do |t|
t.integer :zayavka_id
t.string :naim
t.string :codyktved
t.string :nomenkl
t.string :kolvo
t.string :factstoim
t.string :dopinfo
t.string :opis_all
... |
default['app'] = 'mr-chef'
default['user']['name'] = 'vagrant'
default['user']['group'] = 'vagrant'
default['ruby']['version'] = '2.1.1'
default['mysql']['versions'] = '5.6.16-1.el6.x86_64'
default['mysql']['file_name'] = 'MySQL-5.6.16-1.el6.x86_64.rpm-bundle.tar'
default['mysql']['remote_uri'] = 'http://ftp.jaist... |
class RemoveStatusMkFromCardPlans < ActiveRecord::Migration
def up
remove_column :card_plans, :statusMK
end
def down
add_column :card_plans, :statusMK, :string
end
end
|
class Course < ApplicationRecord
extend EnumerateIt
has_enumeration_for :status, with: CourseStatus
# relations
has_many :classrooms
# validations
validates_presence_of :name
end
|
Given(/^the On-line Help icon on login page of eHMP\-UI$/) do
p "running test #{TestSupport.test_counter} #{TestSupport.test_counter % 20}"
if ENV.keys.include?('LOCAL') || TestSupport.test_counter % 20 == 0
p 'refresh the app'
TestSupport.navigate_to_url(DefaultLogin.ehmpui_url)
else
TestSupport.navi... |
class ItemsController < ApplicationController
before_action :set_auction
before_action :set_item, only: [:show, :edit, :update, :destroy, :highest_bid, :my_bids]
def highest_bid
@bid = @item.bids.order("value DESC").first
respond_to do |format|
if @bid
format.json { render 'bids/show', loca... |
require 'rails_helper'
feature 'Post Delete action' do
given(:user) { create(:user) }
given(:wrong_user) { create(:user) }
given(:admin) { create(:user, admin: true) }
given!(:category) { create(:category) }
given!(:post) { create(:post, category: category, user: user) }
scenario 'admin tries to delete po... |
require 'spec_helper'
describe Mist::PostsHelper do
describe "with 7 posts" do
before do
%w(one two three four five six seven).each do |title|
Mist::Post.create!(:title => title, :content => "#{title} content", :published => true)
end
end
it "should only return 5 posts" do
... |
class SecretsController < ApplicationController
def show
return head(:forbidden) unless session.include?
end
end
|
# coding: utf-8
if node["platform"] != "redhat" && node["platform_version"] != 6.8 then
exit(1)
end
directory "/tmp/work"
directory "/home/"+node["userdata"]["name"]+"/opt"
execute "build yasm" do
cwd "/tmp/work/"
user node["userdata"]["name"]
command <<-EOH
if [ ! -d /tmp/work/yasm ]; then
git clone --dept... |
# == Schema Information
#
# Table name: cat_rental_requests
#
# id :integer not null, primary key
# cat_id :integer not null
# start_date :date not null
# end_date :date not null
# status :string default("PENDING"), not null
# created_at :datet... |
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :books, dependent: :destroy
attachment :pro... |
require 'spec_helper'
describe Libretsy::Request do
before(:each) do
@client = Libretsy::Client.new(default_client_attributes)
end
describe "#initialize" do
end
describe "#self.request" do
it "calls new on the LoginRequest" do
request = mock("request", :do_request => "")
Libretsy::Reque... |
#The ruby test file to check the contents inside the install class in
#the scalr module
require 'spec_helper'
describe 'scalr::install' do
context 'install php5 and all php dependencies' do
it { should contain_package('php5-dev').with_ensure('present')}
it { should contain_package('php5-mcrypt').with_ensure('pr... |
require 'rails_helper'
RSpec.describe Enrollment, type: :model do
describe '#create' do
context 'when subject and study are valid' do
let!(:enrollment) {create(:enrollment)}
it 'creates a delayed job' do
expect(Delayed::Job.count).to eq(2)
end
end
context 'when wither subject o... |
class Delivery < ApplicationRecord
belongs_to :customer
validates :postcode, :name, :address, presence: true
def delivery_full_address
'〒' + self.postcode + ' ' + self.address + ' ' + self.name
end
end
|
require 'rails_helper'
RSpec.describe TimeCardsHelper, type: :helper do
describe '#time_diff_str' do
let(:time_card) { create(:time_card) }
let(:now) { Time.zone.now }
subject(:str) { helper.time_diff_str(time_card.work_hours_in_seconds) }
before { time_card.in_at = now }
it do
time_... |
class LibraryApi < ActiveRecord::Base
# Scopes
scope :active_library, -> { joins(:"library_#{I18n.locale.to_s}").order("library_#{I18n.locale.to_s}s.name").where(active: true) }
# Relations
has_many :library_locations
Reusable.has_many_translations(self)
accepts_nested_attributes_for :library_locations
... |
require 'date'
class Markio::Bookmark
# ## NETSCAPE-Bookmark format settings
# @param [String] :title, :href, :add_date, :last_visit, :last_modified, :folders, :icon_uri, :icon, :last_charset
# @!attribute [rw] title
# @return [String] title of item, example The Ruby Reflector in <DT><A ...>The Ruby Reflecto... |
require "spec_helper"
describe RequisitometrologicosController do
describe "routing" do
it "routes to #index" do
get("/requisitometrologicos").should route_to("requisitometrologicos#index")
end
it "routes to #new" do
get("/requisitometrologicos/new").should route_to("requisitometrologicos#n... |
class FontVazirmatn < Formula
head "https://github.com/google/fonts/raw/main/ofl/vazirmatn/Vazirmatn%5Bwght%5D.ttf", verified: "github.com/google/fonts/"
desc "Vazirmatn"
desc "Combined with roboto"
homepage "https://fonts.google.com/specimen/Vazirmatn"
def install
(share/"fonts").install "Vazirmatn[wght]... |
class CreatePropiedads < ActiveRecord::Migration
def change
create_table :propiedads do |t|
t.string :tipo_operacion
t.string :tipo_inmueble
t.string :titulo
t.string :subtitulo
t.text :descripcion
t.string :localizacion
t.string :distrito
t.string :direccion
... |
# frozen_string_literal: true
require './pdf'
module FasTMassMailing
class LettersPDF < PDF
def initialize(content_name:)
@page_margin = [0, 20.mm]
@content_name = content_name
super page_size: 'A4', page_layout: :portrait, margin: @page_margin
create_stamp('logo') do
draw_logo... |
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
layout :layout_by_resource
before_action :configure_permitted_parameters, if: :devise_controller?
rescue_from Ca... |
class Item < ApplicationRecord
validates :genre_id, :name, :price, presence: true
validates :introduction, length: {maximum: 200}
validates :price, numericality: { only_integer: true }
attachment :image
belongs_to :genre
has_many :item_orders, dependent: :destroy
has_many :cart_items, dependent: :des... |
require 'pry'
require 'pry-byebug'
#CLASS - LAB TIME & HOMEWORK
# Write a program that prints 99 bottles of beer on the wall.
# The song starts with
# 99 bottles of beer on the wall
# 99 bottles of beer!
# You take one down and pass it around,
# 98 bottles of beer on the wall!
#
# And ends with
# 1 bottle of beer on ... |
require 'rails_helper'
describe Ingredient do
it "has valid factories" do
expect(build(:ingredient)).to be_valid
end
let(:ingredient) { build(:ingredient) }
describe "ActiveModel validations" do
it { should validate_presence_of(:measure) }
it { should validate_presence_of(:item) }
it ... |
class CreateThirds < ActiveRecord::Migration
def change
create_table :thirds do |t|
t.string :register_number
t.string :name
t.string :fantasy_name
t.string :social_name
t.string :rg
t.string :cpf
t.references :diligent_profile, index: true, foreign_key: true
t.refe... |
FactoryGirl.define do
factory :piece do
association :piece_name
association :judicial_type
initial_date {Faker::Date.between(30.days.ago, Date.today)}
deadline {Faker::Date.between(30.days.ago, Date.today)}
association :piece_result
association :client
associa... |
require 'rails_helper'
RSpec.describe Tweet, type: :model do
# Association test
# ensure a tweet record belongs to a single user record
it { should belong_to(:user) }
# Validation test
# ensure column text is present before saving
it { should validate_presence_of(:text) }
end
|
require 'rugged'
require 'pathname'
module Flaggrocrag
class Repository
def initialize(dir)
@repo = Rugged::Repository.new(dir)
end
def dirty?
diff_workdir.size.nonzero?
end
def deltas
diff_workdir.deltas.map do |delta|
delta.new_file[:path]
end
end
def ... |
require File.expand_path('../../../config/environment', __FILE__)
require 'faraday'
require 'flickraw'
require 'dotenv'
::Dotenv.load
FlickRaw.api_key = ENV['FLICKR_API_KEY']
FlickRaw.shared_secret = ENV['FLICKR_API_SECRET']
class DlImage < Thor
desc "latest_image_url", "output latest image url."
def latest_ima... |
require 'snmp2mkr/config_types/base'
module Snmp2mkr
module ConfigTypes
class HostSnmpDefinition < Base
def setup(h)
@version = h.fetch('version', '2c')
@community = EnvString.new(h.fetch('community', 'public'))
end
attr_reader :version, :community
def collect_children
... |
$:.unshift File.expand_path(File.dirname(__FILE__) + "/../../lib")
$:.unshift File.expand_path(File.dirname(__FILE__) + "/../../ext")
require 'ray'
def path_of(res)
File.expand_path File.join(File.dirname(__FILE__), '../../test/res', res)
end
class SpriteAnimation < Ray::Animation
register_for :sprite_animation
... |
json.description 'Authenticate based on credentials.'
json.login {
json.identifier {
json.description 'Unique identifier. Currently username and email are supported.'
json.type 'String'
json.required true
}
json.password {
json.description "The User's password."
json.type 'String'
... |
class Lock
def initialize
@semaphore = Semaphore.new(1)
end
def critical_section
@semaphore.wait
yield
@semaphore.signal
end
end
|
class PostsController < ApplicationController
def index
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
@post.user = current_user
if @post.save
redirect_to event_path(@post.event_id)
end
end
private
def post_params
params.require(:post).permi... |
Rails.application.routes.draw do
devise_for :users
resources :user ,only: [:update]
resources :lists
root to: 'lists#index'
delete '/select_delete', to: 'lists#select_delete', as: 'select_delete'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
|
class MemberTariff < ActiveRecord::Base
has_many :members
attr_accessible :name, :description
validates :name, :presence => true, :uniqueness => true
end
|
class PromotionSetVariable < ArrayVariable
store_accessor :data, :promotion_string
attr_accessor :promotion_ids
validates :promotion_string, presence: { message: "请至少选择一个活动!" }
def call
Promotion.where(ids: promotion_ids).to_a
end
def promotion_ids
(promotion_string || '').split(',')
end
end
|
class FontLinuxLibertine < Formula
version "5.3.0_2012_07_02"
sha256 "24a593a949808d976850131a953c0c0d7a72299531dfbb348191964cc038d75d"
url "https://downloads.sourceforge.net/linuxlibertine/LinLibertineTTF_#{version}.tgz"
desc "Linux Libertine"
homepage "https://sourceforge.net/projects/linuxlibertine/"
def... |
class FontRubikMonoOne < Formula
head "https://github.com/google/fonts/raw/main/ofl/rubikmonoone/RubikMonoOne-Regular.ttf", verified: "github.com/google/fonts/"
desc "Rubik Mono One"
homepage "https://fonts.google.com/specimen/Rubik+Mono+One"
def install
(share/"fonts").install "RubikMonoOne-Regular.ttf"
... |
# @see http://www.gurobi.com/documentation/5.0/quick-start-guide/node12
$LOAD_PATH.unshift(
File.expand_path('../../lib', __FILE__),
File.join(ENV['GUROBI_HOME'], 'lib')
)
require 'java'
require 'gurobi'
java_import 'gurobi.GRBException'
begin
# Create a new model
model = Gurobi::Model.new
# Create varia... |
module Praxis
class Collection
# checks if +type+ is a MediaType, and if so, if it has an inner
# Collection class defined
def self.of(type)
if type < Attributor::Type && defined?(type::Collection)
return type::Collection
end
Attributor::Collection.of(type)
end
end
end... |
require "simplecov"
if ENV["TRAVIS"]
require "coveralls"
SimpleCov.formatter = Coveralls::SimpleCov::Formatter
end
SimpleCov.start do
# No need to report coverage metrics for the test code
add_filter "test"
end
# Eager load the entire lib directory so that SimpleCov is able to report
# accurate code coverage... |
require 'rails_helper'
RSpec.describe Company, type: :model do
describe 'validations' do
it { should have_many :users }
it { should have_many :calendars }
it { should have_many(:api_keys).through(:calendars) }
end
end
|
FactoryGirl.define do
factory :comment do
message "Welcome"
rating "5_stars"
association :usermodel
association :stay
end
factory :usermodel do
sequence :email do |n|
"test#{n}@gmail.com"
end
password "lalalala"
password_confirmation "lalalala"
end
factory :stay do
name "Home"
descripti... |
# -*- encoding : utf-8 -*-
class CourseTrack < ActiveRecord::Base
belongs_to :track_type, class_name: 'CourseTrackType', foreign_key: 'course_track_type_id'
belongs_to :course
validate :costs_completeness
private
def costs_completeness
(costs && costs_currency) || (costs.nil? && costs_currency.nil?)
... |
require 'rails_helper'
RSpec.describe StatisticsController, type: :controller do
before do
request.headers.merge!(
'Api-Key': ENV['API_KEY'], 'Api-Secret': ENV['API_SECRET']
)
end
describe '#show' do
let(:final_statistics) do
{
temperature: { min: 9, avg: 9, max: 9 },
hum... |
# encoding: UTF-8
# Copyright 2012 Twitter, Inc
# http://www.apache.org/licenses/LICENSE-2.0
require 'spec_helper'
describe TwitterCldr::Transforms::RuleSet do
test_data = YAML.load_file(
File.join(File.dirname(__FILE__), 'test_data.yml')
)
# Use this to specify a list of transform tests to run.
# Mostl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.