text stringlengths 10 2.61M |
|---|
# == Schema Information
#
# Table name: contacts
#
# id :integer not null, primary key
# name :string(255)
# phone :string(255)
# email :string(255)
# method :string(255)
# notes :text
# type :string(255)
# contactable_id ... |
# This is for a basic device version check. Platforms with more parameters can subclass.
class DeviceConfig
attr_reader :host, :platform, :topic
def initialize(config)
@host = config['host']
@platform = config['platform']
@topic = config['topic']
raise "Version check definition does not include a... |
require 'test_helper'
class StaticPagesControllerTest < ActionDispatch::IntegrationTest
def setup
@base_title = "Bio Topics"
end
test "ページタイトル付きでhome(root)ページを取得" do
get "/"
assert_response :success
assert_select "title", "Home | #{@base_title}"
end
test "ページタイトル付きでhelpページを取得" do
get... |
class User < ApplicationRecord
has_one_attached :avatar
has_secure_password
before_validation {email.downcase!}
before_destroy :least_one
# before_update :thumbnail
has_many :tasks , dependent: :destroy
has_many :user_groups, dependent: :destroy
has_many :groups, through: :user_groups, source: :grou... |
require 'csv'
def convert
in_file = "cc-full.txt"
out_file = File.new("pzd.txt", "w")
# Write header row
# City State Zip County SPLC Country Placeholder
out_file << "City\tState\tZip\tCounty\tSPLC\tCountry\tPlaceholder\n"
reader = CSV.open(in_file, "r")
i = 0
reader.each do |row|
city = row[2]... |
class ContactMailer < ApplicationMailer
def contact_mail(musical_instrument, contact, current_user)
@musical_instrument = musical_instrument
@contact = contact
@current_user = current_user
if @current_user.id == @musical_instrument.lender.id
mail to: @musical_instrument.borrower.email, subject:... |
class HomePostsController < ApplicationController
before_filter :admin_filter
skip_before_filter :admin_filter, :only => [:show]
# GET /home_posts
# GET /home_posts.json
def index
@home_posts = HomePost.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @ho... |
# -*- encoding: UTF-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'gem-changelog/version'
Gem::Specification.new do |spec|
spec.name = "gem-changelog"
spec.version = Gem::Changelog::VERSION
spec.authors = ["OZAWA Sakuro"]
s... |
class CreateEnergyApplications < ActiveRecord::Migration[5.2]
def change
create_table :energy_applications do |t|
t.integer :clientID
end
end
end
|
# encoding: utf-8
class Offer < ActiveRecord::Base
belongs_to :user
belongs_to :team
validates :content, :presence => true, :length => { :maximum => 350 }
def from
if originated_from_player
user
else
team
end
end
def to
if originated_from_player
team
else
... |
require 'dm-timestamps'
require 'dm-validations'
class Post
include DataMapper::Resource
property :id, Serial
property :name, String, :required => true, :length => 3..20
property :body, String, :required => true, :length => 5..500
property :created_at, DateTime
validates_length_of :name, :message... |
class User < ActiveRecord::Base
before_save :encrypt_password
validates_presence_of :username
validates_uniqueness_of :username
validates_length_of :username, :within => 4..20
validates_confirmation_of :password, :if => :password_required?
def self.encrypt(pass,salt)
Digest::SHA1.hexdigest(salt+p... |
require 'test_helper'
require 'stripe_mock'
class CheckoutsControllerTest < ActionDispatch::IntegrationTest
include Devise::Test::IntegrationHelpers
setup do
sign_in users(:client)
end
teardown do
sign_out users(:client)
end
test 'must checkout as a registered user' do
sign_out users(:client)... |
require_dependency 'projects_controller'
module LikeProjectsControllerPatch
def self.included(base)
base.send(:include, InstanceMethods)
base.class_eval do
unloadable
alias_method_chain :show, :like_count
before_filter :find_project, :except => [ :index, :list, :new, :create, :copy, :rank... |
class CategoriesController < ApplicationController
def index
end
def show
@category = Category.find(params[:id])
@topics = Topic.where(category_id: @category)
@root = Topic.find(0)
map = {}
@topics.each do |e|
map[e[:id]] = e
end
@tree = {}
@topics.each do ... |
require 'open3'
module AssertExec # mix-in
def assert_exec(cmd)
stdout,stderr,status = Open3.capture3(cmd)
if status != 0
raise ArgumentError.new("#{stdout}:#{stderr}:#{status}:#{cmd}")
end
stdout
end
end
|
require_relative 'spec_helper'
describe 'App' do
let(:realm) { ENV['quickbooks_realm'] }
let(:secret) { ENV['quickbooks_access_secret'] }
let(:token) { ENV['quickbooks_access_token'] }
let(:headers) {
{
"Content-Type": "application/json"
}
}
include Rack::Test::Methods
def app
Quickb... |
dep 'cultureamp' do
log <<-LOG
Welcome to Culture Amp.
Commands you're probably interested in:
babushka 'cultureamp appusers'
-- Configure all the users require to support the Culture Amp apps.
Generally you will want to run babushka with --defaults. This will run
with preconfigured defaults for Culture ... |
require 'rails_helper'
describe Problem do
before do
@problem = create(:problem)
end
subject { @problem }
it { should respond_to :title }
it { should respond_to :statement }
it { should respond_to :contest_only? }
it { should respond_to :permalink }
it { should respond_to :setter }
it { should... |
# frozen_string_literal: true
require 'encase'
module Jiji::Model::Trading
class TickRepository
include Encase
include Jiji::Errors
needs :securities_provider
def fetch(pairs, start_time, end_time, interval_id = :fifteen_seconds)
illegal_argument('illegal pairs') if pairs.blank? || pairs.em... |
class CadastroPlanoDeVoosController < ApplicationController
before_action :set_cadastro_plano_de_voo, only: [:show, :edit, :update, :destroy]
# GET /cadastro_plano_de_voos
# GET /cadastro_plano_de_voos.json
def index
@cadastro_plano_de_voos = CadastroPlanoDeVoo.all
end
# GET /cadastro_plano_de_voos/1
... |
name 'amazon-ecs-agent'
maintainer 'Will Salt'
maintainer_email 'williamejsalt@gmail.com'
source_url 'https://github.com/willejs/chef-amazon-ecs-agent'
issues_url 'https://github.com/willejs/chef-amazon-ecs-agent/issues'
license 'Apache 2.0'
description 'Installs/Configures amazon-ecs-agent'
long_description 'Installs/... |
# Inserts a new middleware between each actual middleware in the application,
# so as to trace the time for each one.
#
# Currently disabled due to the overhead of this approach (~10-15ms per request
# in practice). Instead, middleware as a whole are instrumented via the
# MiddlewareSummary class.
#
# There will likel... |
require 'fileutils'
# Code shared between ruby/ and ruby_parallel/
class Mapper
attr_accessor :input_file, :output_file
def initialize(input_file, output_file)
@input_file = input_file
@output_file = output_file
end
def map
puts "mapping #{input_file} to #{output_file}"
FileUtils.mkdir_p File... |
# frozen_string_literal: true
require 'spec_helper'
describe 'preview', type: :feature do
before(:each) do
@site = Factory(:site, domain: '127.0.0.1.xip.io')
url = 'post/1'
@post_url = "#{root_url(domain: @site.domain)}#{url}"
@post_title = 'post 1'
@post = Factory(:post, title: @post_title, url: ... |
def hotels_available
hotel1 = "Ritz Carlton"
hotel2 = "Hilton"
puts "Which hotel is available?"
yield(hotel1, hotel2)
end
puts "Before the block runs"
hotels_available { |hotel1, hotel2| puts "The #{hotel1} is available. The #{hotel2} is not available."}
puts "After the block runs"
#Release 1
pets = ["d... |
# --------------------------------------------------------------------------- #
# By starting at the top of the triangle below and moving to adjacent numbers
# on the row below, the maximum total from top to bottom is 23.
#
# 3
# 7 4
# 2 4 6
# 8 5 9 3
#
# That is, 3 + 7 + 4 + 9 = 23.
#
# Find the maximum tota... |
class Character
#include Validates
attr_reader :level, :race, :prof, :fullhp
attr_accessor :currenthp
def initialize (args={})
args.each { |k, v| eval "@#{k}=v" }
post_init(args)
end
def post_init(args) # Hook for subtypes
raise NotImplementedError, "This #{self.class} cannot respond to: "
... |
Pod::Spec.new do |spec|
spec.name = "MGEDateFormatter"
spec.version = "2.0.1"
spec.summary = "A handy API to convert `Date` to `String` and back written in swift"
spec.description = <<-DESC
MGEDateFormatter provides a set of extensions to `Date` and `DateFormatter` to build a nice API whic... |
require File.expand_path('../boot', __FILE__)
require 'active_record/railtie'
require 'action_controller/railtie'
require 'action_mailer/railtie'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module CryptoTeller
clas... |
#
# Monit is a website for visulizing information on the
# availablilty of applications running on systems.#
#
if node['nginx']['monit_available']
template '/etc/nginx/sites-available/monit' do
owner 'root'
group 'root'
mode '0644'
source 'monit_virtual_server.erb'
variables(
monit_addre... |
module OpenAssets
module Protocol
# Asset Definition loader for http or https uri scheme
class HttpAssetDefinitionLoader
attr_reader :url
def initialize(url)
@url = url
end
# load asset definition
def load
begin
definition = AssetDefinition.parse_jso... |
# frozen_string_literal: true
feature 'user sign up' do
scenario 'user enter their name' do
signup
expect(page).to have_text('Fran')
end
end
feature 'store user in database' do
scenario 'enter password' do
expect { signup }.to change(User, :count).by 1
end
end
|
require 'rails_helper'
RSpec.describe UsersController, :type => :controller do
let(:user1) { FactoryGirl.create(:user)}
before do
DatabaseCleaner.clean
login_with(user1)
end
context "show action" do
let(:num){User.last.id}
it "should assign @displayed_user variable" do
get :show, :id => ... |
def merge(array1, array2)
result = []
index1 = 0
index2 = 0
loop do
if (index1 < array1.size) && (index2 < array2.size)
if array1[index1] <= array2[index2]
result << array1[index1]
index1+=1
else
result << array2[index2]
index2+=1
end
elsif index1 >= array1.size
resul... |
require "spec_helper"
describe DiscountNetwork::Destination do
describe ".list" do
it "returns the similar destinations" do
search_term = "bang"
stub_destination_list_api(term: search_term)
destinations = DiscountNetwork::Destination.list(term: search_term)
destination = destinations.fir... |
require "net/http"
require "uri"
module Picolib
module Webhook
class API
def initialize(end_point, headers=nil, opts={})
@end_point = end_point
@debug = opts[:debug]
if headers.class == String
@args = {headers: {authorization: headers}}
elsif headers.cla... |
require('minitest/autorun')
require('minitest/reporters')
require_relative('../book_shop')
Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new
class TestBookShop < MiniTest::Test
def setup()
@book1 = BookShop.new(4, "Dune", "Frank Herbert", 1965)
@book2 = BookShop.new(10, "Great Expectations", "C... |
# frozen_string_literal: true
class UpdateIndexes < ActiveRecord::Migration[5.1]
def change
remove_index :comments, :author_id
remove_index :comments, %i[commentable_type commentable_id]
add_index :comments, %i[commentable_type commentable_id author_id], name: :by_commentable_and_author
remove_index... |
class Settings::Core::GrowMethodsController < ApplicationController
def index
if params[:onboarding_type].present?
@facility = Facility.find(params[:facility_id])
@facility.update_onboarding('ONBOARDING_GROW_METHOD')
end
@grow_methods = Common::GrowMethod.all.order(name: :asc)
if Inventory... |
class AddGamesToGeneration < ActiveRecord::Migration[5.2]
def change
add_column :generations, :games, :text
end
end
|
describe "DataObjects" do
let(:attribute_groups) { double put: nil }
let(:runtime_table) { double }
let(:row) { double }
let(:row_under_construction) { double }
let(:pipe) { double }
subject(:data_objects) do
require __FILE__.sub('/spec/', '/').sub('_spec.rb', '.rb')
new_data_objects
end
def ne... |
class RemoveMeta < ActiveRecord::Migration[4.2]
def change
remove_column :feeds, :meta
end
end
|
p 'hello'.class # String
p String.class # Class
# 记得吗:对象的 my_method 其实是定义在 class MyClass 里的
#
# 如果把 String 当作一个对象,它的类就是 Class
# 那么String.xxx 的 xxx 方法其实是定义在 class Class 里的
p Class.instance_methods(false) # [:allocate, :superclass, :new]
# 因此 String.new 之所以可以调用,是因为 class Class 里面 def new 了
p 'hello'.is_a? String #... |
class AddTextFieldsToProductGroup < ActiveRecord::Migration[6.0]
def change
change_table :refinery_caststone_product_groups, if_exists: true do |t|
t.text :description, if_not_exists: true
t.text :features, if_not_exists: true
t.text :summary, if_not_exists: true
end
end
end
|
class Skill < ApplicationRecord
has_many :user_skills
has_many :users, through: :user_skills
has_many :vacancy_skills
has_many :preferred_skills, dependent: :destroy
has_many :vacancies, through: :vacancy_skills
has_many :develop_skills
has_many :users, through: :develop_skills
mount_uploader :photo, P... |
require_relative '../request_spec_helper'
describe Playercenter::Backend::API do
before do
AUTH_HELPERS.delete_existing_users!
AUTH_HELPERS.create_user!
end
describe "player info" do
it "doesn't work unauthenticated" do
response = client.get "/v1/#{user['uuid']}"
response.status.must_equ... |
class RenameTablesWithoutVirtual < ActiveRecord::Migration
def up
rename_table :virtual_users, :users
rename_table :virtual_aliases, :aliases
rename_table :virtual_domains, :domains
end
def down
rename_table :users, :virtual_users
rename_table :aliases, :virtual_aliases
rename_table :doma... |
class AddPartnersCodesToSettings < ActiveRecord::Migration
def change
add_column :settings, :hotels, :text
add_column :settings, :flights, :text
add_column :settings, :car_rental, :text
end
end
|
# frozen_string_literal: true
RSpec.describe GitHubChangelogGenerator::Options do
describe "#initialize" do
context "with known options" do
it "instantiates successfully" do
expect(described_class.new(user: "olle")[:user]).to eq("olle")
end
end
context "with unknown options" do
... |
class GardenInventory < ActiveRecord::Base
has_many :gardens
has_many :tool_names
end
|
class Team
attr_accessor :name, :motto
@@teams = []
def initialize(arguments)
@name = arguments[:name]
@motto = arguments[:motto]
@@teams << self
end
def self.all
@@teams
end
end |
class BankStatement < ActiveRecord::Base
belongs_to :admin
has_many :bank_transactions
end
|
class GameManager
def initialize(seed=(Time.now.day+Time.now.month*100))
#Kernel.srand(Time.now.day+Time.now.month*100)
Kernel.srand(seed+2)
puts "Enter number of players:"
@numplayers = gets.chomp.to_i
@players = []
@numplayers.times do |i|
player = User... |
class Question < ActiveRecord::Base
belongs_to :survey
has_many :answers
has_many :responses
validates :prompt, :presence => true
end
|
class AddForeignKeyForLedgers < ActiveRecord::Migration[5.2]
def change
add_foreign_key :ledgers, :users, on_delete: :cascade
end
end
|
class UsersController < ApplicationController
before_action :require_current_user!, except [:create, :new]
def create
@user = User.new(params[:user])
if @user.save
login!(@user)
redirect_to user_url(@user)
else
flash.now[:errors] << "Did not save"
render flash.now[:errors]
en... |
require 'xpash/cmd/commands'
module XPash
class Base
DEFAULT_PATH = "/"
ROOT_PATH = "/"
DEFAULT_NS = "xmlns"
attr_reader :query
def initialize(filepath, opts = {})
# setup logger
@log = Logger.new($stdout)
@log.datetime_format = "%Y-%m-%d %H:%M:%S"
@log.level = Logger::... |
class CartItem < SimpleDelegator
attr_reader :quantity, :item
def initialize(item, quantity)
@quantity = quantity
@item = Item.find_by_dao(item)
super(@item)
end
def total
price * @quantity
end
def to_param
@item.id
end
end
|
require_relative 'questions_database'
require_relative 'question'
require_relative 'reply'
require_relative 'question_follow'
require_relative 'question_like'
require_relative 'model_base'
require 'byebug'
class User < ModelBase
def self.find_by_id(id)
super(id)
end
def self.from
self.to_s.tableize
... |
class ScriptBeat < ActiveRecord::Base
belongs_to :episode
has_many :script_beat_characters
has_many :characters, through: :script_beat_characters
accepts_nested_attributes_for :characters
enum beat_type: [
:slugline,
:action,
:character,
:dialogue,
:parenthetical,
:extension,
:du... |
class AddImgUrlToItems < ActiveRecord::Migration[5.1]
def change
add_column :items, :image_url, :string, default: 'background/moretools.png'
end
end
|
class Api::FoundPetsController < ApplicationController
before_action :set_found_pet, only: [:show, :update, :destroy]
# before_action :set_s3_direct_post, only: [:create, :update]
def index
render json: FoundPet.all
end
def show
render json: @found_pet
end
def create
... |
class SettingsModel
extend ActiveModel::Naming
include Singleton
attr_accessor :default_values
def set_default(key, value)
@default_values ||= ActiveSupport::HashWithIndifferentAccess.new
@default_values[key] = value
end
private
def method_missing(name, *args, &block)
names = name.to_s.spl... |
class CreateTrackings < ActiveRecord::Migration
def change
create_table :trackings do |t|
t.string :txn_id
t.date :time_created
t.text :name
t.string :template_ref
t.string :email
t.string :tracking
t.timestamps null: false
end
end
end
|
FactoryGirl.define do
factory :device do
_type 'CIC'
ear 'Direito'
battery '10'
serial_number '123123'
warantee 2
store 'Unidade I - Santo André'
brand 'Samsung'
model 'xpto-1.0'
purchased_at { Faker::Time.between(1.years.ago, Time.current, :all) }
end
end
|
class CreateOrders < ActiveRecord::Migration[6.0]
def change
create_table :orders do |t|
t.references :dish, null: false, foreign_key: true
t.references :wine, null: false, foreign_key: true
t.integer :total_cost_cents, null: false
t.references :restaurant, foreign_key: true
t.refere... |
require "test_helper"
class ProductIngredientsControllerTest < ActionDispatch::IntegrationTest
setup do
@product_ingredient = product_ingredients(:one)
end
test "should get index" do
get product_ingredients_url, as: :json
assert_response :success
end
test "should create product_ingredient" do
... |
class DialogFlowController < ApplicationController
skip_before_action :verify_authenticity_token
include ActionView::Helpers::DateHelper
def webhook
parking_spot = ParkingSpot.recently_confirmed_free.first
ParkingSpot.where(status: 'reserved').where('updated_at < ?', 1.minute.ago).update_all(status: 'fre... |
class AddAnonColumnToRequests < ActiveRecord::Migration[5.0]
def change
add_column :requests, :anonymous, :string
end
end
|
class ListingsController < ApplicationController
before_action :set_listing, except: [:create, :new, :index]
before_action :set_shop
# GET /listings
# GET /listings.json
def index
@listings = @shop.listings
end
# GET /listings/1
# GET /listings/1.json
def show
@shops = Shop.all
end
# GE... |
require 'scanf'
require 'yaml'
require 'ipaddress'
require_relative 'out'
class Node
attr_accessor :config # Name of stand
attr_accessor :name
attr_accessor :state
attr_accessor :provider
attr_accessor :ip
def initialize(config, initString)
parts = initString.scanf('%s %s %s')
if parts.length ==... |
require 'open-uri'
require 'script_loader'
require 'redis'
Dir[File.expand_path('../support/**/*.rb', __FILE__)].each { |f| require f }
HOST = '127.0.0.1'
REDIS_HOST = '127.0.0.1'
REDIS_PORT = 6379
REDIS_DB = 0
LOG_PLAYER_INTEGRATION = false
LOG_PLAYER_REDIS_DB ... |
# coding: utf-8
class WelcomeController < ApplicationController
before_action :apiKey, only: [:update]
def index
@countries = Country.order(max_temp: :desc)
end
def update
countries = Country.all
countries.each do |country|
url = URI.encode("http://api.openweathermap.org/data/2.5/weather?q=#{co... |
class Category < ActiveRecord::Base
# attr_accessible :title, :body
attr_accessible :name
has_many :songs
validates :name, presence: true
scope :visible, where(:visible => true)
scope :invisible, where(:visible => false)
scope :search, lambda {|query| where(["name LIKE ?", "%#{query}%"])}
def self.... |
class Song
attr_accessor :title, :artist
def name
self.artist.name
end
end
|
require 'minitest/autorun'
require 'shoulda'
require 'mocha/setup'
require 'webmock/minitest'
require 'salesforce_bulk'
class ActiveSupport::TestCase
def self.test(name, &block)
define_method("test #{name.inspect}", &block)
end
def api_url(client)
"https://#{client.login_host}/services/async/#{client.v... |
require_relative './../../spec_helper.rb'
require 'rest-client'
require 'json'
describe TranslateModule::TranslateService do
it 'returns query translated' do
@plural = TranslateModule::PluralService.new({"query" => 'People'})
response = @plural.call()
expect(response).to match("People")
end
end
|
class ToDosController < ApplicationController
################################################################
# The To-Dos controller deals with Present Until Done events,
# which we call To-Dos in our project. Each To-Do can have its
# own reminder, which will send an email reminder to the user
# about th... |
require 'ruby-hl7'
class PidSegment
def initialize
base_pid = "PID||||||||||||||||||"
@pid = HL7::Message::Segment::Default.new(base_pid)
end
def get_mrn
@pid.e3[0..@pid.e3.index('^')]
end
def set_mrn(mrn)
@pid.e3 = mrn.to_s + "^^^^CMRN"
end
... |
# frozen_string_literal: true
class CharactersController < ApplicationController
before_action :authenticate_as_privileged_except_self!, only: %i[show update]
before_action :authenticate_as_privileged!, only: %i[create retire]
before_action :authenticate_as_admin!, only: %i[approve unapprove]
after_action :log... |
# encoding: utf-8
# require 'icov'
class Users::WineCellarItem < ActiveRecord::Base
set_table_name "user_wine_cellar_items"
belongs_to :wine_cellar, :class_name => 'Users::WineCellar', :foreign_key => 'user_wine_cellar_id'
belongs_to :user
belongs_to :wine_detail, :class_name => 'Wines::Deta... |
class Repository
attr_accessor :path
def initialize(path)
@path = path
raise ArgumentError, "#{path} repository does not exist" unless Dir.exists? path
end
def uses_carthage?
File.exists? path + "/Cartfile"
end
def uses_cocoapods?
File.exists? path + "/Podfile"
end
end
|
# encoding: utf-8
#! /usr/bin/env ruby
##
# Auteur CrakeTeam
# Version 0.1 : Date : Mon Mar 17 09:42 2013
#
require_relative 'Fenetre'
require './Vue/Elements/ListeElements'
class FenetreChoixCreation < Fenetre
@texteChoixCreation
@boutonPrecedent
@boutonSuivant
@boutonSupprimer
@listeCreation
@texteAu... |
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'specmon/version'
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = 'specmon'
s.version = Specmon::VERSION
s.authors = ['Quentin Roussea... |
module Maktoub
class SubscribersController < ApplicationController
layout 'maktoub/application'
def edit
@email = params[:email]
end
def update
if params[:email].blank?
@message = "email is required"
render :edit, :status => 400
else
Maktoub.unsubscribe params[:email]
end
end
en... |
require 'helper'
describe 'entity references' do
subject { EntityReferences.new }
let(:id) { 43 }
let(:object_id) { 42 }
let(:entity) { Struct.new(:object_id).new(object_id) }
describe 'save' do
it 'returns the passed id' do
assert_equal id, subject.save(id, entity)
end
end
describe 'fin... |
class RemoveImprovementsWondersColumnsFromNationsTable < ActiveRecord::Migration
def up
remove_column :nations, :improvements
remove_column :nations, :wonders
end
def down
end
end
|
module Fog
module Parsers
module TerremarkEcloud
module Compute
class GetVdc < Fog::Parsers::Base
def reset
@response = {
'storageCapacity' => {}, 'cpuCapacity' => {},
'memoryCapacity' => {}, 'networks' => [], 'vms' => []
}
en... |
class User < ApplicationRecord
has_many :orders
validates :email, format: {with: /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/, message: "is invalid"}
validates :phone_number, format: {with: /\A[+]?(\d){9,12}+\z/, message: "is invalid, must contains only numbers (between 9 and 12). Could it start with '+'"}
... |
class UsersController < ApplicationController
before_action :authenticate_user!, only: [:review, :like, :bookmark, :edit, :update]
before_action :set_user, only: [:show, :edit, :update]
def review
@reviews = Review.where(user_id: params[:id]).order(created_at: :desc).page(params[:page]).per(5)
end
def ... |
class BadFileName < Package
desc "Bad File Name"
homepage "http://www.libone.org"
release version: '1.0', crystax_version: 1
end
|
class Api::V1::CurrencyHoldingsController < ApplicationController
def index
@currency_holding = CurrencyHolding.all
render json: @currency_holding
end
def show
@currency_holding = CurrencyHolding.find(params[:id])
render json: @currency_holding
end
def edit
@currency_holding = CurrencyHo... |
class StudentKlassSerializer < ActiveModel::Serializer
attributes :id
belongs_to :teacher_klass
end
|
Warden::Strategies.add(:devise_strategy) do
def valid?
return false if request.get?
user_data = params.fetch("user", {})
!(user_data["phone"].blank? && user_data["email"].blank? || user_data["password"].blank?)
end
def authenticate!
u = if params[:user_admin]
UserAdmin.find_for_authenti... |
# Common setup for running the example tests
require 'benchmark'
# The function we'll memoize
def factorial(n)
return 1 if n == 0
return factorial(n - 1) * n
end
# Main wrapper
def run
unless ARGV.length == 2
puts "Usage: ruby #{$0} number_of_times_to_calc_factorial factorial_to_calc";
puts " e.g. rub... |
class CreateComplaintChats < ActiveRecord::Migration[5.0]
def change
create_table :complaint_chats do |t|
t.string :chats
t.string :role
t.text :image
t.integer :complaint_id
t.timestamps
end
end
end
|
# (c) Copyright 2016-2017 Hewlett Packard Enterprise Development LP
#
# 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 applicabl... |
require 'rails_helper'
RSpec.feature 'Loggin in as admin' do
before do
@admin = create(:admin)
visit '/admins/sign_in'
expect(page).to have_button('Log in')
end
scenario 'with valid credential' do
fill_in 'Email', with: @admin.email
fill_in 'Password', with: @admin.password
click_button... |
# twenty_one_bonus.rb
# Methods
def prompt(message)
puts "=> #{message}"
end
def deal_card(deck)
remaining_cards = deck.select { |_, value| !value.empty? }
card = remaining_cards.keys.sample
if card.nil?
puts "Deck is empty."
else
value = deck[card].pop if !deck[card].nil?
[card, value]
end
en... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.