text stringlengths 10 2.61M |
|---|
class DropCatRentalRequestsTable < ActiveRecord::Migration
def up
drop_table :cat_rental_requests
end
def down
raise ActiveRecord::IrreversibleMigration
end
end
|
module ThanksHelper
def some_sample_thanks(count, user=nil)
raise "unsupported" if count > 10
thanks = []
while thanks.count < count
thanks << sample_thank(user)
thanks.uniq!
end
thanks.shuffle
end
def sample_thank(user=nil)
cs = nil
if user && rand(10)==0
cs = context_specific_thank(user)
... |
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "taas/version"
Gem::Specification.new do |s|
s.name = "taas"
s.version = Taas::VERSION
s.authors = ["Akash"]
s.email = ["akashm@thoughtworks.com"]
s.homepage = ""
s.summary = %q{Testing As A Services}... |
module Fptools
module Pdf
class GutterGenerator
include_package 'com.itextpdf.text'
include_package 'com.itextpdf.text.pdf'
def self.generate(in_file, out_file)
gutter_width = 9
orig = PdfReader.new(in_file)
orig_dims = orig.getPageSizeWithRotation(1)
page_widt... |
# Your Names
# 1) Jack Abernathy
# 2) KB DiAngelo
# Guide : Charlotte
# We spent [1] hours on this challenge.
# Bakery Serving Size portion calculator.
def serving_size_calc(item_to_make, order_quantity)
menu = {"cookie" => 1, "cake" => 5, "pie" => 7}
# Error checking
if !menu.has_key?(item_to... |
class CommentsController < ApplicationController
def create
comment = Comment.new(comment_params)
if comment.valid?
if !params[:new_username].empty? && params[:comment][:user_id].empty?
newuser = User.find_or_create_by(username: params[:new_username])
comment.user_id = newuser.id
... |
module RedisClient
# we should use a connection pool for production apps
# this way we may exhaust redis resource unnecessarily
def self.new_client
Redis.new(host: 'localhost', port: 6379, db: 1)
end
end
|
class Dvd < ActiveRecord::Base
attr_accessible :ASIN, :director, :title, :release_date, :summary
validates :title,
:presence => { :message => "Dvd title is required"}
validates :title,
:uniqueness => { :message => "Dvd title must be unique"}
validates :summary,
:presence ... |
require 'rack/server'
require 'rack/builder'
module Circuit
module Rack
# Extensions to Rack::Builder
module BuilderExt
# @return [Boolean] true if a default app is set
def app?
!!@run
end
# Duplicates the `@use` Array and `@map` Hash instance variables
def initialize_c... |
class ApplicationController < ActionController::Base
protect_from_forgery unless: -> { request.format.json? }, prepend: true
private
def after_sign_in_path_for(resource)
session["player_return_to"] || root_path
end
end
|
class Player
attr_reader :life
attr_reader :weapon
attr_accessor :spell_damage
attr_reader :field
attr_reader :deck
attr_reader :hand
def initialize
@life = 30
@weapon = nil
@spell = nil
@spell_damage = 0
@field = Field.new
@deck = Deck.new
@hand = Hand.new
end
e... |
class PurchasesController < ApplicationController
before_action :authenticate_user!, only: [:index, :edit]
before_action :getcard_id, only: [:index, :create]
before_action :item_param, only: [:index, :create]
before_action :back_index, only: [:index]
before_action :solditem_to_top, only: [:index]
def index... |
module Sidekick
class LocationSharesController < InheritedResources::Base
InheritedResources.flash_keys = [:success, :failure]
before_filter :authenticate_user!
actions :all, :only => [:new, :create]
defaults :resource_class => Share, :collection_name => 'shares', :instance_name => 'share'
respond... |
class AddAvatarReceiptToItemComments < ActiveRecord::Migration
def change
add_column :item_comments, :avatar_receipt, :string
end
end
|
require './lib/Grid'
class Cell
attr_reader :x, :y, :life, :living_neighbors
def initialize(x, y)
@x = x
@y = y
@life = false
end
def kill
@life = false
end
def give_life
@life = true
end
def anybody_out_there
@living_neighbors = []
Grid.spaces.each do |cell|
if (ce... |
class Hash
def to_hash_map
hm = java.util.HashMap.new
if block_given?
each do |key, value|
hm.put(*yield(key, value))
end
else
each do |key, value|
hm.put key, value
end
end
hm
end
end
|
require "spec_helper"
describe "govuk collector" do
ARTEFACT_URL = "http://www.gov.uk/api/artefacts.json"
it "should retrieve artefacts from govuk api" do
artefacts = {
results: []
}
FakeWeb.register_uri(:get, ARTEFACT_URL, body: artefacts.to_json)
collector = GovUkCollector.new(ARTEFA... |
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
helper_method :mailbox, :conversation
helper_method :current_user, :authenticate_user
def require_admin
redir... |
module DamperRepairReport
class PhotoSection
include Report::SectionWritable
def write(pdf)
records.each { |r| PhotoPage.new(r).write(pdf) }
end
end
end |
class UsersController < ApplicationController
load_and_authorize_resource
def new
@user=User.new
end
def show
if params[:id].blank?
@user = current_user
else
@user = User.find(params[:id])
end
end
def index
@users = User.paginate(:page => params[:page], :per_page => 10)
... |
class RemoveUnnecesaryFields < ActiveRecord::Migration[5.0]
def change
remove_column :categories, :topic_type
remove_column :categories, :topic_id
remove_column :topics, :post_type
remove_column :topics, :post_id
remove_column :users, :post_id
remove_column :users, :thread_id
end
end
|
module Telegram
module Bot
class UpdatesController
# Allows to store context in session and treat next message according to this context.
#
# It provides `save_context` method to store method name
# to be used as action for next update:
#
# def set_location!(*)
# ... |
require "formula"
class PcscLite < Formula
homepage "http://pcsclite.alioth.debian.org"
url "https://alioth.debian.org/frs/download.php/file/4126/pcsc-lite-1.8.13.tar.bz2"
sha1 "baa1ac3a477c336805cdf375912da5cbc8ebab8d"
bottle do
sha1 "8b726aaf4467583d1fd808650229757c9561c4d5" => :yosemite
sha1 "42eff... |
class Train
def initialize(number, type, waggons)
$number = number
@type = type
@waggons = waggons
@speed = 0
end
def speed_up
@speed += 10
@speed = 110 if @speed > 110
end
def print_sp
puts "Current speed of #{@number} is #{@speed} kmh"
end
def speed_down
@speed -= 10
... |
class AssistiveTechnology < ActiveRecord::Base
belongs_to :platform, inverse_of: :assistive_technologies
has_many :matrixEntries, inverse_of: :assistive_technology
end
|
class CategoriesController < ApplicationController
before_filter :authenticate_user!
def index
@categories = Category.all
end
def new
@category = Category.new()
end
def edit
@category = Category.find(params[:id])
end
def update
@category = Category.find(params[:id])
if @category.update_attributes(... |
require "json"
require "open-uri"
class TodoSorter
def initialize(formats)
@formats = formats
end
def sort(results)
results.sort_by do |c|
[
-c.num_exh_votes,
-$CardDatabase.decks_containing(c).count
] + @formats.map{|format| (format.legality(c).nil? ? 3 : format.legality(c).... |
def bubble_sort(sort_array)
# set swapcounter to non zero value
swap_count = 1
## loop swap counter != 0
while swap_count != 0
# set swap counter to 0
swap_count = 0
# loop through each element in array
sort_array.each_with_index do |item, index|
if sort_array[index + 1]
# check... |
# UpdatesWorker.perform_async
class UpdatesWorker
include Sidekiq::Worker
sidekiq_options queue: 'updates', retry: true
def perform
Settings.strategies.each do |strategy|
"#{strategy.capitalize}Strategy".constantize.new.check_for_updates
end
end
end |
LiminalApparel::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to resta... |
class Intervention < ActiveRecord::Base
belongs_to :parliament_member
belongs_to :session
has_many :intervention_words
def to_hash
{ :parliament_member_id => parliament_member_id,
:date => date,
:content => content,
:sequence => sequence || -1,
:session_id => session.id,
:sess... |
module Endpoints
class Users < Sapp::Base
index 'users' do
'All users'
end
show 'user' do
'One User'
end
end
end
|
# A join class of sorts between nouns and user. Tracks references
# to which user created specific nouns.
class NounCreator < ActiveRecord::Base
belongs_to :noun, polymorphic: true
belongs_to :user
validates_presence_of :user
validates_presence_of :noun
end
|
require "rails_helper"
RSpec.describe MyFacilitiesHelper, type: :helper do
describe "patient_days_css_class" do
it "is nil if patient_days is nil" do
expect(patient_days_css_class(nil)).to be_nil
end
it "returns red-new if < 30" do
expect(patient_days_css_class(29)).to eq("bg-red")
end
... |
class LawsuitsController < ApplicationController
before_action :authenticate_user!
before_action :set_lawsuit, only: [:show, :edit, :update, :destroy]
# GET /lawsuits
def index
@lawsuits = Lawsuit.all
end
# GET /lawsuits/1
def show
end
# GET /lawsuits/new
def new
@lawsuit = Lawsuit.new
... |
# -*- coding: utf-8 -*-
class SoliderQueuesController < ApplicationController
before_filter :authenticate_user
before_filter :find_city
def new
end
# 增加一批新的训练士兵的任务
def create
if @city.waiting_solider_queues.count >= 5
flash[:notice] = '等待接受训练的批次已经达到5批'
redirect_to :action => 'new'
r... |
class DepartmentDocumentsController < ApplicationController
before_filter :find_doc
before_filter :authenticate_user!
def edit
respond_to do |format|
format.html { render layout: !request.xhr? }
end
end
# PUT text_documents/1
# PUT text_documents/1.json
def update
if @doc.update_from_para... |
require 'rails_helper'
RSpec.describe 'Category', type: :system do
describe 'Category function' do
let(:user) { create(:user) }
let!(:category) { create(:category) }
let!(:category1) { create(:category, :category1) }
let!(:post) { create(:post, category_ids: [category.id]) }
let!(:post1) { cre... |
# Version module
module ToyRobot
# Toy Robot Simulator version
VERSION = "1.0.0"
end
|
class WechatKey < ActiveRecord::Base
belongs_to :instance
validates :tips, :key, :msg_type, :content, presence: true
validates_uniqueness_of :key, scope: :instance_id
mount_uploader :banner, BannerUploader
TYPES = {
text: '纯文本',
news: '图文消息'
}
end
|
class AddPublishedAtToArticles < ActiveRecord::Migration
def self.up
add_column :articles, :published_at, :datetime
Article.all.each do |article|
if article.published
article.update_attributes!(:published_at => article.created_at)
end
end
end
def self.down
remove_column :articl... |
module ApplicationHelper
def resource_name
:user
end
def resource
@resource ||= User.new
end
def devise_mapping
@devise_mapping ||= Devise.mappings[:user]
end
#/////////////////////devise//////////////////////////
# def render_country_category(country)
# key = CountryData.country_categ... |
# frozen_string_literal: true
module VmTranslator
module Commands
Call = Struct.new(:function_name, :arguments_number) do
def accept(visitor)
visitor.visit_call(self)
end
end
end
end
|
dep "code" do
met? { shell("file -b ~/code") == "directory" }
meet { shell("mkdir -p ~/code") }
end |
class Api::V1::BaseResource < JSONAPI::Resource
class << self
def verify_key(key, context = nil)
if key.is_a?(Hash)
if key.key?(:attributes)
key
else
if key.key?(:id)
key = key[:id]
super
else
fail 'Actually we can not handle... |
require 'rails_helper'
RSpec.feature "タスク管理機能", type: :feature do
let(:user) { FactoryBot.create(:user) }
before do
# ユーザー作成
@user = (:user)
# サインイン
visit new_session_path
fill_in 'Email', with: user.email
fill_in 'Password', with: user.password
click_button 'Log in'
end
background ... |
class ItemImage < ApplicationRecord
belongs_to :item
mount_uploader :image, ItemImageUploader
validates :image, presence: true
end
|
# Write a program that converts a number to a string per the following rules:
# If the number contains 3 as a prime factor, output 'Pling'.
# If the number contains 5 as a prime factor, output 'Plang'.
# If the number contains 7 as a prime factor, output 'Plong'.
# If the number does not contain 3, 5, or 7 as a pri... |
class ChangeColumnToWants < ActiveRecord::Migration[5.2]
def up
change_column_default :wants, :count, 0
end
def down
change_column_default :wants, :count
end
end
|
require 'rubygems'
require 'nokogiri'
require 'zip'
require 'rubyXL/hash'
require 'rubyXL/generic_storage'
module RubyXL
class Parser
def self.parse(file_path, opts = {})
self.new(opts).parse(file_path)
end
# +:data_only+ allows only the sheet data to be parsed, so as to speed up parsing
# Ho... |
require 'spec_helper'
describe Curation do
let(:curation) { Curation.new }
it { should respond_to :image }
it { should respond_to :kind }
it { should respond_to :products }
it { should respond_to :retailers }
it { should respond_to :meta }
describe '#meta' do
subject { curation.meta }
its(:keys... |
class RequestHandlersController < ApplicationController
def create
@post = Post.find_by id: params[:post_id]
if @post.photographer
flash[:alert] = t ".already_accepted_someone"
redirect_to root_path
return
end
@photographer = @post.candidates.find_by id: params[:photographer_id]
... |
module Backgrounded
attr_reader :delegate, :options
class Proxy
def initialize(delegate, options={})
@delegate = delegate
@options = options || {}
end
def method_missing(method_name, *args)
Backgrounded.handler.request(@delegate, method_name, args, @options)
nil
end
end
en... |
# DJ воркер. Создает и отправляет архив перерегистрации на email
class SessionDataSender < Struct.new(:id, :email)
def perform
@session = Session.find(id)
path = create_archive!
zip = path[/\/([\-\w]+\.zip)/, 1]
Mailer.delay.session_archive_is_ready(email, zip)
end
private
def create_archive!
... |
class Department < ApplicationRecord
has_many :designations
validates :dep_code, presence: true, uniqueness: true
validates :dep_name, presence: true, uniqueness: true
end
|
class AddBeerIdToDrinks < ActiveRecord::Migration
def change
add_column :drinks, :beer_id, :integer
end
end
|
# frozen_string_literal: true
module PetsHelper
def pet_id
Pet.find(params[:id])
end
def pet_params
params[:status] = 'adoptable'
params.permit(:image, :name, :description, :age, :sex, :status)
end
end
|
# == Schema Information
#
# Table name: themes
#
# id :integer not null, primary key
# title :string(255)
# css_doc :text
# activated_at :datetime
# account_id :integer
# created_at ... |
Rails.application.routes.draw do
# Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html
# Defines the root path route ("/")
resource :tracers, only: %w[index create]
root "tracers#index"
end
|
module BadContactService
class IndexBadContact
prepend SimpleCommand
attr_reader :user, :params
def initialize(user = nil, params = {})
@user = user
@params = params
end
def call
BadContact.includes([:uploaded_file]).where(user: user).order(created_at: :desc)
end
... |
class Action
attr_accessor :actor
attr_accessor :type
attr_accessor :amount
def self.debit(from:, amount:)
Action.new(from, 'debit', amount)
end
def self.credit(to:, amount:)
Action.new(to, 'credit', amount)
end
def initialize(actor, type, amount)
@actor = actor
@type = type
@amou... |
# encoding: UTF-8
# Copyright © Emilio González Montaña
# Licence: Attribution & no derivates
# * Attribution to the plugin web page URL should be done if you want to use it.
# https://redmine.ociotec.com/projects/advanced-roadmap
# * No derivates of this plugin (or partial) are allowed.
# Take a look to licen... |
class BasicTrainee::UsersController < ApplicationController
layout "basic_application"
before_action :logged_in_user
before_action :load_user, only: %i(show edit update)
def show; end
def edit; end
def update
if @user.update_attributes user_params
flash[:success] = t "controllers.users.update_u... |
desc 'This task is called by the Heroku scheduler add-on'
task pay_participants: :environment do |t, args|
Participation.where(paid: false, accepted: true).each do |participation|
return if participation.rated
PayParticipantsWorker.perform_async(participation.id)
end
end
|
class OrdersController < ApplicationController
before_action :authenticate_user!
before_filter :set_order, :except => [:create, :index, :new, :assign_shipped, :add_shipping_confirmation, :show]
def index
@campaign = Campaign.friendly.find(params[:campaign_id])
@orders = @campaign.orders
end
def sho... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.