text stringlengths 10 2.61M |
|---|
class OrdersController < ApplicationController
def new
@order = Order.new
end
def create
@carts = Cart.where(user_id: current_user.id)
@order = Order.new(order_params)
@order.user_id = current_user.id
if @carts.any? {|cart| cart.item.stock < cart.count }
render :new ,flash: {n:"在庫がないため購入できません。数量をご確認くださ... |
class AddFoodPartsToRecipes < ActiveRecord::Migration
def change
add_column :recipes, :food_parts, :text
end
end
|
class HeatsController < ApplicationController
before_action :set_heat
before_action :authenticate_user!
def show
render json: build_heat_json
end
def add_score
score = add_score_params.merge({judge_id: current_user.id})
begin
@heat.add_score!(score)
Pusher.trigger("scores-#{@heat.eve... |
class UsersController < ApplicationController
before_action :authenticate_user!, only: [:edit, :my_favorites, :setavatar]
def show
@user = User.find(params[:id])
@itisme = user_signed_in? && @user.id == current_user.id
end
def my_favorites
# this one was interesting lol
@places = Place.where(id: current_u... |
require 'rails_helper'
RSpec.describe Procedure, type: :model do
it { is_expected.to have_one(:protocol) }
it { is_expected.to have_one(:arm) }
it { is_expected.to have_one(:participant) }
it { is_expected.to belong_to(:appointment) }
it { is_expected.to belong_to(:visit) }
it { is_expected.to belong_to(... |
#
# Observador que envia automaticamente un correo electronico cuando se registra un mensaje.
#
class MensajeObserver < ActiveRecord::Observer
def after_save(mensaje)
UserMailer.deliver_mensaje(mensaje.recibido, mensaje.enviado.nombre + ' ' + mensaje.enviado.apellido) if !mensaje.recientemente_creado
end
... |
# TODO:
# - Implement handling of close_end / close_start when time give and multiple opening/closing times per day
# - Implement handling of errors (no library, date in the past & etc)
# - Fix bug with date overrun (week 53) - implement handling of next year dates
class LibView2::LibrarySchedulesController < Applicat... |
class TeacherKlassSerializer < ActiveModel::Serializer
attributes :id, :teacher_id
belongs_to :klass
end
|
class CreateContracts < ActiveRecord::Migration
def change
create_table :contracts do |t|
t.belongs_to :person, index: true
t.belongs_to :contract_partner, index: true
t.belongs_to :contract_template, index: true
t.belongs_to :interval, index: true
t.date :start_date
t.date :en... |
class Asteroids::PlayerComponent
include Gamey::Component
attr_accessor :score, :alive, :did_shoot, :shot_timer, :thrust_sound
def initialize
@score = 0
@alive = true
@did_shoot = false
@shot_timer = Gamey::Timer.new
end
end |
require 'rake/testtask'
Rake::TestTask.new do |t|
t.libs << "test"
t.pattern = 'test/**/test_*.rb'
t.warning = true
t.verbose = true
end
task :default => 'test:all'
namespace :test do
%w(sprockets_37 sprockets_40).each do |gemfile|
desc "Run Tests against #{gemfile}"
task gemfile do
sh "BUNDL... |
# encoding: utf-8
module Glyph
# A Macro object is instantiated by a Glyph::Interpreter whenever a macro is found in the parsed text.
# The Macro class contains shortcut methods to access the current node and document, as well as other
# useful methods to be used in macro definitions.
class Macro
include Valid... |
# == Schema Information
#
# Table name: faculties
#
# id :integer not null, primary key
# name :string(255)
# gender :string(255)
# avatar :string(255)
# teaching_age :integer
# academic_level :string(255)
# school :string(255)
# major :string(25... |
module Mutations
# class IntervalEnd
#
class IntervalEnd < BaseMutation
argument :id, Int, required: true
type Types::IntervalType
def resolve(id:)
i = Interval.find(id)
i.update(updated_at: DateTime.now)
return i
end
end
end |
module AccountMovementsHelper
def prev_month_link
month_link(@report.prev_month, "Anterior")
end
def next_month_link
month_link(@report.next_month, "Siguiente")
end
def month_link(date, title)
return tag.span(title) unless date
num_date = l(date, format: :numeric_month)
link_to(title, ac... |
require 'rails_helper'
describe 'Encryptor Utils' do
before do
@obj = {a: 1, b: 'test', c: Time.now}
@ie = Itpkg::Encryptor
end
it 'password' do
pwd = @ie.password(@obj)
expect(pwd).to be_an_instance_of(String)
expect(@ie.password?(@obj, pwd)).to be true
end
it 'encode and decode' do
... |
require "rspec/rest/matchers/in_json_path"
module RSpec
module Rest
module Matchers
class Contain < RSpec::Matchers::BuiltIn::BaseMatcher
include RSpec::Rest::Matchers::JsonPath
def initialize(expected, mode = nil)
@expected = expected
unless @expected.is_a?(Fixnum)
... |
# An interval operator is used to run of an number range like Haskell:
xs = (1..10)
xs.each { |e| puts e }
# Is an instance of Range class:
puts xs.class |
#!/usr/bin/env ruby -w
class Buffer
def initialize(buffer_size_limit, stream)
@stream = stream
@buffer_size_limit = buffer_size_limit
@buffer = ""
end
def empty?
@buffer.empty?
end
def index(str, offset=0)
@buffer.index(str, offset)
end
def skip_to(pos)
@buffer = @buffer.slice(... |
require "rails_helper"
RSpec.describe Entry do
subject { build(:entry) }
it "has a valid factory" do
expect(subject.valid?).to eq true
subject.save!
end
describe "validations" do
it { is_expected.to validate_presence_of :pool }
it { is_expected.to validate_presence_of :name }
end
describ... |
class Prediction
def initialize(id)
@id = id
end
def get_autonomy_ratio_prediction
calculation = Calculation.find(@id)
if calculation.autonomy_ratio < 0.5
"Оскільки коефіцієнт автономії менше за 0.5, а саме #{calculation.autonomy_ratio.to_s}, тим більшою мірою організація залежна
від по... |
require 'linkeddata'
require 'sparql'
module Sdp
module Responder
# This method should make the necessary inference and query, then should
# return the result with a unicast message to the destination.
def self.solicitation(packet,address, service_description_file,mtu=1500)
Log.info "INCOMING SOLI... |
require 'spec_helper'
describe JsonTableSchema::Constraints do
let(:field) {
{
'name' => 'Name',
'type' => '',
'format' => 'default',
'constraints' => {}
}
}
let(:constraints) { JsonTableSchema::Constraints.new(field, @value) }
describe JsonTableSchema::Constraints::Required ... |
# frozen_string_literal: true
module GraphQL
class Schema
class Member
# These constants are interpreted as GraphQL types when defining fields or arguments
#
# @example
# field :is_draft, Boolean, null: false
# field :id, ID, null: false
# field :score, Int, null: false
... |
class DonationProgram < ApplicationRecord
# Relationships
# -----------------------------
has_many :donation_histories
has_many :constituents, through: :donation_histories
# Scopes
# -----------------------------
scope :alphabetical, -> { order('program') }
# Validations
# -----------------------... |
Rails.application.routes.draw do
devise_for :users
get "/", to: "books#index"
get "/books/overview", to: "books#overview"
get "/books/favorite", to: "books#favorite"
get "/books", to: "books#overview"
get "/users/about_me", to: "users#about_me"
get "/users/edit_me", to: "users#edit"
patch "/users/:id", ... |
module Locomotive
module Wagon
class ThemeAssetDecorator < SimpleDelegator
include ToHashConcern
def __attributes__
%i(source folder checksum)
end
def source
Locomotive::Coal::UploadIO.new(filepath, nil, realname)
end
def priority
stylesheet_or_java... |
require 'uri'
##
# The controller responsible for dealing with views related to SSE website posts
class PostController < BasePostEditorController
# GET post/list
def list
PostImageManager.instance.clear
@pr_posts = GithubService.get_all_posts_in_pr_for_user(session[:access_token])
@posts = GithubServic... |
FactoryGirl.define do
factory :artist do
name "Maria"
bio { Faker::Lorem.sentence(40) }
origin { Faker::Address.city }
trait :active do
active true
end
trait :inactive do
active false
end
end
end
|
class AddPings < ActiveRecord::Migration
def change
create_table :pings do |t|
t.string :token
t.string :dateTime
t.string :latitude
t.string :longitude
t.string :speed
t.string :course
t.string :altitude
t.string :hdop
t.string :vdop
t.string :pdop
... |
class Api::V1::TasksController < Api::ApiController
before_action :find_task, only: %i[destroy update]
def index
render json: current_user.tasks
end
def destroy
@task.destroy
# render status: :no_content # 204 = No Content
head :no_content
end
def update
new_attrs = {}
new_attrs... |
class CreateImportMembers < ActiveRecord::Migration
def change
create_table :import_members do |t|
t.integer :user_id
t.integer :case_id
t.integer :member_id
t.timestamps null: false
end
add_column :menus, :cpl_android, :float, :default => 0
add_column :menus, :cpl_ios, :float... |
# == Schema Information
#
# Table name: resource_storage_arrays
#
# id :integer not null, primary key
# instance_id :integer
# instance_type :string
# created_at :datetime not null
# updated_at :datetime not null
# data_center_id :integer
#
# Indexes
#
# index_res... |
module TinyCI
module OutputParser
class RakeParser < Base
def parse!
@result = TinyCI::Report::BuildReport.new
@result.build_tool = 'rake'
while !empty?
line = consume!.line
if line =~ /^\*\* Execute (.*)$/
task = case $1
... |
# Write a method that takes an array of strings, and returns an array of the same string values, except with the vowels (a, e, i, o, u) removed.
=begin
approach:
- initialize a new array (empty)
- iterate over the given array, for each element:
- remove vowels from the element
- push element with vowels removed t... |
require 'mirren/api/auth'
require 'mirren/api/query_params'
require 'mirren/api/header'
require 'mirren/api/response'
require 'mirren/api/request'
module Mirren
module Api
def get(path, params: {})
Request.new(host, auth, :get, request)
.call(path, get_params: params.compact)
end
def ... |
module LazyMode
def self.create_file(file_name, &block)
file = LazyMode::File.new(file_name)
file.instance_eval(&block)
end
end
class LazyMode::Date
attr_reader :year, :month, :day
def initialize(string)
@representation = string
@year = string.split('-')[0].to_i
@month = string.split('-')... |
class TweetsController < ApplicationController
def index
@tweets = Tweet.all.limit(25)
end
end
|
class CharityMailer < Base
def activated_charity(charity)
@charity = charity
greeting(charity.user.first_name)
mail to: charity.user.email
end
end
|
# frozen_string_literal: true
# This migration comes from alchemy (originally 20200423073425)
class CreateAlchemyEssenceNodes < ActiveRecord::Migration[5.2]
def change
create_table :alchemy_essence_nodes do |t|
t.references "node"
t.timestamps
end
add_foreign_key "alchemy_essence_nodes", "alc... |
Given /^I have a confirmed user$/ do
@user = Factory(:user)
@user.confirm!
@user.save!
@user.should be_confirmed
end
When /^I sign in$/ do
Given %{I'm at the sign in page}
When %{I fill in an "email" field with "#{@user.email}"}
And %{I fill in a "password" field with "#{@user.password}"}
And %{I click... |
# frozen_string_literal: true
module LargeTextField
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
end
|
# frozen_string_literal: true
class DevelopersController < ApplicationController
before_action :ensure_developer, only: %i[show edit update]
before_action :ensure_create_developer, only: [:create]
def index
@developers = Developer.all
end
def show; end
def new
@developer = Developer.new
end
... |
require_relative 'my_process'
require_relative 'init_process'
require_relative 'my_resource'
require_relative 'ready_list'
$ready_list = nil
def scheduler
$ready_list.current.scheduler
print $ready_list.current.pid + ' '
$stdout.flush
end
def init
$ready_list = ReadyList.new
MyProcess.init($ready_list)
M... |
require 'httparty'
require 'json'
class TestingWeatherData
include HTTParty
base_uri 'http://api.openweathermap.org/data/2.5'
def retrieve(city_id, api_key)
@json_result = JSON.parse(self.class.get("/weather?id=#{city_id}&APPID=#{api_key}").body)
end
def get_coord
@json_result['coord']
end
def get_co... |
require File.join(File.dirname(__FILE__), 'spec_helper')
describe Baked do
include Rack::Test::Methods
describe "POST /vote" do
it "should create a new ballot" do
post "/vote", :ballot => {:name => 'Ballot', :taste => { "Cookies" => "0", "Muffins" => "2", "Brownies" => "1"}}
Ballot.count.should ==... |
# -*- mode: ruby -*-
# vi: set ft=ruby :
#
Vagrant.require_version ">= 1.6.0"
# NOTE: Due to virtualbox mounting constraints, this must be run in squential mode:
# export VAGRANT_NO_PARALLEL=yes
# or
# vagrant up --no-parallel
ENV['VAGRANT_DEFAULT_PROVIDER'] = 'docker'
DOCKER_HOST_NAME = "dockerhost-apix"
DOCKER_HO... |
class UpdateMembersTable < ActiveRecord::Migration[5.0]
def change
remove_column :members, :hometown
end
end
|
require_relative 'gambler'
class Dealer < Gambler
def to_s
"#{name}: #{" * " * hand.count}; денег: #{cash}"
end
end
|
feature "Posting messages to Chitter" do
scenario "Can't post to Chitter if not signed in" do
visit('/')
expect(page).not_to have_content("Post a Peep!")
end
scenario "Can post a message to Chitter" do
sign_in
fill_in "message", with: "Here's a message!"
click_button("Post")
expect(page).... |
require 'rails_helper'
require 'utilities'
describe "signing up a new user" do
it "allows a currently signed-in user to create a new user" do
user = User.create(:username => 'cat', :password => "123", :password_confirmation => "123")
sign_in(user)
expect(page).to have_content "Sanctuaries"
new_user =... |
require 'rails_helper'
RSpec.describe ContactsInteractor, type: :interactor do
describe 'create' do
context 'when parameters valid' do
let(:args) do
{ name: 'onur',
last_name: 'elibol',
phone: '+90 555 1111111' }
end
subject(:context) { ContactsInteractor::Create.c... |
class Music::MusicFindsController < Music::MusicWorksController
# Injected actions
# GET /music/finds/find
def find
@find = MusicFind.new
@search = MusicFind.search(params[:q])
end
def search
@find = MusicFind.new
@q_params = params[:q]
# Set for validation
@find.publication_year_gte... |
# Por ser uma linguagem puramente orientada a objeto, onde tudo é um objeto, Ruby possui apenas métodos e não funções.
# Quanto se comentad sobre funções e métodos em Ruby, se referem a mesma coisa.
# Nota: Funções não possuem um objeto associado / Métodos são chamados em um objeto receptor.
# !!! Utiliza-se por conv... |
#!/usr/bin/env ruby
require "./account"
class SavingsAccount < Account
def initialize(amount, interest)
super(amount)
@interest = interest
end
def includeInterest
abs_interest = @amount * @interest
@amount += abs_interest
end
end
if $0 == __FILE__
myAccount = SavingsAccount.new(100, 0.01)
balance = my... |
class CommentPolicy
attr_reader :user, :comment
def initialize(user, comment)
@user = user
@comment = comment
end
def create?
!!user
end
def destroy?
!!user && (user == comment.author || user == comment.post.author)
end
end
|
::ClassificationsController
class ClassificationsController
def index
repo_id = params.fetch(:rid, nil)
if !params.fetch(:q, nil)
DEFAULT_CL_SEARCH_PARAMS.each do |k,v|
params[k] = v
end
end
search_opts = default_search_opts( DEFAULT_CL_SEARCH_OPTS)
search_opts['fq'] = Advance... |
# frozen_string_literal: true
require "spec_helper"
require "generators/graphql/loader_generator"
class GraphQLGeneratorsLoaderGeneratorTest < BaseGeneratorTest
tests Graphql::Generators::LoaderGenerator
test "it generates an empty loader by name" do
run_generator(["RecordLoader"])
expected_content = <<-... |
class DefaultLikeCount < ActiveRecord::Migration
def change
change_column :topics, :like_counter, :integer,default: 0
end
end
|
#!/usr/bin/env ruby
# A few helpful tips about the Rules file:
#
# * The order of rules is important: for each item, only the first matching
# rule is applied.
#
# * Item identifiers start and end with a slash (e.g. “/about/” for the file
# “content/about.html”). To select all children, grandchildren, … of an
# ... |
class Address < ActiveRecord::Base
belongs_to :addresstable, :polymorphic => true
belongs_to :state
belongs_to :city
validates_presence_of :zipcode, :address, :district, :number, :state_id, :city_id
end
|
require_relative '../spec_helper'
require_relative '../../app/html_view'
describe "HtmlView#wrap_page" do
it "wraps the page"
end
describe "HtmlView#render" do
check_rendered_document({}, [], HtmlView)
describe "when handed a document with one text item" do
check_rendered_document(
{some_text: "tex... |
require 'spec_helper'
class Dummy
include Apiable::Object
def name
'John Doe'
end
def level
:beginner
end
def senior
false
end
outgoing :name
outgoing :level
outgoing :senior
end
describe Dummy do
let(:object) { Dummy.new }
it 'returns hash' do
expect(object.external).to i... |
# 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... |
# This file was generated by GoReleaser. DO NOT EDIT.
class ForkCleaner < Formula
desc "Cleans up old and inactive forks on your github account."
homepage "https://github.com/caarlos0/fork-cleaner"
version "1.5.1"
bottle :unneeded
if OS.mac?
url "https://github.com/caarlos0/fork-cleaner/releases/download... |
require "spec_helper"
describe CommentsController do
describe "routing" do
it "routes to #index" do
get("/tailgates/1/posts/1/comments").should route_to("comments#index", tailgate_id:"1", post_id:"1")
end
it "routes to #new" do
get("/tailgates/1/posts/1/comments/new").should route_to("comme... |
class User < ActiveRecord::Base
devise :trackable
devise :omniauthable, :omniauth_providers => [:facebook, :twitter, :instagram]
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
attr_accessible :provider, :uid
attr_accessibl... |
class CreateBooks < ActiveRecord::Migration
def self.up
create_table :books do |t|
t.string :title
t.string :author
t.string :seller
t.decimal :price
t.text :comments
t.string :isbn
t.boolean :delta
t.boolean :confirmed
t.boolean :disabled
t.string :salt... |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Staff::Api::V1::InteractionsController, type: :controller do
let(:staff) { create(:staff) }
before { sign_in_as(staff) }
describe 'POST #create' do
context 'with valid attributes' do
let(:options) { { interaction: attributes_for(:in... |
# frozen_string_literal: true
module Helpers
module RequestHelpers
def token_credentials_for(user)
user.create_new_auth_token.slice('client', 'access-token', 'uid')
end
end
end
|
class FranchiseContact < ActiveRecord::Base
validates_presence_of :name
validates_presence_of :email
validates_format_of :email,
:with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
end
|
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
added_attrs = [ :first_name, :last_name, :first_name_kana, :last_name_kana, :zip_code, :prefectur... |
require "styleguide/engine"
require "styleguide/navigation"
require "styleguide/section"
module Styleguide
def self.navigation
@navigation ||= Navigation.new
yield @navigation if block_given?
@navigation
end
end
|
require 'net/http'
require 'cgi'
require 'thread'
semaphore = Mutex.new
keywords = IO.read( "../analysis/src/main/resources/task_2.txt" ).lines.to_a.map { |x| x.to_s.strip }
def fetch_tag( semaphore, keyword )
semaphore.synchronize { puts "request #{keyword}" }
url = URI.parse( "http://ec2-54-206-49-26.ap-southea... |
#!/usr/bin/env ruby
# encoding: utf-8
begin
load File.expand_path('../spring', __FILE__)
rescue LoadError => error
STDERR.puts error
end
require_relative '../config/boot'
require 'rake'
Rake.application.run
|
require 'test_helper'
class PackagesControllerTest < ActionDispatch::IntegrationTest
include Devise::Test::IntegrationHelpers
setup do
@user = users(:qiang)
@address = @user.addresses.first
@package = @user.packages.first
end
test 'delete package also deletes associated package_item' do
perfo... |
@b3 = Episode.create(
"title" => "Ep 3: Spirituality & The Singularity with Mike Morrell",
"number" => 3,
"published_at" => "2012-09-10 03:25:53",
"media" => "http://resources.brickcaster.com/singularity/003_spirituality_mike_morrell.mp3",
"media_length" => 1489.176,
"media_size" => 23545688,
"summary" => "How does the... |
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.admin?
can :manage, :all
end
can [:profile], User
can [:index, :dashboard], Welcome
can [:index, :show, :new, :create], Job
can [:edit, :update, :destroy], Job, poster_id... |
class SkillCategory < ActiveRecord::Base
has_many :skills
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 rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Ch... |
package "ejabberd"
service "ejabberd" do
action :enable
supports :restart => true
end
template "/etc/ejabberd/ejabberd.cfg" do
source "ejabberd.cfg.erb"
variables(:jabber_domain => node[:web_app][:ui][:domain])
notifies :restart, resources(:service => "ejabberd")
owner "root"
group "ejabberd"
mode 064... |
class Apps::IntegrationsController < Apps::ApplicationController
before_action :set_app
before_action :set_integration, only: [:show, :update, :destroy]
def index
@integrations = @app.integrations.all
end
def show
end
def create
@integration = @app.integrations.new(integration_params)
@inte... |
require "formula"
class Kf5Kinit < Formula
url "http://download.kde.org/stable/frameworks/5.38/kinit-5.38.0.tar.xz"
sha256 "ae49e0a3cf8a86868afb57bfd820c65be60939e4a79d39e54608fcc9f307914c"
homepage "http://www.kde.org/"
head "git://anongit.kde.org/kinit.git"
depends_on "cmake" => :build
depends_on "chig... |
module Nordea
module FileTransfer
class Response
include Virtus
attribute :response_header, ResponseHeader
attribute :application_response, ApplicationResponse
attribute :signature, Hash
end
end
end
|
require "spec_helper"
describe TherapiesController do
describe "routing" do
it "routes to #index" do
get("/therapies").should route_to("therapies#index")
end
it "routes to #new" do
get("/therapies/new").should route_to("therapies#new")
end
it "routes to #show" do
get("/therap... |
namespace :setup do
desc 'Upload database.yml file.'
task :upload_yml do
on roles(:app) do
execute "mkdir -p #{shared_path}/config"
upload! StringIO.new(File.read('config/database.yml')), "#{shared_path}/config/database.yml"
end
end
desc 'Seed the database.'
task :seed_db do
on roles(... |
class Follow < ActiveRecord::Base
attr_accessible :user_id, :follow_id
belongs_to :user, :class_name => 'User'
belongs_to :follower, :class_name => 'User', :foreign_key => 'follow_id'
validates :user_id, :uniqueness => { :message => 'already being followed', :scope => :follow_id}
validates :user_id, :follow_id,... |
require 'test_helper'
class CharacterTest < ActiveSupport::TestCase
should belong_to :avatar
should belong_to :user
should belong_to :location
should have_many :items
test "can compute total skills from items and avatar" do
character = create(:character)
create_character_with_many_items(character)
... |
class FeaturedCommentBucket < ActiveRecord::Base
self.table_name = 'contentbase_featuredcommentbucket'
outpost_model
has_secretary
has_many :comments, class_name: "FeaturedComment", foreign_key: "bucket_id", order: "created_at desc"
validates :title, presence: true
define_index do
indexes title, s... |
class ProtocolImporter
def initialize(callback_url)
@callback_url = callback_url
@logger = Logger.new(File.join(Rails.root, 'log', "protocol_importer-#{Rails.env}.log"))
end
def create
PaperTrail.enabled = false
api_sub_service_request = RemoteObjectFetcher.fetch(@callback_url)["sub_service_req... |
class TestLuaPredicate < CLIPPTest::TestCase
include CLIPPTest
def make_config(lua_program, extras = {})
return {
modules: ['lua', 'pcre', 'htp'],
predicate: true,
lua_include: lua_program,
config: "",
default_site_config: "RuleEnable all",
}.merge(extras)
end
def test_ba... |
class Array
def shuffle!
each_index {|j|
i = rand(size-j);
self[j], self[j+1] = self[j+1], self[j]
}
end
end
class Maze
TOP = 1
LEFT = 2
def initilaize(w, h)
@w = w
@h = h
@size = @w*h
@maze = Array.new(@size)
@wall = Array.new(@size, TOP|LEFT)
@w.times do |i|
@h.times do |j|
putMaz... |
require './caesar_cipher'
RSpec.describe "caesar_cipher" do
it "shifts the input string by a positive number" do
expect(caesar_cipher("Hello", 7)).to eq "Olssv"
end
it "shifts the input string by a negative number" do
expect(caesar_cipher("Hello", -4)).to eq "Dahhk"
end
it "keeps the same case" do
... |
require 'spec_helper'
module Boilerpipe::SAX::TagActions
describe AnchorText do
describe '#start' do
it 'increase in_anchor count' do
handler = Boilerpipe::SAX::HTMLContentHandler.new
expect { subject.start(handler, nil, nil) }.to change { handler.in_anchor_tag }.from(0).to(1)
end
... |
require "chandler/cli/parser"
require "chandler/commands/push"
require "chandler/logging"
require "forwardable"
module Chandler
# Handles constructing and invoking the appropriate chandler command
# based on command line arguments and options provided by the CLI::Parser.
# Essentially this is the "router" for th... |
require 'spec_helper'
describe "have_many_to_many_matcher" do
before :all do
define_model :item
define_model :comment do
many_to_many :items
end
end
subject{ Comment }
describe "messages" do
describe "without option" do
it "should contain a description" do
@matcher = have_... |
json.array!(@donators) do |donator|
json.extract! donator, :first_name, :last_name, :email
json.url donator_url(donator, format: :json)
end
|
require "hexagon.rb"
require "rubygems"
require "rmagick"
@gc = Magick::Draw.new
# Have red and green be twice as likely as healthy
def weighted_rand
r = rand(5)
r < 1 ? 0 : r < 3 ? 1 : 2
end
def draw_hex(x,y, code)
color = code == 0 ? "white" : code == 1 ? "green" : "red"
@gc.fill(color)
@gc.polygon(x, ... |
class RequestSpeakersController < ApplicationController
def index
@request = RequestSpeaker.new
end
def create
begin
@request = RequestSpeaker.new(params[:request_speaker])
@request.request = request
if @request.deliver
flash[:heading] = "Thanks!"
flash[:notice] =... |
class AddSynopsisToPost < ActiveRecord::Migration
def change
add_column :posts, :synopsis, :text
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.