text stringlengths 10 2.61M |
|---|
require File.dirname(__FILE__) + '/test_helper'
class SitemapGeneratorTest < Test::Unit::TestCase
context "SitemapGenerator Rake Task" do
setup do
::Rake::Task['sitemap:refresh'].invoke
end
should "fail if hostname not defined" do
end
end
context "SitemapGenerator library" do
should "be have x elements" do
assert_equal SitemapGenerator::Sitemap.links.size, 14
end
end
end
|
# frozen_string_literal: true
module Dry
# Helper methods for constraint types
#
# @api public
module Types
# @param [Hash] options
#
# @return [Dry::Logic::Rule]
#
# @api public
def self.Rule(options)
rule_compiler.(
options.map { |key, val|
::Dry::Logic::Rule::Predicate.build(
::Dry::Logic::Predicates[:"#{key}?"]
).curry(val).to_ast
}
).reduce(:and)
end
# @return [Dry::Logic::RuleCompiler]
#
# @api private
def self.rule_compiler
@rule_compiler ||= ::Dry::Logic::RuleCompiler.new(::Dry::Logic::Predicates)
end
end
end
|
class EditAndAddColumnsToMembers < ActiveRecord::Migration
def change
add_column :members, :firstname, :string
add_column :members, :lastname, :string
remove_column :members, :name
end
end
|
# Copyright 2013 Sami Samhuri <sami@samhuri.net>
#
# MIT License
# http://sjs.mit-license.org
module Kwikemon
class Monitor
DefaultTTL = 86400 # 1 day
attr_accessor :redis
attr_reader :name, :text, :ttl, :created, :modified
@listeners = Hash.new { |h, k| h[k] = [] }
def Monitor.on(event, &block)
@listeners[event] << block
end
def Monitor.emit(event, *args)
@listeners[event].each { |handler| handler.call(*args) }
end
def initialize(name, text = nil)
@name = name
@text = text
end
def save
if exists?
update(text)
else
create
end
end
def exists?
redis.exists(key)
end
def create
raise MonitorError.new('name cannot be blank') if name.to_s.strip.length == 0
redis.hmset(key, *to_a)
self.class.emit(:create, name)
self
end
def update(text, ttl = nil)
raise MonitorError.new('name cannot be blank') if name.to_s.strip.length == 0
redis.hmset(key, 'text', text, 'modified', Time.now.to_i)
redis.ttl(key, ttl) if ttl
self
end
def remove
redis.del(key)
self.class.emit(:remove, name)
self
end
def key
Kwikemon.key("monitor:#{name}")
end
def ttl
@ttl ||= exists? ? redis.ttl(key) : nil
end
def created
@created ||= exists? ? redis.hget(key, 'created').to_i : nil
end
def modified
@modified ||= exists? ? redis.hget(key, 'modified').to_i : nil
end
def text
@text ||= exists? ? redis.hget(key, 'text') : nil
end
private
def redis
Kwikemon.redis
end
def to_hash
{ name: name,
text: text,
ttl: ttl || DefaultTTL,
created: created || Time.now.to_i,
modified: modified || Time.now.to_i
}
end
def to_a
to_hash.to_a
end
end
end |
class RemoveShiftsFromJobs < ActiveRecord::Migration[5.2]
def change
remove_column :jobs, :shifts
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 rails db:seed command (or created alongsnamee the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
random_cats = [{
"name"=> "Jaclin",
"sex"=> "F",
"birth_date"=> "2019/05/20",
"description"=> "Ameliorated reciprocal hierarchy"
}, {
"name"=> "Krystalle",
"sex"=> "F",
"birth_date"=> "2016/06/11",
"description"=> "Business-focused tertiary extranet"
}, {
"name"=> "Donal",
"sex"=> "M",
"birth_date"=> "2015/05/19",
"description"=> "Optional high-level standardization"
}, {
"name"=> "Norene",
"sex"=> "F",
"birth_date"=> "2016/08/11",
"description"=> "Multi-tiered multi-tasking info-mediaries"
}, {
"name"=> "Griswold",
"sex"=> "M",
"birth_date"=> "2017/01/18",
"description"=> "Implemented composite open architecture"
}, {
"name"=> "Cheryl",
"sex"=> "F",
"birth_date"=> "2017/09/21",
"description"=> "Profound logistical instruction set"
}, {
"name"=> "Conchita",
"sex"=> "F",
"birth_date"=> "2016/02/01",
"description"=> "User-friendly encompassing firmware"
}, {
"name"=> "Estella",
"sex"=> "F",
"birth_date"=> "2016/12/18",
"description"=> "Synergistic bi-directional workforce"
}, {
"name"=> "Thaddeus",
"sex"=> "M",
"birth_date"=> "2017/04/07",
"description"=> "Business-focused client-driven ability"
}, {
"name"=> "Conroy",
"sex"=> "M",
"birth_date"=> "2017/02/18",
"description"=> "Pre-emptive neutral portal"
}, {
"name"=> "Georgeanne",
"sex"=> "F",
"birth_date"=> "2016/09/04",
"description"=> "Vision-oriented solution-oriented synergy"
}, {
"name"=> "Phebe",
"sex"=> "F",
"birth_date"=> "2015/11/13",
"description"=> "Centralized foreground forecast"
}, {
"name"=> "Claire",
"sex"=> "F",
"birth_date"=> "2018/04/10",
"description"=> "Upgradable modular architecture"
}, {
"name"=> "Lindsay",
"sex"=> "F",
"birth_date"=> "2014/12/10",
"description"=> "Operative 24 hour mnamedleware"
}, {
"name"=> "Margaux",
"sex"=> "F",
"birth_date"=> "2016/01/30",
"description"=> "Universal hybrname artificial intelligence"
}, {
"name"=> "Jesse",
"sex"=> "F",
"birth_date"=> "2016/10/29",
"description"=> "Upgradable value-added secured line"
}, {
"name"=> "Abbey",
"sex"=> "M",
"birth_date"=> "2018/07/03",
"description"=> "Enterprise-wnamee reciprocal task-force"
}, {
"name"=> "Verina",
"sex"=> "F",
"birth_date"=> "2016/11/13",
"description"=> "Enterprise-wnamee multi-tasking extranet"
}, {
"name"=> "Averell",
"sex"=> "M",
"birth_date"=> "2018/12/29",
"description"=> "Versatile global projection"
}, {
"name"=> "Herb",
"sex"=> "M",
"birth_date"=> "2016/10/27",
"description"=> "Progressive 5th generation help-desk"
}, {
"name"=> "Eran",
"sex"=> "F",
"birth_date"=> "2015/12/30",
"description"=> "Object-based local model"
}, {
"name"=> "Phylys",
"sex"=> "F",
"birth_date"=> "2019/04/03",
"description"=> "Monitored static help-desk"
}, {
"name"=> "Lorne",
"sex"=> "F",
"birth_date"=> "2016/03/02",
"description"=> "Enhanced national framework"
}, {
"name"=> "Shep",
"sex"=> "M",
"birth_date"=> "2019/02/09",
"description"=> "Public-key object-oriented matrices"
}, {
"name"=> "Sergei",
"sex"=> "M",
"birth_date"=> "2016/02/04",
"description"=> "Polarised upward-trending solution"
}, {
"name"=> "Gustavus",
"sex"=> "M",
"birth_date"=> "2017/11/16",
"description"=> "Upgradable value-added challenge"
}, {
"name"=> "Tiffy",
"sex"=> "F",
"birth_date"=> "2015/09/08",
"description"=> "Assimilated contextually-based customer loyalty"
}, {
"name"=> "Regen",
"sex"=> "M",
"birth_date"=> "2019/04/30",
"description"=> "Pre-emptive 5th generation instruction set"
}, {
"name"=> "Bruce",
"sex"=> "M",
"birth_date"=> "2017/12/04",
"description"=> "Fundamental dynamic projection"
}, {
"name"=> "Emilia",
"sex"=> "F",
"birth_date"=> "2017/11/30",
"description"=> "Cross-group bi-directional hierarchy"
}, {
"name"=> "Xymenes",
"sex"=> "M",
"birth_date"=> "2017/02/28",
"description"=> "Fully-configurable full-range intranet"
}, {
"name"=> "Jordan",
"sex"=> "M",
"birth_date"=> "2017/12/21",
"description"=> "Reverse-engineered real-time challenge"
}, {
"name"=> "Berthe",
"sex"=> "F",
"birth_date"=> "2015/06/17",
"description"=> "Face to face contextually-based concept"
}, {
"name"=> "Ricky",
"sex"=> "F",
"birth_date"=> "2017/04/21",
"description"=> "Sharable 4th generation analyzer"
}, {
"name"=> "Francyne",
"sex"=> "F",
"birth_date"=> "2016/05/26",
"description"=> "Universal homogeneous projection"
}, {
"name"=> "Robinet",
"sex"=> "F",
"birth_date"=> "2018/11/20",
"description"=> "Re-engineered dedicated orchestration"
}, {
"name"=> "Penrod",
"sex"=> "M",
"birth_date"=> "2016/12/14",
"description"=> "Expanded methodical circuit"
}, {
"name"=> "Asher",
"sex"=> "M",
"birth_date"=> "2016/01/07",
"description"=> "Stand-alone motivating help-desk"
}, {
"name"=> "Cacilie",
"sex"=> "F",
"birth_date"=> "2018/08/11",
"description"=> "Upgradable empowering mnamedleware"
}, {
"name"=> "Ches",
"sex" => "M",
"birth_date"=> "2017/11/26",
"description"=> "Automated 24/7 productivity"
}]
COLORS = [
"Fuscia",
"Pink",
"Turquoise",
"Yellow",
"Purple",
"Maroon",
]
random_cats.each do |hash|
Cat.create!(name:hash['name'], sex:hash['sex'], birth_date:hash['birth_date'], description:hash['description'], color:COLORS.sample)
end |
require 'rails_helper'
describe 'leagues/show' do
let(:league) { build_stubbed(:league) }
let(:divisions) { build_stubbed_list(:league_division, 3) }
let(:roster) { build_stubbed(:league_roster) }
let(:matches) do
[
build_stubbed(:league_match, status: :confirmed),
build_stubbed(:league_match, status: :confirmed, forfeit_by: :home_team_forfeit),
build_stubbed(:league_match, status: :confirmed, forfeit_by: :away_team_forfeit),
build_stubbed(:league_match, status: :confirmed, forfeit_by: :mutual_forfeit),
build_stubbed(:league_match, status: :confirmed, forfeit_by: :technical_forfeit),
build_stubbed(:bye_league_match),
]
end
before do
all_rosters = []
ordered_rosters = []
divisions.each do |division|
rosters = build_stubbed_list(:league_roster, 5)
all_rosters += rosters
ordered_rosters << [division, rosters]
end
allow(league).to receive(:ordered_rosters_by_division).and_return(ordered_rosters)
tiebreakers = League::Tiebreaker.kinds.map do |kind, _|
build_stubbed(:league_tiebreaker, kind: kind)
end
allow(league).to receive(:tiebreakers).and_return(tiebreakers)
assign(:league, league)
assign(:rosters, all_rosters)
assign(:ordered_rosters, ordered_rosters)
assign(:divisions, divisions)
assign(:roster, roster)
assign(:matches, divisions.map { |div| [div, matches] }.to_h)
end
context 'hidden league' do
before { league.status = 'hidden' }
it 'displays league details for' do
assign(:top_div_matches, matches)
render
expect(rendered).to include(league.name)
expect(rendered).to include('Private')
end
end
context 'league with signups open' do
before do
# Fake login
allow(view).to receive(:user_signed_in?).and_return(true)
allow(view).to receive(:current_user).and_return(build(:user))
league.signuppable = true
end
it 'displays league details' do
assign(:personal_matches, matches)
render
expect(rendered).to include(league.name)
divisions.each do |division|
expect(rendered).to_not include(division.name)
division.rosters.active.each do |roster|
expect(rendered).to include(roster.name)
end
end
end
end
it 'displays league details' do
assign(:top_div_matches, matches)
render
expect(rendered).to include(league.name)
divisions.each do |division|
expect(rendered).to include(division.name)
division.rosters.active.each do |roster|
expect(rendered).to include(roster.name)
end
end
end
end
|
# Returns true if we are running on a MS windows platform, false otherwise.
def Kernel.is_windows?
(RUBY_PLATFORM =~ /mswin32/) != nil
end
|
module Alf
module Iterator
module ClassMethods
#
# Coerces something to an iterator
#
def coerce(arg, environment = nil)
case arg
when Iterator, Array
arg
when String, Symbol
Proxy.new(environment, arg.to_sym)
else
Reader.coerce(arg, environment)
end
end
end # module ClassMethods
extend(ClassMethods)
end # module Iterator
end # module Alf
|
unless ARGV.length == 2
puts "Usage: ruby #{$0} <dictionary> <numbers>"
exit 1
end
unless File.exists? dict_filepath = ARGV[0]
puts "Dictionary file #{dict_filepath} does not exist"
exit 1
end
unless File.exists? numbers_filepath = ARGV[1]
puts "Numbers file #{numbers_filepath} does not exist"
exit 1
end
require 'dictionary'
require 'encoder'
dictionary = Dictionary.load_from(dict_filepath)
File.open(numbers_filepath) do |numbers_file|
Encoder.new(dictionary).for_each_in numbers_file do |number, encoded|
puts "#{number}: #{encoded}"
end
end |
require "hodor"
module Hodor
class CLI
def call(argv)
case argv[0]
when "build"
build
else
fail "Unknown command #{argv[0]}"
end
end
def build
builder.build
end
protected
def builder
@builder ||= Hodor::Builder.new(Dir.pwd)
end
end
end
|
class Addtimestamps < ActiveRecord::Migration[5.2]
def change_tabel
add_timestamps(:users)
add_timestamps(:bands)
end
end
|
require 'rails_helper'
RSpec.describe ImportCsvContactsJob, type: :job do
let(:uploaded_file) { create(:uploaded_file, :with_attachment) }
let(:user) { uploaded_file.user }
let(:params) {
{
address: "address",
birth_date: "birth_date",
credit_card: "credit_card",
email: "email",
name: "name",
phone: "phone"
}
}
let(:arguments) { [user.id, params, uploaded_file, nil] }
subject(:job) { described_class.perform_later(*arguments) }
it 'queues the job' do
expect { job }.to have_enqueued_job(described_class)
.with(*arguments)
.on_queue("default")
end
end
|
component "component1" do |pkg, settings, platform|
pkg.version "1.2.3"
pkg.md5sum "abcd1234"
pkg.url "http://my-file-store.my-app.example.com/component1-1.2.3.tar.gz"
pkg.mirror "http://mirror-01.example.com/component1-1.2.3.tar.gz"
pkg.mirror "http://mirror-02.example.com/component1-1.2.3.tar.gz"
pkg.mirror "http://mirror-03.example.com/component1-1.2.3.tar.gz"
pkg.build_requires "tar"
if platform.is_deb?
pkg.build_requires "zlib1g-dev"
elsif platform.is_rpm?
pkg.build_requires "zlib-devel"
end
pkg.configure do
["./configure --prefix=#{settings[:prefix]} "]
end
pkg.build do
["#{platform[:make]}"]
end
pkg.install do
["#{platform[:make]} install"]
end
end
|
describe "integer_math.rb" do
it "should output '1'", points: 1 do
math_file = "integer_math.rb"
file_contents = File.read(math_file)
File.foreach(math_file).with_index do |line, line_num|
if line.include?("p") || line.include?("puts")
expect(line).to_not match(/1/),
"Expected 'integer_math.rb' to NOT literally print '1', but did anyway."
end
end
expect { require_relative '../../integer_math' }.to output("1\n").to_stdout
end
end
describe "integer_odd.rb" do
it "should output 'true' if the entered number is odd", points: 1 do
allow_any_instance_of(Object).to receive(:gets).and_return("13")
expect { require_relative '../../integer_odd' }.to output(/true/i).to_stdout
end
end
|
module Webapp
##Exceptions for the web App.
## TODO: Check what is the best base Exception
class NotAllowedError < StandardError
end
class FBUserNotAuthenticableError < StandardError
end
class FBUserNotRegisteredError < StandardError
end
class NoFBSessionError < StandardError
end
class UserNotActiveError < StandardError
end
class InvalidPasswordError < StandardError
end
class NoPasswordMatchError < StandardError
end
class BadRequestError < StandardError
end
class NoSuchPasswordRecovery < StandardError
end
class BadParametersError < StandardError
end
class NotImplemented < StandardError
end
class WrongPasswordError < StandardError
end
class NoSuchSessionError < StandardError
end
class UserSessionExistsError < StandardError
end
end
|
class CareMonth < ApplicationRecord
has_many :baby_cares, dependent: :destroy
end
|
require './lib/game.rb'
describe Game do
subject(:g) {Game.new(2, 100)}
it "should initialize 2 players" do
g.players.length.should == 2
end
it "should give the players 5 cards" do
g.players[0].hand.cards_in_hand.length.should == 5
end
end
|
class CompaniesController < ResourceController
before_action :build_user, only: :new
#rspec remaining
skip_load_resource only: :create
def index
@search = Company.search(params[:q])
@companies = @search.result.includes(:owner).page(params[:page])
end
def create
@company = Company.new(company_params)
if @company.save
redirect_to @company, notice: "Company #{ @company.name } is successfully created."
else
render action: :new
end
end
def toggle_enabled
@company.toggle!(:enabled)
end
private
def company_params
params.require(:company).permit(:name, :owner_name, :owner_email)
end
def build_user
@company.users.build
end
end
|
# -*- coding: utf-8 -*-
require 'spec_helper'
require 'ostruct'
require 'flail/backtrace'
require 'flail/exception'
describe Flail::Exception do
#Setup flail with dummy handler as these tests aren't very complex.
Flail.configure do
handle do |payload|
# Do nothing.
end
end
subject { Flail::Exception.new(Exception.new, {}) }
it "should not choke on bad utf-8" do
b1r = 0xc0..0xc2
b2r = 0x80..0xbf
b1r.each do |b1|
b2r.each do |b2|
string = [b1,b2].pack("C*")
lambda { subject.clean_unserializable_data({:test => string}).to_json }.should_not raise_error
end
end
end
it "should be able to accept a generic exception with no request attached" do
lambda { Flail::Exception.notify(Exception.new) }.should_not raise_error
end
end
|
if ENV['__test_coverage__']
require 'simplecov'
SimpleCov.start do
add_filter '/autotest/'
add_filter '/config/'
add_filter '/db/'
add_filter '/deploy/'
add_filter '/doc/'
add_filter '/features/'
add_filter '/lib/jobs/'
add_filter '/lib/tasks/'
add_filter '/log/'
add_filter '/public/'
add_filter '/script/'
add_filter '/spec/'
add_filter '/test/'
add_filter '/tmp/'
add_filter '/vendor/'
add_group 'Concerns', 'app/concerns'
add_group 'Controllers', 'app/controllers'
add_group 'Helpers', 'app/helpers'
add_group 'Libraries', 'lib'
add_group 'Mailers', 'app/mailers'
add_group 'Models', 'app/models'
add_group 'Presenters', 'app/presenters'
add_group 'Observers', 'app/observers'
add_group 'Services', 'app/services'
#add_group 'Views', 'app/views'
end
end
# This file is copied to ~/spec when you run 'ruby script/generate rspec'
# from the project root directory.
ENV["RAILS_ENV"] ||= 'test'
require File.dirname(__FILE__) + "/../config/environment" unless defined?(Rails)
require 'rspec/rails'
require 'webmock/rspec'
require 'email_spec'
require 'ostruct'
require 'paperclip/matchers'
require 'pp'
# Requires supporting files with custom matchers and macros, etc,
# in ./support/ and its subdirectories.
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}
Rspec.configure do |config|
config.mock_with :rspec
config.include CustomMatchers
config.include WebMock::API
config.include StubbedHttpRequests
config.include Paperclip::Shoulda::Matchers
config.include Devise::TestHelpers, :type => :controller
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.use_transactional_fixtures = true
config.before :each do
stub_contribution_urls
stub_amazon_s3_request
end
end
|
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "sysloggly/version"
Gem::Specification.new do |spec|
spec.name = "sysloggly"
spec.version = Sysloggly::VERSION
spec.licenses = ["MIT"]
spec.authors = ["Joergen Dahlke"]
spec.email = ["joergen.dahlke@gmail.com"]
spec.homepage = "https://github.com/jdahlke/sysloggly"
spec.summary = %q{Lograge and Syslog integration for Rails apps.}
spec.description = %q{Lograge and Syslog integration for Rails apps.}
spec.rubyforge_project = "sysloggly"
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
# specify any dependencies here:
spec.required_ruby_version = "~> 2.0"
spec.add_runtime_dependency "multi_json"
spec.add_runtime_dependency "lograge"
# specify any development dependencies here:
spec.add_development_dependency "rspec"
spec.add_development_dependency "rake"
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
# Available Boxes: https://atlas.hashicorp.com/search
config.vm.box = "ubuntu/xenial64"
# Virtual Machine will be available at 10.10.10.15
config.vm.network "private_network", ip: "10.10.10.15"
# Synced folder
config.vm.synced_folder "./", "/vagrant", disabled: true
config.vm.synced_folder "./", "/srv/inboundreview", create: true, mount_options: ['dmode=774','fmode=775']
# VirtualBox settings
config.vm.provider "virtualbox" do |v|
# Don't boot with headless mode
v.gui = false
# Use VBoxManage to customize the VM. For example to change memory:
v.customize ["modifyvm", :id, "--memory", "512"]
v.customize ["modifyvm", :id, "--cpuexecutioncap", "50"]
v.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
v.customize ["modifyvm", :id, "--natdnsproxy1", "on"]
end
# Installing the required packages and internal workflow
config.ssh.shell = "bash -c 'BASH_ENV=/etc/profile exec bash'"
config.vm.provision "shell", inline: <<-SHELL
########################################################################################################################
################################################# SHELL START ##########################################################
########################################################################################################################
# Add the default web server user to the vagrant group
sudo usermod -a -G ubuntu www-data
# Force a blank root password for mysql
export DEBIAN_FRONTEND="noninteractive"
sudo debconf-set-selections <<< "mysql-server mysql-server/root_password password password"
sudo debconf-set-selections <<< "mysql-server mysql-server/root_password_again password password"
# Install mysql, nginx, php-fpm
sudo apt-get update
sudo apt-get install -y -f mysql-server mysql-client nginx php-fpm
# Proper user
sudo sed -i "s/user www-data;/user ubuntu;/g" /etc/nginx/nginx.conf
sudo sed -i "s/user = www-data/user = ubuntu/g" /etc/php/7.0/fpm/pool.d/www.conf
sudo sed -i "s/group = www-data/group = ubuntu/g" /etc/php/7.0/fpm/pool.d/www.conf
# Install required used php packages
sudo apt-get install -y -f php-mysql php-curl php-gd
# Creating required folders
sudo rm -rf /srv/inboundreview.local
sudo mkdir -p /srv/inboundreview.local/{www,logs}
sudo chmod -R 7777 /srv/inboundreview.local
# Nginx virtual host
cat << 'EOF' | sudo tee /etc/nginx/sites-enabled/default
server {
listen 80;
server_name inboundreview.local;
root /srv/inboundreview.local/www;
error_log /srv/inboundreview.local/logs/error.log error;
index index.php;
location / {
try_files $uri $uri/ /index.php?$args;
# Required for compatibility with Virualbox
sendfile off;
}
rewrite /wp-admin$ $scheme://$host$uri/ permanent;
location ~ [^/]\.php(/|$) {
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
if (!-f $document_root$fastcgi_script_name) {
return 404;
}
include fastcgi.conf;
fastcgi_index index.php;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}
}
EOF
sudo service nginx restart
sudo service php7.0-fpm restart
# Proper database credentials
echo 'create database `wp`;' | mysql -uroot -ppassword
# Installing WP CLI
curl -s -o /usr/local/bin/wp https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar > /dev/null
chmod +x /usr/local/bin/wp
sudo chown ubuntu:ubuntu /usr/local/bin/wp
# Creating site
sudo chown -R ubuntu:ubuntu /srv
cd /srv/inboundreview.local/www
wp core download --locale=en_AU --allow-root
wp core config --dbname=wp --dbuser=root --dbpass=password --allow-root
wp core install --url="inboundreview.local" --title="InboundReview WordPress Site" --admin_user=admin --admin_password=admin --admin_email="admin@example.com" --allow-root
# Adding child theme
ln -s /srv/inboundreview /srv/inboundreview.local/www/wp-content/themes/inboundreview
echo "Done"
########################################################################################################################
################################################## SHELL END ###########################################################
########################################################################################################################
SHELL
end
|
class CreateCharges < ActiveRecord::Migration
def change
create_table :charges do |t|
t.integer :customer_id, null: false
t.integer :created, null: false
t.boolean :paid, null: false
t.integer :amount, null: false
t.string :currency, null: false
t.boolean :refunded, null: false
t.foreign_key :customers
end
add_index :charges, :customer_id
end
end
|
# encoding: utf-8
control "V-52445" do
title "The DBMS software libraries must be periodically backed up."
desc "Information system backup is a critical step in maintaining data assurance and availability.
System-level information includes: system-state information, operating system and application software, and licenses.
Backups shall be consistent with organizational recovery time and recovery point objectives.
The DBMS application depends upon the availability and integrity of its software libraries. Without backups, compromise or loss of the software libraries can prevent a successful recovery of DBMS operations.false"
impact 0.5
tag "check": "Review evidence of inclusion of the DBMS libraries in current backup records. If any DBMS library files are not included in regular backups, this is a finding."
tag "fix": "Configure backups to include all DBMS application and third-party database application software libraries."
# Write Check Logic Here
end |
# migrations are used to change the structure of the database. for example: creating tables. dropping tables, adding colums to tables, removing colums from tables. adding indexes, remove indexes
class CreateQuestions < ActiveRecord::Migration
def change
create_table :questions do |t|
t.string :title
t.text :body
t.timestamps null: false
end
end
end
|
require 'setback/base'
describe Setback::Base do
subject do
Class.new do
include Setback::Base
end.new
end
it 'should proxy #[] to provider#get' do
subject.provider.should_receive(:get).with(:foo).and_return(:bar)
subject[:foo].should == :bar
end
it 'should proxy #[]= to provider#set' do
subject.provider.should_receive(:set).with(:ham, :bones).and_return(:bones)
(subject[:ham] = :bones).should == :bones
end
it 'should proxy #merge! to provider via #[]=' do
subject.provider.set(:hamster, :poodle)
subject[:hamster].should == :poodle
subject.merge!(:hamster => :noodle)
subject.provider.get(:hamster).should == :noodle
subject[:hamster].should == :noodle
end
it 'should proxy #keys to provider#keys' do
subject.provider.should_receive(:keys).and_return([:samwiches, :milkyshakes])
subject.keys.should == [:samwiches, :milkyshakes]
end
it 'should proxy #all to provider#all' do
subject.provider.merge!({:snarf => :mumra})
subject.all.should == {:snarf => :mumra}
end
it 'should not claim to be backed by anything' do
subject.backed_by.should == :nothing
end
end
|
require_relative 'installer_errors'
class InstallerIO
def initialize(silent=false)
@silent = !!silent
end
def silent?
@silent
end
def log(text)
puts text
end
def prompt(message, default=nil)
print "\n#{MESSAGES[message]}#{default.nil? ? '' : " [#{default}]"}: "
get_input
end
def prompt_or_default(message, default)
return default if silent?
prompt(message, default) || default
end
def require_confirmation(message)
user_input = prompt_or_default(message, 'y')
unless %w(y yes).include? user_input.downcase
raise InstallerErrors::InstallAborted, "Cancelled by user."
end
end
def prompt_until(message, &block)
input = nil
begin
input = prompt message
end until yield input
input
end
MESSAGES = {
destination_path: "Please enter Chorus destination path",
data_path: "Please enter the data storage directory",
confirm_upgrade: "Existing version of Chorus detected. Upgrading will restart services. Continue now?",
passphrase: "Enter optional passphrase to generate a recoverable secret key for encrypting passwords. By default, a random key will be generated.",
confirm_legacy_upgrade: "Chorus 2.1 installation detected, do you want to upgrade to 2.2?",
legacy_destination_path: "Chorus 2.2 cannot be installed in the same directory as 2.1, please provide an empty directory",
select_os: <<-TEXT
Could not detect your Linux version. Please select one of the following:
[1] - RedHat (CentOS/RHEL) 5.5 or compatible
[2] - RedHat (CentOS/RHEL) 6.2 or compatible
[3] - SuSE Enterprise Linux Server 11 or compatible
[4] - Abort install
TEXT
}
private
def get_input
input = gets.strip
input.empty? ? nil : input
end
end |
require_relative "sha256lib.rb"
# ----------
# hash256.rb - The hash function used in Bitcoin. Basically just runs sha256.rb twice.
# ----------
# Command Line Arguments
$input = ARGV[0] || "0x0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49ffff001d1dac2b7c" # "string"|"0xaabbcc"|"0b10110100"
$delay = ARGV[1] || "fast" # [enter|normal|fast|nodelay]
# Assume that every input is hexadecimal bytes
if $input[0..1] != "0x"
$input = "0x" + $input # prepend 0x if there isn't one (so the upcoming functions can detect it correctly)
end
# Make sure it's a valid size (even number of characters)
if $input.size % 2 != 0
puts "Invalid input to hash256.rb. Expecting even number of hex characters (i.e. bytes)."
exit
end
# Convert hex to bytes
$type = input_type($input)
$bytes = bytes($input, $type)
$message = $bytes.map { |x| x.to_s(2).rjust(8, "0") }.join
# Note about hitting enter to step
if $delay == "enter"
puts "Hit enter to step through."
STDIN.gets
end
# Catch Ctrl-C to prevent unsightly errors when terminating early
Signal.trap("SIGINT") do
exit
end
# 1. First Hash
load "sha256.rb"
# 2. Use output of first hash as input to second hash
$input = "0x" + $digest # prepend 0x to show that it's hex bytes
$type = input_type($input)
$bytes = bytes($input, $type)
$message = $bytes.map { |x| x.to_s(2).rjust(8, "0") }.join
# 2. Second Hash
load "sha256.rb"
|
module Viberroo
##
# This class' methods serve as declarative wrappers with predefined types for
# each message type Viber API offers.
#
# @see https://developers.viber.com/docs/api/rest-bot-api/#message-types
#
class Message
##
# Simple text message.
#
# @example
# message = Viberroo::Message.plain(text: 'Hello there!')
#
# @param [Hash] params
# @option params [String] text **Required**.
#
# @return [Hash]
#
# @see https://developers.viber.com/docs/api/rest-bot-api/#text-message
#
def self.plain(params)
{ type: :text }.merge(params)
end
##
# The Rich Media message type allows sending messages with pre-defined layout,
# including height (rows number), width (columns number), text, images and buttons.
#
# @example Send a rich media
# search = Button.reply({
# Columns: 4,
# Rows: 3,
# ActionBody: '/search',
# Text: 'Search something...'
# }
#
# locate = Button.reply({
# Columns: 4,
# Rows: 3,
# ActionBody: '/near_me'
# }
#
# browse = Button.url({
# Columns: 4,
# Rows: 2,
# ActionBody: 'parrot.live',
# Text: 'Browse something wierd'
# }
#
# @bot.send_rich_media(
# rich_media: {
# ButtonsGroupColumns: 4,
# ButtonsGroupRows: 6,
# Buttons: [search, locate, browse]
# }
# )
#
# @param [Hash] params
# @option params [Hash] rich_media
# @option params [Integer] rich_media.ButtonsGroupColumns Number of columns per carousel content block. Possible values 1 - 6. **API Default**: 6.
# @option params [Integer] rich_media.ButtonsGroupRows Number of rows per carousel content block. Possible values 1 - 7. **API Default**: 7.
# @option params [Hash] rich_media.Buttons Array of buttons. Max of 6 * `ButtonsGroupColumns` * `ButtonsGroupRows`.
#
# @return [Hash]
#
# @see https://developers.viber.com/docs/api/rest-bot-api/#rich-media-message--carousel-content-message
#
def self.rich(params)
{ type: :rich_media, min_api_version: 2 }.merge(params)
end
##
# Location message.
#
# @example
# message = Message.location(location: { lat: '48.9215', lon: '24.7097' })
#
# @param [Hash] params
# @option params [Hash] location
# @option params [Float] location.lat **Required**. Latitude
# @option params [Float] location.lon **Required**. Longitude
#
# @return [Hash]
#
# @see https://developers.viber.com/docs/api/rest-bot-api/#location-message
#
def self.location(params)
{ type: :location }.merge(params)
end
##
# Picture message.
#
# @note Max image size: 1MB on iOS, 3MB on Android.
#
# @param [Hash] params
# @option params [String] media **Required**. Image URL. Allowed extensions: .jpeg, .png .gif. Animated GIFs can be sent as URL messages or file messages.
# @option params [String] text **Optional**. Max 120 characters.
# @option params [String] thumbnail **Optional**. Thumbnail URL. Max size 100 kb. Recommended: 400x400.
#
# @return [Hash]
#
# @see https://developers.viber.com/docs/api/rest-bot-api/#picture-message
#
def self.picture(params = {})
{ type: :picture, text: '' }.merge(params)
end
##
# Video message.
#
# @note Max video size is 26MB.
#
# @param [Hash] params
# @option params [String] media **Required**. URL of the video (MP4, H264). Only MP4 and H264 are supported.
# @option params [Integer] size **Required**. Size of the video in bytes.
# @option params [Integer] duration **Optional**. Duration in seconds. Max value - 180.
# @option params [String] thumbnail **Optional**. Thumbnail URL. Max size 100 kb. Recommended: 400x400. Only JPEG format is supported.
#
# @return [Hash]
#
# @see https://developers.viber.com/docs/api/rest-bot-api/#video-message
#
def self.video(params = {})
{ type: :video }.merge(params)
end
##
# File message.
#
# @note Max file size is 50MB.
#
# @param [Hash] params
# @option params [String] media **Required**. File URL.
# @option params [Integer] size **Required**. File size in bytes.
# @option params [String] file_name **Required**. Name of the file, should include extension. Max 256 characters (including extension).
#
# @return [Hash]
#
# @see https://developers.viber.com/docs/api/rest-bot-api/#file-message
# @see https://developers.viber.com/docs/api/rest-bot-api/#forbiddenFileFormats
#
def self.file(params = {})
{ type: :file }.merge(params)
end
##
# Contact message.
#
# @param [Hash] params
# @option params [Hash] contact
# @option params [Float] contact.name **Required**. Name of the contact. Max 28 characters.
# @option params [Float] contact.phone_number **Required**. Phone number of the contact. Max 18 characters.
#
# @return [Hash]
#
# @see https://developers.viber.com/docs/api/rest-bot-api/#contact-message
#
def self.contact(params = {})
{ type: :contact }.merge(params)
end
##
# URL message.
#
# @param [Hash] params
# @option params [String] media **Required**. Max 2000 characters.
#
# @return [Hash]
#
# @see https://developers.viber.com/docs/api/rest-bot-api/#url-message
#
def self.url(params = {})
{ type: :url }.merge(params)
end
##
# Sticker message.
#
# @param [Hash] params
# @option params [Integer] sticker_id **Required**. Max 2000 characters.
#
# @return [Hash]
#
# @see https://developers.viber.com/docs/api/rest-bot-api/#sticker-message
# @see https://developers.viber.com/docs/tools/sticker-ids/
#
def self.sticker(params = {})
{ type: :sticker }.merge(params)
end
end
end
|
class TournamentGroup < ApplicationRecord
belongs_to :tournament
has_many :tournament_rounds
has_many :matches, through: :tournament_rounds
has_many :teams, through: :tournament_rounds
def teams
tournament_rounds.map(&:teams).flatten.uniq
end
end
|
# TODO: update employee_create_params so that password is random
class EmployeesController < ApplicationController
before_action :logged_in_user
before_action :correct_user_or_admin, only: [:show, :edit, :update]
before_action :admin_employee_user, only: [:index, :new, :create, :delete]
before_action :not_self, only: [:delete]
def index
@employees = Employee.all.paginate(page: params[:page])
end
def show
@employee = Employee.find(params[:id])
end
def new
@employee = Employee.new
@employee.build_employee_record
end
def create
@employee = Employee.new(employee_create_params)
if @employee.save
@employee.build_employee_record(employee_record_create_params)
if @employee.save
@employee.send_activation_email
flash[:success] = "Staff member added"
redirect_to new_employee_path
else
@employee.destroy
render 'new'
end
else
@employee.remove_second_email_error_if_present
@employee.build_employee_record
render 'new'
end
end
def edit
@employee = Employee.find(params[:id])
end
def update
@employee = Employee.find(params[:id])
if current_user?(@employee) && !employee_update_params_if_self.empty?
unless @employee.authenticate(update_params[:current_password])
if current_employee.admin?
@employee.assign_attributes(
employee_update_params_if_admin_and_self
)
else
@employee.assign_attributes(
employee_update_params_if_self
)
end
@employee.valid?
@employee.errors.messages[:current_password] = ["is incorrect"]
render 'edit'
return
end
end
if current_employee.admin?
if current_user?(@employee)
if @employee.update_attributes(
employee_update_params_if_admin_and_self
)
if @employee.employee_record.update_attributes(
employee_record_update_params_if_admin
)
flash[:success] = "Account updated"
redirect_to @employee
else
render 'edit'
end
else
render 'edit'
end
else # if !current_user?(@employee)
if @employee.update_attributes(employee_update_params_if_admin)
if @employee.employee_record.update_attributes(
employee_record_update_params_if_admin
)
flash[:success] = "Employee updated"
redirect_to @employee
else
byebug
render 'edit'
end
else
render 'edit'
end
end
else # if !current_employee.admin?
if @employee.update_attributes(employee_update_params_if_self)
flash[:success] = "Password updated"
redirect_to @employee
else
render 'edit'
end
end
end
private
# Filters
def correct_user_or_admin
employee = Employee.find(params[:id])
unless current_user?(employee) || current_employee.admin?
redirect_to(root_url)
end
end
def not_self
employee = Employee.find(params[:id])
current_user?(employee)
end
# For Create params
def create_params
params.require(:employee).permit(:name, :email,
employee_record_attributes:
[:tutor, :admin])
end
def employee_create_params
{
name: create_params[:name],
email: create_params[:email],
password: 'password',
password_confirmation: 'password'
}
end
def employee_record_create_params
{
tutor: create_params[:employee_record_attributes][:tutor],
admin: create_params[:employee_record_attributes][:admin]
}
end
# For Update params
def update_params
params.require(:employee).permit(:name, :email,
:current_password,
:password,
:password_confirmation,
employee_record_attributes:
[:tutor, :admin])
end
def employee_update_params_if_admin
{
name: update_params[:name],
email: update_params[:email]
}
end
def employee_record_update_params_if_admin
{
tutor: update_params[:employee_record_attributes][:tutor],
admin: update_params[:employee_record_attributes][:admin]
}
end
def employee_update_params_if_self
pass = update_params[:password]
pass_conf = update_params[:password_confirmation]
unless pass.length == 0 && pass_conf.length == 0
{
password: update_params[:password],
password_confirmation: update_params[:password_confirmation]
}
else
{}
end
end
def employee_update_params_if_admin_and_self
employee_update_params_if_admin.reverse_merge(
employee_update_params_if_self
)
end
end
|
module Views
RSpec.describe Text do
let(:text) { "Some really cool text" }
subject { Text.new(text) }
it_behaves_like "Views::Base"
it "sets the text correctly" do
expect(subject.text).to eq(text)
end
describe "#setup_bottom_right_screen_rect" do
it "has the expected sizing" do
expected_rect = Rect.new(x: 90 - text.length - 1, y: 34, width: text.length + 1, height: 1)
expect(subject).to receive(:setup) do |rect|
expect(rect.to_h).to eq(expected_rect.to_h)
end
subject.setup_bottom_right_screen_rect
end
context "the text is larger than the screen" do
let(:text) { "T" * 100 }
it "has the expected height for a multi line text label" do
expected_rect = Rect.new(x: 0, y: 33, width: 90, height: 2)
expect(subject).to receive(:setup) do |rect|
expect(rect.to_h).to eq(expected_rect.to_h)
end
subject.setup_bottom_right_screen_rect
end
end
it "adds the text to the view" do
expect(FFI::NCurses).to receive(:mvwaddstr).with(any_args, 0, 0, text)
subject.setup_bottom_right_screen_rect
end
end
end
end
|
module Parcel
class Runner
def self.install
exec_with_sym(:yarn, :add, 'parcel-bundler')
end
def self.watch
exec_parcel(:watch)
end
def self.build
exec_parcel(:build)
end
def self.serve
exec_parcel(:serve)
end
def self.clobber
clean(Configuration.out_path)
clean(Configuration.cache_path)
end
private_class_method :new
class << self
private
def exec_with_sym(*args)
system(*args.map(&:to_s))
end
def exec_parcel(cmd)
exec_with_sym(:yarn, :run, :parcel, cmd,
'--out-dir', Configuration.out_path, '--cache-dir', Configuration.cache_path,
*Configuration.entry_points)
end
def clean(directory)
return unless directory.exist?
directory.rmtree
Parcel.logger.info "Removed #{directory}"
end
end
end
end
|
class Gitapi
URL = "https://api.github.com/users"
attr_reader :users, :search
def initialize search
@search = search
@users = []
values = {owner: search, type: "xml"}
url = [URL, "?", values.to-query].join
response = HTTParty.get(url).body
xml = Nokogiri::XML(response)
xml.xpath("/repos/:owner/:repo/stats/contributors").each do |item|
@users << User.new(item)
end
end
end |
class CreateFulfillments < ActiveRecord::Migration[5.0]
def change
create_table :fulfillments, id: :uuid do |t|
t.belongs_to :orders, index: true, type: :uuid
t.integer :status
t.string :tracking_company
t.string :tracking_number
t.timestamps
end
end
end
|
class UnitTestRunner
def self.ironruby?
defined?(RUBY_ENGINE) and RUBY_ENGINE == "ironruby"
end
def parse_options(args)
require "optparse"
pass_through_args = false
parser = OptionParser.new(args) do |opts|
opts.banner = "USAGE: utr libname [-a] [-l] [-g] [-i] [-t TestClass#test_method] [-s \"Spec Context#specify name\"] [-- <Test::Unit options>]"
opts.separator ""
opts.on("-a", "--all", "Run all tests without ignoring the monkeypatched tests") do |a|
@all = true
end
opts.on('-l', '--list', "List test files being run") do |l|
@list_test_files = true
end
opts.on('-s', '--spec SPECNAME', 'Run specific spec') do |t|
@one_spec = t
end
opts.on("-t", "--test TESTNAME", "Run specific test") do |t|
@one_test = t
end
opts.on("-g", "--generate-tags", "Generate tags to disable failing tests") do |g|
@generate_tags = true
end
opts.on("-i", "--generate-incremental", "Generate tags to disable *additional* failing tests") do |g|
@generate_tags = true
@generate_incremental = true
end
opts.on_tail("-h", "--help", "Show this message") do |n|
puts opts
puts
puts "Test::Unit help:"
require "rubygems"
require "test/unit"
require "test/unit/autorunner"
$0 = ""
Test::Unit::AutoRunner.new(true).process_args(["-h"])
exit
end
opts.on_tail("--", "Pass the remaining options to Test::Unit") do |n|
pass_through_args = true
opts.terminate
end
end
remaining_args = parser.parse!
abort "Please specify the test suite to use" if remaining_args.empty?
test_suite = remaining_args.shift
@lib = File.expand_path("utr/#{test_suite}_tests.rb", File.dirname(__FILE__))
abort "Extra arguments: #{remaining_args}" if not remaining_args.empty? and not pass_through_args
end
def initialize(args)
parse_options(args)
require @lib
@setup = UnitTestSetup.new
end
def run
@setup.require_files
@setup.gather_files
@setup.exclude_critical_files
@setup.sanity
@setup.require_tests
@setup.disable_mri_failures unless @all
if UnitTestRunner.ironruby?
@setup.disable_critical_failures
@setup.disable_unstable_tests
if !@generate_tags
@setup.disable_tests unless @all
else
@setup.disable_tests if @generate_incremental
require "generate_test-unit_tags.rb"
TagGenerator.test_file = @lib
TagGenerator.initial_tag_generation = !@generate_incremental
end
else
@setup.disable_mri_only_failures unless @all
end
if @one_test
run_test
elsif @one_spec
run_spec
else
at_exit {
puts "Disabled #{@setup.disabled || 0} tests"
p @setup.all_test_files if @list_test_files
}
end
end
class TestResultLogger
def respond_to?(name, *args) true end
def method_missing(name, *args)
puts [name] + args
if name == :add_error
puts args[1].backtrace if args[1]
end
end
end
def run_spec
@one_spec =~ /(.*)#(.*)/
context, specify = $1, $2
klass = @setup.get_context_class(context)
specify = '.*' if specify == '*' # wildcard allow for all specifies to be run in a context
@setup.get_specify_methods(context, specify).each do |method|
klass.new(method).run(TestResultLogger.new){}
end
exit!(0)
end
# Run just one test and exit
def run_test()
@one_test =~/(.*)#(test_.*)/
class_name, test_name = $1, $2
# Use class_eval instead of const_get in case of nested names like TestSuite::TestCase
test_class = Object.class_eval(class_name)
test_class.new(test_name).run(TestResultLogger.new) {}
# We do a hard exit. Otherwise all the tests will run as part of at_exit
exit!(0)
end
end
class UnitTestSetup
def require_files; end
def gather_files; end
def exclude_critical_files; end
def disable_mri_failures; end
def disable_mri_only_failures; end
def disable_critical_failures; end
def disable_unstable_tests; end
def disable_tests;end
def sanity; end
attr :disabled
attr_reader :all_test_files
def require_tests
# Note that the tests are registered using Kernel#at_exit, and will run during shutdown
# The "require" statement just registers the tests for being run later...
@all_test_files.each {|f| require f}
end
def valid_context?(context)
not Test::Spec::CONTEXTS[context].nil?
end
def get_context_class(context)
if not valid_context? context
raise "'#{context}' is an invalid context; pick from #{Test::Spec::CONTEXTS.keys.sort.inspect}"
end
Test::Spec::CONTEXTS[context].testcase
end
def get_specify_methods(context, specify)
klass = get_context_class(context)
klass.instance_methods.grep(/^test_spec \{#{context}\} .*? \[#{specify.gsub('(', '\(').gsub(')', '\)')}\]$/)
end
private
def disable(klass, *methods)
@disabled ||= 0
@disabled += methods.size
klass.class_eval do
methods.each do |method|
undef_method method.to_sym rescue puts "Could not undef #{klass}##{method}"
end
# If all the test methods have been removed, test/unit complains saying "No tests were specified."
# So we monkey-patch the offending method to be a noop.
klass.class_eval { def default_test() end }
end
end
def disable_by_name names
names.each do |name|
/(.*)[(](.*)[)][:]?/ =~ name
disable Object.const_get($2), $1
end
end
def disable_spec(context, *specifies)
@disabled ||= 0
@disabled += specifies.size
specify_methods = specifies.inject([]) do |ss, specify|
ss << get_specify_methods(context, specify)
end.flatten.uniq
get_context_class(context).instance_eval do |klass|
specify_methods.each do |method|
undef_method method.to_sym rescue puts "Could not undef #{klass}##{method}"
end
def default_test() end
end
end
def sanity_size(size)
abort("Did not find enough #{@name} tests files... \nFound #{@all_test_files.size}, expected #{size}.\n") unless @all_test_files.size >= size
end
def sanity_version(expected, actual)
abort("Loaded the wrong version #{actual} of #{@name} instead of the expected #{expected}...") unless actual == expected
end
# Helpers for Rails tests
RailsVersion = "3.0.0"
TestUnitVersion = "2.1.1"
SqlServerAdapterVersion = "3.0.0"
RAILS_TEST_DIR = File.expand_path("Languages/Ruby/Tests/Libraries/Rails-#{RailsVersion}", ENV['DLR_ROOT'])
def gather_rails_files
@root_dir = File.join(File.expand_path(@name, RAILS_TEST_DIR), "test")
$LOAD_PATH << @root_dir
@all_test_files = Dir.glob("#{@root_dir}/**/*_test.rb").sort
end
end
UnitTestRunner.new(ARGV).run if $0 == __FILE__
|
# frozen_string_literal: true
require "test_helper"
class DuckDuckGoTest < Minitest::Test
test "detects DuckDuckGo on iOS device" do
browser = Browser.new(Browser["DUCKDUCKGO_BROWSER_IOS"])
assert browser.duck_duck_go?
refute browser.safari?
refute browser.chrome?
assert browser.webkit?
refute browser.bot?
assert_equal "DuckDuckGo", browser.name
assert_equal :duckduckgo, browser.id
end
test "detects DuckDuckGo on Android device" do
browser = Browser.new(Browser["DUCKDUCKGO_BROWSER_ANDROID"])
assert browser.duck_duck_go?
refute browser.safari?
refute browser.chrome?
refute browser.bot?
assert_equal "DuckDuckGo", browser.name
assert_equal :duckduckgo, browser.id
end
test "detects correct version" do
browser = Browser.new(Browser["DUCKDUCKGO_BROWSER_IOS"])
assert_equal "7", browser.full_version
assert_equal "7", browser.version
end
test "detects version by range" do
browser = Browser.new(Browser["DUCKDUCKGO_BROWSER_IOS"])
assert browser.duck_duck_go?(%w[>=7 <8])
end
end
|
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :customer do
people_type "MyString"
title_partner nil
observation "MyText"
partner nil
agreement nil
agreement_number 1
email "MyString"
active_record false
end
end
|
class Request < ActiveRecord::Base
belongs_to :user
belongs_to :host, class_name: 'User'
end
|
class Review < ActiveRecord::Base
include Protocols::Shareable
def shareable?
status.active? && super
end
delegate :title, :to => :product
alias_attribute :description, :content
alias_attribute :user_generated_content, :sound_bite
def media
product.local_photos.primary || product.remote_photos.first
end
end
|
require 'spec_helper'
describe FuelSDK::HTTPRequest do
let(:client) { Class.new.new.extend FuelSDK::HTTPRequest }
subject { client }
it { should respond_to(:get) }
it { should respond_to(:post) }
it { should respond_to(:patch) }
it { should respond_to(:delete) }
it { should_not respond_to(:request) } # private method
describe '#get' do
it 'makes and Net::HTTP::Get request' do
client.stub(:request).with(Net::HTTP::Get, 'http://some_url', {}).and_return({'success' => 'get'})
expect(client.get('http://some_url')).to eq 'success' => 'get'
end
end
describe '#post' do
describe 'makes and Net::HTTP::Post request' do
it 'with only url' do
Net::HTTP.any_instance.stub(:request)
client.stub(:request).with(Net::HTTP::Post, 'http://some_url', {}).and_return({'success' => 'post'})
expect(client.post('http://some_url')).to eq 'success' => 'post'
end
it 'with params' do
client.stub(:request)
.with(Net::HTTP::Post, 'http://some_url', {'params' => {'legacy' => 1}})
.and_return({'success' => 'post'})
expect(client.post('http://some_url', {'params' => {'legacy' => 1}})).to eq 'success' => 'post'
end
end
end
end
|
# frozen_string_literal: true
require "rails_helper"
module Renalware
module Diaverum
module Incoming
module Nodes
describe Node do
subject(:node) { described_class.new(xml.root) }
let(:xml) do
Nokogiri::XML(<<-XML)
<SomeElement>
<SomeAttribute>TEST</SomeAttribute>
</SomeElement>
XML
end
it "can call XML elements as if they were methods" do
expect(node.SomeAttribute).to eq("TEST")
end
end
end
end
end
end
|
require 'rails_helper'
RSpec.describe Teacher, type: :model do
describe '#subject_name' do
let(:subject) { create(:subject) }
let(:teacher) { create(:teacher, subject: subject) }
it "returns subject's name" do
expect(teacher.subject_name).to eq(subject.name)
end
end
end
|
class Node
attr_accessor :name, :parent
attr_reader :children
def initialize(name)
@name = name
@children = []
end
def add_child(node)
@children << node
node.parent = self
end
alias << add_child
def remove_child(node)
@children.delete node
end
def [](index)
@children[index]
end
def []=(index, node)
replaced_child = @children[index]
@children[index] = node
replaced_child.parent = nil
node.parent = self
end
def leaf?
children.empty?
end
end
|
require "spec_helper"
describe Booking, type: :request do
context "when authenticated" do
before do
@coach = create(:coach)
user = create(:user)
login(user)
create(:availability,
coach: @coach,
duration: 60)
@booking = create(:booking,
user: user,
coach: @coach,
start_at: Time.zone.parse("9:00AM") + 1.day,
end_at: Time.zone.parse("10:00AM") + 1.day)
create(:booking,
user: user,
coach: @coach,
start_at: Time.zone.parse("10:00AM") + 1.day,
end_at: Time.zone.parse("11:00AM") + 1.day)
end
describe "GET #index" do
before do
get("/api/bookings.json")
end
it "should respond with array of 2 Bookings" do
expect(json.count).to eq(2)
end
it "should respond with status 200" do
expect(response.status).to eq 200
end
end
describe "GET #show" do
before do
get("/api/bookings/#{@booking.id}.json")
end
it "should respond with 1 Booking" do
expect(json["start_at"]).to eq(@booking.start_at.as_json)
end
it "should respond with status 200" do
expect(response.status).to eq 200
end
end
describe "POST #create" do
context "with valid attributes" do
before do
@booking_attributes =
attributes_for(:booking,
coach_id: @coach.id,
start_at: Time.zone.parse("9:00AM") + 2.days,
end_at: Time.zone.parse("10:00AM") + 2.days)
post(
"/api/bookings.json",
{ booking: @booking_attributes })
end
it "should respond with created Booking" do
expect(json["start_at"].as_json).to eq @booking_attributes[:start_at].as_json
end
it "should respond with new id" do
expect(json.keys).to include("id")
end
it "should respond with status 201" do
expect(response.status).to eq 201
end
end
context "with invalid attributes" do
before do
booking_attributes =
attributes_for(:booking,
coach_id: @coach.id,
start_at: Time.zone.parse("9:00AM") + 3.days,
end_at: Time.zone.parse("10:00AM") + 2.days)
post(
"/api/bookings.json",
{ booking: booking_attributes })
end
it "should respond with errors" do
expect(json.keys).to include("errors")
end
it "should respond with status 422" do
expect(response.status).to eq 422
end
end
end
describe "PATCH #update" do
context "with valid attributes" do
before do
@booking_attributes =
{ start_at: @booking.start_at + 4.hours,
end_at: @booking.end_at + 4.hours }
patch(
"/api/bookings/#{@booking.id}.json",
{ booking: @booking_attributes })
end
it "should respond with updated Booking" do
expect(Booking.find(@booking.id).start_at).to eq(@booking_attributes[:start_at])
end
it "should respond with status 200" do
expect(response.status).to eq 200
end
end
context "with invalid attributes" do
before do
booking_attributes =
{ start_at: @booking.start_at + 6.hours,
end_at: @booking.start_at + 5.hours }
patch(
"/api/bookings/#{@booking.id}.json",
{ booking: booking_attributes })
end
it "should respond with errors" do
expect(json.keys).to include("errors")
end
it "should respond with status 422" do
expect(response.status).to eq 422
end
end
end
describe "DELETE #destroy" do
before do
delete("/api/bookings/#{@booking.id}.json")
end
it "should respond with status 200" do
expect(response.status).to eq 200
end
end
end
context "when unauthenticated" do
before do
get "/api/bookings.json"
end
it "should respond with status 401" do
expect(response.status).to eq 401
end
end
end
|
require "test_helper"
require "fluent/plugin/buf_file"
module Fluentd::Setting
class OutS3Test < ActiveSupport::TestCase
setup do
@klass = Fluentd::Setting::OutS3
@valid_attributes = {
s3_bucket: "bucketname"
}
@instance = @klass.new(@valid_attributes)
end
sub_test_case "#valid?" do
test "valid" do
assert_true(@instance.valid?)
end
test "invalid if s3_bucket is missing" do
instance = @klass.new({})
assert_false(instance.valid?)
end
end
test "#plugin_name" do
assert_equal("s3", @instance.plugin_name)
end
test "#plugin_type" do
assert_equal("output", @instance.plugin_type)
end
test "#to_config" do
assert do
@instance.to_config.to_s.include?("@type s3")
end
end
test "with assume_role_credentials" do
params = {
pattern: "s3.*",
s3_bucket: "bucketname",
assume_role_credentials: {
"0" => {
role_arn: "arn",
role_session_name: "session_name",
}
}
}
expected = <<-CONFIG.strip_heredoc
<match s3.*>
@type s3
s3_bucket bucketname
<assume_role_credentials>
role_arn arn
role_session_name session_name
</assume_role_credentials>
</match>
CONFIG
instance = @klass.new(params)
assert_equal(expected, instance.to_config.to_s)
end
test "with instance_profile_credentials" do
params = {
pattern: "s3.*",
s3_bucket: "bucketname",
instance_profile_credentials: {
"0" => {
port: 80
}
}
}
expected = <<-CONFIG.strip_heredoc
<match s3.*>
@type s3
s3_bucket bucketname
<instance_profile_credentials>
port 80
</instance_profile_credentials>
</match>
CONFIG
instance = @klass.new(params)
assert_equal(expected, instance.to_config.to_s)
end
test "with shared_credentials" do
params = {
pattern: "s3.*",
s3_bucket: "bucketname",
shared_credentials: {
"0" => {
path: "$HOME/.aws/credentials",
profile_name: "default",
}
}
}
expected = <<-CONFIG.strip_heredoc
<match s3.*>
@type s3
s3_bucket bucketname
<shared_credentials>
path $HOME/.aws/credentials
profile_name default
</shared_credentials>
</match>
CONFIG
instance = @klass.new(params)
assert_equal(expected, instance.to_config.to_s)
end
end
end
|
module GoogleAnalyticsEventsHelper
def track_home_ga_event(controller, action)
@ga_events ||= []
case controller
when 'home'
@ga_events.push("pageTracker._trackEvent('#{controller.titleize}', '#{action}');")
end
end
def track_where_ga_event(controller, localities)
@ga_events ||= []
# use controller as category, and locality as action
case controller
when 'places', 'locations', 'events', 'search'
Array(localities).compact.each do |locality|
@ga_events.push("pageTracker._trackEvent('#{controller.titleize}', '#{locality.class.to_s}', '#{locality.name}');")
end
else
end
end
def track_what_ga_event(controller, options)
@ga_events ||= []
# use controller as category, and tag or query as action
if !options[:tag].blank?
action = 'Tag'
label = options[:tag]
elsif !options[:query].blank?
action = 'Query'
label = options[:query]
else
# whoops, no action
return
end
case controller
when 'places', 'locations', 'events', 'search'
@ga_events.push("pageTracker._trackEvent('#{controller.titleize}', '#{action}', '#{label}');")
end
end
def track_chain_ga_event(controller, chain, locality=nil)
@ga_events ||= []
action = chain.is_a?(Chain) ? chain.name : chain.to_s
label = locality.name unless locality.blank?
case controller
when 'chains'
@ga_events.push("pageTracker._trackEvent('#{controller.titleize}', '#{action}', '#{label}');")
end
end
def track_special_ga_event(controller, locality, day=nil)
@ga_events ||= []
if day
@ga_events.push("pageTracker._trackEvent('#{controller.titleize}', '#{locality.name.titleize}', '#{day.titleize}');")
else
@ga_events.push("pageTracker._trackEvent('#{controller.titleize}', '#{locality.name.titleize}');")
end
end
end |
class AddOfferToCoupons < ActiveRecord::Migration
def change
add_column :coupons, :offer, :string
end
end
|
require 'spec_helper'
describe CastablesController do
include Devise::TestHelpers
before(:each) do
sign_in_user :maintainer
end
describe "GET index" do
def stub_index
Castable.stub(:all => mock_castables)
end
it "assigns all castables as @castables" do
stub_index
get :index
assigns[:castables].should == mock_castables
end
end
describe "GET show" do
it "assigns the requested castable as @castable" do
Castable.stub(:find).with("37").and_return(mock_castable)
get :show, :id => "37"
assigns[:castable].should equal(mock_castable)
end
end
describe "GET new" do
it "assigns a new castable as @castable" do
Castable.stub(:new).and_return(mock_castable)
get :new
assigns[:castable].should equal(mock_castable)
end
end
describe "GET edit" do
it "assigns the requested castable as @castable" do
Castable.stub(:find).with("37").and_return(mock_castable)
get :edit, :id => "37"
assigns[:castable].should equal(mock_castable)
end
end
describe "POST create" do
describe "with valid params" do
it "assigns a newly created castable as @castable" do
mock_castable.stub(:save => true)
Castable.stub(:new).with({'these' => 'params'}).and_return(mock_castable)
post :create, :castable => {:these => 'params'}
assigns[:castable].should equal(mock_castable)
end
it "redirects to the created castable" do
mock_castable.stub(:save => true)
Castable.stub(:new).and_return(mock_castable)
post :create, :castable => {}
response.should redirect_to(castable_url(mock_castable))
end
end
describe "with invalid params" do
it "assigns a newly created but unsaved castable as @castable" do
mock_castable.stub(:save => false)
Castable.stub(:new).with({'these' => 'params'}).and_return(mock_castable)
post :create, :castable => {:these => 'params'}
assigns[:castable].should equal(mock_castable)
end
it "re-renders the 'new' template" do
mock_castable.stub(:save => false)
Castable.stub(:new).and_return(mock_castable)
post :create, :castable => {}
response.should render_template('new')
end
end
end
describe "PUT update" do
describe "with valid params" do
it "updates the requested castable" do
Castable.should_receive(:find).with("37").and_return(mock_castable)
mock_castable.should_receive(:update_attributes).with({'these' => 'params'})
put :update, :id => "37", :castable => {:these => 'params'}
end
it "assigns the requested castable as @castable" do
mock_castable.stub(:update_attributes => true)
Castable.stub(:find).and_return(mock_castable)
put :update, :id => "1"
assigns[:castable].should equal(mock_castable)
end
it "redirects to the castable" do
mock_castable.stub(:update_attributes => true)
Castable.stub(:find).and_return(mock_castable)
put :update, :id => "1"
response.should redirect_to(castable_url(mock_castable))
end
end
describe "with invalid params" do
it "updates the requested castable" do
Castable.should_receive(:find).with("37").and_return(mock_castable)
mock_castable.should_receive(:update_attributes).with({'these' => 'params'})
put :update, :id => "37", :castable => {:these => 'params'}
end
it "assigns the castable as @castable" do
mock_castable.stub(:update_attributes => false)
Castable.stub(:find).and_return(mock_castable)
put :update, :id => "1"
assigns[:castable].should equal(mock_castable)
end
it "re-renders the 'edit' template" do
mock_castable.stub(:update_attributes => false)
Castable.stub(:find).and_return(mock_castable)
put :update, :id => "1"
response.should render_template('edit')
end
end
end
describe "DELETE destroy" do
it "destroys the requested castable" do
Castable.should_receive(:find).with("37").and_return(mock_castable)
mock_castable.should_receive(:destroy)
delete :destroy, :id => "37"
end
it "redirects to the castables list" do
mock_castable.stub(:destroy => true)
Castable.stub(:find).and_return(mock_castable)
delete :destroy, :id => "1"
response.should redirect_to(castables_url)
end
end
end
|
require 'rails_helper'
RSpec.describe 'readiness survey page', :onboarding do
let(:owner) { account.owner }
let(:companion) { account.companion }
context 'for a solo account' do
let(:account) { create_account(:eligible, onboarding_state: 'readiness') }
before do
login_as_account(account)
visit survey_readiness_path
end
example '' do
expect(page).to have_field "Yes - I'm ready now", checked: true
expect(page).to have_field "No - I'm not ready yet"
expect(page).to have_no_content "#{owner.first_name} is ready"
end
example 'submitting "ready"' do
click_button 'Save and continue'
expect(owner.reload.unresolved_recommendation_request?).to be true
expect(current_path).to eq new_phone_number_path
end
example 'submitting "ready"' do
choose "No - I'm not ready yet"
click_button 'Save and continue'
expect(owner.reload.unresolved_recommendation_request?).to be false
expect(current_path).to eq new_phone_number_path
end
end
context 'for a couples account' do
let(:account) { create_account(:couples, onboarding_state: 'readiness') }
before do
owner.update!(eligible: owner_eligible)
companion.update!(eligible: companion_eligible)
login_as_account(account)
visit survey_readiness_path
end
let(:companion_eligible) { true }
let(:companion_name) { companion.first_name }
let(:owner_eligible) { true }
let(:owner_name) { owner.first_name }
context 'owner eligible' do
let(:companion_eligible) { false }
example '' do
expect(page).to have_field "Yes - I'm ready now", checked: true
expect(page).to have_field "No - I'm not ready yet"
expect(page).to have_no_content "#{owner_name} is ready"
expect(page).to have_no_content "#{companion_name} is ready"
end
example 'submitting "ready"' do
click_button 'Save and continue'
expect(owner.reload.unresolved_recommendation_request?).to be true
expect(companion.reload.unresolved_recommendation_request?).to be false
expect(current_path).to eq new_phone_number_path
end
example 'submitting "ready"' do
choose "No - I'm not ready yet"
click_button 'Save and continue'
expect(owner.reload.unresolved_recommendation_request?).to be false
expect(companion.reload.unresolved_recommendation_request?).to be false
expect(current_path).to eq new_phone_number_path
end
end
context 'when only companion is eligible' do
let(:owner_eligible) { false }
example '' do
expect(page).to have_field "Yes - I'm ready now", checked: true
expect(page).to have_field "No - I'm not ready yet"
expect(page).to have_no_content "#{owner_name} is ready"
expect(page).to have_no_content "#{companion_name} is ready"
end
example 'submitting "ready"' do
click_button 'Save and continue'
expect(owner.reload.unresolved_recommendation_request?).to be false
expect(companion.reload.unresolved_recommendation_request?).to be true
expect(current_path).to eq new_phone_number_path
end
example 'submitting "ready"' do
choose "No - I'm not ready yet"
click_button 'Save and continue'
expect(owner.reload.unresolved_recommendation_request?).to be false
expect(companion.reload.unresolved_recommendation_request?).to be false
expect(current_path).to eq new_phone_number_path
end
end
context 'both people are eligible' do
example '' do
expect(page).to have_field(
"Both #{owner_name} and #{companion_name} are ready now", checked: true,
)
expect(page).to have_field("#{owner_name} is ready now but #{companion_name} isn't")
expect(page).to have_field("#{companion_name} is ready now but #{owner_name} isn't")
expect(page).to have_field('Neither of us is ready yet')
end
example 'both ready' do
click_button 'Save and continue'
expect(owner.reload.unresolved_recommendation_request?).to be true
expect(companion.reload.unresolved_recommendation_request?).to be true
expect(current_path).to eq new_phone_number_path
end
example 'owner ready' do
choose "#{owner_name} is ready now but #{companion_name} isn't"
click_button 'Save and continue'
expect(owner.reload.unresolved_recommendation_request?).to be true
expect(companion.reload.unresolved_recommendation_request?).to be false
expect(current_path).to eq new_phone_number_path
end
example 'companion ready' do
choose "#{companion_name} is ready now but #{owner_name} isn't"
click_button 'Save and continue'
expect(owner.reload.unresolved_recommendation_request?).to be false
expect(companion.reload.unresolved_recommendation_request?).to be true
expect(current_path).to eq new_phone_number_path
end
example 'neither ready' do
choose 'Neither of us is ready yet'
click_button 'Save and continue'
expect(owner.reload.unresolved_recommendation_request?).to be false
expect(companion.reload.unresolved_recommendation_request?).to be false
expect(current_path).to eq new_phone_number_path
end
end
end
end
|
class CreateParshas < ActiveRecord::Migration
def change
create_table :parshas do |t|
t.string :name
t.boolean :available, :default => true
t.integer :people_id
t.integer :past_id
t.integer :sefer_id
t.date :date
t.timestamps null: true
end
end
end
|
module Taskmgr
module Core
class Task
attr_reader :title, :description, :due_date, :category
def initialize
@title = ""
@description = ""
@parent = nil
@due_date = nil
@subtasks = Array.new
@category = nil
end
end
class Category
attr_reader :name
def initialize
@name = ""
end
end
class TaskManager
end
end
end |
# frozen_string_literal: true
# Image paths with different compression
class Image < ApplicationRecord
has_many :image_product_items, dependent: :delete_all
has_many :product_items, through: :image_product_items
validates :full_webp, presence: true
validates :full_jpegxr, presence: true
validates :full_jpeg2000, presence: true
end
|
class Tutorial < ApplicationRecord
validates :title, length: { minimum: 5 }
validates :description, length: { minimum: 10 }
has_many :videos, -> { order(position: :ASC) }, dependent: :destroy
acts_as_taggable_on :tags, :tag_list
accepts_nested_attributes_for :videos
scope :classroom, -> { where(classroom: false) }
end
|
module Hippo::Segments
class ISA < Base
segment_identifier 'ISA'
segment_fixed_width
field :name => 'AuthorizationInformationQualifier',
:datatype => :list,
:list => [ '00','01','02','03','04','05','06'],
:maximum => 2,
:required => false
field :name => 'AuthorizationInformation',
:datatype => :alpha_numeric,
:maximum => 10,
:required => false
field :name => 'SecurityInformationQualifier',
:datatype => :list,
:list => [ '00','01'],
:maximum => 2,
:required => false
field :name => 'SecurityInformation',
:datatype => :alpha_numeric,
:maximum => 10,
:required => false
field :name => 'InterchangeIdQualifier1',
:datatype => :list,
:list => [ '01','02','03','04','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36','37','AM','NR','SN','ZZ'],
:maximum => 2,
:required => false
field :name => 'InterchangeSenderId',
:datatype => :alpha_numeric,
:maximum => 15,
:required => false
field :name => 'InterchangeIdQualifier2',
:datatype => :alpha_numeric,
:maximum => 2,
:required => false
field :name => 'InterchangeReceiverId',
:datatype => :alpha_numeric,
:maximum => 15,
:required => false
field :name => 'InterchangeDate',
:datatype => :alpha_numeric,
:maximum => 6,
:required => false
field :name => 'InterchangeTime',
:datatype => :alpha_numeric,
:maximum => 4,
:required => false
field :name => 'InterchangeControlStandardsIdentifier',
:datatype => :list,
:list => [ 'U'],
:maximum => 1,
:required => false
field :name => 'InterchangeControlVersionNumber',
:datatype => :list,
:list => [ '00200','00201','00204','00300','00301','00302','00303','00304','00305','00306','00307','00400','00401','00402'],
:maximum => 5,
:required => false
field :name => 'InterchangeControlNumber',
:datatype => :alpha_numeric,
:maximum => 9,
:required => false
field :name => 'AcknowledgmentRequested',
:datatype => :list,
:list => [ '0','1'],
:maximum => 1,
:required => false
field :name => 'UsageIndicator',
:datatype => :list,
:list => [ 'I','P','T'],
:maximum => 1,
:required => false
field :name => 'ComponentElementSeparator',
:datatype => :alpha_numeric,
:maximum => 1,
:required => false
end
end
|
require 'rails_helper'
describe 'meta/games/show' do
let(:game) { build_stubbed(:game) }
it 'shows data' do
assign(:game, game)
render
expect(rendered).to include(game.name)
end
end
|
require 'spec_helper'
describe CanvasStatsd::RequestTracking do
describe '#enable' do
it 'should delegate log messages to the optional logger' do
log_double = double()
expect(log_double).to receive(:info)
CanvasStatsd::RequestTracking.enable logger: log_double
CanvasStatsd::RequestTracking.start_processing
CanvasStatsd::RequestTracking.finalize_processing('name', 1000, 10001, 1234, {})
end
end
end
|
require 'dist_server/util/array'
class Hash
end
class FSInputStream
def read_hash
size = self.read_uint16
hash = {}
for i in 0...size
key = self.read_string
value = self.read_type_val
hash[key] = value
end
hash
end
end
class FSOutputStream
def write_hash(hash)
self.write_uint16(hash.size)
for k, v in hash
self.write_string(k.to_s)
self.write_type_val(v)
end
end
end |
require 'steam'
class Participant < ActiveRecord::Base
include ApplicationHelper
include HeroesHelper
belongs_to :match
belongs_to :player, :class_name => "Player", :foreign_key => "player_id"
belongs_to :hero
def hero
Steam::Constants::Heroes[self.hero_id]
end
def winner
self.match.winner == side.downcase ? "winner" : "loser"
end
def side
self.player_slot < 5 ? "Radiant" : "Dire"
end
def item_imgs
items = self.items.split(' ').select { |item| not item.include?('empty')}
items.map { |item| item_small_img(item)}
end
def item_small_img(item)
ENV["ITEM_IMG_URL"] + item + "_eg.png"
end
end
|
class SessionsController < ApplicationController
layout false
skip_before_filter :authenticate
def create
if authorize(request.env['omniauth.auth'])
flash[:notice] = "Logged in as #{session[:employee][:name]}."
else
flash[:error] = "Please log in using a Shopify account."
end
redirect_to request.env['omniauth.origin'] || root_path
end
def destroy
reset_session
@message = "Successfully logged out"
redirect_to root_path
end
private
def authorize(oauth_response)
return false unless oauth_response.info.email.end_with?("@shopify.com")
reset_and_copy_session
session[:employee] = {
email: oauth_response.info.email,
name: oauth_response.info.name,
first_name: oauth_response.info.first_name,
last_name: oauth_response.info.last_name
}.with_indifferent_access
end
# http://guides.rubyonrails.org/security.html#session-fixation
def reset_and_copy_session
temp_flash = flash.to_hash
temp_session = session.to_hash
reset_session
flash.update(temp_flash)
session.update(temp_session.symbolize_keys)
session[:_csrf_token] = nil
request.session_options[:id] = SecureRandom.hex(16)
end
end
|
require_relative 'Validations'
class User
include Validator
attr_accessor :user_credits, :score, :credits
attr_reader :name, :inital_credits
REWARD = 0.25
@score = @credits = nil
def initialize name:, user_credits:
# p user_credits, name
@inital_credits = @user_credits = user_credits || 500
@name = name
@score = nil
@bet = nil
end
def to_s
"Name: #{@name} credits: #{@user_credits}"
end
def bet score:, credits:
if (valid_bet? credits) && (valid_score? score)
@score = score
@credits = credits
@user_credits -= @credits
puts "Игрок #{@name} делал ставку в #{@credits} кредитов на число #{@score}. осталось денег #{@user_credits}"
else puts "Неправильная ставка"
end
def bet?
@bet != nil
end
def reset
@score = nil
@credits = nil
end
def win
puts "#{@name} выиграл #{@credits * REWARD}"
@user_credits += @credits * REWARD
reset
end
def lose
puts "#{@name} проиграл"
reset
end
end
end
|
require 'orocos/test'
module Orocos
describe "logging" do
attr_reader :orogen_project, :orogen_deployment, :process
before do
@orogen_project = OroGen::Spec::Project.new(Orocos.default_loader)
@orogen_deployment = orogen_project.deployment('test')
@process = Process.new('test', orogen_deployment)
flexmock(process)
end
def create_mock_deployment
task_model = OroGen::Spec::TaskContext.new(orogen_project)
yield(task_model) if block_given?
orogen_deployment.task 'test', task_model
default_logger = RubyTasks::TaskContext.from_orogen_model(
'test_logger', Orocos.default_loader.task_model_from_name('logger::Logger'))
flexmock(default_logger).should_receive(:log).by_default
ruby_task = RubyTasks::TaskContext.from_orogen_model(
'test', task_model)
register_allocated_ruby_tasks(default_logger, ruby_task)
process.should_receive(:task).with('test').and_return(ruby_task)
process.default_logger = default_logger
return default_logger, ruby_task
end
it "returns an empty set if the process has no default logger" do
process.default_logger = false
assert_equal Set.new, Orocos.log_all_process_ports(process)
end
it "calls the process' #setup_default_logger method with the value returned by process.default_logger" do
default_logger, _ = create_mock_deployment
process.should_receive(:setup_default_logger).
with(default_logger, log_file_name: 'testfile').
once.
pass_thru
Orocos.log_all_process_ports(process, log_file_name: 'testfile')
end
it "configures and starts a pre-operational logger" do
default_logger, _ = create_mock_deployment
Orocos.log_all_process_ports(process)
assert default_logger.running?
end
it "starts a stopped logger" do
default_logger, _ = create_mock_deployment
default_logger.configure
Orocos.log_all_process_ports(process)
assert default_logger.running?
end
it "does not change the logger's state if it is already running" do
default_logger, _ = create_mock_deployment
default_logger.configure
default_logger.start
Orocos.log_all_process_ports(process)
assert default_logger.running?
end
it "setups logging for the task's output ports" do
default_logger, ruby_task = create_mock_deployment do |task_m|
task_m.output_port 'test', '/int32_t'
end
default_logger.should_receive(:log).
with(ruby_task.port('state')).once
default_logger.should_receive(:log).
with(ruby_task.test).once
assert_equal Set[['test', 'state'], ['test', 'test']],
Orocos.log_all_process_ports(process)
end
it "excludes a task whose name is not matched by the tasks object" do
matcher = flexmock do |m|
m.should_receive(:===).and_return { |task_name| task_name != 'test' }
end
default_logger, ruby_task = create_mock_deployment do |task_m|
task_m.output_port 'test', '/int32_t'
end
default_logger.should_receive(:log).never
assert_equal Set.new, Orocos.log_all_process_ports(process, tasks: matcher)
end
it "includes a task whose name is matched by the tasks object" do
matcher = flexmock do |m|
m.should_receive(:===).and_return { |task_name| task_name == 'test' }
end
default_logger, ruby_task = create_mock_deployment do |task_m|
task_m.output_port 'test', '/int32_t'
end
default_logger.should_receive(:log).
with(ruby_task.port('state')).once
default_logger.should_receive(:log).
with(ruby_task.test).once
assert_equal Set[['test', 'test'], ['test', 'state']],
Orocos.log_all_process_ports(process, tasks: matcher)
end
it "excludes a port whose name is matched by the exclude_ports object" do
matcher = flexmock do |m|
m.should_receive(:===).and_return { |port_name| port_name == 'state' }
end
default_logger, ruby_task = create_mock_deployment do |task_m|
task_m.output_port 'test', '/int32_t'
end
default_logger.should_receive(:log).
with(ruby_task.port('state')).never
default_logger.should_receive(:log).
with(ruby_task.test).once
assert_equal Set[['test', 'test']],
Orocos.log_all_process_ports(process, exclude_ports: matcher)
end
it "excludes a port whose type name is matched by the exclude_types object" do
matcher = flexmock do |m|
m.should_receive(:===).and_return { |type_name| type_name == '/double' }
end
default_logger, ruby_task = create_mock_deployment do |task_m|
task_m.output_port 'test', '/double'
end
default_logger.should_receive(:log).
with(ruby_task.port('state')).once
default_logger.should_receive(:log).
with(ruby_task.test).never
assert_equal Set[['test', 'state']],
Orocos.log_all_process_ports(process, exclude_types: matcher)
end
it "excludes a port for which the block returns false" do
default_logger, ruby_task = create_mock_deployment do |task_m|
task_m.output_port 'test', '/double'
end
default_logger.should_receive(:log).
with(ruby_task.port('state')).never
default_logger.should_receive(:log).
with(ruby_task.test).once
assert_equal Set[['test', 'test']],
Orocos.log_all_process_ports(process) { |port| port.name != 'state' }
end
end
end
|
class UsersArtistItemsTag < ActiveRecord::Base
belongs_to :user
belongs_to :artist_item
belongs_to :tag
end
|
#!/usr/bin/env ruby
# action.rb
# createdby: Micah Rosales
# modified: 12/27/14
#
# Called by an alfred workflow with a JSON blob
# as the first argument. Parameter must have a
# type field and a arg field
require "json"
# Copies the given string to the OSX system
# clipboard using pbcopy and piping to stdin
def pbcopy(input)
str = input.to_s
IO.popen('pbcopy', 'w') { |f| f << str }
str
end
begin
args = JSON.parse(valid, :symbolize_names => true)
arg = args[:arg]
type = args[:type]
rescue NameError
puts "Could not parse JSON!"
end
# geo cmds will have lat,lon format arg
if type == 'geo'
`open "http://maps.apple.com/?sll=#{arg}"`
else
# Otherwise copy to sys clipboard
pbcopy(arg)
end
|
module Setback
class MemoryProvider
def initialize(settings_hash = {})
@settings_hash = settings_hash
end
def get(key)
@settings_hash[key]
end
def set(key, value)
@settings_hash[key] = value
end
def keys(filter_internal = true)
@settings_hash.keys
end
def all(filter_internal = true)
@settings_hash.clone
end
end
end
|
# encoding: binary
require "amq/protocol/client"
# We will need to introduce concept of mappings, because
# AMQP 0.9, 0.9.1 and RabbitMQ uses different letters for entities
# http://dev.rabbitmq.com/wiki/Amqp091Errata#section_3
module AMQ
module Protocol
class Table
class InvalidTableError < StandardError
def initialize(key, value)
super("Invalid table value on key #{key}: #{value.inspect} (#{value.class})")
end
end
TYPE_STRING = 'S'.freeze
TYPE_INTEGER = 'I'.freeze
TYPE_HASH = 'F'.freeze
TYPE_TIME = 'T'.freeze
TYPE_DECIMAL = 'D'.freeze
TYPE_BOOLEAN = 't'.freeze
TYPE_SIGNED_8BIT = 'b'.freeze
TYPE_SIGNED_16BIT = 's'.freeze
TYPE_SIGNED_64BIT = 'l'.freeze
TYPE_32BIT_FLOAT = 'f'.freeze
TYPE_64BIT_FLOAT = 'd'.freeze
TYPE_VOID = 'V'.freeze
TYPE_BYTE_ARRAY = 'x'.freeze
TEN = '10'.freeze
def self.encode(table)
buffer = String.new
table ||= {}
table.each do |key, value|
key = key.to_s # it can be a symbol as well
buffer << key.bytesize.chr + key
case value
when String then
buffer << TYPE_STRING
buffer << [value.bytesize].pack(PACK_UINT32)
buffer << value
when Integer then
buffer << TYPE_INTEGER
buffer << [value].pack(PACK_UINT32)
when Float then
buffer << TYPE_64BIT_FLOAT
buffer << [value].pack(PACK_64BIT_FLOAT)
when TrueClass, FalseClass then
value = value ? 1 : 0
buffer << TYPE_INTEGER
buffer << [value].pack(PACK_UINT32)
when Hash then
buffer << TYPE_HASH # TODO: encoding support
buffer << self.encode(value)
when Time then
buffer << TYPE_TIME
buffer << [value.to_i].pack(PACK_INT64).reverse # FIXME: there has to be a more efficient way
else
# We don't want to require these libraries.
if defined?(BigDecimal) && value.is_a?(BigDecimal)
buffer << TYPE_DECIMAL
if value.exponent < 0
decimals = -value.exponent
# p [value.exponent] # normalize
raw = (value * (decimals ** 10)).to_i
#pieces.append(struct.pack('>cBI', 'D', decimals, raw)) # byte integer
buffer << [decimals + 1, raw].pack(PACK_UCHAR_UINT32) # somewhat like floating point
else
# per spec, the "decimals" octet is unsigned (!)
buffer << [0, value.to_i].pack(PACK_UCHAR_UINT32)
end
else
raise InvalidTableError.new(key, value)
end
end
end
[buffer.bytesize].pack(PACK_UINT32) + buffer
end
def self.length(data)
data.unpack(PACK_UINT32).first
end
def self.decode(data)
table = Hash.new
size = data.unpack(PACK_UINT32).first
offset = 4
while offset < size
key_length = data.slice(offset, 1).unpack(PACK_CHAR).first
offset += 1
key = data.slice(offset, key_length)
offset += key_length
type = data.slice(offset, 1)
offset += 1
case type
when TYPE_STRING
length = data.slice(offset, 4).unpack(PACK_UINT32).first
offset += 4
value = data.slice(offset, length)
offset += length
when TYPE_INTEGER
value = data.slice(offset, 4).unpack(PACK_UINT32).first
offset += 4
when TYPE_DECIMAL
decimals, raw = data.slice(offset, 5).unpack(PACK_UCHAR_UINT32)
offset += 5
value = BigDecimal.new(raw.to_s) * (BigDecimal.new(TEN) ** -decimals)
when TYPE_TIME
timestamp = data.slice(offset, 8).unpack(PACK_UINT32_X2).last
value = Time.at(timestamp)
offset += 8
when TYPE_HASH
length = data.slice(offset, 4).unpack(PACK_UINT32).first
value = self.decode(data.slice(offset, length + 4))
offset += 4 + length
when TYPE_BOOLEAN
value = data.slice(offset, 2)
integer = value.unpack(PACK_CHAR).first # 0 or 1
value = integer == 1
offset += 1
when TYPE_SIGNED_8BIT then raise NotImplementedError.new
when TYPE_SIGNED_16BIT then raise NotImplementedError.new
when TYPE_SIGNED_64BIT then raise NotImplementedError.new
when TYPE_32BIT_FLOAT then
value = data.slice(offset, 4).unpack(PACK_32BIT_FLOAT).first
offset += 4
when TYPE_64BIT_FLOAT then
value = data.slice(offset, 8).unpack(PACK_64BIT_FLOAT).first
offset += 8
when TYPE_VOID
value = nil
when TYPE_BYTE_ARRAY
else
raise "Not a valid type: #{type.inspect}\nData: #{data.inspect}\nUnprocessed data: #{data[offset..-1].inspect}\nOffset: #{offset}\nTotal size: #{size}\nProcessed data: #{table.inspect}"
end
table[key] = value
end
table
end
end
end
end
|
Given(/^I am a new customer who is enrolled in online servicing$/) do
on(LoginPage) do |page|
login_data = page.data_for(:td_non_cycled_account)
username = login_data['username']
password = login_data['password']
ssoid = login_data['ssoid']
page.login(username, password, ssoid)
end
end
Given(/^I am an existing customer whose account has cycled$/) do
on(LoginPage) do |page|
login_data = page.data_for(:td_single_miles_account)
username = login_data['username']
password = login_data['password']
ssoid = login_data['ssoid']
page.login(username, password, ssoid)
end
end
Then(/^there (is|is no) "([^"]*)" option displayed in the "([^"]*)" dropdown$/) do |arg1, arg2, arg3|
on(TransactionsDetailsPage) do |page|
page.wait_for_td_page_load
if(arg1 == 'is')
page.dropdown_contains_option("#"+arg3, arg2).should == true
else
page.dropdown_contains_option("#"+arg3, arg2).should == false
end
end
end |
module SimpleTableFor
class Defaults
def self.get
@defaults || {}
end
def self.set(options)
@defaults = options
end
end
end
|
class Animal
attr_reader :name
attr_accessor :mood
def initialize(name)
# binding.pry
puts "I'm an animal"
@name = name
@mood = 'nervous'
end
def speak
puts 'just a plain animal here. sorry.'
end
end |
class TimeTrackerCategory < ActiveRecord::Base
unloadable
include Redmine::SafeAttributes
safe_attributes 'name','parent_id'
validates_length_of :name, :maximum => 255
validate :validate_exist_parent_id
validate :validate_not_parent, on: :update
before_validation :require_before_save_parent_id
def validate_exist_parent_id
if (self.parent_id != 0) && (TimeTrackerCategory.find_by_id(self.parent_id).nil?)
errors.add(l('parent_id'), l('msg_is_not_exist'))
end
end
def require_before_save_parent_id
self.parent_id = '0' if self.parent_id.nil?
end
def validate_not_parent
if !TimeTracker.find_by_time_tracker_category_id(self.id).nil? && self.parent_id == 0
errors.add(l('field_time_tracker_category_id'), l('msg_is_not_empty'))
end
end
end
|
require 'pg'
class Peep
attr_reader :content, :created_at, :id
def initialize(content:, id:, created_at:)
@content = content
@id = id
@created_at = created_at
end
def self.all
result = DatabaseConnection.query("SELECT * FROM peeps ORDER BY id DESC;")
result.map do |peep|
Peep.new(
id: peep['id'],
content: peep['content'],
created_at: peep['created_at']
)
end
end
def self.create(content:)
result = DatabaseConnection.query(
"INSERT INTO peeps (content, created_at)
VALUES('#{content}', CURRENT_TIME(0))
RETURNING id, content, created_at;"
)
Peep.new(
id: result[0]['id'],
content: result[0]['content'],
created_at: result[0]['created_at']
)
end
def time
created_at[0..4]
end
end
|
# encoding: utf-8
##
# Backup Generated: nyc_collegeline_production_backup
# Once configured, you can run the backup with the following command:
#
# $ backup perform -t nyc_collegeline_production_backup [-c <path_to_configuration_file>]
#
# For more information about Backup's components, see the documentation at:
# http://meskyanichi.github.io/backup
#
##
# This file is generated by this command:
# backup generate:model -t garden_backup --databases="postgresql" --storages="s3" --compressor="gzip" --notifiers="mail" --config-file ./config/backup/backup.rb
ENV = "production"
# This means that backup needs to be ran relative to project root (see schedule.rb)
secrets = YAML.load(File.open("config/secrets.yml"))[ENV]
db_config = YAML.load(File.open("config/database.yml"))[ENV]
Model.new(:nyc_collegeline_production_backup, 'Description for nyc collegeline production backup') do
##
# PostgreSQL [Database]
#
database PostgreSQL do |db|
# To dump all databases, set `db.name = :all` (or leave blank)
db.name = db_config["database"]
db.username = db_config["username"] if db_config["username"]
db.password = db_config["password"] if db_config["password"]
db.host = db_config["host"] if db_config["host"]
db.port = db_config["port"] if db_config["port"]
# db.socket = "/tmp/pg.sock"
# When dumping all databases, `skip_tables` and `only_tables` are ignored.
# db.skip_tables = ["skip", "these", "tables"]
# db.only_tables = ["only", "these", "tables"]
db.additional_options = ["-O"]
end
##
# Amazon Simple Storage Service [Storage]
#
store_with S3 do |s3|
# AWS Credentials
s3.access_key_id = secrets["backup_aws_access_key_id"]
s3.secret_access_key = secrets["backup_aws_secret_access_key_id"]
s3.region = secrets["backup_s3_region"]
s3.bucket = secrets["backup_s3_bucket"]
s3.path = secrets["backup_s3_path"]
print s3.inspect
end
##
# Gzip [Compressor]
#
compress_with Gzip
##
# Mail [Notifier]
#
# The default delivery method for Mail Notifiers is 'SMTP'.
# See the documentation for other delivery options.
#
# notify_by Ses do |ses|
# ses.on_success = false
# ses.on_warning = true
# ses.on_failure = true
#
# ses.access_key_id = secrets["backup_aws_access_key_id"]
# ses.secret_access_key = secrets["backup_aws_secret_access_key_id"]
# ses.region = secrets["backup_s3_region"]
#
# ses.from = secrets["backup_email_from"]
# ses.to = secrets["backup_email_to"]
# end
end
|
class RubricsController < ApplicationController
before_action :find_rubric, only: [:show, :update, :destroy]
def index
@rubrics = Rubric.all
@rubrics = @rubrics.where('lower(rubrics.title) LIKE ?', "%#{params[:search_string].downcase}%") if params[:search_string]
paginate json: ActiveModelSerializers::SerializableResource.new(
@rubrics,
each_serializer: RubricsSerializer::Main,
include: [
]
).as_json
end
def show
render json: ActiveModelSerializers::SerializableResource.new(
@rubric,
serializer: RubricsSerializer::Main,
include: [
]
).as_json
end
def create
@rubric = Rubric.new(rubric_params)
if @rubric.save
render json: @rubric.as_json, status: :created
else
render json: { success: false, errors: @rubric.errors.as_json }, status: :unprocessable_entity
end
end
def update
if @rubric.update(rubric_params)
render json: @rubric.as_json, status: :accepted
else
render json: { success: false, errors: @rubric.errors.as_json }, status: :unprocessable_entity
end
end
def destroy
if @rubric.destroy
render json: { success: true }, status: :no_content
else
render json: { success: false, errors: @rubric.errors.as_json }, status: :unprocessable_entity
end
end
private
def find_rubric
@rubric = Rubric.find(params[:id])
end
def rubric_params
params.require(:rubric).permit(:title)
end
end
|
module Fog
module Storage
class GoogleJSON
class Real
# Get an expiring object url from Google Storage for putting an object
# https://cloud.google.com/storage/docs/access-control#Signed-URLs
#
# @param bucket_name [String] Name of bucket containing object
# @param object_name [String] Name of object to get expiring url for
# @param expires [Time] Expiry time for this URL
# @param headers [Hash] Optional hash of headers to include
# @option options [String] "x-goog-acl" Permissions, must be in ['private', 'public-read', 'public-read-write', 'authenticated-read'].
# If you want a file to be public you should to add { 'x-goog-acl' => 'public-read' } to headers
# and then call for example: curl -H "x-goog-acl:public-read" "signed url"
# @return [String] Expiring object https URL
def put_object_url(bucket_name, object_name, expires, headers = {})
raise ArgumentError.new("bucket_name is required") unless bucket_name
raise ArgumentError.new("object_name is required") unless object_name
https_url({
:headers => headers,
:host => @host,
:method => "PUT",
:path => "#{bucket_name}/#{object_name}"
}, expires)
end
end
class Mock
def put_object_url(bucket_name, object_name, expires, headers = {})
raise ArgumentError.new("bucket_name is required") unless bucket_name
raise ArgumentError.new("object_name is required") unless object_name
https_url({
:headers => headers,
:host => @host,
:method => "PUT",
:path => "#{bucket_name}/#{object_name}"
}, expires)
end
end
end
end
end
|
class Game < ActiveRecord::Base
MAX_PLAYERS = 4
MIN_PLAYERS = 4
HAND_SIZE = 10
TARGET_SCORE = 500
has_many :players, dependent: :destroy
has_many :rounds, dependent: :destroy
def finished?
odd_players_score.abs >= TARGET_SCORE || even_players_score.abs >= TARGET_SCORE
end
def active_round
unless finished?
rounds.in_playing_order.last
end
end
def odd_players_score
rounds.sum(:odd_players_score)
end
def even_players_score
rounds.sum(:even_players_score)
end
end
|
require 'find'
class Bolts < Thor::Group
include Thor::Actions
argument :group, :default => "", :desc => "leave blank for all"
desc "choose which group of bolts you would like to install"
def install
dir_path = [".", "/#{group}"].join
Find.find(dir_path) do |bolt|
if File.extname(bolt).eql?(".thor")
thor :install, bolt, :force => true
end
end
end
end |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe User, type: :model do
let(:user) { build(:user) }
context 'associations' do
it { should have_many(:post_types) }
it { should have_many(:posts).through(:post_types) }
end
end
|
# a method that returns the sum of two integers
=begin
START
# Given two integers
SET number1 = the first integer
SET number2 = the second integer
SET sum = READ number1 + READ number2
PRINT sum
END
=end
# a method that takes an array of strings, and returns a string that is all those strings concatenated together
=begin
START
# Given a collection of strings called "strings"
SET iterator = 0
SET joined_string = empty string
WHILE iterator < string's length
SET current_string = a value from within "strings" at location of iterator
joined_string = joined_string + current_string
iterator = iterator + 1
PRINT joined_string
END
=end
# a method that takes an array of integers, and returns a new array with every other element
=begin
START
# Given a collection of integers called 'numbers'
SET iterator = 0
SET new_array = empty array
WHILE iterator < numbers' length
SET current_number = a value from within 'numbers' at location of iterator
add current_number to new_array
iterator = iterator + 2
PRINT new_array
END
=end |
RSpec.describe CopyrightNoticesHelper do
before do
allow(Time).to receive(:now).and_return(Time.new(2014,1,1,0,0))
end
context "when the start year is the current year" do
let :correct_format do
"© 2014 Toggle Professional Services LLC"
end
it "formats correctly" do
expect(helper.copyright_notice).to eq correct_format
end
end
context "when the start year is not the current year" do
let :correct_format do
"© 2013 - 2014 Toggle Professional Services LLC"
end
it "formats correctly" do
expect(helper.copyright_notice(2013)).to eq correct_format
end
end
end
|
Before do |scenario|
LOG.info("Starting : #{scenario.name}")
$helper.go_to(LOGIN_URL)
sleep 2
end
After do |scenario|
LOG.info("Result : #{scenario.passed?} - #{scenario.name}")
if scenario.exception
LOG.info("The full exception is : #{scenario.exception.inspect}")
LOG.info("Backtrace is : #{scenario.exception.backtrace}")
end
end |
class CommentsController < ApplicationController
#before_action :authenticate_user!
def create
@article = Article.find(params[:comment][:article_id])
@comment = @article.comments.build(comment_params)
@comment.user = current_user
@comment.save
respond_to do |format|
format.html { redirect_to @article }
format.js
end
end
def destroy
@comment = Comment.find(params[:id])
@article = @comment.article
@comment.destroy
redirect_to article_path(@article)
end
private
def comment_params
params.require(:comment).permit(:content)
end
def authenticate_user
if !logged_in?
flash[:danger] = "you must be logged in to perform that action"
redirect_to article_path(@article)
end
end
end |
class CreateMeasurements < ActiveRecord::Migration
def change
create_table :measurements do |t|
t.belongs_to :user, index: true, foreign_key: true
t.belongs_to :act_indicator_relation, index: true, foreign_key: true
t.datetime :date
t.decimal :value
t.text :details
t.boolean :active, default: true, null: false
t.datetime :deactivated_at
t.timestamps null: false
end
end
end
|
module MongoDoc
module Railties
module Config
extend self
def config(app)
MongoDoc::Connection.config_path = app.root + 'config/mongodb.yml'
MongoDoc::Connection.default_name = "#{app.root.basename}_#{Rails.env}"
MongoDoc::Connection.env = Rails.env
end
end
end
end
|
class AddingFieldsToProduct < ActiveRecord::Migration
def change
add_column :products, :length, :string
add_column :products, :author_desc, :text
add_column :products, :author_image_n, :string
end
end
|
module Analyst
module Entities
class Root < Entity
handles_node :analyst_root
def full_name
""
end
def inspect
"\#<#{self.class}>"
end
def contents
@contents ||= actual_contents.map do |child|
# skip top-level CodeBlocks
child.is_a?(Entities::CodeBlock) ? child.contents : child
end.flatten
end
private
def actual_contents
@actual_contents ||= process_nodes(ast.children)
end
end
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)
Category.create([
{ name: 'Electronics' },
{ name: 'Household' },
{ name: 'Gardening' },
{ name: 'Automotive' },
{ name: 'Ninjas' }
])
#Product.create([
# { name: 'hose', description: 'for watering things', pricing: 28.99 },
# { name: 'lights', description: 'pathway solar lights', pricing: 38.98 },
# { name: 'rocks', description: 'landscape', pricing: 15.99 },
#
# { name: 'monitor', description: '27 inch', pricing: 299.99 },
# { name: 'power strip', description: '5 sockets', pricing: 12 },
# { name: 'mac air', description: 'apple computer', pricing: 1999.99 },
#
# { name: 'dawn', description: 'dishwashing detergent', pricing: 7.99 },
# { name: 'toyota', description: 'year 2000 model avalon', pricing: 2888.99 },
# { name: 'leonardo', description: 'plush ninja turtle', pricing: 13.84 },
#])
|
# vim: ts=2:sw=2:softtabstop=2:et
require 'cinch'
require 'plugin_helpers'
class Learn
include Cinch::Plugin, SlackCat::PluginHelpers
match /learn ([^ ]*) (.*)?/i, prefix: ".", method: :learn
match /(.*)?/i, prefix: ".", method: :respond
match /learned/i, prefix: ".", method: :learned
def respond(memo, command)
db = SQLite3::Database.new "pluses.db"
db.execute("SELECT response FROM commands WHERE command = ? ORDER BY RANDOM() LIMIT 1", [command]) do |response|
memo.reply response[0]
end
end
def learn(memo, command, response)
db = SQLite3::Database.new "pluses.db"
db.execute("INSERT OR IGNORE INTO commands VALUES (?, ?, ?)", [memo.user.to_s, command, response])
memo.reply "Learned command: #{command}"
end
def learned(memo)
message = "Learned Commands:\n"
db = SQLite3::Database.new "pluses.db"
db.execute("SELECT command, COUNT(1) FROM commands GROUP BY command ORDER BY command") do |command, num|
message += "#{command} (#{num})\n"
end
memo.reply message
end
end
|
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable,
:validatable, :authentication_keys => [:login]
has_many :volunteer_commitments
has_many :user_skills
has_many :skills, through: :user_skills
has_many :user_issues
has_many :issues, through: :user_issues
validates :username, presence: true
validates_uniqueness_of :username, message: 'An account with that username already exists'
validates_uniqueness_of :email, message: 'An account with that email address already exists'
attr_accessor :login
def signed_up_for shift
VolunteerCommitment.exists? user: self, shift: shift
end
def self.find_first_by_auth_conditions conditions, opts = {}
(User.find_by username: conditions[:login]) || (User.find_by email: conditions[:login])
end
# Return true is this user is linked with the given issue
def has_issue? issue
UserIssue.exists? user: self, issue: issue
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
# General Vagrant VM configuration.
config.vm.box = "debian/jessie64"
config.ssh.insert_key = false
config.vm.synced_folder ".", "/vagrant", disabled: true
config.vm.provider :virtualbox do |v|
v.memory = 1000
v.linked_clone = true
end
# Web server 1.
config.vm.define "ditelk1" do |webservers|
webservers.vm.hostname = "ditelkin1"
webservers.vm.network "private_network", ip: "192.168.34.11"
end
# Monitor server 2.
config.vm.define "ditelk2" do |monservers|
monservers.vm.hostname = "ditelkin2"
monservers.vm.network "private_network", ip: "192.168.34.12"
end
# Web server 3.
config.vm.define "ditelk3" do |webservers|
webservers.vm.hostname = "ditelkin3"
webservers.vm.network "private_network", ip: "192.168.34.13"
end
# Web server 4.
config.vm.define "ditelk4" do |webservers|
webservers.vm.hostname = "ditelkin4"
webservers.vm.network "private_network", ip: "192.168.34.14"
end
# Database server.
config.vm.define "db_ditelk" do |dbservers|
dbservers.vm.hostname = "ditelkin5"
dbservers.vm.network "private_network", ip: "192.168.34.20"
end
end |
require 'spec_helper'
describe Apohypaton::Config do
context "#chroot" do
subject { config.chroot }
let(:config) { Apohypaton::Config.new }
context "with a app_name and DEPLOY_ENV" do
let(:app_name) { "no" }
before do
ENV['DEPLOY_ENV'] = 'testing'
config.app_name = app_name
end
after do
ENV.delete('DEPLOY_ENV')
end
it {is_expected.to eq "#{app_name}/testing"}
end
context "with a app_name, no DEPLOY_ENV, and RAILS_ENV" do
let(:app_name) { "no" }
before do
ENV['RAILS_ENV'] = 'testing'
config.app_name = app_name
end
after do
ENV.delete('RAILS_ENV')
end
it { is_expected.to eq "#{app_name}/testing" }
end
end
context "defaults" do
subject { Apohypaton::Config.new }
it {is_expected.to be_enabled }
it {expect(subject.url).to eq URI("consul://localhost") }
it {expect(subject.token).to be_nil }
it {expect(subject.scheme).to eq 'https' }
it "should raise an error when asking for chroot" do
expect { subject.chroot }.to raise_error(Apohypaton::ConfigException)
end
end
end
describe Apohypaton do
describe "#configure" do
it "has a config block" do
expect { |b| Apohypaton.configure(&b) }.to yield_control
end
context "when a block is passed" do
subject do
ENV['DEPLOY_ENV'] = 'testing'
Apohypaton.configure do |c|
c.url = URI("consul://consul.omadahealth.net:443")
c.token = 'ACTUAL_TOKEN'
c.app_name = 'apohypaton'
c.enabled = false
end
end
after do
ENV.delete('DEPLOY_ENV')
end
it { is_expected.to be_a(Apohypaton::Config) }
it "returns the correct configuration" do
expect(subject.url).to eq URI('consul://consul.omadahealth.net:443')
expect(subject.token).to eq 'ACTUAL_TOKEN'
expect(subject.chroot).to eq 'apohypaton/testing'
expect(subject.app_name).to eq 'apohypaton'
expect(subject.enabled).to eq false
end
context "#enabled?" do
it "returns false" do
expect(subject).to_not be_enabled
end
it "returns false" do
subject
expect(Apohypaton).to_not be_enabled
end
end
end
end
end
|
#!/usr/bin/ruby
require 'yaml'
require "#{File.dirname(__FILE__)}/lib/array_extender.rb"
c = YAML.load_file("#{File.dirname(__FILE__)}/config.yml")
ENTRIES = 9
HEADER = ",%usr,%nice,%sys,%iowait,%irq,%soft,%steal,%guest,%idle,%all\n"
avg = File.new("mpstat_baremetal_avg.csv", 'w')
avg.write HEADER
arr_usr = []
arr_nice = []
arr_sys = []
arr_iowait = []
arr_irq = []
arr_soft = []
arr_steal = []
arr_guest = []
arr_idle = []
log = File.new("mpstat.baremetal.log")
log.gets
log.gets
log.gets
cnt = 0
log.each do |l|
break if cnt == c['duration']
line = l.split
arr_usr << line[3].to_f
arr_nice << line[4].to_f
arr_sys << line[5].to_f
arr_iowait << line[6].to_f
arr_irq << line[7].to_f
arr_soft << line[8].to_f
arr_steal << line[9].to_f
arr_guest << line[10].to_f
arr_idle << line[11].to_f
cnt+=1
end
avg.write "baremetal,"
avg.write "#{arr_usr.avg},"
avg.write "#{arr_nice.avg},"
avg.write "#{arr_sys.avg},"
avg.write "#{arr_iowait.avg},"
avg.write "#{arr_irq.avg},"
avg.write "#{arr_soft.avg},"
avg.write "#{arr_steal.avg},"
avg.write "#{arr_guest.avg},"
avg.write "#{arr_idle.avg},"
avg.write "#{arr_usr.avg + arr_nice.avg + arr_sys.avg + arr_irq.avg + arr_soft.avg + arr_steal.avg + arr_guest.avg}\n"
avg.close
|
class CreateAffordances < ActiveRecord::Migration
def change
create_table :affordances do |t|
t.string :type
t.boolean :verified
t.json :details
t.references :matrix_entry, index: true, foreign_key: true
t.timestamps null: false
end
end
end
|
describe GitHubChangelogGenerator::Parser do
describe ".user_project_from_remote" do
context "when remote is type 1" do
subject { GitHubChangelogGenerator::Parser.user_project_from_remote("origin https://github.com/skywinder/ActionSheetPicker-3.0 (fetch)") }
it { is_expected.to be_a(Array) }
it { is_expected.to match_array(["skywinder", "ActionSheetPicker-3.0"]) }
end
context "when remote is type 2" do
subject { GitHubChangelogGenerator::Parser.user_project_from_remote("https://github.com/skywinder/ActionSheetPicker-3.0") }
it { is_expected.to be_a(Array) }
it { is_expected.to match_array(["skywinder", "ActionSheetPicker-3.0"]) }
end
context "when remote is type 3" do
subject { GitHubChangelogGenerator::Parser.user_project_from_remote("https://github.com/skywinder/ActionSheetPicker-3.0") }
it { is_expected.to be_a(Array) }
it { is_expected.to match_array(["skywinder", "ActionSheetPicker-3.0"]) }
end
context "when remote is type 4" do
subject { GitHubChangelogGenerator::Parser.user_project_from_remote("origin git@github.com:skywinder/ActionSheetPicker-3.0.git (fetch)") }
it { is_expected.to be_a(Array) }
it { is_expected.to match_array(["skywinder", "ActionSheetPicker-3.0"]) }
end
context "when remote is invalid" do
subject { GitHubChangelogGenerator::Parser.user_project_from_remote("some invalid text") }
it { is_expected.to be_a(Array) }
it { is_expected.to match_array([nil, nil]) }
end
end
describe ".user_project_from_option" do
context "when option is invalid" do
it("should return nil") { expect(GitHubChangelogGenerator::Parser.user_project_from_option("blah", nil, nil)).to be_nil }
end
context "when option is valid" do
subject { GitHubChangelogGenerator::Parser.user_project_from_option("skywinder/ActionSheetPicker-3.0", nil, nil) }
it { is_expected.to be_a(Array) }
it { is_expected.to match_array(["skywinder", "ActionSheetPicker-3.0"]) }
end
context "when option nil" do
subject { GitHubChangelogGenerator::Parser.user_project_from_option(nil, nil, nil) }
it { is_expected.to be_a(Array) }
it { is_expected.to match_array([nil, nil]) }
end
context "when site is nil" do
subject { GitHubChangelogGenerator::Parser.user_project_from_option("skywinder/ActionSheetPicker-3.0", nil, nil) }
it { is_expected.to be_a(Array) }
it { is_expected.to match_array(["skywinder", "ActionSheetPicker-3.0"]) }
end
context "when site is valid" do
subject { GitHubChangelogGenerator::Parser.user_project_from_option("skywinder/ActionSheetPicker-3.0", nil, "https://codeclimate.com") }
it { is_expected.to be_a(Array) }
it { is_expected.to match_array(["skywinder", "ActionSheetPicker-3.0"]) }
end
context "when second arg is not nil" do
subject { GitHubChangelogGenerator::Parser.user_project_from_option("skywinder/ActionSheetPicker-3.0", "blah", nil) }
it { is_expected.to be_a(Array) }
it { is_expected.to match_array([nil, nil]) }
end
end
end
|
class RequestedTweetResponder < ApplicationResponder
topic :requested_tweet
def respond(data)
respond_to :requested_tweet, data
end
end |
# rubocop:todo all
shared_context 'auth unit tests' do
let(:generation_manager) do
Mongo::Server::ConnectionPool::GenerationManager.new(server: server)
end
let(:pool) do
double('pool').tap do |pool|
allow(pool).to receive(:generation_manager).and_return(generation_manager)
end
end
let(:connection) do
Mongo::Server::Connection.new(server, SpecConfig.instance.monitoring_options.merge(
connection_pool: pool))
end
end
|
require_relative('array_element_expr')
require_relative('assignment_expr/div_assignment_expr')
require_relative('constant_expr/constant_expr')
class ArrayAssignmentExpr < ArrayElementExpr
def initialize(array_id, index, ass_op, ass_expr, lineno)
@ass_op = ass_op
@ass_expr = ass_expr
super(array_id, index, lineno)
end
def code(scope)
type = scope.get_type(@array_id)
llvm_type = Type.to_llvm(type)
ass_expr_code, ass_expr_reg = @ass_expr.code(scope)
ass_type = @ass_expr.type(scope)
convert_code, convert_reg = Type.build_conversion(ass_type, type, ass_expr_reg, scope)
element_code, element_reg = get_element_code(type, scope)
return ass_expr_code + convert_code + element_code + " store #{llvm_type} #{convert_reg}, #{llvm_type}* #{element_reg}\n", element_reg
end
end |
require 'rails_helper'
RSpec.describe Purchase, type: :model do
before do
@purchase = FactoryBot.build(:purchase)
end
describe "商品購入情報の保存" do
context "購入情報が保存できるとき" do
it "token, postal_code, city, house_number, building, prefecture_id, phone_number, item_id, user_idの値が存在する" do
expect(@purchase).to be_valid
end
it "bulidingが空のとき" do
@purchase.building = nil
expect(@purchase).to be_valid
end
end
context "購入情報が保存できないとき" do
it "tokenが空の時" do
@purchase.token = nil
@purchase.valid?
expect(@purchase.errors.full_messages).to include("Token can't be blank")
end
it "postal_codeが空の時" do
@purchase.postal_code = nil
@purchase.valid?
expect(@purchase.errors.full_messages).to include("Postal code can't be blank")
end
it "cityが空の時" do
@purchase.city = nil
@purchase.valid?
expect(@purchase.errors.full_messages).to include("City can't be blank")
end
it "housenumberが空の時" do
@purchase.house_number = nil
@purchase.valid?
expect(@purchase.errors.full_messages).to include("House number can't be blank")
end
it "phone_numberが空の時" do
@purchase.phone_number = nil
@purchase.valid?
expect(@purchase.errors.full_messages).to include("Phone number can't be blank")
end
it "prefecture_idが空の時" do
@purchase.prefecture_id = nil
@purchase.valid?
expect(@purchase.errors.full_messages).to include("Prefecture is not a number")
end
it "prefecture_idのidが0のとき" do
@purchase.prefecture_id = 0
@purchase.valid?
expect(@purchase.errors.full_messages).to include("Prefecture must be other than 0")
end
it "postal_codeのハイフンがない時" do
@purchase.postal_code = "1234567"
@purchase.valid?
expect(@purchase.errors.full_messages).to include("Postal code is invalid")
end
it "phone_numberにハイフンつける時" do
@purchase.phone_number = "111-2222-3333"
@purchase.valid?
expect(@purchase.errors.full_messages).to include("Phone number is not a number")
end
it "phone_numberが11字未満のとき" do
@purchase.phone_number = 1234567
@purchase.valid?
expect(@purchase.errors.full_messages).to include("Phone number is too short (minimum is 10 characters)")
end
end
end
end
|
require 'test_helper'
class PadreadoresControllerTest < ActionDispatch::IntegrationTest
setup do
@padreador = padreadores(:one)
end
test "should get index" do
get padreadores_url
assert_response :success
end
test "should get new" do
get new_padreador_url
assert_response :success
end
test "should create padreador" do
assert_difference('Padreador.count') do
post padreadores_url, params: { padreador: { caracteristica_id: @padreador.caracteristica_id, data_nascimento: @padreador.data_nascimento, falecido: @padreador.falecido, nome: @padreador.nome, raca_id: @padreador.raca_id } }
end
assert_redirected_to padreador_url(Padreador.last)
end
test "should show padreador" do
get padreador_url(@padreador)
assert_response :success
end
test "should get edit" do
get edit_padreador_url(@padreador)
assert_response :success
end
test "should update padreador" do
patch padreador_url(@padreador), params: { padreador: { caracteristica_id: @padreador.caracteristica_id, data_nascimento: @padreador.data_nascimento, falecido: @padreador.falecido, nome: @padreador.nome, raca_id: @padreador.raca_id } }
assert_redirected_to padreador_url(@padreador)
end
test "should destroy padreador" do
assert_difference('Padreador.count', -1) do
delete padreador_url(@padreador)
end
assert_redirected_to padreadores_url
end
end
|
# encoding: utf-8
describe Faceter::Functions, ".split" do
let(:arguments) { [:split, Selector.new(options)] }
let(:input) { { foo: :FOO, bar: :BAR, baz: :BAZ } }
it_behaves_like :transforming_immutable_data do
let(:options) { {} }
let(:output) { [{ foo: :FOO, bar: :BAR, baz: :BAZ }, {}] }
end
# :only
it_behaves_like :transforming_immutable_data do
let(:options) { { only: [] } }
let(:output) { [{}, { foo: :FOO, bar: :BAR, baz: :BAZ }] }
end
it_behaves_like :transforming_immutable_data do
let(:options) { { only: :qux } }
let(:output) { [{}, { foo: :FOO, bar: :BAR, baz: :BAZ }] }
end
it_behaves_like :transforming_immutable_data do
let(:options) { { only: :foo } }
let(:output) { [{ foo: :FOO }, { bar: :BAR, baz: :BAZ }] }
end
it_behaves_like :transforming_immutable_data do
let(:options) { { only: [:foo, :bar, :qux] } }
let(:output) { [{ foo: :FOO, bar: :BAR }, { baz: :BAZ }] }
end
# :except
it_behaves_like :transforming_immutable_data do
let(:options) { { except: [] } }
let(:output) { [{ foo: :FOO, bar: :BAR, baz: :BAZ }, {}] }
end
it_behaves_like :transforming_immutable_data do
let(:options) { { except: :qux } }
let(:output) { [{ foo: :FOO, bar: :BAR, baz: :BAZ }, {}] }
end
it_behaves_like :transforming_immutable_data do
let(:options) { { except: :foo } }
let(:output) { [{ bar: :BAR, baz: :BAZ }, { foo: :FOO }] }
end
it_behaves_like :transforming_immutable_data do
let(:options) { { except: [:foo, :bar, :qux] } }
let(:output) { [{ baz: :BAZ }, { foo: :FOO, bar: :BAR }] }
end
# :except and :only
it_behaves_like :transforming_immutable_data do
let(:options) { { except: /z/, only: /b/ } }
let(:output) { [{ bar: :BAR }, { foo: :FOO, baz: :BAZ }] }
end
end # describe Faceter::Functions.split
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.