text stringlengths 10 2.61M |
|---|
class TodolistsController < ApplicationController
def index
@todolists = Todolist.all
end
def show
@todolist = Todolist.find(params[:id])
end
def new
@todolist = Todolist.new
end
def create
@todolist = Todolist.new(todolists_params)
if @todolist.save
redirect_to todolists_path
else
render :new
end
end
private
def todolists_params
params.require(:todolists).permit(:list, :item, :status)
end
end
|
class AddBlogImageToBlogEntry < ActiveRecord::Migration
def self.up
add_attachment :blog_entries, :blog_image
remove_column :blog_entries, :image_url
end
def self.down
remove_attachment :blog_entries, :blog_image
add_column :blog_entries, :image_url
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
def forward_port(d)
# d.vm.network "forwarded_port", guest: 3000, host: 53000, auto_correct: true
# d.vm.network "forwarded_port", guest: 8080, host: 58080, auto_correct: true
# d.vm.network "forwarded_port", guest: 8083, host: 58083, auto_correct: true
# d.vm.network "forwarded_port", guest: 8086, host: 58086, auto_correct: true
# d.vm.network "forwarded_port", guest: 9080, host: 59080, auto_correct: true
# d.vm.network "forwarded_port", guest: 9082, host: 59082, auto_correct: true
end
# setup docker host
config.vm.define :cds do |d|
# configure network
d.vm.box = "puppetlabs/centos-7.2-64-nocm"
d.vm.hostname = "cds.local"
d.vm.network "private_network", ip: "192.168.11.11"
#forward_port d
d.vm.provision :shell, path: "bootstrap/run_cds.sh"
config.vm.provider "virtualbox" do |v|
v.memory = 4096
v.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
v.customize ["modifyvm", :id, "--natdnsproxy1", "on"]
end
end
end
|
class AddMoreCols < ActiveRecord::Migration[5.2]
def change
add_column :restaurants, :dresscode, :string
add_column :restaurants, :dining_style, :string
end
end
|
require 'spreadsheet/compatibility'
module Spreadsheet
module Excel
##
# This module is used to keep track of offsets in modified Excel documents.
# Considered internal and subject to change without notice.
module Offset
include Compatibility
attr_reader :changes, :offsets
def initialize *args
super
@changes = {}
@offsets = {}
end
def Offset.append_features mod
super
mod.module_eval do
class << self
include Compatibility
def offset *keys
keys.each do |key|
attr_reader key unless instance_methods.include? method_name(key)
define_method "#{key}=" do |value|
@changes.store key, true
instance_variable_set ivar_name(key), value
end
define_method "set_#{key}" do |value, pos, len|
instance_variable_set ivar_name(key), value
@offsets.store key, [pos, len]
havename = "have_set_#{key}"
send(havename, value, pos, len) if respond_to? havename
end
end
end
end
end
end
end
end
end
|
require 'test_helper'
class Resources::ProductCategoriesControllerTest < ActionController::TestCase
def setup
@controller.stub! :oauth_handshake, :return => true
end
test "should get index" do
get :index # , :oauth_consumer_key => @key
assert_response :success, @response.body
assert_not_nil assigns(:product_categories)
end
test "should get show" do
get :show, :id => Factory(:category).to_param, :oauth_consumer_key => @key
assert_response :success, @response.body
assert_not_nil assigns(:product_category)
end
test "should get visible questions count" do
category = Factory(:category)
another_category = Factory(:category)
product = Factory(:product, :category => category)
question1 = Factory(:activated_qa_question, :owner => category)
question2 = Factory(:activated_qa_question, :owner => category)
Factory(:rejected_qa_question, :owner => category)
question3 = Factory(:activated_qa_question, :owner => product)
question4 = Factory(:activated_qa_question, :owner => product)
Factory(:rejected_qa_question, :owner => product)
Factory(:activated_qa_question, :owner => another_category)
questions_count = [question1, question2, question3, question4].size
@request.accept = 'application/json'
get :questions_summary, :id => category.to_param
assert_response :success
response = JSON.load @response.body
assert_equal questions_count, response["count"]
@request.accept = 'application/xml'
get :questions_summary, :id => category.to_param
assert_response :success
assert_tag :tag => 'count', :content => questions_count.to_s, :parent => {:tag => 'questions_summary'}
end
test "should get visible answers count" do
owner = Factory(:category)
question1 = Factory(:activated_qa_question, :owner => owner)
answer1 = Factory(:activated_qa_answer, :question => question1)
answer2 = Factory(:rejected_qa_answer, :question => question1)
question2 = Factory(:rejected_qa_question, :owner => owner)
answer3 = Factory(:qa_answer, :question => question2)
@request.accept = 'application/json'
get :answers_summary, :id => owner.to_param
assert_response :success
response = JSON.load @response.body
assert_equal 1, response["count"]
@request.accept = 'application/xml'
get :answers_summary, :id => owner.to_param
assert_response :success
assert_tag :tag => 'count', :content => '1', :parent => {:tag => 'answers_summary'}
end
#Focussed functional tests for getting questions are in the products_controller_test. We're not reapeating those tests here
test "should get questions for a category" do
category = Factory(:category)
category_question = Factory(:qa_question, :owner => category, :title => 'Question 1', :body => 'Question body 1', :created_at => Time.now)
product = Factory(:product, :category => category)
product_question = Factory(:qa_question, :owner => product, :title => 'Question 2', :body => 'Question body 2', :created_at => Time.now + 1)
@request.accept = 'application/json'
get :qa_questions, :id => category.to_param, :sort => :most_recent
assert_response :success
response = JSON.load @response.body
assert_equal ['Question 2', 'Question 1'], response['questions'].map {|question| question['title']}
end
test "routes" do
assert_routing({:method => :get, :path => '/resources/product_categories/Video-Games/questions_summary.json'}, {:controller => 'resources/product_categories', :action => 'questions_summary', :id => 'Video-Games', :format => 'json'})
assert_routing({:method => :get, :path => '/resources/product_categories/Video-Games/questions_summary.xml'}, {:controller => 'resources/product_categories', :action => 'questions_summary', :id => 'Video-Games', :format => 'xml'})
assert_routing({:method => :get, :path => '/resources/product_categories/Video-Games/answers_summary.json'}, {:controller => 'resources/product_categories', :action => 'answers_summary', :id => 'Video-Games', :format => 'json'})
assert_routing({:method => :get, :path => '/resources/product_categories/Video-Games/answers_summary.xml'}, {:controller => 'resources/product_categories', :action => 'answers_summary', :id => 'Video-Games', :format => 'xml'})
assert_routing({:method => :get, :path => '/resources/product_categories/Video-Games/qa_questions.json'}, {:controller => 'resources/product_categories', :action => 'qa_questions', :id => 'Video-Games', :format => 'json'})
end
end
|
# frozen_string_literal: true
class Hello
def initialize(val)
@val = val
end
def say
"Hello, #{@val}!"
end
end
|
class Event < ApplicationRecord
belongs_to :user, class_name: 'User', foreign_key: 'creator_id'
has_many :attendees, class_name: 'User', through: :attendance, foreign_key: 'attendee_id'
has_many :attendances
scope :future, -> { where('date >= ?', Date.today).order(date: :ASC) }
scope :past, -> { where('date < ?', Date.today).order(date: :ASC) }
end
|
require 'csv'
require_relative 'recipe.rb'
class Cookbook
def initialize(csv_file)
# load existing recipe from CSV -> parsing
@csv_file = csv_file
@recipes = []
parsing_csv
end
def all
@recipes
end
def save
save_to_csv
end
def add_recipe(recipe)
@recipes << recipe
save_to_csv
end
def remove_recipe(index)
# removes a recipe from the cookbook -> delete
@recipes.delete_at(index)
save_to_csv
end
def to_boolean(string)
if string == 'true'
true
elsif string == 'false'
false
end
end
private
def parsing_csv
CSV.foreach(@csv_file) do |row|
recipe = Recipe.new(row[0], row[1], row[2], row[3])
recipe.marked = to_boolean(row[4])
@recipes << recipe
end
end
def save_to_csv
CSV.open(@csv_file, 'wb') do |csv|
@recipes.each { |recipe| csv << [recipe.name, recipe.time, recipe.difficulty, recipe.description, recipe.marked] }
end
end
end
|
# frozen_string_literal: true
module HistoricMarketplaceData
class Spreadsheet
def append_rows(rows)
pos = num_rows
rows.each_with_index do |row, i|
append_row(row, pos + i, false)
end
worksheet.save
end
def append_row(row, last_pos = num_rows, save = true)
pos = last_pos + 1
row.each_with_index do |cell, index|
worksheet[pos, index + 1] = encode_cell(cell)
end
worksheet.save if save
end
def rows
worksheet.rows
end
def ids
worksheet.rows.map { |r| r[0] }
end
private
def encode_cell(cell)
cell.to_s.dup.force_encoding('UTF-8')
end
def num_rows
worksheet.num_rows
end
def last_row
return nil if num_rows <= 1
worksheet.rows[num_rows - 1]
end
def key
@key ||= StringIO.new(ENV['GOOGLE_DRIVE_JSON_KEY'])
end
def session
@session ||= GoogleDrive::Session.from_service_account_key(key)
end
def worksheet
@worksheet ||= spreadsheet.worksheets[0]
end
def spreadsheet
@spreadsheet ||= session.spreadsheet_by_key(ENV['SPREADSHEET_ID'])
end
end
end
|
class ChangeNameUSerBuildings < ActiveRecord::Migration
def change
rename_table :userbuildings, :buildings
end
end
|
module CustomActiveRecordObserver
module Rules
class UpdateRule < BaseRule
attr_reader :attribute, :pattern
def initialize(block, attribute: nil, pattern: nil)
super(block)
if pattern.is_a?(Array) && pattern.size != 2
raise ArgumentError, "#{ pattern } is expected to be an array of two elements"
end
@attribute = attribute
@pattern = pattern
end
def allowed?(changes)
attribute &&
changes.has_key?(attribute) &&
matches_pattern?(*changes.fetch(attribute))
end
private
def matches_pattern?(value_was, value)
return true unless pattern # no pattern => allowed for all
pattern.first === value_was && pattern.last === value
end
end
end
end
|
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update]
before_action :require_user, only: [:edit, :update, :follow, :unfollow, :timeline, :mentions]
before_action :correct_user, only: [:edit, :update]
def index
@users = User.all
end
def new
@user = User.new
end
def create
binding.pry
@user = User.new(user_params)
if @user.save
flash[:notice] = "You register success"
redirect_to root_path
else
render :new
end
end
def show; end
def edit; end
def update
if @user.update(user_params)
flash[:notice] = "edit success"
redirect_to user_path(@user.username)
else
render :edit
end
end
def follow
user = User.find(params[:id])
if user
current_user.following_users << user
flash[:notice] = "you following success"
redirect_to user_path(user.username)
else
wrong_path
end
end
def unfollow
user = User.find(params[:id])
relationship = Relationship.where(follower: current_user, leader: user).first
if user && relationship
relationship.delete
flash[:notice] = "you unfollow success"
redirect_to user_path(user.username)
else
wrong_path
end
end
def timeline
@statuses = []
current_user.following_users.each do |following|
@statuses << following.statuses.all
end
@statuses.flatten!
end
def mentions
current_user.mark_unread_mentions!
end
private
def set_user
@user = User.find_by(username: params[:username])
end
def user_params
params.require(:user).permit(:username, :email, :password)
end
def correct_user
@user = User.find_by(username: params[:username])
access_denied unless current_user?(@user)
end
end
|
require 'yaml'
conf = YAML.load_file('config.yaml')
Vagrant.configure('2') do |config|
# Machine
# https://www.vagrantup.com/docs/vagrantfile/machine_settings.html
config.vm.box = conf['vm']['box']
config.vm.hostname = conf['vm']['hostname']
# SSH
# https://www.vagrantup.com/docs/vagrantfile/ssh_settings.html
config.ssh.insert_key = false
# Network
# https://www.vagrantup.com/docs/networking/
config.vm.network 'private_network', ip: conf['vm']['ip']
# Synced folders
# https://www.vagrantup.com/docs/synced-folders/
config.vm.synced_folder conf['vm']['shared']['source'], conf['vm']['shared']['target'],
id: 'var/www',
type: 'virtualbox',
group: 'vagrant', # NodeJS will be run as this user.
owner: 'www-data',
mount_options: ['dmode=775', 'fmode=774']
# Provider (Virtual Box)
# https://www.vagrantup.com/docs/virtualbox/configuration.html
config.vm.provider 'virtualbox' do |vb|
vb.name = conf['vm']['name']
vb.cpus = conf['vm']['cpus']
vb.memory = conf['vm']['memory']
# Allow guest to use host DNS in order to speed up domain names resolutions.
# https://www.virtualbox.org/manual/ch09.html#nat_host_resolver_proxy
vb.customize ['modifyvm', :id, '--natdnshostresolver1', 'on']
# VirtualBox prevents service `systemd-timesyncd` to start, as it already
# handles time sync (based on host time), but related settings are not low
# enough in order to keep it synced when VM is up since a long time.
# http://www.virtualbox.org/manual/ch09.html#changetimesync
vb.customize ['guestproperty', 'set', :id, '/VirtualBox/GuestAdd/VBoxService/--timesync-set-threshold', '6000']
# Following statements are related to an issue regarding symlinks.
# See https://www.virtualbox.org/manual/ch04.html#sharedfolders
# But it's not enough to enable this privilege. Run Vagrant as admin or
# see https://www.virtualbox.org/ticket/10085#comment:32
vb.customize ['setextradata', :id, 'VBoxInternal2/SharedFoldersEnableSymlinksCreate//vagrant', '1']
vb.customize ['setextradata', :id, 'VBoxInternal2/SharedFoldersEnableSymlinksCreate//var/www', '1']
end
# Provisioning
# https://www.vagrantup.com/docs/provisioning/
# Create a directory managing provisioning tasks status.
config.vm.provision :shell, inline: 'mkdir -p /.vagrant'
# Hook before first vagrant up (executed once or use 'provision' flag/command).
config.vm.provision :shell do |s|
s.path = 'provision/shell/exec-hooks.sh'
s.args = ['exec-preprovision']
end
# Puppet install and (main) provisionning (executed once or use 'provision' flag/command).
# https://www.vagrantup.com/docs/provisioning/puppet_apply.html
config.vm.provision :shell, path: 'provision/shell/install-puppet.sh'
config.vm.provision :puppet do |puppet|
puppet.environment = 'development'
puppet.environment_path = 'provision/puppet'
puppet.facter = conf
puppet.structured_facts = true
puppet.synced_folder_type = 'virtualbox'
puppet.options = '--verbose'
end
# Hook after first vagrant up (executed once or use 'provision' flag/command).
config.vm.provision :shell do |s|
s.path = 'provision/shell/exec-hooks.sh'
s.args = ['exec-once', 'exec-always']
end
# Hook after first vagrant up (executed once or use 'provision' flag/command), without sudo privileges.
config.vm.provision :shell, privileged: false do |s|
s.path = 'provision/shell/exec-hooks.sh'
s.args = ['exec-once-unprivileged', 'exec-always-unprivileged']
end
# Hook after each vagrant up/reload (executed once or use 'provision' flag/command).
config.vm.provision :shell, run: 'always' do |s|
s.path = 'provision/shell/exec-hooks.sh'
s.args = ['startup-once', 'startup-always']
end
# Hook after each vagrant up/reload (executed once or use 'provision' flag/command), without sudo privileges.
config.vm.provision :shell, run: 'always', privileged: false do |s|
s.path = 'provision/shell/exec-hooks.sh'
s.args = ['startup-once-unprivileged', 'startup-always-unprivileged']
end
end
|
module Wordy
class Cli
class << self
def check_for_exceptions(json_data)
if (!json_data.is_a? Array) && json_data['error'].present?
raise WordyException, json_data['verbose']
end
end
def decoded_response_body(response_body)
if !response_body.empty?
json_data = ActiveSupport::JSON.decode(response_body)
check_for_exceptions(json_data)
json_data
else
{}
end
end
def http_get(url, params)
path = "#{url.path}?".concat(params.collect { |k,v| "#{k}=#{CGI::escape(v.to_s)}" }.reverse.join('&')) unless params.nil?
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(url.request_uri)
request.basic_auth Wordy.username, Wordy.api_key
response = http.request(request)
decoded_response_body(response.body)
end
def http_post(url, params)
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new(url.request_uri)
request.set_form_data(params)
request.basic_auth Wordy.username, Wordy.api_key
response = http.request(request)
decoded_response_body(response.body)
end
end
end
class WordyException < StandardError
end
end |
require 'spec_helper'
describe UsersController do
render_views
context "user is logged in" do
let(:current_user) { FactoryGirl.create :user }
before do
basic_auth_login
sign_in current_user
end
describe "#edit" do
subject { get :edit, id: current_user.to_param, format: "html" }
it { should be_success }
end
describe "#update" do
subject { put :update, id: current_user.to_param, format: "html", user: {
current_password: current_user.password,
password: current_user.password,
password_confirmation: current_user.password,
}}
it { should be_redirect }
end
end
end
|
#! /usr/local/bin/ruby
require 'fiber'
reader=Fiber::new do
File::open(__FILE__) do |f|
f.each_line { |l| Fiber.yield(l) unless l.strip.empty? }
end
end
puts "Let's get a line: #{reader.resume}"
puts "Let's get anothe line: #{reader.resume}"
puts "And the rest:"
puts reader.resume while reader.alive?
|
require 'fileutils'
namespace :install do
desc "Install Zurb Foundation"
task :foundation => %i[
install:foundation:install
install:foundation:cleanup
]
namespace :foundation do
task :install do
system "compass install foundation -c compass.rb"
end
task :cleanup do
FileUtils.rm("humans.txt")
FileUtils.rm("index.html")
FileUtils.rm("MIT-LICENSE.txt")
FileUtils.rm("robots.txt")
if File.directory?(".sass-cache")
FileUtils.rm_rf(".sass-cache")
else
raise "Compass has stopped creating .sass-cache/"
end
FileUtils.mv("vendor/lib/vendor/custom.modernizr.js", "vendor/lib")
FileUtils.mv("vendor/lib/vendor/zepto.js", "vendor/lib")
# Don't take Foundation's jQuery, just nuke the directory next
FileUtils.rm_rf("vendor/lib/vendor")
end
end
end |
class User < ApplicationRecord
before_validation :set_auth_token
has_many :places, dependent: :destroy
has_many :votes, dependent: :destroy
validates :name, presence: true
validates :username, presence: true
validates :email, presence: true
validates :password_digest, presence: true
validates :auth_token, presence: true
has_secure_password
private
def set_auth_token
if auth_token.nil?
self.auth_token = SecureRandom.uuid.delete("-")
end
end
end
|
module Acs
module RouteHelpers
def self.included(base)
base.class_eval do
def exposes_acs_api(route_name, *args)
# TODO: sanitize and check args before setting to options
options = args.extract_options!
raise "Must specify :controller" if options[:controller].blank?
raise "Must specify :action" if options[:action].blank?
begin
cont_klass_name = "#{options[:controller].classify.pluralize}Controller"
cont_klass = cont_klass_name.constantize
rescue NameError => e
raise "could not find a controller named #{cont_klass_name}."
end
if options[:model].blank?
model_klass_name = cont_klass_name.classify.singularize
else
end
begin
model_klass = model_klass_name.constantize
rescue NameError => e
raise "could not find a model named #{model_klass_name}."
end
# Keep in mind where this code is being executed, on an instance of
# ActionController::Routing::Routes.draw do |map| map
# map.<THE_NAMED_ROUTE>
self.send(route_name,
"#{route_name}_json/:q",
:controller => options[:controller],
:action => options[:action],
:conditions => {:method => :post}
)
# cont_klass.class_eval(<<-EOS, __FILE__, __LINE__)
# def #{options[:action]}
# end
# EOS
# Inject the basic API methods into controller class
cont_klass.send :include, Acs::ControllerMethods
end
end
end
end
end |
require 'SimpleCov'
SimpleCov.start
require_relative '../lib/customer'
require 'bigdecimal'
RSpec.describe Customer do
before(:each) do
@c = Customer.new({
:id => 1,
:first_name => 'Jennifer',
:last_name => 'Flowers',
:created_at => '2021-06-11 09:34:06 UTC',
:updated_at => '2021-06-11 09:34:06 UTC',
})
end
it 'exists' do
expect(@c).to be_an_instance_of(Customer)
end
it 'has attributes' do
expect(@c.id).to eq(1)
expect(@c.first_name).to eq('Jennifer')
expect(@c.last_name).to eq('Flowers')
expect(@c.created_at).to eq(Time.parse('2021-06-11 09:34:06 UTC'))
expect(@c.updated_at).to eq(Time.parse('2021-06-11 09:34:06 UTC'))
end
it 'can parse time or create time' do
c = Customer.new({
:id => 1,
:first_name => 'Jennifer',
:last_name => 'Flowers',
:created_at => '',
:updated_at => nil,
})
expect(c.created_at).to be_a(Time)
expect(c.updated_at).to be_a(Time)
allow(@c).to receive(:created_at).and_return(Time.parse('2021-06-11 02:34:56 UTC'))
expect(@c.created_at).to eq(Time.parse('2021-06-11 02:34:56 UTC'))
end
it 'can update attributes' do
@c.update({
:first_name => 'Dan',
:last_name => 'Spring'
})
expect(@c.first_name).to eq('Dan')
expect(@c.last_name).to eq('Spring')
expect(@c.updated_at).to be_a(Time)
@c.update({
:first_name => 'Sam',
})
expect(@c.first_name).to eq('Sam')
expect(@c.last_name).to eq('Spring')
expect(@c.updated_at).to be_a(Time)
end
end
|
class BooksController < ApplicationController
before_action :correct_post,only: [:edit]
protect_from_forgery
def new
@book = Book.new
end
# 投稿データの保存
def create
@book = Book.new(book_params)
@book.user_id = current_user.id
if @book.save
redirect_to book_path(@book.id), notice:"Welcome! You have signed up successfully."
else
@user = current_user
@books = Book.all
render :index
end
end
def index
@books = Book.all
@book = Book.new
@user = current_user
end
def show
@book = Book.find(params[:id])
@book_new = Book.new
@user = current_user
end
def edit
@book = Book.find(params[:id])
end
def destroy
@book = Book.find(params[:id])
@book.destroy
redirect_to books_path
end
def update
@book = Book.find(params[:id])
if @book.update(book_params)
redirect_to book_path(@book), notice:"You have updated book successfully."
else
render :edit
end
end
def correct_post
@book = Book.find(params[:id])
unless @book.user.id == current_user.id
redirect_to books_path
end
end
# 投稿データのストロングパラメータ
private
def book_params
params.require(:book).permit(:title, :body, :image)
end
end |
#!/usr/bin/env ruby2.0
#
# This is a simple integraiton test performing some usefull server actions.
#
# This is also intended as some kind of documentation on how to use the library
#
#
require 'fog/hetznercloud'
require 'pp'
# Connecto to Hetznercloud
connection = Fog::Compute[:hetznercloud]
# Some variables
ssh_public_keyfile = "./keys/testkey.pub" # needs to be generated first with 'ssh-keygen -t rsa testkey'
ssh_private_keyfile = "./keys/testkey" # needs to be generated first with 'ssh-keygen -t rsa testkey'
ssh_keyname = "testkey" # Name of the ssh key
servername = "testserver" # Name of the server
# resources created
image_snapshot = nil
image_backup = nil
server = nil
floating_ip = nil
ssh_key = nil
elements_created = [] # collector for cleanup
raise "Error: Fild #{ssh_private_keyfile} missing (create with 'ssh-keygen -t rsa -N \"\" -f #{ssh_private_keyfile}')" unless File.file?(ssh_private_keyfile)
def listall(connection:)
puts "==== Left ====="
connection.servers.each { |x|
puts "Server #{x.id}: #{x.name} #{x.public_ip_address}"
}
connection.floating_ips.each { |x|
puts "Floating IP #{x.id}: #{x.ip}"
}
connection.images.all(:type => 'snapshot').each { |x|
puts "Snapshot Image #{x.id}: #{x.description}"
}
connection.images.all(:type => 'backup').each { |x|
puts "Backup Image #{x.id}: #{x.description}"
}
end
def cleanup(elements_created: [], connection:)
puts "==== Cleanup ====="
elements_created.each { |e|
puts "Destroying #{e.class} with id #{e.identity}"
e.destroy()
}
## List Accounts
listall(:connection => connection)
end
begin
puts "==== Running Tests ===="
# Lookups, see api doc https://docs.hetzner.cloud for filters
connection.datacenters.each { |x| puts "Datacenter #{x.name} located in #{x.location.name}" }
connection.locations.each { |x| puts "Location #{x.name} located in #{x.city}" }
connection.locations.all(:name => 'fsn1').each { |x| puts "FSN Found" }
connection.locations.all(:name => 'nbg1').each { |x| puts "NBG Found" }
connection.server_types.each { |x| puts "Server Type #{x.name} (#{x.cores}/#{x.memory}/#{x.disk})" }
connection.server_types.all(:name => 'cx11').each { |x| puts "Server cx11 found" }
## create or select ssh key ...
ssh_key = connection.ssh_keys.all(:name => ssh_keyname).first
if !ssh_key
puts "Creating SSH Key ..."
ssh_key = connection.ssh_keys.create(:name => ssh_keyname, :public_key => ssh_public_keyfile)
elements_created << ssh_key
else
puts "Using existing SSH Key ..."
end
puts "Creating Floating IP"
floating_ip = connection.floating_ips.create(:type => 'ipv4', :home_location => 'fsn1' )
elements_created << floating_ip
puts "Using existing VIP #{floating_ip.ip} #{floating_ip.server.nil? ? 'unbound' : 'assigned to' + floating_ip.server.name}"
# lookup existing server by name or create new server, works with most resources
server = connection.servers.all(:name => servername).first
if !server
puts "Bootstrapping Server (waiting until ssh is ready)..."
server = connection.servers.bootstrap(
:name => servername,
:image => 'centos-7',
:server_type => 'cx11',
:location => 'nbg1',
:user_data => "./userdata.txt",
:private_key_path => ssh_private_keyfile,
:ssh_keys => [ ssh_key.identity ],
:bootstap_timeout => 120,
)
elements_created << server
else
puts "Using existing Server ... "
end
puts "Server public_ip_address:#{server.public_ip_address} (#{server.public_dns_name}/#{server.reverse_dns_name})"
puts "Power On"
server.poweron()
puts "Wait for SSH"
server.wait_for { server.sshable? }
puts "Assign VIP #{floating_ip.ip} to #{server.name}"
floating_ip.assign(server)
# now wait for the server to boot
puts "Waiting for Server SSH ..."
server.wait_for { server.sshable? }
puts "Adding VIP to server"
server.ssh("/sbin/ip addr add dev eth0 #{floating_ip.ip}")
puts "Changing Root Password"
action,password = server.reset_root_password
puts "New Root password #{password}"
puts "Unassigning VIP"
floating_ip.unassign()
puts "SSH in server ..."
puts server.ssh('cat /tmp/test').first.stdout # => "test1\r\n"
puts "Setting API to syncronous mode (wait for action to complete)"
server.sync=true
puts "Create Image (Sync) ..."
action, image_snapshot = server.create_image()
elements_created << image_snapshot
puts "Enable Backup ..."
server.enable_backup
puts "Create Backup (ASync) ..."
action, image_backup = server.create_backup()
elements_created << image_backup
puts "Disable Backup ..."
server.enable_backup
# Boot Server in rescue system with SSH Keys
puts "Booting into rescue mode"
server.enable_rescue(:ssh_keys => [ ssh_keyname ])
server.reboot()
server.wait_for { server.sshable? }
puts "SSH in Rescue System ..."
puts server.ssh('hostname').first.stdout # => "test1\r\n"
# Reboot again
puts "Booting into normal mode"
server.disable_rescue()
server.reset()
server.wait_for { server.sshable? }
# Change Server Type
puts "Changing Server Type to cx21"
server.shutdown()
# FIXME: Handle in GEM, sometimes API error ?
server.wait_for { server.stopped? }
server.change_type(:upgrade_disk => false, :server_type => 'cx21', :async => false)
server.poweron()
server.wait_for { server.sshable? }
puts server.ssh('hostname').first.stdout # => "test1\r\n"
# Change PTR
puts "Changing PTR"
server.change_dns_ptr('www.elconas.de')
server.reload
puts "PowerOff Server"
server.poweroff
puts "Setting API to asynchronous mode"
server.async=true
puts "Destroy Server ..."
server.destroy
elements_created.delete(server)
rescue Exception => e
cleanup(:elements_created => elements_created, :connection => connection)
raise e
else
cleanup(:elements_created => elements_created, :connection => connection)
end
|
# == Schema Information
#
# Table name: slides
#
# id :integer not null, primary key
# created_at :datetime not null
# updated_at :datetime not null
# deleted_at :datetime
# presentation_id :integer
# sequence :integer
# picture :string
# picture_processing :boolean default(FALSE)
# picture_tmp :string
# memo :text
#
# Indexes
#
# index_slides_on_deleted_at (deleted_at)
# index_slides_on_presentation_id (presentation_id)
#
class Slide < ActiveRecord::Base
include RankedModel
ranks :sequence, with_same: :presentation_id
mount_uploader :picture, ImageUploader
process_in_background :picture
store_in_background :picture
validates :picture, presence: true
end
|
class Presentify
class Slide
attr_reader :head, :code
def initialize(content)
@head, @code = parse(content)
end
private
HEAD_RE = /\A#([^\n]+)\n/
CODE_RE = /\A#[^\n]+\n([\s\S]+)/
def parse(content)
[HEAD_RE, CODE_RE].map do |re|
content.scan(re)[0][0].strip
end
end
end
end
|
class CreateOrders < ActiveRecord::Migration[5.0]
def change
create_table :orders do |t|
t.integer :user_id
t.datetime :formed
t.string :comment
t.float :total, default: 0.0
t.jsonb :order_list, default: {}
t.index :user_id, name: "index_orders_on_user_id", using: :btree
t.timestamps
end
end
end
|
# frozen_string_literal: true
module Browser
class SamsungBrowser < Chrome
def id
:samsung_browser
end
def name
"Samsung Browser"
end
def full_version
ua[%r{SamsungBrowser/([\d.]+)}, 1] || super
end
def match?
ua.include?("SamsungBrowser")
end
end
end
|
module Api
module V1
class PropertiesController < ApplicationController
respond_to :json
before_action :set_property,except: [:index,:order]
before_action :detect_device, only: [:index]
def index
params[:active] = 'true'
if params[:offer_price].present?
offer_price = params[:offer_price]
params.delete :offer_price
end
q = QueryTools.query params
pagination_by_device
@properties = Property.where(q)
.page(params[:page])
.per(@per_page)
.order_by_status
filter_by_offer_price(offer_price) if offer_price.present?
@properties = @properties.order(offer_price: params[:order]) if params[:order].present?
respond_with @properties,
meta: {
current_page: @properties.current_page,
next_page: @properties.next_page,
prev_page: @properties.prev_page,
total_pages: @properties.total_pages,
total_count: @properties.total_count,
limit: (params[:limit] || 100).to_i
}
end
def pagination_by_device
if @browser.device.tablet?
per_page = Settings.pagination.properties.per_page.tablet
elsif @browser.device.mobile?
per_page = Settings.pagination.properties.per_page.mobile
else
per_page = Settings.pagination.properties.per_page.default
end
@per_page = per_page
end
def filter_by_offer_price(offer_price)
offer_price = offer_price.split(',')
min_price = offer_price.first.to_i
max_price = offer_price.last.to_i
offer_price = Range.new(min_price, max_price)
@properties = @properties.where(offer_price: min_price..max_price)
end
def show
respond_with @property
end
def order
properties = params.require(:properties)
order = {}
properties.each_with_index do |id,i|
order.merge! id => {featured: i+1}
end
if Property.update(order.keys,order.values)
render json: nil,status: :ok
else
render json: nil,status: :unprocessable_entity
end
end
private
def set_property
@property = Property.friendly.find(params[:id])
end
def detect_device
user_agent = request.user_agent
@browser = Browser.new(user_agent, accept_language: "en-us")
end
end
end
end |
require 'rails_helper'
RSpec.describe Surgery, type: :model do
describe "validations" do
it { should validate_presence_of :title }
it { should validate_presence_of :day }
it { should validate_presence_of :room }
end
describe "relationships" do
it { should have_many :doctor_surgeries }
it { should have_many(:doctors).through(:doctor_surgeries) }
end
describe "instance methods" do
it "can print most/least experienced doctors" do
@doctor_1 = Doctor.create!(name: "Jim", years: 15 , university: "Brown")
@doctor_2 = Doctor.create!(name: "Kat", years: 20 , university: "Harvard")
@doctor_3 = Doctor.create!(name: "Ian", years: 25 , university: "Stanford")
@surgery_1 = Surgery.create!(title: "brain" , day: "Monday", room: 1)
@surgery_1.doctors << [@doctor_1, @doctor_2]
@surgery_2 = @doctor_2.surgeries.create!(title: "shoulder", day: "Tuesday", room: 2)
@surgery_3 = @doctor_3.surgeries.create!(title: "heart", day: "Wednesday", room: 3)
# require "pry"; binding.pry
expect(@surgery_1.most.name).to eq("Kat")
expect(@surgery_1.most.years).to eq(20)
expect(@surgery_1.least.name).to eq("Jim")
expect(@surgery_1.least.years).to eq(15)
end
end
end
|
# require "pry"
def roll_call_dwarves(array)
array.each_with_index do |dwarves,index|
puts "#{index + 1}. #{dwarves}"
end
end
def summon_captain_planet(array)
array.collect { |i| i.capitalize << "!" }
end
def long_planeteer_calls(array)
array.any? { |x| x.length > 4 }
end
def find_the_cheese(array)
array.find { |i| i == "cheddar" || i == "gouda" || i == "camembert" }
end
|
require 'Date'
class Structure
def initialize(parent_directory)
@default_layout = "<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>Post Title</title>
</head>
<body>
<%= html_content %>
</body>
</html>"
@parent_directory = parent_directory
make_dir
end
def make_dir
if Dir.exists?(@parent_directory)
puts "!!!This Directory Already Exists!!!"
raise ArgumentError
else
Dir.mkdir(@parent_directory)
build_folder_structure
end
end
def build_folder_structure
date = Date.today.strftime("%Y-%m-%d")
Dir.mkdir("#{@parent_directory}/_output")
source_dir = "#{@parent_directory}/source"
Dir.mkdir("#{source_dir}")
Dir.mkdir("#{source_dir}/layouts")
File.write("#{source_dir}/layouts/default.html.erb", @default_layout)
File.write("#{source_dir}/index.markdown", "# Some Markdown\n\n* a list\n* another item")
Dir.mkdir("#{source_dir}/css")
File.write("#{source_dir}/css/main.css", ' ')
Dir.mkdir("#{source_dir}/pages")
File.write("#{source_dir}/pages/about.markdown", "# Some Markdown\n\n* a list\n* another item")
Dir.mkdir("#{source_dir}/posts")
File.write("#{source_dir}/posts/#{date}-welcome-to-hyde.markdown", "# Some Markdown\n\n* a list\n* another item")
end
end
|
class CreatePlaces < ActiveRecord::Migration
def self.up
create_table :places do |t|
t.string :address
t.string :phone
t.float :longitude
t.float :latitude
t.datetime :startTime
t.string :name
t.string :url
t.string :email
t.integer :rsvp_event_id
t.string :subtitle
t.string :blurb
t.timestamps
end
end
def self.down
drop_table :places
end
end
|
class AddNsfwToRooms < ActiveRecord::Migration
def change
add_column :rooms, :nsfw, :boolean, null: false, default: false
add_index :rooms, :nsfw
end
end
|
# frozen_string_literal: true
RSpec.describe WelcomeConfirmedAttendancesJob, type: :job do
context 'with active events to welcome attendances' do
it 'calls the queue server twice' do
travel_to Time.zone.local(2021, 10, 5, 10, 0, 0) do
event = Fabricate :event, start_date: 4.days.from_now, end_date: 6.days.from_now, event_remote: false
other_event = Fabricate :event, start_date: 4.days.from_now, end_date: 6.days.from_now, event_remote: true
Fabricate :event, start_date: 1.day.ago
Fabricate :event, start_date: Time.zone.now
Fabricate :event, start_date: 3.days.ago, end_date: 2.days.ago
user = Fabricate :user, country: 'US', email: 'luciana.mdias@gmail.com'
other_user = Fabricate :user, country: 'US', email: 'celso.av.martins@gmail.com'
Fabricate :attendance, event: event, user: user, status: :confirmed
Fabricate :attendance, event: other_event, user: other_user, status: :confirmed
Fabricate :attendance, event: other_event, status: :pending
expect(EmailNotificationsMailer).to(receive(:welcome_attendance)).once.and_call_original
expect(EmailNotificationsMailer).to(receive(:welcome_attendance_remote_event)).once.and_call_original
described_class.perform_now
end
end
end
end
|
require 'open-uri'
require 'json'
class VK
attr_reader :app_id, :api_key
attr_accessor :permissions, :redirect_uri
def initialize app_id, api_key, permissions=[]
@app_id = app_id
@api_key = api_key
@permissions = permissions
end
def auth_url
"https://oauth.vk.com/authorize?" +
"client_id=#{app_id}&" +
"scope=#{permissions.join(',')}&" +
"redirect_uri=#{redirect_uri}&" +
"response_type=code&" +
"v=5.21"
end
def token_url code
"https://oauth.vk.com/access_token?" +
"client_id=#{app_id}&" +
"client_secret=#{api_key}&" +
"code=#{code}&" +
"redirect_uri=#{redirect_uri}"
end
def auth code
JSON.parse(open(token_url code).read)
end
def get_photos_with token, uid
uri = user_photos_uri token, uid
photos = JSON.parse( open(uri).read )["response"]
photos.shift
photos.each{|photo| set_photo_url(photo)}
photos
end
private
def user_photos_uri token, uid
'https://api.vk.com/method/photos.getUserPhotos?' +
"user_id=#{uid}&" +
"count=1000&" +
"sort=0&" +
"access_token=#{token}"
end
def set_photo_url photo
url = photo["src_xxxbig"] || photo["src_xxbig"] || photo["src_xbig"] || photo["src_big"] || photo["src_small"] || photo["src"]
photo["url"] = url
end
end |
class Project < ActiveRecord::Base
belongs_to :round
has_many :contributions
after_create :generate_name
def initialize(attributes = nil, options = {})
super
self.goal_amount = 400
self.funded_amount = 0
end
def generate_name
# self.name = "Project " + self.id.to_s
self.name = $project_names[0]
$project_names.delete($project_names[0])
# if we run out of names refill the array again
if $project_names == []
reseed_names
end
self.save!
end
def funded?
self.goal_amount <= self.funded_amount
end
def reseed_names
require 'csv'
$project_names = []
CSV.foreach("colors4.csv", :headers => false) do |row|
$project_names << row[0]
end
$project_names.each do |n|
n.gsub!(";",'')
end
end
end
|
#
# Lexical Scanner of Sreg Project
#
# Shou Ya, 30 July
#
require 'stringio'
module Sreg
module Builder
class LexerError < Exception; end
class Lexer
attr_reader :string
attr_reader :state
attr_reader :options
attr_reader :scanner_options
attr :stream
ESCAPE_SEQENCES = {
'n' => "\n",
't' => "\t",
'r' => "\r",
'a' => "\a",
'e' => "\e",
}
SPEC_CHAR_CLASSES = %w/w s d v h/
SPEC_CHAR_CLASSES_INV = SPEC_CHAR_CLASSES.map(&:upcase)
def initialize(scanner_options = {})
reset
@scanner_options.merge(scanner_options)
end
def set_input_string(string, regexp_options = {})
reset
@string = string
@stream = StringIO.new(string)
@options.merge(regexp_options)
end
def error(msg)
if @scanner_options[:debug] == true
puts
puts @string
print '-' * (@stream.pos - 1)
print '^'
print '-' * (@stream.length - @stream.pos)
puts ''
end
raise LexerError, msg
end
def tokens
toks = []
begin
toks << next_token
end until toks.last == [false, false]
toks
end
def next_token
char = @stream.getc
case char
when nil
if @state[:in_group] != 0
error 'Group stack is not terminated.'
else
return [false, false] # EOF
end
when '.'
if @state[:in_char_class]
return [:CHAR, '.']
else
return ['.', nil]
end
when '('
if @state[:in_char_class]
return [:CHAR, '(']
else
@state[:in_group] += 1
if peek_char == '?'
@stream.getc
case @stream.getc
when '#'
error 'Endless comment.' unless eat_until(')')
@state[:in_group] -= 1
return next_token
else
error 'Unrecognized extension.'
end
else
return ['(', nil]
end
end
when ')'
if @state[:in_char_class]
return [:CHAR, ')']
else
if @state[:in_group] > 0
@state[:in_group] -= 1
return [')', nil]
else
return [:CHAR, ')']
end
end
when '['
if @state[:in_char_class]
if peek_char == ':'
@stream.getc
pclass_name = get_letters
if @stream.getc == ':'
if @stream.getc == ']'
return [:POSIX_CHAR_CLASS, pclass_name]
end
end
error 'Invalid syntax for POSIX char class.'
else
return [:CHAR, '[']
end
else
@state[:in_char_class] = true
if peek_char == '^'
@stream.getc
return ['[^', nil]
else
return ['[', nil]
end
end
when ']'
if @state[:in_char_class]
@state[:in_char_class] = false
return [']', nil]
else
return [:CHAR, ']']
end
when '-'
if @state[:in_char_class]
return ['-', nil]
else
return [:CHAR, '-']
end
when '*'
return [:CHAR, '*'] if @state[:in_char_class]
return ['*', nil]
when '+'
return [:CHAR, '+'] if @state[:in_char_class]
return ['+', nil]
when '?'
return [:CHAR, '?'] if @state[:in_char_class]
return ['?', nil]
when '{'
return [:CHAR, '{'] if @state[:in_char_class]
if @state[:in_repetition_spec]
error 'Can\'t have special characters in repetition specification.'
else
@state[:in_repetition_spec] = true
return parse_repetition
end
when '}'
return [:CHAR, '}']
when '\\'
return parse_escape
when '^', '$'
return [char, nil]
else
return [:CHAR, char]
end
end
private
def reset
@string = ''
@stream = nil
@state = {
:in_group => 0,
:in_char_class => false,
:in_repetition_spec => false,
}
@options = {}
@scanner_options = {}
end
def parse_repetition
unless @state[:in_repetition_spec]
error 'Invalid calling `parse_repetition`.'
end
min = (peek_char == ',' ? -1 : get_integer)
next_char = @stream.getc
if next_char != ','
if next_char == '}' # Fixed time repetition
if min != -1
return [:VAR_REPETITION, [min, min]]
else
error 'Invalid repetition specification.'
end
else
@stream.ungetc(next_char)
error 'Invalid repetition specification.'
end
end
max = peek_char == '}' ? -1 : get_integer
if @stream.getc != '}'
error 'Invalid repetition specification.'
end
@state[:in_repetition_spec] = false
if max == -1 and min == -1
error 'Invalid repetition specification.'
elsif max != -1 and min == -1
return [:VAR_REPETITION, [0, max]]
elsif max == -1 and min != -1
return [:VAR_REPETITION, [min, -1]]
elsif min <= max
return [:VAR_REPETITION, [min, max]]
else
error 'Repetition specification min > max.'
end
end
def parse_escape
escaped_char = @stream.getc
error 'Undesignated escaped charater.' unless escaped_char
case escaped_char
when *ESCAPE_SEQENCES.keys
return [:CHAR, ESCAPE_SEQENCES[escaped_char]]
when '0'
return [:CHAR, "\0"] unless ('0'..'9').include?(peek_char)
return [:CHAR, get_octal.chr]
when 'x', 'X'
if peek_char == '{'
@stream.getc
hex = get_hex
error 'invalid quoted hex char' if peek_char != '}'
@stream.getc
return [:CHAR, hex.chr]
else
return [:CHAR, get_hex.chr]
end
when *SPEC_CHAR_CLASSES
return [:SPEC_CHAR_CLASS, escaped_char]
when *SPEC_CHAR_CLASSES_INV
return [:SPEC_CHAR_CLASS_INV, escaped_char]
when '1'..'9'
@stream.ungetc(escaped_char)
return [:BACK_REFERENCE, get_integer]
else
return [:CHAR, escaped_char]
end
end
def get_integer(digit_range = '0'..'9', base = 10)
number_str = get_chars(digit_range)
error 'Invalid character.' if number_str.empty?
return number_str.to_i(base)
end
def get_octal
get_integer('0'..'7', 8)
end
def get_hex
get_integer(('0'..'9').to_a + ('a'..'f').to_a + ('A'..'F').to_a, 16)
end
def get_letters
get_chars(('a'..'z').to_a + ('A'..'Z').to_a)
end
def get_chars(char_range)
result_str = ''
char = nil
loop do
char = @stream.getc
if char_range.include? char
result_str << char
else
break
end
end
@stream.ungetc(char)
result_str
end
def peek_char
@stream.ungetc(tmp = @stream.getc)
return tmp
end
# Eat until specific character, respect escaping.
# returns the length it eats, or nil if EOS reaches.
def eat_until(char)
length = 0
loop do
c = @stream.getc
return nil if c.nil?
if c == '\\'
@stream.getc
length += 1
next
end
length += 1
break if c == char
end
return length
end
end
end
end
|
$LOAD_PATH << File.expand_path(File.dirname(__FILE__) + '/../lib')
require 'spec_helper'
require 'scanner'
require 'templates/csv'
RSpec.describe Scanner, :type => :aruba do
before(:all) {
setup_aruba
Dir.chdir('tmp/aruba')
}
after(:all) {
Dir.chdir('../..')
}
let(:attr_labels) { %w[directory file_name latitude longitude] }
let(:report) { Templates::Csv.new('images', attr_labels) }
let(:scanner) { Scanner.new(Pathname.new('../images/'), report, false) }
context 'responds to its methods' do
it { expect(scanner).to respond_to(:begin_scan) }
end
end
|
require File.expand_path '../../test_helper', __dir__
# Test class for Create Sql Server Firewall Rule
class TestCreateOrUpdateFirewallRule < Minitest::Test
def setup
@service = Fog::Sql::AzureRM.new(credentials)
@token_provider = Fog::Credentials::AzureRM.instance_variable_get(:@token_provider)
end
def test_create_or_update_sql_server_firewall_rule_success
firewall_rule_response = ApiStub::Requests::Sql::FirewallRule.create_firewall_rule_response
data_hash = ApiStub::Requests::Sql::FirewallRule.firewall_rule_hash
@token_provider.stub :get_authentication_header, 'Bearer <some-token>' do
RestClient.stub :put, firewall_rule_response do
assert_equal @service.create_or_update_firewall_rule(data_hash), JSON.parse(firewall_rule_response)
end
end
end
def test_create_or_update_sql_server_firewall_rule_failure
@token_provider.stub :get_authentication_header, 'Bearer <some-token>' do
assert_raises ArgumentError do
@service.create_or_update_firewall_rule('test-resource-group', 'test-server-name')
end
end
end
end
|
require 'spec_helper'
describe Api::Service::V1::SolutionsController do
let(:valid_solution) { create :solution }
let(:valid_attributes) { attributes_for(:solution) }
let(:invalid_attributes) { attributes_for(:solution, solution: '') }
describe 'GET index' do
before :each do
@issue = create :issue
@solutions = Array(3..6).sample.times.map do
create(:solution, issue_id: @issue.id)
end
end
it 'should have a valid response' do
get :index, {format: 'json', issue_id: @issue.to_param}
expect(response.status).to eq 200
end
it 'should return an array of solutions' do
get :index, {format: 'json', issue_id: @issue.to_param}
expect(assigns(:solutions)).to eq @solutions
end
it 'should fail without a valid issue id' do
get :index, {format: 'json', issue_id: 99}
expect(response.status).to eq 400
end
end
describe 'GET show' do
it 'should have a valid response' do
get :show, {format: 'json', id: valid_solution.to_param}
expect(response.status).to eq 200
end
it 'should return the requested solution' do
get :show, {format: 'json', id: valid_solution.to_param}
expect(assigns(:solution)).to eq valid_solution
end
it 'should return a failure response if solution is not found' do
get :show, {format: 'json', id: 99}
expect(response.status).to eq 400
end
end
describe 'POST create' do
before :each do
@issue = create :issue
@account = create :account
end
describe 'with valid params' do
it 'should have a valid response' do
post :create, {format: 'json', issue_id: @issue.to_param, solution: valid_attributes.merge(account_id: @account.id)}
expect(response.status).to eq 201
end
it 'should create a new solution' do
expect {
post :create, {format: 'json', issue_id: @issue.to_param, solution: valid_attributes.merge(account_id: @account.id)}
}.to change(Solution, :count).by 1
end
it 'should persist' do
post :create, {format: 'json', issue_id: @issue.to_param, solution: valid_attributes.merge(account_id: @account.id)}
expect(assigns :solution).to be_a Solution
expect(assigns :solution).to be_persisted
end
it 'should render the show template' do
post :create, {format: 'json', issue_id: @issue.to_param, solution: valid_attributes.merge(account_id: @account.id)}
expect(response).to render_template :show
end
end
describe 'with invalid params' do
it 'should return a failure response' do
post :create, {format: 'json', issue_id: @issue.to_param, solution: invalid_attributes.merge(account_id: @account.id)}
expect(response.status).to eq 422
end
it 'should not create a new solution' do
expect {
post :create, {format: 'json', issue_id: @issue.to_param, solution: invalid_attributes.merge(account_id: @account.id)}
}.not_to change(Solution, :count)
end
it 'should return errors' do
post :create, {format: 'json', issue_id: @issue.to_param, solution: invalid_attributes.merge(account_id: @account.id)}
expect(assigns(:solution).errors).not_to be_nil
end
end
end
describe 'PATCH update' do
before :each do
@solution = create :solution
end
describe 'with valid params' do
before :each do
@solution_text = Faker::Lorem.paragraph
end
it 'should have a valid response' do
patch :update, {format: 'json', id: @solution.to_param, solution: {solution: @solution_text}}
expect(response.status).to eq 200
end
it 'should update the requested solution' do
patch :update, {format: 'json', id: @solution.to_param, solution: {solution: @solution_text}}
expect(assigns(:solution).solution).to eq @solution_text
end
it 'should return the requested solution' do
patch :update, {format: 'json', id: @solution.to_param, solution: {solution: @solution_text}}
expect(assigns :solution).to eq @solution
end
it 'should render the show template' do
patch :update, {format: 'json', id: @solution.to_param, solution: {solution: @solution_text}}
expect(response).to render_template :show
end
end
describe 'with invalid params' do
it 'should return a failure response' do
patch :update, {format: 'json', id: @solution.to_param, solution: {solution: ''}}
expect(response.status).to eq 422
end
it 'should not update the requested solution' do
patch :update, {format: 'json', id: @solution.to_param, solution: {solution: ''}}
expect(@solution.solution).not_to eq ''
end
it 'should return errors' do
patch :update, {format: 'json', id: @solution.to_param, solution: {solution: ''}}
expect(assigns(:solution).errors).not_to be_nil
end
end
end
describe 'DELETE destroy' do
before :each do
@solution = create :solution
end
it 'should have a valid response' do
delete :destroy, {format: 'json', id: @solution.to_param}
expect(response.status).to be 200
end
it 'should delete the solution' do
expect {
delete :destroy, {format: 'json', id: @solution.to_param}
}.to change(Solution, :count).by(-1)
end
end
end
|
module Prov
class AMEE < RDF::Vocabulary("http://xml.amee.com/provenance#")
property :test
property :via
property :browser
property :output
property :container
property :input
property :download
property :outfolder
property :manual
property :numeric # numeric operand in a calculation process
property :calculation # a process type representing numeric calculation
property :ameem # a process type indicating ameem upload
property :category # the concept of an AMEE DC
property :manualllabel
property :autolabel
property :graph #the amee provenance graph
property :assembly #A process type involving assembling things together
property :component
property :assumption
end
class OPM < RDF::Vocabulary("http://openprovenance.org/ontology#")
property :cause
property :effect
property :role
property :account
property :label
property :value
property :type
property :Process
property :WasGeneratedBy
property :WasDerivedFrom
property :Role
property :Agent
property :Account
property :OPMGraph
property :Artifact
property :Used
property :hasArtifact
property :hasProcess
property :hasDependency
property :hasAccount
property :hasAgent
end
end |
class RemovePermitsIdsFromTradeShipments < ActiveRecord::Migration
def up
remove_column :trade_shipments, :permits_ids
end
def down
add_column :trade_shipments, :permits_ids, :string
end
end
|
# == Schema Information
#
# Table name: leagues
#
# id :integer not null, primary key
# league_name :string(255)
# league_short :string(255)
# level :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class League < ActiveRecord::Base
has_many :clubs
attr_accessible :league_name, :league_short, :level
validates :league_name, :league_short, :level, presence: true
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Ambassador, type: :model do
# describe '#country_name' do
# it 'displays the country name of the ambassador' do
# ambassador = create :ambassador, country: 'US'
# expect(ambassador.country_name).to eq 'United States'
# end
# end
end
|
require 'hier_menu/hier_menu'
# -*- coding: utf-8 -*-
# Configures your navigation
SimpleNavigation::Configuration.run do |navigation|
# navigation.renderer = SimpleNavigationRenderers::Bootstrap2
# Specify a custom renderer if needed.
# The default renderer is SimpleNavigation::Renderer::List which renders HTML lists.
# The renderer can also be specified as option in the render_navigation call.
# navigation.renderer = Your::Custom::Renderer
# Specify the class that will be applied to active navigation items.
# Defaults to 'selected' navigation.selected_class = 'your_selected_class'
# Specify the class that will be applied to the current leaf of
# active navigation items. Defaults to 'simple-navigation-active-leaf'
# navigation.active_leaf_class = 'your_active_leaf_class'
# Item keys are normally added to list items as id.
# This setting turns that off
# navigation.autogenerate_item_ids = false
# You can override the default logic that is used to autogenerate the item ids.
# To do this, define a Proc which takes the key of the current item as argument.
# The example below would add a prefix to each key.
# navigation.id_generator = Proc.new {|key| "my-prefix-#{key}"}
# If you need to add custom html around item names, you can define a proc that
# will be called with the name you pass in to the navigation.
# The example below shows how to wrap items spans.
# navigation.name_generator = Proc.new {|name, item| "<span>#{name}</span>"}
# The auto highlight feature is turned on by default.
# This turns it off globally (for the whole plugin)
# navigation.auto_highlight = false
# If this option is set to true, all item names will be considered as safe (passed through html_safe). Defaults to false.
# navigation.consider_item_names_as_safe = false
# Define the primary navigation
navigation.items do |primary|
primary.dom_id = 'side-menu'
primary.dom_class = 'nav nav-pills nav-stacked'
# Add an item to the primary navigation. The following params apply:
# key - a symbol which uniquely defines your navigation item in the scope of the primary_navigation
# name - will be displayed in the rendered navigation. This can also be a call to your I18n-framework.
# url - the address that the generated item links to. You can also use url_helpers (named routes, restful routes helper, url_for etc.)
# options - can be used to specify attributes that will be included in the rendered navigation item (e.g. id, class etc.)
# some special options that can be set:
# :if - Specifies a proc to call to determine if the item should
# be rendered (e.g. <tt>if: -> { current_user.admin? }</tt>). The
# proc should evaluate to a true or false value and is evaluated in the context of the view.
# :unless - Specifies a proc to call to determine if the item should not
# be rendered (e.g. <tt>unless: -> { current_user.admin? }</tt>). The
# proc should evaluate to a true or false value and is evaluated in the context of the view.
# :method - Specifies the http-method for the generated link - default is :get.
# :highlights_on - if autohighlighting is turned off and/or you want to explicitly specify
# when the item should be highlighted, you can set a regexp which is matched
# against the current URI. You may also use a proc, or the symbol <tt>:subpath</tt>.
#
primary.item :menu_home, 'Home', '/', :icon => ['fa fa-home fa-fw'] # class: 'fa fa-home fa-fw'
primary.item :menu_prosumers, 'Prosumers', prosumers_path, :icon => ['fa fa-plug fa-fw'], :split => false do |sub_nav|
ProsumerCategory.order(id: :asc).each do |pc|
sub_nav.item "menu_prosumers_#{pc.name}", pc.name, prosumers_path(category: pc), :split => false do |sub_sub_nav|
sub_sub_nav.item :menu_prosumers_sub, "Prosumer list", prosumers_path(category: pc)
sub_sub_nav.item :menu_prosumer_new, "New Prosumer", new_prosumer_path(category: pc)
HierMenu::HierMenu.new("prosumers_hier_#{pc.name}",
Proc.new { |p| prosumer_url(p) }
).fill_node sub_sub_nav, pc.prosumers.order(name: :asc), 4
sub_sub_nav.dom_class = 'nav nav-third-level collapse'
end
sub_nav.dom_class = 'nav nav-second-level collapse'
end
end
primary.item :menu_clusters, 'Clusters', clusters_path, :icon => ['fa fa-sitemap fa-fw'], :split => false do |sub_nav|
# primary.item :menu_clusters, 'Clusters' do |sub_nav|
sub_nav.item :menu_clusters_sub, "Cluster list", clusters_path
# sub_nav.item :menu_auto_cluster, "Automatic clustering", "/clusterings/select"
HierMenu::HierMenu.new("clusters_hier", Proc.new { |p| cluster_url(p) }, nil, 4
).fill_node sub_nav, Cluster.all.order(name: :asc)
sub_nav.dom_class = 'nav nav-second-level collapse'
end
primary.item :menu_clusterings, 'Clusterings', '#' do |sub_nav|
sub_nav.item :menu_clusterings_sub, "Clusterings List", clusterings_path
sub_nav.item :menu_clustering_new, "New Clustering", new_clustering_path
sub_nav.item :menu_clustering_new_from_existing, "New Clustering from existing allocation", new_from_existing_clustering_path
HierMenu::HierMenu.new("clusterings_hier",
Proc.new { |p| clustering_url(p) },
nil,
4).fill_node sub_nav, Clustering.all.order(name: :asc)
sub_nav.dom_class = 'nav nav-second-level collapse'
end
primary.item :menu_demand_responses, 'Demand Responses', demand_responses_path
primary.item :menu_bids, 'Bids', bids_path
primary.item :menu_sla, 'Monitor SLA progress', sla_monitor_path
# primary.item :menu_meters, 'Meters', '#' do |sub_nav|
# HierMenu::HierMenu.new('meters_hier', Proc.new { |p| meter_url(p) }, :mac, 4).fill_node sub_nav, Meter.all.order(id: :asc)
# sub_nav.dom_class = 'nav nav-second-level collapse'
# end
primary.item :menu_algorithms, 'Algorithms', "#" do |sub_nav|
sub_nav.item :menu_clustering, 'Clustering', "/clusterings/select"
sub_nav.item :menu_dunamic_adaptation, 'Dynamic Adaptation', "/clusterings/new_from_existing"
sub_nav.item :menu_target_clustering, "Target Clustering", "/target_clustering"
sub_nav.item :menu_RES_scheduling, 'RES scheduling', "#"
sub_nav.item :menu_VMG_modeling, 'VMG production - consumption modeling', "#"
sub_nav.item :menu_VMG_profiling, 'VMG profile maximization algorithms', "#"
sub_nav.item :menu_comm_algos, 'Communication algorithms', "#"
sub_nav.item :menu_virt_netw_micro, 'Virtual netwrok microgrid', "#"
sub_nav.dom_class = 'nav nav-second-level collapse'
end
primary.item :menu_data_points, 'Data points', data_points_path, :icon => ['fa fa-bar-chart-o fa-fw']
# primary.item :menu_day_aheads, 'Day-ahead forecasts', day_aheads_path, :icon => ['fa fa-bar-chart-o fa-fw']
primary.item :menu_market_prices, 'Market Prices', market_prices_path, :icon => ['fa fa-bar-chart-o fa-fw']
primary.item :menu_configurations, 'Configurations', '/configurations', :icon => ['fa fa-tasks fa-fw']
primary.item :menu_cloud_platform, 'Cloud Platform', "#" do |sub_nav|
sub_nav.item :menu_instances, 'Instances', '/cloud_platform', :icon => ['fa fa-cog fa-fw']
sub_nav.item :menu_cloud_resources, 'Resources', '/cloud_platform/resources', :icon => ['fa fa-tachometer fa-fw']
sub_nav.item :menu_engines, 'Machines', '/cloud_platform/machines', :icon => ['fa fa-server fa-fw']
sub_nav.item :menu_tasks, 'Tasks', '/cloud_platform/tasks', :icon => ['fa fa-list fa-fw']
sub_nav.dom_class = 'nav nav-second-level collapse'
end
#primary.item :menu_cloud_platform, 'Cloud Platform', '/cloud_platform', :icon => ['fa fa-cog fa-fw']
primary.item :menu_users, 'Users', users_path, :icon => ['fa fa-user fa-fw']
# primary.item :key_1, 'name', url, options
# Add an item which has a sub navigation (same params, but with block)
# primary.item :key_2, 'name', url, options do |sub_nav|
# Add an item to the sub navigation (same params again)
# sub_nav.item :key_2_1, 'name', url, options
# end
# You can also specify a condition-proc that needs to be fullfilled to display an item.
# Conditions are part of the options. They are evaluated in the context of the views,
# thus you can use all the methods and vars you have available in the views.
# primary.item :key_3, 'Admin', url, class: 'special', if: -> { current_user.admin? }
# primary.item :key_4, 'Account', url, unless: -> { logged_in? }
# you can also specify html attributes to attach to this particular level
# works for all levels of the menu
# primary.dom_attributes = {id: 'menu-id', class: 'menu-class'}
# You can turn off auto highlighting for a specific level
primary.auto_highlight = true
end
end
|
require 'singleton'
module CoreClients
class GetTaskListsClient < RabbitmqPubSub::RpcPublisher
include Singleton
def initialize
@pub_queue_name = 'rpc_TMC_get_task_lists_request'
@sub_queue_name = 'rpc_TMC_get_task_lists_response'
super
end
end
end
|
module Typhoid
class Parser
attr_reader :json_string
def self.call(json_string)
new(json_string).parse
end
def initialize(json_string)
@json_string = json_string
end
def parse
parsed_body if json_string.present?
end
def parsed_body
engine.call json_string
rescue
raise ReadError, json_string
end
private :parsed_body
def engine
JSON.method(:parse)
end
private :engine
end
class ReadError < StandardError
attr_reader :body
def initialize(body)
@body = body
end
def to_s
"Could not parse JSON body: #{cleaned_body}"
end
def cleaned_body
clean = body[0..10]
clean = clean + "..." if add_dots?
clean
end
private :cleaned_body
def add_dots?
body.length > 10
end
private :add_dots?
end
end
|
class SavedSearch < ApplicationRecord
attr_accessor :is_being_copied
validates_presence_of :title, :team_id
validates :title, uniqueness: { scope: :team_id }, unless: proc { |ss| ss.is_being_copied }
belongs_to :team, optional: true
has_many :feeds, dependent: :nullify
has_many :feed_teams, dependent: :nullify
end
|
class CreateCustomerJobActionResults < ActiveRecord::Migration[5.1]
def change
create_table :customer_job_action_results do |t|
t.references :CustomerJob, foreign_key: true
t.references :ActionResults, foreign_key: true
t.timestamps
end
end
end
|
Rails.application.configure do
config.lograge.enabled = true
config.lograge.formatter = Lograge::Formatters::Json.new
config.lograge.custom_options = lambda do |event|
ElasticAPM.log_ids do |transaction_id, span_id, trace_id|
{ :'pid' => Process.pid,
:'timestamp' => Time.now.utc,
:'transaction.id' => transaction_id,
:'span.id' => span_id,
:'trace.id' => trace_id }
end
end
end
|
class CreateCourses < ActiveRecord::Migration[6.0]
def change
create_table :courses do |t|
t.text :title, null: false
t.text :term, null: false
t.text :units, null: false
t.text :campus
t.text :subject, default: 'CSE'
t.text :catalog_number, null: false
t.timestamps
end
end
end
|
# encoding: utf-8
$:.push File.expand_path("../lib", __FILE__)
require "skiima/version"
Gem::Specification.new do |s|
s.name = "skiima"
s.version = Skiima::VERSION
s.authors = ["David Conner"]
s.email = ["dconner.pro@gmail.com"]
s.homepage = "http://github.com/dcunited001/skiima"
s.summary = %q{A SQL object manager for Rails projects}
s.description = %q{Skiima helps to manage SQL objects like views and functions}
s.rubyforge_project = "skiima"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
s.add_dependency "fast_gettext", '~> 0.6.0'
s.add_dependency "erubis", '~> 2.7.0'
s.add_development_dependency "appraisal", '~> 1.0.0'
s.add_development_dependency "bundler", '>= 1.3.3'
s.add_development_dependency "minitest", '~> 4.6.2'
s.add_development_dependency "minitest-matchers", '~> 1.2.0'
s.add_development_dependency "mocha", '~> 0.13.2'
s.add_development_dependency "pry"
s.add_development_dependency 'rake', '~> 10.1'
s.add_development_dependency 'pg', '~> 0.14.1'
s.add_development_dependency 'mysql', '~> 2.9.1'
s.add_development_dependency 'mysql2', '~> 0.3.11'
end
# Logging
# TODO: add logging messages
# TODO: convert to i18n messages
# SQL Objects
# add functions
# add procs
# add triggers
# Adapters
# SQL Server Adapter
# Skiima Options
# add a way to just return a list of scripts to be executed
# Refactor:
# reorganize modules
# Thor tasks ??
# TODO: thor task to load all sets
# TODO: thor task to load specific sets
# TODO: delegate rake tasks to thor (how?)
|
require 'spec_helper'
describe SessionsController do
it 'creates an authenticated user' do
@request.env['omniauth.auth'] =
OmniAuth::AuthHash.new(
provider: 'facebook',
uid: 1234,
info: OmniAuth::AuthHash::InfoHash.new(email: 'test@facebook.com'))
get :create, provider: 'facebook'
expect(Authorization.count).to eq 1
expect(User.count).to eq 1
end
end
|
# frozen_string_literal: true
require "base64"
require "json"
require "server_sent_events"
require "redfish_client/event_listener"
require "redfish_client/resource"
module RedfishClient
# Root resource represents toplevel entry point into Redfish service data.
# Its main purpose is to provide authentication support for the API.
class Root < Resource
# AuthError is raised if the user session cannot be created.
class AuthError < StandardError; end
# Basic and token authentication headers.
BASIC_AUTH_HEADER = "Authorization"
TOKEN_AUTH_HEADER = "X-Auth-Token"
# Authenticate against the service.
#
# Calling this method will try to create new session on the service using
# provided credentials. If the session creation fails, basic
# authentication will be attempted. If basic authentication fails,
# {AuthError} will be raised.
#
# @param username [String] username
# @param password [String] password
# @raise [AuthError] if user session could not be created
def login(username, password)
# Since session auth is more secure, we try it first and use basic auth
# only if session auth is not available.
if session_login_available?
session_login(username, password)
else
basic_login(username, password)
end
end
# Sign out of the service.
#
# If the session could not be deleted, {AuthError} will be raised.
def logout
session_logout
basic_logout
end
# Find Redfish service object by OData ID field.
#
# @param oid [String] Odata id of the resource
# @return [Resource, nil] new resource or nil if resource cannot be found
def find(oid)
find!(oid)
rescue NoResource
nil
end
# Find Redfish service object by OData ID field.
#
# @param oid [String] Odata id of the resource
# @return [Resource] new resource
# @raise [NoResource] resource cannot be fetched
def find!(oid)
Resource.new(@connector, oid: oid)
end
# Return event listener.
#
# If the service does not support SSE, this function will return nil.
#
# @return [EventListener, nil] event listener
def event_listener
address = dig("EventService", "ServerSentEventUri")
return nil if address.nil?
EventListener.new(ServerSentEvents.create_client(address))
end
private
def session_login_available?
!@content.dig("Links", "Sessions").nil?
end
def session_login(username, password)
r = @connector.post(
@content["Links"]["Sessions"]["@odata.id"],
"UserName" => username, "Password" => password
)
raise AuthError, "Invalid credentials" unless r.status == 201
session_logout
payload = r.data[:headers][TOKEN_AUTH_HEADER]
@connector.add_headers(TOKEN_AUTH_HEADER => payload)
@session = Resource.new(@connector, content: JSON.parse(r.data[:body]))
end
def session_logout
return unless @session
r = @session.delete
raise AuthError unless r.status == 204
@session = nil
@connector.remove_headers([TOKEN_AUTH_HEADER])
end
def auth_test_path
@content.values.map { |v| v["@odata.id"] }.compact.first
end
def basic_login(username, password)
payload = Base64.encode64("#{username}:#{password}").strip
@connector.add_headers(BASIC_AUTH_HEADER => "Basic #{payload}")
r = @connector.get(auth_test_path)
raise AuthError, "Invalid credentials" unless r.status == 200
end
def basic_logout
@connector.remove_headers([BASIC_AUTH_HEADER])
end
end
end
|
module SuperInteraction
module Layout
FRAMEWORKS = [ :bootstrap3, :bootstrap4, :beyond ]
def self.framework=(f)
raise "Not support framework: #{f}" if FRAMEWORKS.include?(f) == false
@@framework = f
end
def self.framework
@@framework
end
def self.modal_layout
case @@framework
when :bootstrap3
"modal_bs3.haml"
when :bootstrap4
"modal_bs4.haml"
when :beyond
"modal_beyond.haml"
else
# Default
"modal_bs3.haml"
end
end
end
end
|
require_relative 'abstract_factory'
require_relative 'circle'
require_relative 'red'
class RedCircleFactory < AbstractFactory
def get_shape
Circle.new
end
def get_color
Red.new
end
end
|
require "integration_test_helper"
require "gds_api/test_helpers/mapit"
require "gds_api/test_helpers/imminence"
class PlacesTest < ActionDispatch::IntegrationTest
include GdsApi::TestHelpers::Mapit
include GdsApi::TestHelpers::Imminence
setup do
stub_mapit_has_a_postcode("SW1A 1AA", [51.5010096, -0.1415871])
@payload = {
title: "Find a passport interview office",
base_path: "/passport-interview-office",
schema_name: "place",
document_type: "place",
phase: "beta",
public_updated_at: "2012-10-02T15:21:03+00:00",
details: {
introduction: "<p>Enter your postcode to find a passport interview office near you.</p>",
more_information: "Some more info on passport offices",
need_to_know: "<ul><li>Proof of identification required</li></ul>",
place_type: "find-passport-offices",
},
external_related_links: [],
}
stub_content_store_has_item("/passport-interview-office", @payload)
@places = [
{
"access_notes" => "The London Passport Office is fully accessible to wheelchair users. ",
"address1" => nil,
"address2" => "89 Eccleston Square",
"email" => nil,
"fax" => nil,
"general_notes" => "Monday to Saturday 8.00am - 6.00pm. ",
"location" => {
"longitude" => -0.14411606838362725,
"latitude" => 51.49338734529598,
},
"name" => "London IPS Office",
"phone" => "0800 123 4567",
"postcode" => "SW1V 1PN",
"text_phone" => nil,
"town" => "London",
"url" => "http://www.example.com/london_ips_office",
},
{
"access_notes" => "The doors are always locked.\n\nAnd they are at the top of large staircases.",
"address1" => nil,
"address2" => "Station Way",
"email" => nil,
"fax" => nil,
"general_notes" => "Monday to Saturday 8.00am - 6.00pm.\n\nSunday 1pm - 2pm.",
"location" => {
"longitude" => -0.18832238262617113,
"latitude" => 51.112777245292826,
},
"name" => "Crawley IPS Office",
"phone" => nil,
"postcode" => "RH10 1HU",
"text_phone" => nil,
"town" => "Crawley",
"url" => nil,
},
]
end
context "when visiting the start page" do
setup do
visit "/passport-interview-office"
end
should "render the place page" do
assert_equal 200, page.status_code
within "head", visible: :all do
assert page.has_selector?("title", text: "Find a passport interview office - GOV.UK", visible: :all)
end
within "#content" do
within ".page-header" do
assert_has_component_title "Find a passport interview office"
end
assert page.has_content?("Enter your postcode to find a passport interview office near you.")
assert page.has_field?("Enter a postcode")
assert_has_button("Find")
assert page.has_no_content?("Please enter a valid full UK postcode.")
within ".further-information" do
assert page.has_content?("Further information")
within "ul" do
assert page.has_selector?("li", text: "Proof of identification required")
end
end
end
assert page.has_selector?(".gem-c-phase-banner")
end
should "add google analytics tags for postcodeSearchStarted" do
track_category = page.find(".postcode-search-form")["data-track-category"]
track_action = page.find(".postcode-search-form")["data-track-action"]
assert_equal "postcodeSearch:place", track_category
assert_equal "postcodeSearchStarted", track_action
end
end
context "given a valid postcode" do
setup do
stub_imminence_has_places_for_postcode(@places, "find-passport-offices", "SW1A 1AA", Frontend::IMMINENCE_QUERY_LIMIT)
visit "/passport-interview-office"
fill_in "Enter a postcode", with: "SW1A 1AA"
click_on "Find"
end
should "redirect to same page and not put postcode as URL query parameter" do
assert_current_url "/passport-interview-office"
end
should "not display an error message" do
assert page.has_no_content?("Please enter a valid full UK postcode.")
end
should "not show the 'no results' message" do
assert page.has_no_content?("We couldn't find any results for this postcode.")
end
should "display places near to the requested location" do
names = page.all("#options li p.adr span.fn").map(&:text)
assert_equal ["London IPS Office", "Crawley IPS Office"], names
within "#options > li:first-child" do
assert page.has_content?("89 Eccleston Square")
assert page.has_content?("London")
assert page.has_content?("SW1V 1PN")
assert page.has_link?("http://www.example.com/london_ips_office", href: "http://www.example.com/london_ips_office")
assert page.has_content?("Phone: 0800 123 4567")
assert page.has_content?("Monday to Saturday 8.00am - 6.00pm.")
assert page.has_content?("The London Passport Office is fully accessible to wheelchair users.")
end
end
should "format general notes and access notes" do
within "#options > li:nth-child(2)" do
assert page.has_content?("Station Way")
assert page.has_selector?("p", text: "Monday to Saturday 8.00am - 6.00pm.")
assert page.has_selector?("p", text: "Sunday 1pm - 2pm.")
assert page.has_selector?("p", text: "The doors are always locked.")
assert page.has_selector?("p", text: "And they are at the top of large staircases.")
end
end
should "add google analytics for postcodeResultsShown" do
track_category = page.find(".places-results")["data-track-category"]
track_action = page.find(".places-results")["data-track-action"]
track_label = page.find(".places-results")["data-track-label"]
assert_equal "postcodeSearch:place", track_category
assert_equal "postcodeResultShown", track_action
assert_equal "London IPS Office", track_label
end
end
context "given a valid postcode for report child abuse" do
setup do
stub_mapit_has_a_postcode("N5 1QL", [51.5505284612, -0.100467152148])
@payload_for_report_child_abuse = {
title: "Find your local child social care team",
base_path: "/report-child-abuse-to-local-council",
schema_name: "place",
document_type: "place",
in_beta: true,
details: {
description: "Find your local child social care team",
place_type: "find-child-social-care-team",
introduction: "<p>Contact your local council if you think a child is at risk</p>",
},
}
stub_content_store_has_item("/report-child-abuse-to-local-council", @payload_for_report_child_abuse)
@places_for_report_child_abuse = [
{
"name" => "Islington",
"phone" => "020 7226 1436 (Monday to Friday)",
"general_notes" => "020 7226 0992 (out of hours)",
"url" => "http://www.islington.gov.uk/services/children-families/cs-worried/Pages/default.aspx",
},
]
stub_imminence_has_places_for_postcode(@places_for_report_child_abuse, "find-child-social-care-team", "N5 1QL", Frontend::IMMINENCE_QUERY_LIMIT)
visit "/report-child-abuse-to-local-council"
fill_in "Enter a postcode", with: "N5 1QL"
click_on "Find"
end
should "not display an error message" do
assert page.has_no_content?("Please enter a valid full UK postcode.")
end
should "not show the 'no results' message" do
assert page.has_no_content?("We couldn't find any results for this postcode.")
end
should "display places near to the requested location" do
within "#options" do
names = page.all("li p.adr span.fn").map(&:text)
assert_equal ["You can call the children's social care team at the council in Islington"], names
within first("li:first-child") do
assert page.has_link?("020 7226 1436", href: "tel://020%207226%201436")
assert page.has_content?("(Monday to Friday)")
assert page.has_link?("020 7226 0992", href: "tel://020%207226%200992")
assert page.has_content?("(out of hours)")
assert page.has_link?("Go to their website", href: "http://www.islington.gov.uk/services/children-families/cs-worried/Pages/default.aspx")
end
end
end
end
context "given a valid postcode with no nearby places" do
setup do
@places = []
stub_imminence_has_places_for_postcode(@places, "find-passport-offices", "SW1A 1AA", Frontend::IMMINENCE_QUERY_LIMIT)
visit "/passport-interview-office"
fill_in "Enter a postcode", with: "SW1A 1AA"
click_on "Find"
end
should "not error on a bad postcode" do
assert page.has_no_content?("Please enter a valid full UK postcode.")
end
should "inform the user on the lack of results" do
assert page.has_content?("We couldn't find any results for this postcode.")
end
should "add google analytics for noResults" do
track_category = page.find(".gem-c-error-alert")["data-track-category"]
track_action = page.find(".gem-c-error-alert")["data-track-action"]
track_label = page.find(".gem-c-error-alert")["data-track-label"]
assert_equal "userAlerts: place", track_category
assert_equal "postcodeErrorShown: validPostcodeNoLocation", track_action
assert_equal "We couldn't find any results for this postcode.", track_label
end
end
context "given an invalid postcode" do
setup do
query_hash = { "postcode" => "BAD POSTCODE", "limit" => Frontend::IMMINENCE_QUERY_LIMIT }
return_data = { "error" => "invalidPostcodeError" }
stub_imminence_places_request("find-passport-offices", query_hash, return_data, 400)
visit "/passport-interview-office"
fill_in "Enter a postcode", with: "BAD POSTCODE"
click_on "Find"
end
should "display error message" do
assert page.has_content?("This isn't a valid postcode")
end
should "not show the 'no results' message" do
assert page.has_no_content?("We couldn't find any results for this postcode.")
end
should "display the postcode form" do
within ".location-form" do
assert page.has_field?("Enter a postcode")
assert page.has_field? "postcode", with: "BAD POSTCODE"
assert_has_button("Find")
end
end
end
context "given a valid postcode with no locations returned" do
setup do
query_hash = { "postcode" => "JE4 5TP", "limit" => Frontend::IMMINENCE_QUERY_LIMIT }
return_data = { "error" => "validPostcodeNoLocation" }
stub_imminence_places_request("find-passport-offices", query_hash, return_data, 400)
visit "/passport-interview-office"
fill_in "Enter a postcode", with: "JE4 5TP"
click_on "Find"
end
should "display the 'no locations found' message" do
assert page.has_content?("We couldn't find any results for this postcode.")
end
end
context "when previously a format with parts" do
should "reroute to the base slug if requested with part route" do
visit "/passport-interview-office/old-part-route"
assert_current_url "/passport-interview-office"
end
end
end
|
module RSence
module ArgvUtil
# Tests, if the port on addr responds or refuses the connection.
# Automatically replaces '0.0.0.0' with '127.0.0.1'
def test_port( port, addr='127.0.0.1' )
require 'socket'
require 'timeout'
begin
addr = '127.0.0.1' if addr == '0.0.0.0'
timeout(1) do
if RUBY_VERSION.to_f >= 1.9
sock = TCPSocket.open( addr, port )
else
begin
sock = TCPsocket.open( addr, port )
rescue NameError => e # Rubinius
warn "TCPsocket not available, trying TCPSocket.."
sock = TCPSocket.open( addr, port )
end
end
sock.close
end
return true
rescue Timeout::Error
puts "Address #{addr} port #{port} timed out"
return false
rescue Errno::ECONNREFUSED
return false
rescue => e
warn e.inspect
return false
end
end
end
end
|
class Sponsor < ActiveRecord::Base
has_and_belongs_to_many :amendments
end |
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :set_current_user
protected # prevents method from being invoked by a route
def set_current_user
# we exploit the fact that find_by_id(nil) returns nil
@current_user ||= Moviegoer.find_by_id(session[:user_id])
redirect_to login_path and return unless @current_user
end
end
|
require File.join(File.dirname(__FILE__), 'array_extensions')
require File.join(File.dirname(__FILE__), 'card')
class Board
attr_reader :cards
def initialize(*cards)
raise "Incorrect number of cards you gave #{cards.size}, you need 12" unless cards.flatten.size % 3 == 0
@cards = cards.flatten
end
def solve
solutions = []
@cards.combinations_without_repetitions(3).each do |combination|
solutions << combination if solution?(combination)
end
solutions
end
private
def solution?(combination)
color?(combination) && shape?(combination) && shading?(combination) && number?(combination)
end
def color?(c)
check_attribute(c, :color)
end
def shape?(c)
check_attribute(c, :shape)
end
def shading?(c)
check_attribute(c, :shading)
end
def number?(c)
check_attribute(c, :number)
end
def check_attribute(c, attribute)
filtered = c.collect {|card| card.send(attribute)}
(filtered.uniq == filtered) || (filtered.uniq.size == 1)
end
end
|
class Dancer
attr_accessor :age
def initialize(name,age)
@name="Misty Copeland"
@age=33
@arr=[]
@i=0
end
def name
@name
end
def pirouette
"*twirls*"
end
def bow
"*bows*"
end
def queue_dance_with(name)
@arr << name
end
def card
@arr
end
def begin_next_dance
n= "Now dancing with #{@arr[@i]}."
@arr.delete_at(@i)
@i=@i+1
return n
end
def tutu_color(color)
color= "She is wairing #{color}."
end
end
#l= Dancer.new("bew",33)
#p l.name |
#
# Author:: RiotCode
# Cookbook Name:: laravel
# Recipe:: composer
#
# Copyright 2009-2011, Opscode, Inc.
#
# 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
node[:deploy].each do |application, deploy|
execute "composer install" do
command "php composer.phar install && touch /var/log/.php_composer_installed"
creates "/var/log/.php_composer_installed"
action :run
end
end
# node[:deploy].each do |application, deploy|
#
# script "install_composer" do
# interpreter "bash"
# user "root"
# cwd "#{deploy[:deploy_to]}/current"
# code <<-EOH
# curl -s https://getcomposer.org/installer | php
# php composer.phar install
# EOH
# end
#
# end
|
class Rook
attr_accessor :incremental_moves, :ending_positions, :possible_positions, :color
def initialize(color)
@color = color
@possible_positions = []
@incremental_moves = [[0,1], [0,-1], [1,0], [-1,0]].freeze
@ending_positions = [[0,1], [0,2], [0,3], [0,4], [0,5], [0,6], [0,7],
[0,-1], [0,-2], [0,-3], [0,-4], [0,-5], [0,-6], [0,-7],
[1,0], [2,0], [3,0], [4,0], [5,0],[6,0], [7,0],
[-1,0], [-2,0], [-3,0], [-4,0], [-5,0],[-6,0], [-7,0]].freeze
end
def to_s
if @color == "black"
"\u{2656}"
elsif @color == "white"
"\u{265C}"
end
end
end |
class FollowsController < ApplicationController
def create
@user = User.find(params[:user_id])
@follow = Follow.new(follow_params)
@follow.user = @user
@follow.follower = current_user
if @follow.save
flash[:info] = "#{@follow.follower.username} is now following #{@follow.user.username}"
redirect_to :back
else
flash[:info] = "Error"
redirect_to :back
end
end
private
def follow_params
params.require(:follow).permit(:follower_id, :leader_id)
end
end |
class ToddlersController < ApplicationController
before_action :set_daycare
before_action :set_toddler, only: [:show, :destroy]
# GET /toddlers
def index
@toddlers = Toddler.all
render json: @toddlers
end
# GET /toddlers/1
def show
render json: @toddler
end
# POST /toddlers
def create
# byebug
# @daycare = Daycare.find_by(params[:daycare_id])
@toddler = @daycare.toddlers.new(toddler_params)
if @toddler.save
render json: @toddler, status: :created, location: @toddler
# render json: {message: "Successfully submitted #{@toddler.name}!"}
else
render json: @toddler.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /toddlers/1
def update
if @toddler.update(toddler_params)
render json: @toddler
else
render json: @toddler.errors, status: :unprocessable_entity
end
end
# DELETE /toddlers/1
def destroy
@toddler = Toddler.find(params[:id])
# byebug
@toddler.destroy
render json: {message: "Successfully deleted #{@toddler.name}!"}
end
private
# Use callbacks to share common setup or constraints between actions.
def set_toddler
@toddler = Toddler.find(params[:id])
end
def set_daycare
@daycare = Daycare.find_by(params[:daycare_id])
end
# Only allow a trusted parameter "white list" through.
def toddler_params
params.require(:toddler).permit(:name, :birthday, :contact, :phone, :allergy, :daycare_id)
end
end
|
class GradesController < ApplicationController
protect_from_forgery with: :null_session
def index
@grades = Grade.all.order(created_at: :desc)
apply_filters
render json: @grades
end
def show
grade = Grade.find_by(id: params[:id])
render json: grade
end
def create
grade = Grade.create(grade_params)
if grade.save
render json: grade
else
render json: { error: grade.errors.messages }, status: 422
end
end
def update
grade = Grade.find_by(id: params[:id])
if grade.update(grade_params)
render json: grade
else
render json: { error: Grade.errors.messages }, status: 422
end
end
def destroy
grade = Grade.find_by(id: params[:id])
if grade&.destroy!
render json: { message: "Grade destroyed!" }
else
render json: { error: "Grade not found!" } , status: 422
end
end
def students
grade = Grade.find_by(id: params[:id])
render json: { students: grade&.students }
end
def assign_students
grade = Grade.find_by(id: params[:id])
students = Student.where(id: params[:students_ids])
grade.students << students
render json: { message: "Students assigned succesfully!" }
end
private
def grade_params
params.require(:grade).permit(:code, :title, :description)
end
def apply_filters
%i[code title description].each do |filter|
@grades = @grades.where("#{filter.to_s} ilike ?", "%#{params[filter]}%") if params[filter]
end
end
end
|
require 'boxzooka/return_notification'
module Boxzooka
class ReturnsNotificationRequest < BaseRequest
collection :returns,
flat: true,
entry_field_type: :entity,
entry_type: Boxzooka::ReturnNotification,
entry_node_name: 'Return'
end
end
|
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'spree_cmcic'
s.version = '2.0.0'
s.summary = 'Add gem summary here'
s.description = 'Spree commerce extension for CM-CIC payment'
s.required_ruby_version = '>= 1.9.3'
s.author = 'Vincent Charlet'
s.email = ''
s.files = Dir['CHANGELOG', 'README.md', 'LICENSE', 'lib/**/*', 'app/**/*']
s.require_path = 'lib'
s.requirements << 'none'
s.has_rdoc = true
end |
class WelcomeController < ApplicationController
caches_page :index
def index
@account = Account.find_by_company_name('Boopis Media')
if @account.present?
@account.users.build
@form = @account.forms.find_by_name('QM Contact Form')
@request = @account.requests.new
end
end
end
|
class Monkey
attr_accessor :name, :type, :favorite_food
def initialize(array = [name, type, favorite_food])
@name = array[0]
@type = array[1]
@favorite_food = array[2]
end
end
|
class AdminController < ApplicationController
before_filter :admin_only
layout 'index'
def index
render :layout => !request.xhr?
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
NUM_WORKERS = 2
Vagrant.configure("2") do |config|
(1..NUM_WORKERS).each do |n|
config.vm.define "kube-node#{n+1}" do |worker|
worker.vm.provider 'virtualbox' do |vb|
vb.memory = '2048'
end
worker.vm.box = 'centos/7'
worker.vm.box_check_update = false
worker.vm.hostname = "kube-node#{n+1}"
worker.vm.network 'private_network', ip: "172.27.129.11#{n}"
worker.vm.provision :shell, path: "bootstrap.sh"
end
end
config.vm.define 'kube-node1' do |master|
master.vm.provider 'virtualbox' do |vb|
vb.memory = '2048'
vb.cpus = 2
end
master.vm.box = 'centos/7'
master.vm.box_check_update = false
master.vm.hostname = 'kube-node1'
master.vm.network 'private_network', ip: '172.27.129.105'
master.vm.provision :shell, path: "bootstrap.sh"
master.vm.provision :shell, path: "init_etcd.sh"
master.vm.provision :shell, path: "init_flanneld.sh"
master.vm.provision :shell, path: "init_master.sh"
master.vm.provision :shell, path: "init_worker.sh"
master.vm.provision :shell, path: "init_addons.sh"
end
end
|
class AddSocialMediaLinkToRestaurant < ActiveRecord::Migration
def change
add_column :restaurants, :facebook_link, :string
add_column :restaurants, :twitter_link, :string
add_column :restaurants, :pinterest_link, :string
end
end
|
class Ioiprint
def initialize(url = ENV.fetch('IOIPRINT_URL'))
@conn = Faraday.new(url: url) do |faraday|
faraday.request :json
faraday.response :raise_error
faraday.use :instrumentation
faraday.adapter Faraday.default_adapter
end
end
attr_reader :conn
# title:: String
# users:: [{name: String, username: String, password: String}]
def print_passwords(title:, users:)
conn.post '/password', {title: title, users: users}
end
# message:: String
# contestant:: {id: String, name: String, special_requirement_note: String?}
# desk:: {id: String, map: URI?, zone: String?}
def print_staff_call(message:, contestant:, desk:)
conn.post '/staff_call', {message: message, contestant: contestant, desk: desk}
end
end
|
class Movie < ActiveRecord::Base
belongs_to :genre
has_many :comments, dependent: :destroy
validates :name, presence: true
def average_stars
comments.average(:starts)
end
end
|
=begin
input: two numbers
output: list of strings (print?)
algorithm:
puts the numbers in to the array
initiate an empty string
iterate through the array
use three conditions to output three types
attach the types to the string
=end
require 'pry'
require 'pry-byebug'
def fizzbuzz(number1, number2)
numbers = (number1..number2).to_a
result = []
numbers.each do |number|
result << fizzbuzz_value(number)
end
puts result.join(', ')
end
def fizzbuzz_value(number)
binding.pry
case
when number % 15 == 0
'FizzBuzz'
when number % 3 == 0
'Fizz'
when number % 5 == 0
'Buzz'
else
number
end
end
fizzbuzz(1, 15)
fizzbuzz(1,1)
|
# frozen_string_literal: true
require './lib/space.rb'
feature 'request button' do
scenario 'it submits a request for a space' do
Space.create(name: 'Team Nomad House', description: 'It is a lovely place to stay', price: '£500', available_date: '12/09/20')
visit ('/spaces')
#click_button('Team Nomad House')
expect(page).to have_content('Team Nomad House')
end
end
|
module ShipitAPI
class Config
attr_accessor :x_shipit_email, :x_shipit_access_token, :content_type, :accept, :version
def initialize
@content_type = 'application/json'.freeze
@accept ||= 'application/vnd.shipit.v'.freeze
@version ||= '2'
end
end
def self.config
@config ||= Config.new
end
def self.configure(&block)
yield(config) if block_given?
end
end
|
require 'client'
require 'helper'
describe Client do
before { Helper.set_up }
let(:client) { described_class.new }
it do
1000.times { expect(client.send_request('this is a request body')).to eq('ok') }
end
after { Helper.tear_down }
end
|
class BlogEntry < ActiveRecord::Base
belongs_to :blog
belongs_to :user
has_many :blog_comments
end
|
class WundergroundService
attr_reader :connection
def initialize
@connection = Faraday.new("http://api.wunderground.com/")
@auth = "#{ENV["key"]}"
end
def ten_day(zip)
parse(connection.get("api/#{@auth}/forecast10day/q/#{zip}.json"))[:forecast][:simpleforecast][:forecastday]
# binding.pry
end
private
def parse(response)
JSON.parse(response.body, symbolize_names: true)
end
end
|
class UpdateSubscribeColumnWithDefaultValue < ActiveRecord::Migration
def up
Course.reset_column_information
Course.update_all({:subscribe_state => :allowed}, :subscribe_state => nil)
end
def down
Course.update_all(:subscribe_state => nil)
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
CITIES_IN_URUGUAY = [
['Achar', 468081],
['Aguas Corrientes', 468010],
['Aigua', 468082],
['Algorta', 380896],
['Artigas', 380894],
['Atlantida', 468057],
['Balneario Solis', 468011],
['Baltasar Brum', 468083],
['Belen', 468012],
['Bernabe Rivera', 468013],
['Blanquillo', 468014],
['Canelones', 468058],
['Cardal', 468015],
['Cardona', 468016],
['Carmelo', 468059],
['Carmen', 420098],
['Cebollati', 468085],
['Cerrillos', 469012],
['Cerro Chato', 468086],
['Cerro Colorado', 468087],
['Cerro Vera', 380897],
['Chapicuy', 468017],
['Chuy', 468118],
['Colon', 380898],
['Colonia del Sacramento', 468796],
['Colonia Lavalleja', 468018],
['Colonia Nuevo Paysandu', 380445],
['Cuaro', 468019],
['Dolores', 468060],
['Durazno', 468061],
['Ecilda Paullier', 468020],
['Empalme Olmos', 468021],
['Florencio Sanchez', 380899],
['Florida', 468062],
['Fraile Muerto', 468088],
['Fray Bentos', 468063],
['Fray Marcos', 380900],
['Guichon', 468089],
['Independencia', 468022],
['Ismael Cortinas', 468023],
['Ituzaingo', 468024],
['Joaquin Suarez', 469011],
['Jose Batlle Y Ordonez', 468794],
['Jose Enrique Rodo', 468090],
['Jose Pedro Varela', 468091],
['Juan Lacaze', 468797],
['La Cruz', 468025],
['La Floresta', 468026],
['La Paloma', 380901],
['La Paz', 380558],
['Las Flores', 468027],
['Las Piedras', 468054],
['Libertad', 468092],
['Lorenzo Geyres', 468028],
['Mal Abrigo', 468029],
['Maldonado', 468065],
['Melo', 468066],
['Mercedes', 468067],
['Miguelete', 469013],
['Migues', 468799],
['Minas de Corrales', 468031],
['Minas', 468068],
['Montes', 468032],
['Montevideo', 468052],
['Nuevo Berlin', 468033],
['Ombues De Lavalle', 468094],
['Pando', 468069],
['Paso de Los Toros', 468070],
['Paso del Cerro', 468034],
['Paysandu', 468055],
['Piedras Coloradas', 468035],
['Pinera', 380902],
['Piraraja', 468095],
['Punta del Este', 468108],
['Quebracho', 468096],
['Reboledo', 468037],
['Rio Branco', 468072],
['Rivera', 468053],
['Rocha', 468073],
['Salto', 468056],
['San Antonio', 468038],
['San Bautista', 468039],
['San Carlos', 468074],
['San Javier', 468040],
['San Jorge', 380903],
['San Jose De Mayo', 468798],
['Santa Clara de Olimar', 380822],
['Santa Clara', 420099],
['Santa Lucia', 468076],
['Sauce del Yi', 468043],
['Sauce', 468042],
['Soca', 468044],
['Tacuarembo', 468077],
['Tala', 468098],
['Tambores', 468045],
['Tomas Gomensoro', 468047],
['Tranqueras', 468048],
['Treinta y Tres', 468078],
['Tres Arboles', 380904],
['Trinidad', 468079],
['Tupambae', 380905],
['Valdense', 468795],
['Valentines', 468049],
['Veinticinco de Mayo', 468051],
['Velasquez', 420100],
['Velazquez', 380869],
['Vergara', 380906],
['Villa del Carmen', 380884],
]
CITIES_IN_URUGUAY.each do |name, woeid|
# Create city records by woeid. Make sure we don't create new records with a
# duplicate woeid attribute if seeds get reloaded.
City.find_or_create_by!(woeid: woeid) do |city|
city.name = name
end
end
|
class HomeController < ApplicationController
layout "landing", only: [:landing]
def landing
end
def index
ike = {
pic_path: 'ike_member.jpg',
name: 'T.J. Ike',
instrument: 'Keys',
instrument_info: 'Kurzweil SP88 · Kawai K-4 · Hammond Organ',
info: "Ike has over 40 years experience working with bands and in studios. He first came to the Twin Cities in 1977 with a blues band, out of Iowa, known as The Little Red Rooster Band. In 1978 the band relocated to Minneapolis and cut an album in The Studio in St. Paul. The mixing was done by Sound 80. The title of the album was Authorized Bootleg. The band and the album did well, but the band decided to move back to Iowa where they are now known as The Blue Band.\n\nIke remained in the Twin Cities to further pursue his musical career, playing both with local projects and road bands booked out of the area. In addition to Ike's many musical talents, he also has a degree in Audio Recording from Hennepin Technical College in Eden Prairie, MN."
}
ellis = {
pic_path: 'ellis_member.png',
name: 'Tim Ellis',
instrument: 'Drums & Percussion',
instrument_info: nil,
info: "Tim Ellis, a drummer from St. Paul, Minnesota, has a long history with drums. He has been playing in bands of all genres for over 35 years, while along the way collecting vintage drums. Way back when they weren't called vintage. Rumor has it, Tim opened a shop because he needed a place to store his ballooning collection.\n\nTim makes his own line of drums with the Ellis Drum Company line. Production is done right in the shop basement. Tim employs pro drummers in the shop so they know and understand things from a drummer's point of view. Friendly and quality service is a must."
}
jj = {
pic_path: 'jj_member.jpg',
name: 'James Jamar',
instrument: 'Bassist',
instrument_info: nil,
info: "James has been playing on stages throughout the Midwest for over 25 years. As a bassist he values every note he plays, but knows when not to play as well. He is self-taught and through regular practice and studying with other accomplished musicians, seeks constantly to hone his skills.\n\nAs an entertainer, James is a dynamic, high energy and infectious performer. \"I love to watch you play\" and \"Man, you are really having fun up there!\" are frequent compliments give to him.\n\nJames has played in original and commercial bands as a member and a hired gun. His love of music is great enough that he hopes to be playing until his last day."
}
@fb_events = [
{
event_url: "https://www.facebook.com/cosmicfuseband/posts/946833258686036"
}
]
@members = [ike, ellis, jj]
end
end
|
require 'rspec'
require_relative '../model/batalla_naval'
require_relative '../model/barco'
describe 'BatallaNaval' do
let(:batallaNaval) { BatallaNaval.new }
it 'Creacion del juego, un tablero vacio de 10x10' do
batallaNaval.crear_tablero(10,10)
expect(batallaNaval.medidas_del_tablero).to eq [10,10]
end
it 'Mostrar la lista de barcos en el juego' do
expect(batallaNaval.lista_de_barcos).to eq [['crucero',2],['destructor',3],['submarino',1]]
end
it 'Elegir barco por su nombre' do
crucero = Barco.new('crucero',2)
barco_esperado = batallaNaval.elegir_barco('crucero')
expect(barco_esperado.datos).to eq crucero.datos
end
it 'Poner el barco en la posicion libre' do
barco = batallaNaval.elegir_barco('crucero')
# Al tener el 'crucero' un tama ño de 2 ocuparia horizontalmente 'a3' y 'b3'
expect(batallaNaval.poner_barco(barco, 'a3', 'horizontal')).to eq 'Barco ubicado exitosamente!'
expect(batallaNaval.posicion_ocupada('a3')).to eq true
expect(batallaNaval.posicion_ocupada('b3')).to eq true
end
it 'Tratar de poner barco en posicion ocupada, no poder hacerlo' do
barco = batallaNaval.elegir_barco('crucero')
resultado_crucero= batallaNaval.poner_barco(barco, 'a3', 'horizontal')
barco_destructor = batallaNaval.elegir_barco('destructor')
resultado_destructor = batallaNaval.poner_barco(barco_destructor, 'b3', 'vertical')
# Posiciones del barco 'crucero' estan ocupadas
expect(resultado_crucero).to eq 'Barco ubicado exitosamente!'
expect(batallaNaval.posicion_ocupada('a3')).to eq true
expect(batallaNaval.posicion_ocupada('b3')).to eq true
# Posiciones del barco 'destructor' no se ocupan
expect(resultado_destructor).to eq 'Posicion ocupada!'
expect(batallaNaval.posicion_ocupada('b4')).to eq false
expect(batallaNaval.posicion_ocupada('b5')).to eq false
end
it 'Poner el barco una posicion que caiga fuera del tablero' do
barco = batallaNaval.elegir_barco('destructor')
resultado = batallaNaval.poner_barco(barco, 'k2', 'horizontal')
expect(resultado).to eq 'Posicion FUERA DE TABLERO!'
end
it 'Poner el barco una posicion dentro del tablero, pero que el resto caigan fuera del tablero' do
barco = batallaNaval.elegir_barco('destructor')
resultado = batallaNaval.poner_barco(barco, 'e1', 'horizontal')
expect(resultado).to eq 'Posicion FUERA DE TABLERO!'
end
########################################################################################
it 'Elegir posicion donde disparar' do
batallaNaval.elegir_donde_disparar('c3')
expect(batallaNaval.proximo_disparo).to eq 'c3'
end
it 'Disparo a una posicion vacia' do
batallaNaval_oponente = BatallaNaval.new
batallaNaval.guardar_tablero_enemigo(batallaNaval_oponente.tablero)
batallaNaval.elegir_donde_disparar('c3')
expect(batallaNaval.disparar).to eq 'Has dado en el AGUA!'
end
it 'Poner un barco en el tablero oponente y guardar el tablero en mi juego' do
batallaNaval_oponente = BatallaNaval.new
barco_oponente = batallaNaval_oponente.elegir_barco('crucero')
batallaNaval_oponente.poner_barco(barco_oponente, 'a3', 'horizontal')
batallaNaval.guardar_tablero_enemigo(batallaNaval_oponente.tablero)
expect(batallaNaval_oponente.posicion_ocupada('a3')).to eq true
expect(batallaNaval_oponente.posicion_ocupada('b3')).to eq true
end
it 'Destruir un barco oponente' do
batallaNaval_oponente = BatallaNaval.new
barco_oponente = batallaNaval_oponente.elegir_barco('submarino')
batallaNaval_oponente.poner_barco(barco_oponente, 'b4', 'horizontal')
batallaNaval.guardar_tablero_enemigo(batallaNaval_oponente.tablero)
batallaNaval.elegir_donde_disparar('b4')
expect(batallaNaval.disparar).to eq 'KATAPUM! Has hundido un barco!'
end
it 'Hundir un barco crucero completo' do
batallaNaval_oponente = BatallaNaval.new
barco_oponente = batallaNaval_oponente.elegir_barco('crucero')
batallaNaval_oponente.poner_barco(barco_oponente, 'b1', 'vertical')
batallaNaval.guardar_tablero_enemigo(batallaNaval_oponente.tablero)
batallaNaval.elegir_donde_disparar('b1')
expect(batallaNaval.disparar).to eq 'PUM! Has dado en el blanco!'
batallaNaval.elegir_donde_disparar('b2')
expect(batallaNaval.disparar).to eq 'KATAPUM! Has hundido un barco!'
end
it 'Hundir un barco destructor completo' do
batallaNaval_oponente = BatallaNaval.new
barco_oponente = batallaNaval_oponente.elegir_barco('destructor')
batallaNaval_oponente.poner_barco(barco_oponente, 'b1', 'vertical')
batallaNaval.guardar_tablero_enemigo(batallaNaval_oponente.tablero)
batallaNaval.elegir_donde_disparar('b1')
expect(batallaNaval.disparar).to eq 'PUM! Has dado en el blanco!'
batallaNaval.elegir_donde_disparar('b2')
expect(batallaNaval.disparar).to eq 'PUM! Has dado en el blanco!'
batallaNaval.elegir_donde_disparar('b3')
expect(batallaNaval.disparar).to eq 'KATAPUM! Has hundido un barco!'
end
end |
class WikiPage < ActiveRecord::Base
acts_as_wiki_page
has_one :task_category_and_wiki, dependent: :destroy
has_many :task_category, :through => :task_category_and_wiki
has_many :wiki_and_workflow_informations, dependent: :destroy
has_many :homeland_nodes, class_name: "Homeland::Node", dependent: :destroy
has_many :task_performances, dependent: :destroy
has_many :wiki_relationships, dependent: :destroy
has_many :related_wiki_pages, class_name: "WikiRelationship", foreign_key: "related_wiki_page_id", dependent: :destroy
end
|
class Booking
attr_reader :id, :booking_start, :booking_end , :cat_id , :user_id , :status
def initialize(id: , booking_start: , booking_end: , cat_id: , user_id: , status: "PENDING")
@id = id
@booking_start = booking_start
@booking_end = booking_end
@cat_id = cat_id
@user_id = user_id
@status = status
end
def self.all
result = DatabaseConnection.query("SELECT * FROM bookings;")
result.map { |booking| create_booking_instance(booking) }
end
def self.create(cat_id:, booking_start:, booking_end:, user_id:)
result = DatabaseConnection.query("INSERT INTO bookings (cat_id, booking_start, booking_end, user_id, status)
VALUES ('#{cat_id}', '#{booking_start}', '#{booking_end}', #{user_id}, 'PENDING')
RETURNING id, cat_id, booking_start, booking_end, user_id, status")
create_booking_instance(result[0])
end
def self.change_status(id: , status:)
result = DatabaseConnection.query("UPDATE bookings SET status = '#{status}' WHERE id = '#{id}' RETURNING id, cat_id, booking_start, booking_end, user_id, status")
create_booking_instance(result[0])
end
def self.find_by_user(user_id: )
result = DatabaseConnection.query("SELECT *
FROM bookings JOIN cats ON (cat_id=cats.id) WHERE bookings.user_id = #{user_id}")
result.map { |booking| booking}
end
private
def self.create_booking_instance(params)
new(id: params['id'], booking_start: params['booking_start'],
booking_end: params['booking_end'], cat_id: params['cat_id'],
user_id: params['user_id'], status: params['status'])
end
end
|
class WelcomeMailer < ApplicationMailer
layout nil
def contact(info)
@info = info
mail(:from => 'no-reply@infinitumweb.com', :to => 'davi@infinitumweb.com', :subject => 'Mensagem de Contato do site infinitumweb!')
end
end
|
class Post < ApplicationRecord
validates :author_id, presence: true
has_one_attached :photo
belongs_to :user,
foreign_key: :author_id,
class_name: :User
has_many :comments,
foreign_key: :post_id,
class_name: :Comment
has_many :commenters,
through: :comments,
source: :user
has_many :likes,
foreign_key: :post_id,
class_name: :Like
has_many :likers,
through: :likes,
source: :user
end
|
require 'rails_helper'
RSpec.describe CartsController, type: :controller do
describe 'DELETE destroy' do
it 'destroys cart session' do
cart = create :cart
session[:current_cart] = cart.id
delete :destroy, id: cart
expect(session[:current_cart]).to eq nil
end
end
end
|
require 'spec_helper'
describe Group do
it "has a valid factory" do
expect(build(:group)).to be_valid
end
subject { build(:group) }
it { should respond_to(:group_users) }
it { should respond_to(:users) }
it "is invalid without a no" do
expect(build(:group, no: nil)).to have(1).errors_on(:no)
end
it "is invalid with a duplicate no" do
create(:group, no: 30)
group = build(:group, no: 30)
expect(group).to have(1).errors_on(:no)
end
end |
# frozen_string_literal: true
class SchoolSerializer < ActiveModel::Serializer
cached
attributes :id, :name
delegate :cache_key, to: :object
end
|
class Settings::ManufacturersController < ApplicationController
before_action :set_manufacturer, only: [:destroy]
def create
@manufacturer = Manufacturer.new(manufacturer_params)
authorize! :create, @manufacturer
respond_to do |format|
if @manufacturer.save
format.html { redirect_to settings_root_path, notice: 'Manufacturer was successfully created.' }
format.json { render json: @manufacturer, status: :created }
else
format.html { redirect_to settings_root_path, notice: 'Manufacturer was not created.' }
format.json { render json: @manufacturer.errors, status: :unprocessable_entity }
end
end
end
def destroy
authorize! :delete, @manufacturer
@manufacturer.destroy
respond_to do |format|
format.html { redirect_to settings_root_path }
format.json { head :no_content }
end
end
private
def set_manufacturer
@manufacturer = Manufacturer.find(params[:id])
end
def manufacturer_params
params.require(:manufacturer).permit(:name)
end
end
|
class Customer < ApplicationRecord
validates :first_name, length: { maximum: 30, minimum: 2 }
validates :last_name, length: { maximum: 30, minimum: 2 }
validates :patronymic, length: { maximum: 30, minimum: 2 }
validates :address, length: { maximum: 50, minimum: 2 }
validates :email, length: { maximum: 50, minimum: 2 }
end
|
class AddMarriageToUsers < ActiveRecord::Migration
def change
add_column :users, :marriage, :boolean, default: false
end
end
|
require 'spec_helper'
describe EssayQuestion do
it "must be of type EssayQuestion" do
essay_question = EssayQuestion.new()
essay_question.type.should match "EssayQuestion"
end
it "must have a content" do
essay_question = EssayQuestion.new()
essay_question.should_not be_valid
end
it "must have a max answer length of 100" do
essay_question = EssayQuestion.new()
essay_question.content = "Hello"
essay_question.should_not be_valid
end
end
|
require 'spec_helper.rb'
describe 'API' do
before(:each) do
User.destroy_all
@user = User.create(:name => 'test')
end
describe '/api - basic' do
it '/api returns 400 if user not specifed' do
get '/api/test'
last_response.status.should eq 400
end
it '/api returns 400 if empty user provided' do
get '/api/test?user=' + ' '
last_response.status.should eq 400
end
it '/api returns 400 if invalid user specifed' do
User.destroy_all
get '/api/test?user=' + 'I_DO_NOT_EXIST'
last_response.status.should eq 400
end
it '/api returns 200 if valid user specified' do
get '/api/test?user=' + @user.name
last_response.should be_ok
end
it '/api/version returns correct version info' do
get '/api/version?user=' + @user.name
last_response.should be_ok
last_response.body.should eq('1.0')
end
end
describe '/api/doing' do
it 'calls API.add_activity with the correct parameters' do
data = "Sample activity description."
Api.should_receive(:add_activity).with(@user.name, data)
post '/api/doing?user=' + @user.name, data
last_response.should be_ok
end
it 'removes whitespace from doing item' do
data = " I have too much whitespace "
Api.should_receive(:add_activity).with(@user.name, data.strip)
post '/api/doing?user=' + @user.name, data
end
it 'returns a 400 if data is empty' do
post '/api/doing?user=' + @user.name, ' '
last_response.status.should eq 400
end
end
describe '/api/stop' do
it 'calls API.stop_activity with the correct parameters' do
Api.should_receive(:stop_activity).with(@user.name)
get '/api/stop?user=' + @user.name
last_response.should be_ok
end
end
describe '/api/wait' do
it 'calls API.add_wait with the correct parameters' do
data = 'waiting for something'
Api.should_receive(:add_wait).with(@user.name, data)
post '/api/wait?user=' + @user.name, data
last_response.should be_ok
end
it 'removes whitespace from wait item' do
data = ' I have whitespace here '
Api.should_receive(:add_wait).with(@user.name, data.strip)
post '/api/wait?user=' + @user.name, data
last_response.should be_ok
end
it 'returns a 400 if no wait item specified' do
post '/api/wait?user=' + @user.name
last_response.status.should eq 400
end
it 'returns a 400 if wait item is empty' do
post '/api/wait?user=' + @user.name, ' '
last_response.status.should eq 400
end
end
describe '/api/wait/ping' do
it 'calls API.wait_ping with the correct parameters' do
data = 'some ping note'
wait_id = '1'
Api.should_receive(:wait_ping).with(@user.name, Integer(wait_id), data)
post '/api/wait/ping?user=' + @user.name + '&waitId=' + wait_id, data
last_response.should be_ok
end
it 'returns 400 if waitId not specified' do
data = 'some ping note'
post '/api/wait/ping?user=' + @user.name, data
last_response.status.should eq 400
end
it 'returns 400 if waitId not an integer' do
data = 'some ping note'
post '/api/wait/ping?user=' + @user.name + '&waitId=' + 'NOT_INTEGER', data
last_response.status.should eq 400
end
it 'returns 400 if waitId is negative' do
data = 'some ping note'
post '/api/wait/ping?user=' + @user.name + '&waitId=' + '-1', data
last_response.status.should eq 400
end
it 'returns 400 if no ping note specified' do
wait_id = '1'
post '/api/wait/ping?user=' + @user.name + '&waitId=' + wait_id
last_response.status.should eq 400
end
it 'returns 400 if ping note is empty' do
data = ' '
wait_id = '1'
post '/api/wait/ping?user=' + @user.name + '&waitId=' + wait_id, ' '
last_response.status.should eq 400
end
end
describe '/api/wait/done' do
it 'calls API.wait_done with the correct parameters' do
wait_id = '1'
Api.should_receive(:wait_done).with(@user.name, Integer(wait_id))
get '/api/wait/done?user=' + @user.name + '&waitId=' + wait_id
last_response.should be_ok
end
it 'returns 400 if waitId not specified' do
data = 'some ping note'
get '/api/wait/done?user=' + @user.name, data
last_response.status.should eq 400
end
it 'returns 400 if waitId not an integer' do
data = 'some ping note'
get '/api/wait/done?user=' + @user.name + '&waitId=' + 'NOT_INTEGER', data
last_response.status.should eq 400
end
it 'returns 400 if waitId is negative' do
data = 'some ping note'
get '/api/wait/done?user=' + @user.name + '&waitId=' + '-1', data
last_response.status.should eq 400
end
end
describe '/api/wait/cancel' do
it 'calls API.wait_cancel with the correct parameters' do
wait_id = '1'
Api.should_receive(:wait_cancel).with(@user.name, Integer(wait_id))
get '/api/wait/cancel?user=' + @user.name + '&waitId=' + wait_id
last_response.should be_ok
end
it 'returns 400 if waitId not specified' do
data = 'some ping note'
get '/api/wait/cancel?user=' + @user.name, data
last_response.status.should eq 400
end
it 'returns 400 if waitId not an integer' do
data = 'some ping note'
get '/api/wait/cancel?user=' + @user.name + '&waitId=' + 'NOT_INTEGER', data
last_response.status.should eq 400
end
it 'returns 400 if waitId is negative' do
data = 'some ping note'
get '/api/wait/cancel?user=' + @user.name + '&waitId=' + '-1', data
last_response.status.should eq 400
end
end
describe '/api/goals' do
it 'calls API.goals with the correct parameters' do
Api.should_receive(:goals).with(@user.name)
get '/api/goals?user=' + @user.name
last_response.should be_ok
end
it 'returns correctly formatted json response if goals exist for user' do
data = {:a => 'nothing to see', :b => 'also nothing'}
Api.should_receive(:goals).and_return(data)
get '/api/goals?user=' + @user.name
last_response.body.should eq data.to_json
last_response.should be_ok
end
it 'returns empty json response if no goals exist for the user' do
Api.should_receive(:goals).and_return(nil)
get '/api/goals?user=' + @user.name
last_response.body.should eq "{}"
last_response.should be_ok
end
end
describe '/api/waits' do
it 'calls API.waits with the correct parameters' do
Api.should_receive(:waits).with(@user.name)
get '/api/waits?user=' + @user.name
last_response.should be_ok
end
it 'returns correctly formatted response if waits exist for user' do
data = {:a => 'nothing to see', :b => 'also nothing'}
Api.should_receive(:waits).and_return(data)
get '/api/waits?user=' + @user.name
last_response.body.should eq data.to_json
end
it 'returns correctly formatted response if no waits exist for user' do
Api.should_receive(:waits).and_return(nil)
get '/api/waits?user=' + @user.name
last_response.body.should eq "{}"
end
end
end |
class ChangeCompleteDefaultValueToStories < ActiveRecord::Migration[5.2]
def change
change_column_default :stories, :complete, false
end
end
|
class Anagram
attr_accessor :word
def initialize(word)
@word = word
end
#need to iterate over the array of words that the .match method takes as an argument.
#split word into an array of letters using some_word.split("") and compare =>[1, 2, 3] == [1, 2, 3]
#Remember that you can .sort an arrays elements. This will help in your comparison:
#It should return all matches in an array. If no matches exist, it should return an empty array.
#match diaper to [hello world zombies pants dipper]
def match(word_array)
some_word = @word.split("").sort
#result = []
word_array.select do | element |
element.split("").sort == some_word
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.