text stringlengths 10 2.61M |
|---|
class TracksController < ApplicationController
def show
@track = Track.find_by(id: params[:id])
render :show
end
# GET /tracks/new
def new
@track = Track.new
@parent_album = Album.find_by(id: params[:album_id])
render :new
end
# GET /tracks/1/edit
def edit
@track = Track.find_by(id: params[:id])
@parent_album = @track.album
render :new
end
# POST /tracks
# POST /tracks.json
def create
@track = Track.new(track_params)
if @track && @track.save
redirect_to track_url(@track)
else
flash[:errors] = @track.errors.full_messages
redirect_to new_album_track_url(params[:track][:album_id])
end
end
# PATCH/PUT /tracks/1
# PATCH/PUT /tracks/1.json
def update
@track = Track.find_by(id: params[:id])
if @track.update(track_params)
redirect_to track_url(@track)
else
flash[:errors] = @track.errors.full_messages
redirect_to edit_track(@track)
end
end
# DELETE /tracks/1
# DELETE /tracks/1.json
def destroy
@track = Track.find_by(id: params[:id])
@track.destroy
redirect_to album_url(@track.album)
end
private
def track_params
params.require(:track).permit(:title, :ord, :lyrics, :is_regular_track, :album_id)
end
end
|
# frozen_string_literal: true
#
# Include in specs for classes that are +AffiliateAccount+s.
# Tests here expect an instance variable +@account_attrs+ to
# exist. +@account_attrs+ should be a +Hash+ of attributes for
# #creating!ing an instance of the class being tested
module AffiliateAccountHelper
def self.included(base)
base.context "affiliates" do
before :each do
affiliate = Affiliate.create!(name: "Banana Video")
account_attrs = instance_variable_get(:@account_attrs).merge(affiliate: affiliate)
@affiliate_account = described_class.create!(account_attrs)
end
it { is_expected.to validate_presence_of(:affiliate_id) }
it "requires affiliate_other if affiliate is 'Other'" do
@affiliate_account.affiliate = Affiliate.OTHER
@affiliate_account.affiliate_other = nil
assert !@affiliate_account.save
expect(@affiliate_account)
.to validate_length_of(:affiliate_other).is_at_least(1)
end
it "does not require affiliate_other if affiliate is not 'Other'" do
expect(@affiliate_account.affiliate).to be_present
expect(@affiliate_account.affiliate).not_to be_other
expect(@affiliate_account).to be_valid
expect(@affiliate_account).not_to be_new_record
end
end
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"
remote_user = ENV['ANSIBLE_REMOTE_USER']
raise "You need to set ANSIBLE_REMOTE_USER in your shell" unless remote_user
# Add user #{remote_user} with group wheel
$create_user = <<SCRIPT
useradd -m -s /bin/bash -U #{remote_user}
usermod -a -G wheel #{remote_user}
SCRIPT
# Enable wheel group in sudoers
$enable_wheel = <<SCRIPT
sed -i -e "s/^# %wheel/%wheel/" /etc/sudoers
SCRIPT
# Set local id_rsa.pub as authorized_key for remote_user
$add_authorized_key = <<SCRIPT
rm -f /home/#{remote_user}/.ssh/authorized_keys
mkdir /home/#{remote_user}/.ssh
cp /home/vagrant/host_pubkey /home/#{remote_user}/.ssh/authorized_keys
chown #{remote_user}:#{remote_user} /home/#{remote_user}/.ssh/authorized_keys
chmod 600 /home/#{remote_user}/.ssh/authorized_keys
SCRIPT
# Remove local id_rsa.pub from image
$remove_host_pubkey = <<SCRIPT
rm -f /home/vagrant/host_pubkey
echo "id_rsa.pub installed for user #{remote_user}"
SCRIPT
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.provider :virtualbox do |vb|
vb.customize ['modifyvm', :id, '--natdnshostresolver1', 'on']
vb.name = 'centos6-influxdb'
end
config.vm.box = 'nrel/CentOS-6.5-x86_64'
config.vm.network :forwarded_port, guest: 8088, host: 8888 # Service
config.vm.network :forwarded_port, guest: 8083, host: 8883 # Web-Admin
config.vm.provision 'file',
run: 'once',
source: '~/.ssh/id_rsa.pub',
destination: '/home/vagrant/host_pubkey'
config.vm.provision 'shell', privileged: true, run: 'once', inline: $create_user
config.vm.provision 'shell', privileged: true, run: 'once', inline: $enable_wheel
config.vm.provision 'shell', privileged: true, run: 'once', inline: $add_authorized_key
config.vm.provision 'shell', privileged: true, run: 'once', inline: $remove_host_pubkey
end
|
class FirstAssociatesTransaction < ActiveRecord::Base
belongs_to :first_associates_report
has_one :reconciliation, class: FirstAssociatesReconciliation
def reconciled?
!!reconciliation && reconciliation.persisted?
end
def reconcile!(other_account_id, current_admin)
transaction do # database transaction, not financial transaction
create_reconciliation transaction_id: create_transaction(other_account_id).id,
admin_id: current_admin.id
end
end
private
def create_transaction(other_account_id)
Transaction.create credit_id: other_account_id,
debit_id: receivables_account_id,
amount: payment_amount,
paid_at: Time.now
end
def receivables_account_id
Account.first_associates_receivables.id
end
end
|
# Copyright (c) 2009-2011 VMware, Inc.
$:.unshift(File.dirname(__FILE__))
require 'spec_helper'
describe BackupManagerTests do
it "should be able to terminated while manager is sleeping" do
EM.run do
pid = Process.pid
manager = BackupManagerTests.create_manager("empty", "backups")
EM.defer do
manager.start rescue nil
end
EM.add_timer(1) { Process.kill("TERM", pid) }
EM.add_timer(5) do
manager.shutdown_invoked.should be_true
EM.stop
end
end
end
it "should be able to terminated while manager is running" do
EM.run do
pid = Process.pid
manager = BackupManagerTests.create_manager("cc_test", "backups")
EM.defer do
manager.start rescue nil
end
EM.add_timer(4) { Process.kill("TERM", pid) }
EM.add_timer(10) do
manager.shutdown_invoked.should be_true
EM.stop
end
end
end
it "should be able to generate varz_details" do
EM.run do
manager = BackupManagerTests.create_manager("empty", "backups")
EM.add_timer(1) do
varz = manager.varz_details
varz[:disk_total_size].length.should > 0
varz[:disk_used_size].length.should > 0
varz[:disk_available_size].length.should > 0
varz[:disk_percentage].length.should > 0
EM.stop
end
end
end
end
|
class Integer
def factorial
num = self
if num < 0
return "You can\'t take the factorial of a negative number!"
end
if num <= 1
1
else
num * (num-1).factorial
end
end
end
puts 4.factorial |
class PersonTypeOfBirth < ActiveRecord::Base
self.table_name = :person_type_of_births
self.primary_key = :person_type_of_birth_id
include EbrsMetadata
has_many :person_birth_details, foreign_key: "person_type_of_birth_id"
end
|
require "rubygems"
begin
require 'spec/rake/spectask'
rescue LoadError
desc "Run specs"
task(:spec) { $stderr.puts '`gem install rspec` to run specs' }
else
desc "Run API and Core specs"
Spec::Rake::SpecTask.new do |t|
t.spec_opts = ['--options', "\"#{File.dirname(__FILE__)}/spec/spec.opts\""]
t.spec_files = FileList['spec/public/**/*_spec.rb'] + FileList['spec/private/**/*_spec.rb']
end
desc "Run all specs in spec directory with RCov"
Spec::Rake::SpecTask.new(:rcov) do |t|
t.spec_opts = ['--options', "\"#{File.dirname(__FILE__)}/spec/spec.opts\""]
t.spec_files = FileList['spec/public/**/*_spec.rb'] + FileList['spec/private/**/*_spec.rb']
t.rcov = true
t.rcov_opts = lambda do
IO.readlines(File.dirname(__FILE__) + "/spec/rcov.opts").map {|l| l.chomp.split " "}.flatten
end
end
end
desc "Run everything against multiruby"
task :multiruby do
result = system "multiruby -S rake spec"
raise "Multiruby tests failed" unless result
result = system "jruby -S rake spec"
raise "JRuby tests failed" unless result
Dir.chdir "spec/integration/rails" do
result = system "multiruby -S rake test_unit:rails"
raise "Rails integration tests failed" unless result
result = system "jruby -S rake test_unit:rails"
raise "Rails integration tests failed" unless result
end
Dir.chdir "spec/integration/merb" do
result = system "multiruby -S rake spec"
raise "Merb integration tests failed" unless result
result = system "jruby -S rake spec"
raise "Rails integration tests failed" unless result
end
Dir.chdir "spec/integration/sinatra" do
result = system "multiruby -S rake test"
raise "Sinatra integration tests failed" unless result
result = system "jruby -S rake test"
raise "Sinatra integration tests failed" unless result
end
Dir.chdir "spec/integration/rack" do
result = system "multiruby -S rake test"
raise "Rack integration tests failed" unless result
result = system "jruby -S rake test"
raise "Rack integration tests failed" unless result
end
puts
puts "Multiruby OK!"
end
desc "Run each spec in isolation to test for dependency issues"
task :spec_deps do
Dir["spec/**/*_spec.rb"].each do |test|
if !system("spec #{test} &> /dev/null")
puts "Dependency Issues: #{test}"
end
end
end
namespace :spec do
desc "Run the integration specs"
task :integration => [
"integration:rack",
"integration:sinatra",
"integration:merb",
"integration:mechanize",
"integration:rails:webrat",
"integration:rails:selenium",
]
namespace :integration do
namespace :rails do
task :selenium do
Dir.chdir "spec/integration/rails" do
result = system "rake test_unit:selenium"
raise "Rails integration tests failed" unless result
end
end
task :webrat do
Dir.chdir "spec/integration/rails" do
result = system "rake test_unit:rails"
raise "Rails integration tests failed" unless result
end
end
end
desc "Run the Merb integration specs"
task :merb do
Dir.chdir "spec/integration/merb" do
result = system "rake spec"
raise "Merb integration tests failed" unless result
end
end
desc "Run the Sinatra integration specs"
task :sinatra do
Dir.chdir "spec/integration/sinatra" do
result = system "rake test"
raise "Sinatra integration tests failed" unless result
end
end
desc "Run the Sinatra integration specs"
task :rack do
Dir.chdir "spec/integration/rack" do
result = system "rake test"
raise "Rack integration tests failed" unless result
end
end
desc "Run the Mechanize integration specs"
task :mechanize do
Dir.chdir "spec/integration/mechanize" do
result = system "rake spec"
raise "Mechanize integration tests failed" unless result
end
end
end
end
desc 'Removes trailing whitespace'
task :whitespace do
sh %{find . -name '*.rb' -exec sed -i '' 's/ *$//g' {} \\;}
end
task :default => :spec |
# frozen_string_literal: true
require 'spec_helper'
require 'bolt_spec/conn'
require 'bolt_spec/files'
require 'bolt_spec/integration'
describe 'using module based plugins' do
include BoltSpec::Conn
include BoltSpec::Integration
def with_boltdir(config: nil, inventory: nil, plan: nil)
Dir.mktmpdir do |tmpdir|
File.write(File.join(tmpdir, 'bolt.yaml'), config.to_yaml) if config
File.write(File.join(tmpdir, 'inventory.yaml'), inventory.to_yaml) if inventory
if plan
plan_dir = File.join(tmpdir, 'modules', 'test_plan', 'plans')
FileUtils.mkdir_p(plan_dir)
File.write(File.join(plan_dir, 'init.pp'), plan)
end
yield tmpdir
end
end
let(:plugin_config) { {} }
let(:plugin_hooks) { {} }
let(:config) {
{ 'modulepath' => ['modules', File.join(__dir__, '../../fixtures/plugin_modules')],
'plugins' => plugin_config,
'plugin_hooks' => plugin_hooks }
}
let(:plan) do
<<~PLAN
plan test_plan() {
return(get_target('node1').password)
}
PLAN
end
let(:inventory) { {} }
around(:each) do |example|
with_boltdir(inventory: inventory, config: config, plan: plan) do |boltdir|
@boltdir = boltdir
example.run
end
end
let(:boltdir) { @boltdir }
context 'when resolving references' do
let(:plugin) {
{
'_plugin' => 'identity',
'value' => "ssshhh"
}
}
let(:inventory) {
{ 'targets' => [
{ 'uri' => 'node1',
'config' => {
'ssh' => {
'user' => 'me',
'password' => plugin
}
} }
] }
}
it 'supports a config lookup' do
output = run_cli(['plan', 'run', 'test_plan', '--boltdir', boltdir])
expect(output.strip).to eq('"ssshhh"')
end
context 'with bad parameters' do
let(:plugin) {
{
'_plugin' => 'identity',
'value' => 'something',
'unexpected' => 'foo'
}
}
it 'errors when the parameters dont match' do
result = run_cli_json(['plan', 'run', 'test_plan', '--boltdir', boltdir], rescue_exec: true)
expect(result).to include('kind' => "bolt/validation-error")
expect(result['msg']).to match(/Task identity::resolve_reference:\s*has no param/)
end
end
context 'with a bad result' do
let(:plugin) {
{
'_plugin' => 'bad_result',
'not_value' => 'secret'
}
}
it 'errors when the result is unexpected' do
result = run_cli_json(['plan', 'run', 'test_plan', '--boltdir', boltdir], rescue_exec: true)
expect(result).to include('kind' => "bolt/plugin-error")
expect(result['msg']).to match(/did not include a value/)
end
end
context 'when a task fails' do
let(:plugin) {
{
'_plugin' => 'error_plugin'
}
}
it 'errors when the task fails' do
result = run_cli_json(['plan', 'run', 'test_plan', '--boltdir', boltdir], rescue_exec: true)
expect(result).to include('kind' => "bolt/plugin-error")
expect(result['msg']).to match(/The task failed/)
end
end
end
context 'when a plugin requires config' do
let(:plugin) {
{
'_plugin' => 'conf_plug',
'value' => "ssshhh"
}
}
let(:inventory) {
{ 'targets' => [
{ 'uri' => 'node1',
'config' => {
'transport' => 'remote',
'remote' => {
'data' => plugin
}
} }
] }
}
let(:plan) do
<<~PLAN
plan test_plan() {
return(get_target('node1').config)
}
PLAN
end
it 'fails when config key is present in bolt_plugin.json' do
result = run_cli_json(['plan', 'run', 'test_plan', '--boltdir', boltdir], rescue_exec: true)
expect(result).to include('kind' => "bolt/invalid-plugin-data")
expect(result['msg']).to match(/Found unsupported key 'config'/)
end
context 'with values specified in both bolt.yaml and inventory.yaml' do
context 'and merging config' do
let(:plugin) { { '_plugin' => 'task_conf_plug', 'optional_key' => 'keep' } }
let(:plugin_config) { { 'task_conf_plug' => { 'required_key' => 'foo', 'optional_key' => 'clobber' } } }
it 'merges parameters set in config and does not pass _config' do
result = run_cli_json(['plan', 'run', 'test_plan', '--boltdir', boltdir])
expect(result['remote']['data']).not_to include('_config' => plugin_config['conf_plug'])
expect(result['remote']['data']).to include('_boltdir' => boltdir)
expect(result['remote']['data']).to include('required_key' => 'foo')
expect(result['remote']['data']).to include('optional_key' => 'keep')
end
end
context 'and using task metadata alone for config validation for expected success' do
let(:plugin) { { '_plugin' => 'task_conf_plug', 'required_key' => 'foo' } }
let(:plugin_config) { { 'task_conf_plug' => { 'optional_key' => 'bar' } } }
it 'treats all required values from task paramter metadata as optional' do
result = run_cli_json(['plan', 'run', 'test_plan', '--boltdir', boltdir])
expect(result['remote']['data']).not_to include('_config' => plugin_config['conf_plug'])
expect(result['remote']['data']).to include('_boltdir' => boltdir)
expect(result['remote']['data']).to include('required_key' => 'foo')
expect(result['remote']['data']).to include('optional_key' => 'bar')
end
end
context 'and using task metadata alone for config validation for expected failure' do
let(:plugin) { { '_plugin' => 'task_conf_plug' } }
let(:plugin_config) { { 'task_conf_plug' => { 'random_key' => 'bar' } } }
it 'forbids config entries that do not match task metadata schema' do
result = run_cli_json(['plan', 'run', 'test_plan', '--boltdir', boltdir], rescue_exec: true)
expect(result).to include('kind' => "bolt/validation-error")
expect(result['msg']).to match(/Config for task_conf_plug plugin contains unexpected key random_key/)
end
end
end
context 'with multiple task schemas to validate against' do
context 'with valid type String string set in config and overriden in inventory' do
let(:plugin) {
{
'_plugin' => 'task_conf_plug',
'required_key' => "foo",
'intersection_key' => 1
}
}
let(:plugin_config) { { 'task_conf_plug' => { 'intersection_key' => 'String' } } }
it 'allows valid type in bolt.yaml and expected value is overriden in inventory' do
result = run_cli_json(['plan', 'run', 'test_plan', '--boltdir', boltdir])
expect(result['remote']['data']).to include('_boltdir' => boltdir)
expect(result['remote']['data']).to include('required_key' => 'foo')
expect(result['remote']['data']).to include('intersection_key' => 1)
end
end
end
end
context 'when handling secrets' do
it 'calls the encrypt task' do
result = run_cli(['secret', 'encrypt', 'secret_msg', '--plugin', 'my_secret', '--boltdir', boltdir],
outputter: Bolt::Outputter::Human)
# This is kind of brittle and we look for plaintext_value because this is really the identity task
expect(result).to match(/"plaintext_value"=>"secret_msg"/)
end
it 'calls the decrypt task' do
result = run_cli(['secret', 'decrypt', 'secret_msg', '--plugin', 'my_secret', '--boltdir', boltdir],
outputter: Bolt::Outputter::Human)
# This is kind of brittle and we look for "encrypted_value because this is really the identity task
expect(result).to match(/"encrypted_value"=>"secret_msg"/)
end
end
context 'when managing puppet libraries' do
# TODO: how do we test this cheaply?
end
context 'when manageing puppet_library', docker: true do
let(:plan) do
<<~PLAN
plan test_plan() {
apply_prep('ubuntu_node')
}
PLAN
end
let(:inventory) { docker_inventory(root: true) }
context 'with an unsupported hook' do
let(:plugin_hooks) {
{
'puppet_library' => {
'plugin' => 'identity'
}
}
}
it 'fails cleanly' do
result = run_cli_json(['plan', 'run', 'test_plan', '--boltdir', boltdir], rescue_exec: true)
expect(result).to include('kind' => "bolt/run-failure")
expect(result['msg']).to match(/Plan aborted: apply_prep failed on 1 target/)
expect(result['details']['result_set'][0]['value']['_error']['msg']).to match(
/Plugin identity does not support puppet_library/
)
end
end
context 'with an unknown plugin' do
let(:plugin_hooks) {
{
'puppet_library' => {
'plugin' => 'does_not_exist'
}
}
}
it 'fails cleanly' do
result = run_cli_json(['plan', 'run', 'test_plan', '--boltdir', boltdir], rescue_exec: true)
expect(result).to include('kind' => "bolt/run-failure")
expect(result['msg']).to match(/Plan aborted: apply_prep failed on 1 target/)
expect(result['details']['result_set'][0]['value']['_error']['msg']).to match(/Unknown plugin:/)
end
end
context 'with a failing plugin' do
let(:plugin_hooks) {
{
'puppet_library' => {
'plugin' => 'error_plugin'
}
}
}
it 'fails cleanly' do
result = run_cli_json(['plan', 'run', 'test_plan', '--boltdir', boltdir], rescue_exec: true)
expect(result).to include('kind' => "bolt/run-failure")
expect(result['msg']).to match(/Plan aborted: apply_prep failed on 1 target/)
expect(result['details']['result_set'][0]['value']['_error']['msg']).to match(
/The task failed with exit code 1/
)
end
end
end
end
|
require 'date'
class Puppet < Botpop::Plugin
include Cinch::Plugin
match(/^!pm (\#*\w+) (.*)/, use_prefix: false, method: :send_privmsg)
match(/^!join (\#\w+)/, use_prefix: false, method: :join)
match(/^!part (\#\w+)/, use_prefix: false, method: :part)
# Email handlement
EMAIL = '[[:alnum:]\.\-_]{1,64}@[[:alnum:]\.\-_]{1,64}'
NICK = '\w+'
# Registration of an email address - association with authname
match(/^!mail register (#{EMAIL})$/, use_prefix: false, method: :register)
match(/^!mail primary (#{EMAIL})$/, use_prefix: false, method: :make_primary)
# Send email to user through its nickname (not safe)
match(/^!(mail )?(let|send) (#{NICK}) (.+)/, use_prefix: false, method: :let)
# Send email to user through one of its emails (safe)
match(/^!(mail )?(let|send) (#{EMAIL}) (.+)/, use_prefix: false, method: :let)
# Read email (based on nickname, authname, and emails)
match(/^!(mail )?r(ead)?$/, use_prefix: false, method: :read)
HELP = ["!pm <#chat/nick> <message>", "!join <#chan>", "!part <#chan>", "!let <to> msg", "!read"] +
["!mail read", "!mail send/let <...>", "!mail register address"]
ENABLED = config['enable'].nil? ? false : config['enable']
CONFIG = config
def send_privmsg m, what, message
if what.match(/^\#.+/)
send_privmsg_to_channel(what, message)
else
send_privmsg_to_user(what, message)
end
end
def join m, chan
Channel(chan).join
end
def part m, chan
Channel(chan).part
end
def register m, email
begin
Base::DB[:emails].insert(authname: m.user.authname,
address: email,
created_at: Time.now.utc,
usage: 0)
rescue => _
return m.reply "Error, cannot register this email !"
end
return m.reply "Email #{email} registered for you, #{m.user.authname}"
end
def make_primary m, email
a = get_addresses(m.user).where(address: email)
return m.reply "No your email #{email}" if a.first.nil?
get_addresses(m.user).update(primary: false)
a.update(primary: true)
m.reply "Your primary email #{m.user.nick} is now #{email}"
end
def let m, _, _, to, msg
log "New message addressed to #{to} to send"
# insert new message in database
from = Base::DB[:emails].where(authname: m.user.authname, primary: true).select(:address).first
from = from && from[:address] || m.user.nick
Base::DB[:messages].insert(author: from,
dest: to,
content: msg.strip,
created_at: Time.now,
read_at: nil)
Base::DB[:emails].where(address: to).update('usage = usage+1')
end
def read m, _
msg = get_messages(m.user).first
if msg.nil?
send_privmsg_to_user m.user, "No message."
return
end
Base::DB[:messages].where(id: msg[:id]).update(read_at: Time.now)
date = msg[:created_at]
if Date.parse(Time.now.to_s) == Date.parse(date.to_s)
date = date.strftime("%H:%M:%S")
else
date = date.strftime("%B, %d at %H:%M:%S")
end
send_privmsg_to_user m.user, "##{msg[:id]}# #{date} -- from #{msg[:author]}"
send_privmsg_to_user m.user, msg[:content]
end
listen_to :join, method: :bip_on_join
def bip_on_join m
nb = Base::DB[:messages].where(dest: m.user.nick, read_at: nil).count
send_privmsg_to_user m.user, "#{m.user.nick}: You have #{nb} message unread." unless nb.zero?
end
private
def send_privmsg_to_channel chan, msg
Channel(chan).send(msg.strip)
end
def send_privmsg_to_user user, msg
User(user).send(msg.strip)
end
def get_messages user
emails = Base::DB[:emails].where(authname: user.authname).select(:address).all.map(&:values).flatten
Base::DB[:messages].where(dest: [user.nick, user.authname] + emails).where(read_at: nil)
end
def get_addresses user
Base::DB[:emails].where(authname: user.authname)
end
end
|
class LibraryBuildingDe < ActiveRecord::Base
# Relations
belongs_to :library_building
end |
=begin
Основная идея в том, что в треде дергаем set_lock чтобы привязать коннектор к треду.
Пока тред не закончил работу или не дернули в нем release_lock
коннектор пропускается при выборе.
Выдвать коннекторы надо из main треда.
Верней лучше из того потока где менеджер создан.
Чтобы не получать 1 коннектор в разных потоках. Я обычно так делаю:
if conn = cm.get_connector
treads << Thread.new do
conn.set_lock
...
end
Собственно dummy_lock нужен для того чтобы зарезервировать коннектор.
Если тред его не перехватил, то dummy тред сам умрет и коннектор снова будет доступен
=end
class Connector
attr_reader :thread
def initialize(&block)
@thread = nil
@connector = yield
end
def set_dummy_lock(lock)
@thread = Thread.new { sleep lock }
end
def set_lock
@thread = Thread.current
end
def release_lock
@thread = nil
end
def locked?
if @thread and @thread.alive?
return true
else
return false
end
end
def connector
if @thread == Thread.current
@connector
end
end
end
class ConnectionManager
def initialize(size, dummy_lock = 0.5, &block)
if not size
raise ArgumentError, "No pool size given!"
end
@pool = Array.new
@dummy_lock = dummy_lock
size.times do
@pool << Connector.new(&block)
end
end
def get_connector
if idx = @pool.index { |connector| not connector.locked? }
@pool[idx].set_dummy_lock(@dummy_lock)
return @pool[idx]
else
return false
end
end
def get_connector_via_cycle(pause = 0.1)
idx = @pool.index { |connector| not connector.locked? }
while not idx
sleep pause
idx = @pool.index { |connector| not connector.locked? }
end
@pool[idx].set_dummy_lock(@dummy_lock)
return @pool[idx]
end
def get_info
@pool.each_index do |idx|
puts "Connection ##{idx}: #{@pool[idx].thread} "
end
end
end
|
module API
# Timesheets API
class Timesheets < Grape::API
before { authenticate! }
helpers do
def compute_end(start)
endDate = DateTime.strptime(start, "%Y%m%d")
endDate += 6.days
endDate.strftime("%Y%m%d")
end
def find_member(project_id, user_id)
ProjectMember.where("user_id=? and project_id=?", user_id, project_id).first
end
end
resource :projects do
desc "Returns all tasks for a given period."
get ":id/timesheets/:start/tasks" do
authorize! :read_project, user_project
period_start = params[:start]
period_end = compute_end(period_start)
user_id = params[:user_id] || current_user.id
member = find_member(params[:id], user_id)
tasks = member.assigned_tasks
timesheet_tasks = []
tasks.each do |task|
timesheet_task = TimesheetTask.new(task, period_start, period_end)
timesheet_tasks << timesheet_task
end
present timesheet_tasks, with: Entities::TimesheetTask
end
end
end
end
|
# require 'active_support/all'
class Player
attr_accessor :live, :name, :id
def initialize(live, name, id)
@live = live
@id = id
@name = "Player #{name}"
end
def name=(name)
@name = name
end
def live_update
@live = @live - 1
end
end
|
class AddWeightToOrderItem < ActiveRecord::Migration
def self.up
add_column :order_items, :product_weight, :integer,:default=>0
end
def self.down
remove_column :order_items, :product_weight
end
end
|
class CreateMatch < ActiveRecord::Migration
def change
create_table :matches do |t|
t.integer :result
t.datetime :date_played
t.references :home_team, index: true
t.references :visitor_team, index: true
t.references :toto_form, index: true
end
end
end
|
# == Schema Information
#
# Table name: characters
#
# banner_id :integer
# created_at :datetime not null
# description :text
# id :integer not null, primary key
# is_deleted :boolean default(FALSE)
# name :string
# slug :string
# species :string
# updated_at :datetime not null
# user_id :integer
# visible :boolean default(FALSE)
#
class Character < ApplicationRecord
### Model Config ###
### Modules ###
include Filterable
include SanitizedFilterable
include Illustrable
extend FriendlyId
### Constants ###
### Associations ###
belongs_to :user
belongs_to :banner, -> { where(is_deleted: false) }, class_name: "Asset"
has_many :quotation_characters, dependent: :destroy
has_many :quotations, through: :quotation_characters, dependent: :destroy
has_many :character_assets, dependent: :destroy, inverse_of: :character
has_many :assets, -> { where(is_deleted: false) }, through: :character_assets, dependent: :destroy
### Macros ###
friendly_id :slug_candidates, use: [:slugged, :finders, :history]
filterable :user_id, :name, :species
accepts_nested_attributes_for :character_assets, allow_destroy: true
### Scopes ###
### Validations ###
validates :name, presence: true, length: { maximum: 100 }
validates :species, presence: true, length: { maximum: 100 }
validates :description, length: { maximum: 50000 }
### Callbacks ###
### State machines ###
### Class methods ###
### Instance Methods ###
private
def should_generate_new_friendly_id?
name_changed? || species_changed?
end
def slug_candidates
siblings = Character.sanitized_filter(name: name)
if species.present?
siblings = siblings.sanitized_filter(species: species)
end
[
:name,
[:name, :species],
[:name, :species, siblings.count],
[:name, siblings.count]
]
end
end
|
class FundingLevel < ActiveRecord::Base
belongs_to :project
has_many :pledges
validates :project, :presence => true
validates :reward_name, length: { minimum: 3 }
validates :amount, numericality: { greater_than: 0 }
end
|
require 'test_helper'
class CassandraObject::BaseTest < CassandraObject::TestCase
class Son < CassandraObject::Base
end
class Grandson < Son
end
test 'base_class' do
assert_equal CassandraObject::Base, CassandraObject::Base
assert_equal Son, Son.base_class
assert_equal Son, Grandson.base_class
end
test 'column family' do
assert_equal 'CassandraObject::BaseTest::Sons', Son.column_family
assert_equal 'CassandraObject::BaseTest::Sons', Grandson.column_family
end
test 'custom cassandra configuration' do
assert_equal IssueCustomConfig.config, IssueCustomConfig.custom_config
assert_not_equal CassandraObject::Base.config, IssueCustomConfig.config
end
end
|
class PemFilesController < ApplicationController
skip_before_action :verify_authenticity_token
before_action :set_pem_file, only: [:show, :edit, :update, :destroy]
# GET /pem_files
# GET /pem_files.json
def index
@pem_file = PemFile.where(email: session[:user_email]).where(status: PemFile::ACTIVE).last
end
# GET /pem_files/1
# GET /pem_files/1.json
def show
end
# GET /pem_files/new
def new
@pem_file = PemFile.new
end
# GET /pem_files/1/edit
def edit
end
# POST /pem_files
# POST /pem_files.json
def create
require 'openssl'
password = params[:password]
prefix_file_name = session[:user_email].split('@').first
key_temp = Rails.root.join(pem_file_params[:private_key].tempfile)
cer_temp = Rails.root.join(pem_file_params[:public_key].tempfile)
key_success = system "openssl pkcs8 -inform DER -in #{key_temp} -out public/#{prefix_file_name}_open.key.pem -passin pass:#{password}"
key_success = system "openssl rsa -in public/#{prefix_file_name}_open.key.pem -out public/#{prefix_file_name}.key.pem -aes256 -passout pass:#{password}"
cer_success = system "openssl x509 -inform DER -outform PEM -in #{cer_temp} -pubkey > public/#{prefix_file_name}.cer.pem"
serial_out = `openssl x509 -in public/#{prefix_file_name}.cer.pem -serial -noout`
# Quitar 3 en caracteres nones del serial
serial_out = serial_out[7..-1]
n = 1
serial_cer = ''
serial_out.each_char { |c|
if n % 2 == 0
serial_cer += c
end
n += 1
}
if key_success && cer_success
@pem_file = PemFile.new(
private_key_open:File.read("public/#{prefix_file_name}_open.key.pem"),
private_key:File.read("public/#{prefix_file_name}.key.pem"),
public_key:File.read("public/#{prefix_file_name}.cer.pem"),
cer64:Base64.encode64(File.read(cer_temp)),
serial: serial_cer,
email: session[:user_email]
)
if @pem_file.save
redirect_to root_path, notice: 'PEM creado exitósamente'
else
redirect_to root_path, alert: 'Asegúrese que la contraseña corresponda a los archivos'
end
else
redirect_to root_path, alert: 'Asegúrese que la contraseña corresponda a los archivos'
end
system "rm #{Rails.root.join("public","#{prefix_file_name}*")}"
end
# PATCH/PUT /pem_files/1
# PATCH/PUT /pem_files/1.json
def update
respond_to do |format|
if @pem_file.update(pem_file_params)
format.html {redirect_to @pem_file, notice: 'Se actualizó el PEM'}
format.json {render :show, status: :ok, location: @pem_file}
else
format.html {render :edit}
format.json {render json: @pem_file.errors, status: :unprocessable_entity}
end
end
end
# DELETE /pem_files/1
# DELETE /pem_files/1.json
def destroy
@pem_file.update(status: PemFile::DELETED)
respond_to do |format|
format.html {redirect_to pem_files_url, notice: 'Se eliminaron los archivos PEM'}
format.json {head :no_content}
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_pem_file
@pem_file = PemFile.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def pem_file_params
params.require(:pem_file).permit(:email, :status, :private_key, :public_key)
end
end
|
class CreateTrackers < ActiveRecord::Migration
def change
create_table :trackers do |t|
t.string :driver_name
t.string :mobile_number
t.string :imei
t.string :truck_registration_number
t.timestamps
end
end
end
|
class AddApprovedColumnsToMemberApplications < ActiveRecord::Migration[5.0]
def change
add_column :member_applications, :approved_at, :datetime
add_column :member_applications, :approver_id, :integer
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby sw=2 ts=2 sts=2 et :
# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
# root off of the rackspace provider dummy box
config.vm.box = "dummy"
# rackspace systems even with cloud-init
# don't seem to have the cloud init user ${osname}
# getting the ssh key for some reason, root does
# so use that
config.ssh.username = 'root'
# DEPRECATED
# ==========
#
# NOTE: The Rackspace provider section is deprecated as we are moving into a
# private OpenStack cloud. It may be revived after we've migrated and have a
# chance to do work to reconfigure the Rackspace public cloud to work for
# burst access
#
# make sure to set the following in your
# ~/.vagrant.d/boxes/dummy/0/rackspace/Vagrantfile
# rs.username
# rs.api_key
# rs.rackspace_region
#
# If you are not using a SSH token / smartcard also set this
# rs.key_name
# config.ssh.private_key_path -- set this outside the rackspace block
# in your base box
config.vm.provider :rackspace do |rs|
# create these base builds always on the smallest system possible
rs.flavor = 'general1-1'
# allow for switching to ORD cloud but default to DFW
if (ENV['RSREGION'] == 'ord')
rs.rackspace_region = :ord
else
rs.rackspace_region = :dfw
end
# Default to the Fedora 20 image unless overridden by a RSIMAGE
# environment variable
if ENV['IMAGE']
rs.image = ENV['IMAGE']
else
rs.image = 'Fedora 20 (Heisenbug) (PVHVM)'
end
end
# /DEPRECATED
# Configuration used by ODL Private cloud
# Should be mostly usable by any OpenStack cloud that can
# utilize upstream cloud images
config.vm.provider :openstack do |os, override|
if ENV['BOX']
override.vm.box = ENV['BOX']
else
override.vm.box = 'dummy'
end
config.ssh.username = 'centos'
os.flavor = 'm1.small'
# require an IMAGE to be passed in
# IMAGE must be a human name and not an image ID!
if ENV['IMAGE']
os.image = ENV['IMAGE']
else
os.image = 'BAD IMAGE'
override.ssh.username = 'baduser'
end
case ENV['IMAGE']
when /.*ubuntu.*/i
override.ssh.username = 'ubuntu'
when /.*fedora.*/i
override.ssh.username = 'fedora'
# take care of the tty requirement by fedora for sudo
os.user_data = "#!/bin/bash
/bin/sed -i 's/ requiretty/ !requiretty/' /etc/sudoers;"
when /.*centos.*/i
override.ssh.username = 'centos'
# take care of the tty requirement by centos for sudo
os.user_data = "#!/bin/bash
/bin/sed -i 's/ requiretty/ !requiretty/' /etc/sudoers;"
end
end
# Do a full system update and enable enforcing if needed
config.vm.provision 'shell', path: '../lib/baseline.sh'
# Execute a system clean-up in prep for imaging so that this base
# image can be used for other Rackspace Vagrant configurations
config.vm.provision 'shell', path: '../lib/system_reseal.sh'
end
|
require 'rails_helper'
feature 'Twilio' do
let(:message_params) { twilio_new_message_params }
let(:status_params) { twilio_status_update_params from_number: message_params['From'], sms_sid: message_params['SmsSid'] }
before do
userone = create :user
clientone = create :client, user: userone, phone_number: message_params['From']
rr = ReportingRelationship.find_by(user: userone, client: clientone)
create :text_message, reporting_relationship: rr, twilio_sid: message_params['SmsSid'], twilio_status: 'queued'
end
after do
twilio_clear_after
end
describe 'POSTs to #incoming_sms_status' do
context 'with incorrect signature' do
it 'returns a forbidden response' do
# send false as 2nd argument to send bad signature
twilio_post_sms_status status_params, false
expect(page).to have_http_status(:forbidden)
end
end
context 'with correct signature' do
it 'returns a no content response' do
twilio_post_sms_status status_params
expect(page).to have_http_status(:no_content)
end
end
context 'many requests at once', :js do
let(:user) { create :user }
let(:client) { create :client, user: user }
let(:rr) { ReportingRelationship.find_by(user: user, client: client) }
before do
visit root_path
end
it 'handles it' do
message = create :text_message, reporting_relationship: rr, inbound: false, twilio_status: 'queued'
threads = %w[first second third fourth].each_with_index.map do |status, i|
Thread.new do
status_params = twilio_status_update_params(
to_number: message.number_to,
sms_sid: message.twilio_sid,
sms_status: status
)
twilio_post_sms_status status_params, true, 'X-Request-Start' => "151752434924#{i}"
end
end
threads.map(&:join)
expect(message.reload.twilio_status).to eq 'fourth'
end
end
end
end
|
# Replace in the "<???>" with the appropriate method (and arguments, if any).
# Uncomment the calls to catch these methods red-handed.
# When there's more than one suspect who could have
# committed the crime, add additional calls to prove it.
<<<<<<< HEAD
p "iNvEsTiGaTiOn".swapcase
# => "InVeStIgAtIoN”
p "zom".insert(1 , "o")
# => "zoom”
p "enhance".center(15)
p "enhance".rjust(11, " ").ljust(15, " ")
#=> " enhance ”
p "Stop! You're under arrest!".upcase
# => "STOP! YOU’RE UNDER ARREST!”
p "the usual".concat(" suspects")
#=> "the usual suspects”
p " suspects".prepend("the usual")
#=> "the usual suspects”
p "The case of the disappearing last letter".chomp('r')
p "The case of the disappearing last letter".chop
# => "The case of the disappearing last lette”
p "The mystery of the missing first letter".slice(1..38)
# => "he mystery of the missing first letter”
p "Elementary , my dear Watson!".squeeze(' ')
# => Elementary, my dear Watson!”
p "z".sum
=======
# "iNvEsTiGaTiOn".<???>
# => “InVeStIgAtIoN”
# "zom".<???>
# => “zoom”
# "enhance".<???>
# => " enhance "
# "Stop! You’re under arrest!".<???>
# => "STOP! YOU’RE UNDER ARREST!"
# "the usual".<???>
#=> "the usual suspects"
# " suspects".<???>
# => "the usual suspects"
# "The case of the disappearing last letter".<???>
# => "The case of the disappearing last lette"
# "The mystery of the missing first letter".<???>
# => "he mystery of the missing first letter"
# "Elementary, my dear Watson!".<???>
# => "Elementary, my dear Watson!"
# "z".<???>
>>>>>>> 5aa68c0652e70fe28c68f5efbaf0a1a869c73beb
# => 122
# (That is where z falls in line of all characters that can be understood
# from what I've found it starts with special characters, then caps, then lowercase)
<<<<<<< HEAD
p "How many times does the letter 'a' appear in this string?".count("a")
#=> 4
=======
# "How many times does the letter 'a' appear in this string?".<???>
# => 4
>>>>>>> 5aa68c0652e70fe28c68f5efbaf0a1a869c73beb
|
class ScoresController < ApplicationController
before_action :set_score, only: [:show, :edit, :update, :destroy]
before_action :set_team
before_action :set_cheats, only: [:new, :edit]
before_action :set_holes, only: [:new, :edit]
before_action :restore_cheats, only: [:destroy]
after_action :update_cheats, only: [:create, :update]
def index
@scores = Score.where(team: @team)
end
def show
end
def new
@score = Score.new
if isAuthorized(current_team)
else
redirect_to @team
end
end
def edit
if isAuthorized(current_team)
else
redirect_to @team
end
end
def create
if isAuthorized(current_team)
@score = Score.new(score_params)
@score.team_id = @team.id
@score.tournament_id = @team.tournament.id
@score.course_id = @team.tournament.course.id
respond_to do |format|
if @score.save
if admin_signed_in?
format.html { redirect_to team_scores_path, notice: 'Score was successfully created.' }
else
format.html { redirect_to @team, notice: 'Score was successfully created.' }
end
else
format.html { render :new }
end
end
else
redirect_to @team
end
end
def update
if isAuthorized(current_team)
respond_to do |format|
if @score.update(score_params)
format.html { redirect_to @team, notice: 'Score was successfully updated.' }
else
format.html { render :edit }
end
end
else
redirect_to @team
end
end
def destroy
if isAuthorized(current_team)
@score.destroy
respond_to do |format|
if admin_signed_in?
format.html { redirect_to team_scores_path, notice: 'Score was successfully deleted.' }
else
format.html { redirect_to @team, notice: 'Score was successfully deleted.' }
end
end
else
redirect_to @team
end
end
private
def update_cheats
@cheats = params[:score_cheat]
if !@cheats.blank?
@cheats.each do |cheat|
@thisCheat = Cheat.find(cheat.first)
@thisCheat.update(used: cheat.last)
if cheat.last
@thisCheat.update(score: @score)
end
end
end
end
def restore_cheats
@score.team.cheats.where(score_id: @score.id).update_all({ :used => false, :score_id => nil})
end
def set_score
@score = Score.find(params[:id])
end
def set_team
@team = Team.find(params[:team_id])
end
def set_cheats
@cheats = @team.cheats.where(used: false).sort{ |a,b| a.cheat_type.name <=> b.cheat_type.name }
end
def set_holes
if @team.tournament.holescope == 'front'
@holes = @team.tournament.course.holes.frontNine
elsif @team.tournament.holescope == 'back'
@holes = @team.tournament.course.holes.backNine
else
@holes = @team.tournament.course.holes
end
end
def score_params
params.require(:score).permit(:score, :hole_id, :course_id, :tournament_id, :team_id)
end
end
|
# caesar.rb
#
# Description:: Basic caesar-like cipher
# Author:: Ollivier Robert <roberto@keltia.net>
# Copyright:: 2001-2013 © by Ollivier Robert
#
# $Id: caesar.rb,v 9ea677b34eed 2013/03/10 18:49:14 roberto $
require 'key/caesar'
require 'cipher/subst'
module Cipher
# == Caesar
#
# Caesar cipher, monoalphabetic substitution, offset is 3
#
class Caesar < Substitution
# === initialize
#
def initialize(offset = 3)
@key = Key::Caesar.new(offset)
end # -- initialize
end # -- Caesar
end # -- Cipher
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
# bootstrap script partially copied from https://github.com/Lukx/vagrant-lamp
$script = <<SCRIPT
apt-get update
apt-get -y install git mc golang
apt-get -y install mercurial meld
export GOPATH=~/
echo export GOPATH=$GOPATH >> ~/.bash_profile
export PATH="$PATH:$GOPATH/bin"
echo 'export PATH="$PATH:$GOPATH/bin"' >> ~/.bash_profile
go get github.com/revel/cmd/revel
SCRIPT
# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = "ubuntu/trusty64"
config.vm.network :forwarded_port, host: 6666, guest: 80
config.vm.synced_folder "./", "/home/vagrant"
#config.vm.provider "virtualbox" do |v|
# v.name = "hackaton_vm" # PROJECT NAME PUT HERE
#end
# provisioner config
config.vm.provision "shell", inline: $script
end |
class Ipbt < Formula
desc "Program for recording a UNIX terminal session"
homepage "https://www.chiark.greenend.org.uk/~sgtatham/ipbt/"
url "https://www.chiark.greenend.org.uk/~sgtatham/ipbt/ipbt-20170829.a9b4869.tar.gz"
mirror "https://dl.bintray.com/homebrew/mirror/ipbt-20170829.tar.gz"
version "20170829"
sha256 "80b0c131ceec6f9fb36e551dfb8e63e993efdd2b33c063fd3d77bca32df36409"
bottle do
cellar :any_skip_relocation
sha256 "cba6cc9d871841e1279a7560fd23d9781460c276c93382c32802fdad20ed51f3" => :sierra
sha256 "4086610a0a5a0f531fe48ead28bd89b7457a1b46dfbf3f399c520c56358c5d1b" => :el_capitan
sha256 "f1db5a7998dfdea0960c1eddc97d0534d735ffa92f367c2d1cd4e5f5cf2c6e2f" => :yosemite
end
def install
system "./configure", "--prefix=#{prefix}",
"--disable-dependency-tracking"
system "make", "install"
end
test do
system "#{bin}/ipbt"
end
end
|
# frozen_string_literal: true
FactoryBot.define do
factory :collaborator do
name { Faker::Company.name }
email { Faker::Internet.safe_email }
company
manager { nil }
end
end
|
class ChangeMessageDefaultValues < ActiveRecord::Migration[5.0]
def change
change_column_default :messages, :approved, true
change_column_default :messages, :votes, 0
end
end
|
require 'spec_helper'
describe Artist do
let(:subject) { Artist.new(:similar_artists => [@similar_artist_name]) }
before(:each) do
@first_song = double
@second_song = double
@first_album = double(:tracks => [@first_song], :original_tracks => [@first_song])
@second_album = double(:tracks => [@first_song, @second_song], :original_tracks => [@first_song, @second_song])
@similar_artist_name = double
@similar_artist_result = double(:id => double, :photo_url => double, :to_s => double)
subject.stub!(
:albums => [@first_album, @second_album],
:photo => double(:url => double)
)
end
describe "#to_s" do
it "titlecases the name of the artist" do
artist_title = double
subject.stub_chain(:name, :titlecase).and_return(artist_title)
subject.to_s.should == artist_title
end
end
describe "#tracks" do
it "returns unique tracks for albums" do
subject.tracks.should == [@first_song, @second_song]
end
end
describe "#similar_artists" do
it "attempts to find an artist" do
Artist.should_receive(:find_by_name).with(@similar_artist_name).and_return(@similar_artist_result)
subject.similar_artists.should == [@similar_artist_result]
end
it "removes nil artist search results" do
Artist.should_receive(:find_by_name).with(@similar_artist_name).and_return(nil)
subject.similar_artists.should == []
end
end
describe "#similar_artists_to_json" do
it "returns an array of hashes of needed artist data" do
similar_artist_to_h = {
:id => @similar_artist_result.id,
:photo_url => @similar_artist_result.photo_url,
:to_s => @similar_artist_result.to_s
}
subject.should_receive(:similar_artists).and_return([@similar_artist_result])
subject.similar_artists_to_json.should == [similar_artist_to_h]
end
end
describe "#sync_to_remote_data_source" do
# ...
end
describe "#notify_tracks_to_sync" do
it "calls Track#sync_to_remote_data_source on all uniq tracks" do
@first_song.should_receive(:sync_to_remote_data_source)
@second_song.should_receive(:sync_to_remote_data_source)
subject.send(:notify_tracks_to_sync)
end
end
describe "#photo_url" do
it "returns the url of the photo (for json)" do
subject.send(:photo_url).should == subject.photo.url
end
end
end
|
module Troles::Adapters::ActiveRecord
class Config < Troles::Common::Config
attr_reader :models
def initialize subject_class, options = {}
super
puts "models classes: #{subject_class}, #{object_model}, #{join_model}"
@models = ::Schemaker::Models.new(subject_class, object_model, join_model)
end
def configure_relation
case strategy
when :join_ref_many
configure_join_model
when :ref_many
return configure_join_model if join_model?
subject.quick_join
when :embed_many
raise "Embed many configuration not yet implemented for ActiveRecord"
end
end
# AR sets this up ont its own using DB Table info
def configure_field
end
protected
def subject
@subject ||= models.subject_model
end
def main_field
role_field
end
def join_model
@join_model_found ||= begin
find_first_class(@join_model, join_model_best_guess)
end
rescue ClassExt::ClassNotFoundError
nil
end
def join_model?
join_model
end
def join_model_best_guess
"#{subject_class.to_s.pluralize}#{object_model.to_s.pluralize}"
end
def join_model= model_class
@join_model = model_class and return if model_class.any_kind_of?(Class, String, Symbol)
raise "The join model must be a Class, was: #{model_class}"
end
def join_key
make_key join_model
end
def configure_join_model
if Troles::Common::Config.log_on?
puts "configuring join model..."
puts "Subject class: #{subject_class}"
puts "Role class: #{object_model}"
puts "Join class: #{join_model}"
end
[:object, :subject, :join].each do |type|
clazz = "Schemaker::#{type.to_s.camelize}Model".constantize
clazz.new(model).configure
end
end
end
end |
class Api::V1::TracksController < ApplicationController
private
def track_params
params.require(:track).permit(:name, :length)
params.permit(:query)
end
end
|
# EXCERXCISE 4
1. "FALSE"
2. "did you get it right?"
3. "Alright now!"
# EXCERCISE 5
"You get this error message because this is no reserve word 'end',
for the if/else statement. It is expecting the keyword 'end' to close
equal_to_four method. That 'end' was not found. We want to place the additional
'end' on line 6, indented to the same as the if/else statement."
# EXERECISE 6
1. error
2. false
3. false
4. true
5. false
6. true |
class Cart
attr_reader :id
attr_accessor :x, :y, :dir, :turns
LEFT = {
"^" => "<",
"v" => ">",
"<" => "v",
">" => "^",
}
RIGHT = {
"^" => ">",
"v" => "<",
"<" => "^",
">" => "v",
}
def self.next_id
@id ||= 0
@id += 1
end
def initialize(x, y, dir)
@id = self.class.next_id
@x = x
@y = y
@dir = dir
@turns = 0
end
def to_s
"<Cart id=#{id} x=#{x} y=#{y} dir=#{dir} turns=#{turns}>"
end
def ==(other)
x == other.x && y == other.y && dir == other.dir && turns == other.turns
end
def move!
case dir
when "^"
self.y = y - 1
when "v"
self.y = y + 1
when "<"
self.x = x - 1
when ">"
self.x = x + 1
end
end
def intersection_turn!
@dir = intersection_turn_dir
@turns += 1
end
# direction to face at intersection
def intersection_turn_dir
case @turns % 3
when 0
LEFT[dir]
when 1
dir # straight
when 2
RIGHT[dir]
end
end
def turn_at!(char)
case char
when "/"
turn_slash!
when "\\"
turn_backslash!
when "+"
intersection_turn!
end
end
def turn_slash!
self.dir =
case dir
when "^"
">"
when "<"
"v"
when "v"
"<"
when ">"
"^"
end
end
def turn_backslash!
self.dir =
case dir
when "^"
"<"
when ">"
"v"
when "v"
">"
when "<"
"^"
end
end
end
class Map
attr_reader :lines
def initialize(lines)
@lines = lines
end
def [](x, y)
lines[y][x]
rescue NoMethodError
raise "tried to address #{x}, #{y}: map has w=#{width}, h=#{height}"
end
def width
lines.map { |l| l.length }.max
end
def height
lines.count
end
end
class State
attr_reader :map, :time, :carts
def initialize(map, delete_crashes: false)
@map = map
@time = 0
@carts = init_carts
@delete_crashes = delete_crashes
end
def tick
@time += 1
ids_to_del = []
carts.sort_by { |c| [c.y, c.x] }.each do |cart|
next if ids_to_del.include?(cart.id)
cart.move!
# error if we fell off track
unless %w[- | + / \\].include?(map[cart.x, cart.y])
raise "cart fell off track: #{cart.to_s}"
end
if %w[/ \\ +].include?(map[cart.x, cart.y])
cart.turn_at!(map[cart.x, cart.y])
end
# need to check for crash after each move
if crashed?(cart)
if @delete_crashes
ids_to_del += carts.select { |c| c.x == cart.x && c.y == cart.y }.map(&:id)
else
break
end
end
end
carts.reject! { |c| ids_to_del.include?(c.id) }
end
def viz
lines = map.lines.map(&:dup)
carts.each do |c|
lines[c.y][c.x] = c.dir
end
lines.join("\n")
end
def crashed?(cart1)
carts.any? do |cart2|
cart1.id != cart2.id && cart1.x == cart2.x && cart1.y == cart2.y
end
end
def any_crash?
carts.map { |c| [c.x, c.y] }.uniq.count != carts.count
end
def init_carts
carts = []
map.lines.each_with_index do |line, y|
line.each_char.each_with_index do |c, x|
if %w[^ v < >].include?(c)
carts << Cart.new(x, y, c)
# fill back in the appropriate track for tracking later
line[x] = (%w[< >].include?(c) ? "-" : "|")
end
end
end
carts
end
end
def p1(state)
until state.any_crash?
state.tick
end
pts = state.carts.map { |c| [c.x, c.y] }.group_by
pts.group_by { |p| p }.select { |_, v| v.count > 1 }.keys
end
def p2(state)
until state.carts.count < 2
state.tick
end
c = state.carts[0]
[c.x, c.y]
end
if $0 == __FILE__
lines = File.read(ARGV[0]).lines.map(&:chomp)
state = State.new(Map.new(lines.map(&:dup)))
crashes = p1(state)
puts "p1: first crash is at #{crashes}"
state = State.new(Map.new(lines.map(&:dup)), delete_crashes: true)
puts "p2: last surviving cart is at #{p2(state)}"
end
|
=begin
* Modelo de la tabla ProductLine de la base de datos
* @author rails
* @version 14-10-2017
=end
class ProductLine < ApplicationRecord
has_many :products
validates :name, format: {with: /\A[a-zA-Z ]+\p{Latin}+\z/, message: "El nombre solo puede contener letras"}, length: { maximum: 50 }, presence: true
validates :min_value, numericality: { only_integer: true }, presence: true
validates :max_value, numericality: { only_integer: true }, presence: true
end
|
=begin
#===============================================================================
Title: Effect: Add Self State
Author: Hime
Date: Apr 20, 2013
--------------------------------------------------------------------------------
** Change log
Apr 20, 2013
- initial release
--------------------------------------------------------------------------------
** Terms of Use
* Free to use in non-commercial projects
* Contact me for commercial use
* No real support. The script is provided as-is
* Will do bug fixes, but no compatibility patches
* Features may be requested but no guarantees, especially if it is non-trivial
* Credits to Hime Works in your project
* Preserve this header
--------------------------------------------------------------------------------
** Description
This effect adds a state to the user of a skill/item
--------------------------------------------------------------------------------
** Required
Effects Manager
(http://himeworks.com/2012/10/05/effects-manager/)
--------------------------------------------------------------------------------
** Installation
Place this script below Effect Manager and above Main
--------------------------------------------------------------------------------
** Usage
Tag items or skills with
<eff: add_self_state stateID probability>
Where `stateID` is the ID of the state to apply
`probability` is the chance that it will be added, as a float
For example,
0 is 0%
0.5 is 50%
1 is 100%
#===============================================================================
=end
$imported = {} if $imported.nil?
$imported["TH_AddSelfState"] = true
#===============================================================================
# ** Configuration
#===============================================================================
module TH
module Add_Self_State
#===============================================================================
# ** Rest of Script
#===============================================================================
Effect_Manager.register_effect(:add_self_state, 2.6)
end
end
module RPG
class UsableItem < BaseItem
def add_effect_add_self_state(code, data_id, args)
data_id = args[0].to_i
value = args[1].to_f
add_effect(code, data_id, value)
end
end
end
class Game_Battler < Game_BattlerBase
def item_effect_add_self_state(user, item, effect)
state_id = effect.data_id
prob = effect.value1
if rand < prob
user.add_state(state_id)
end
end
end |
class Ctrole < ActiveRecord::Base
self.table_name = "ctrole"
self.primary_key = "ctroleid"
has_many :ctgxctxs
end
|
class Model::Section::AddDocumentSection < SitePrism::Section
element :tab, ".fieldset-title"
element :internal_name, "#edit-field-generic-media-doc-exposed-filters-title"
element :apply_button, "#edit-field-generic-media-doc-exposed-filters-submit"
element :remove_document, "div[class$='remove'] label.option"
elements :select_checkboxes, "input[id*='edit-field-generic-media-doc-und']"
elements :table_internal_name, "tbody .views-field-title"
end |
class Tile < ActiveRecord::Base
belongs_to :board
def self.ordered
order('tiles.order')
end
end
|
class ChangeInviteLinkInServers < ActiveRecord::Migration[5.2]
def change
remove_column :servers, :invite_link, :string
add_column :servers, :invite_link, :string, null: false
end
end
|
module Ojo
class << self
attr_accessor :configuration
end
def self.configure
self.configuration ||= Configuration.new
yield(configuration) if block_given?
end
class Configuration
attr_accessor :fuzz
attr_accessor :location
attr_accessor :metric
def initialize
@location = nil
@fuzz = '2%'
@metric = 'ae'
end
end
end
|
class AddColumnsToUsers < ActiveRecord::Migration
def change
add_column :users, :twitter_uid, :string
add_column :users, :twitter_username, :string
add_column :users, :twitter_user_description, :string
add_column :users, :twitter_user_url, :string
add_column :users, :twitter_profile_image_url, :string
add_column :users, :facebook_uid, :string
add_column :users, :facebook_username, :string
add_column :users, :facebook_profile_image_url, :string
end
end
|
class Node < ActiveRecord::Base
has_ancestry
def self.node_from_positions(played_positions)
parent = Node.find(1)
played_positions.each do |position|
node = parent.children.find_by_position(position)
(node = Node.create!(parent: parent, position: position)) unless node.present?
parent = node
end
parent
end
end |
require 'gosu'
require_relative 'collision'
class RubyRays < Gosu::Window
def initialize
@source = Vector.new($screen_w/2,$screen_h/2,1,1)
@font = Gosu::Font.new(15)
@rays = []
@collisions = []
@objects = []
for i in 0..5 do
@objects.push(
WorldObject.new($rng.rand($screen_w),$rng.rand($screen_h),$rng.rand(50..160),$rng.rand(3..10),$rng.rand(360),Gosu::Color.new(255,$rng.rand(0..5)*51,$rng.rand(0..5)*51,$rng.rand(0..5)*51)))
end
super $screen_w, $screen_h
end
# Refactor
def button_up(id)
case id
when 4 # A: Move source
@source.set_origin(mouse_x, mouse_y)
when 6 # C: Remove object at cursor
$max_bounces = $max_bounces - 1
if $max_bounces < -1
$max_bounces = -1
end
when 7 # D: Remove object at cursor
for o in @objects do
if o.contains?(self.mouse_x, self.mouse_y)
@objects.delete(o)
end
end
when 8 # E: Remove object at cursor
$max_bounces = $max_bounces + 1
when 30 # thin out line
$line_thickness -= 0.25
if $line_thickness < 0.25
$line_thickness = 0.25
end
when 31 # thicken line
$line_thickness += 0.25
when 32 # Spawn Triangle
@objects.push(
WorldObject.new(self.mouse_x,self.mouse_y,$rng.rand(50..160),3,$rng.rand(360),Gosu::Color.new(255,$rng.rand(0..5)*51,$rng.rand(0..5)*51,$rng.rand(0..5)*51))
)
when 33 # Spawn Square
@objects.push(
WorldObject.new(self.mouse_x,self.mouse_y,$rng.rand(50..160),4,$rng.rand(360),Gosu::Color.new(255,$rng.rand(0..5)*51,$rng.rand(0..5)*51,$rng.rand(0..5)*51))
)
when 34 # Spawn Pentagon
@objects.push(
WorldObject.new(self.mouse_x,self.mouse_y,$rng.rand(50..160),5,$rng.rand(360),Gosu::Color.new(255,$rng.rand(0..5)*51,$rng.rand(0..5)*51,$rng.rand(0..5)*51))
)
when 35 # Spawn Hexagon
@objects.push(
WorldObject.new(self.mouse_x,self.mouse_y,$rng.rand(50..160),6,$rng.rand(360),Gosu::Color.new(255,$rng.rand(0..5)*51,$rng.rand(0..5)*51,$rng.rand(0..5)*51))
)
when 36 # Spawn Septagon
@objects.push(
WorldObject.new(self.mouse_x,self.mouse_y,$rng.rand(50..160),7,$rng.rand(360),Gosu::Color.new(255,$rng.rand(0..5)*51,$rng.rand(0..5)*51,$rng.rand(0..5)*51))
)
when 37 # Spawn Octagon
@objects.push(
WorldObject.new(self.mouse_x,self.mouse_y,$rng.rand(50..160),8,$rng.rand(360),Gosu::Color.new(255,$rng.rand(0..5)*51,$rng.rand(0..5)*51,$rng.rand(0..5)*51))
)
when 38 # Spawn Nonagon
@objects.push(
WorldObject.new(self.mouse_x,self.mouse_y,$rng.rand(50..160),30,180,Gosu::Color::YELLOW)
)
when 39 # Spawn Circle
@objects.push(
WorldObject.new(self.mouse_x,self.mouse_y,$rng.rand(50..160),30,0,Gosu::Color::CYAN)
)
end
end
def button_down(id)
case id
when 45 # -: Shrink Object
for o in @objects do
if o.contains?(self.mouse_x, self.mouse_y)
o.alter(-5, 0 , 0, 0)
end
end
when 46 # +: Grow Object
for o in @objects do
if o.contains?(self.mouse_x, self.mouse_y)
o.alter(5, 0 , 0, 0)
end
end
when 47 # [: Rotate Object CCW (Left)
for o in @objects do
if o.contains?(self.mouse_x, self.mouse_y)
o.alter(0, -Math::PI/16 , 0, 0)
end
end
when 48 # ]: Rotate Object CW (Right)
for o in @objects do
if o.contains?(self.mouse_x, self.mouse_y)
o.alter(0, Math::PI/16, 0, 0)
end
end
when 79 # R: Nudge Right
for o in @objects do
if o.contains?(self.mouse_x, self.mouse_y)
o.alter(0, 0 , 5, 0)
end
end
when 80 # L: Nudge Left
for o in @objects do
if o.contains?(self.mouse_x, self.mouse_y)
o.alter(0, 0, -5, 0)
end
end
when 81 # D: Nudge Down
for o in @objects do
if o.contains?(self.mouse_x, self.mouse_y)
o.alter(0, 0 , 0, 5)
end
end
when 82 # U: Nudge Up
for o in @objects do
if o.contains?(self.mouse_x, self.mouse_y)
o.alter(0, 0 , 0, -5)
end
end
end
end
# needs_cursor? toggles system pointer on
def needs_cursor?
return true
end
def update
@source.set_direction(self.mouse_x, self.mouse_y)
current_ray = @source
# Trace the ray
for i in 0..$max_bounces do
collision = current_ray.trace(@objects)
if collision.exists?
collision.set_reflection
r = (current_ray.color.red + (current_ray.color.red * (collision.color.red.to_f/255))) / 2
g = (current_ray.color.green + (current_ray.color.green * (collision.color.green.to_f/255))) / 2
b = (current_ray.color.blue + (current_ray.color.blue * (collision.color.blue.to_f/255))) / 2
current_ray = Vector.new(collision.x, collision.y, collision.rx, collision.ry, Gosu::Color.new(current_ray.color.alpha*0.9,r,g,b))
@rays.push(current_ray)
#new_ray = Vector.new(collision.x, collision.y, collision.nx, collision.ny, Gosu::Color.new(50,255,0,0))
#@rays.push(new_ray)
end
end
# Trace it one last time to set the endpoint (if applicable)
collision = current_ray.trace(@objects)
# BRDF code goes here
#for r in @rays do
#end
end
def draw
@source.draw
for r in @rays do
r.draw
end
# Clear rays for next wave
@rays = []
for o in @objects do
o.draw
end
# Reference Line for debugging
#Gosu.draw_line(@source.x, @source.y, Gosu::Color::RED, self.mouse_x, self.mouse_y, Gosu::Color::RED, 50)
end
end
|
FactoryGirl.define do
# Define your Spree extensions Factories within this file to enable applications, and other extensions to use and override them.
#
# Example adding this to your spec_helper will load these Factories for use:
# require 'spree_variant_state/factories'
end
FactoryGirl.modify do
factory :base_variant do
trait :with_stock do
transient do
stock 10
end
after(:create) do |variant, evaluator|
stock_location = variant.stock_locations.first
stock_movement = stock_location.stock_movements.build(quantity: evaluator.stock)
stock_movement.stock_item = stock_location.set_up_stock_item(variant.id)
stock_movement.save
variant.stock_items.last.update backorderable: false
end
end
end
end
|
FactoryBot.define do
factory :comment do
comment { Faker::Lorem.sentence }
user
message
end
end |
# require 'susanoo/exports/page_creator'
module Susanoo
class MoveExport < self::Export
self.lock_file = File.join(Dir.tmpdir, 'move_export.lock')
#
#=== Susanoo::Export処理
#
def run
# Creator の logger を move_export.log に変更するための設定
Susanoo::Exports::Helpers::Logger.logger = ::Logger.new(Rails.root.join('log/move_export.log'))
# Susanoo::Export で追加したジョブは、Susanoo::Export で処理させないようにする設定。
#
# 尚、この設定は Susanoo::Export 側で queue を指定していない場合のみ有効
Job.create_with(queue: Job.queues[:move_export]).scoping do
super
end
end
private
def select_jobs
Job.queue_eq(:move_export).datetime_is_nil_or_le(Time.zone.now).where(action: self.action_methods.to_a)
end
end
end
|
class Category < ActiveRecord::Base
attr_accessible :id, :name, :description
has_many :artists
end
|
class Province < ApplicationRecord
belongs_to :region
def full_name
"Provincia de #{name}, #{region.full_name}"
end
end
|
require 'test_helper'
class DocumentCollectionGroupMembershipTest < ActiveSupport::TestCase
test 'maintain ordering of documents in a group' do
group = create(:document_collection_group, document_collection: build(:document_collection))
documents = [build(:document), build(:document)]
group.documents = documents
assert_equal [1, 2], group.memberships.reload.map(&:ordering)
end
test 'is invalid without a document' do
refute build(:document_collection_group_membership, document: nil).valid?
end
test 'is invalid without a document_collection_group' do
refute build(:document_collection_group_membership, document_collection_group: nil).valid?
end
test 'is invalid when document is a document collection' do
membership = build(:document_collection_group_membership, document: create(:document_collection).document)
refute membership.valid?
end
end
|
require 'test_helper'
class AuthorTest < ActiveSupport::TestCase
test "does not save without a name" do
@author_without_name = Author.new(name: nil)
assert @author_without_name.save == false
end
test "does save with valid params" do
@valid_author = Author.new(name: "valid name")
assert @valid_author.save == true
end
end
|
# frozen_string_literal: true
require "kafka/broker_pool"
require "resolv"
require "set"
module Kafka
# A cluster represents the state of a Kafka cluster. It needs to be initialized
# with a non-empty list of seed brokers. The first seed broker that the cluster can connect
# to will be asked for the cluster metadata, which allows the cluster to map topic
# partitions to the current leader for those partitions.
class Cluster
# Initializes a Cluster with a set of seed brokers.
#
# The cluster will try to fetch cluster metadata from one of the brokers.
#
# @param seed_brokers [Array<URI>]
# @param broker_pool [Kafka::BrokerPool]
# @param logger [Logger]
# @param resolve_seed_brokers [Boolean] See {Kafka::Client#initialize}
def initialize(seed_brokers:, broker_pool:, logger:, resolve_seed_brokers: false)
if seed_brokers.empty?
raise ArgumentError, "At least one seed broker must be configured"
end
@logger = TaggedLogger.new(logger)
@seed_brokers = seed_brokers
@broker_pool = broker_pool
@resolve_seed_brokers = resolve_seed_brokers
@cluster_info = nil
@stale = true
# This is the set of topics we need metadata for. If empty, metadata for
# all topics will be fetched.
@target_topics = Set.new
end
# Adds a list of topics to the target list. Only the topics on this list will
# be queried for metadata.
#
# @param topics [Array<String>]
# @return [nil]
def add_target_topics(topics)
topics = Set.new(topics)
unless topics.subset?(@target_topics)
new_topics = topics - @target_topics
unless new_topics.empty?
if new_topics.any? { |topic| topic.nil? or topic.empty? }
raise ArgumentError, "Topic must not be nil or empty"
end
@logger.info "New topics added to target list: #{new_topics.to_a.join(', ')}"
@target_topics.merge(new_topics)
refresh_metadata!
end
end
end
def api_info(api_key)
apis.find {|api| api.api_key == api_key }
end
def supports_api?(api_key, version = nil)
info = api_info(api_key)
if info.nil?
return false
elsif version.nil?
return true
else
return info.version_supported?(version)
end
end
def apis
@apis ||=
begin
response = random_broker.api_versions
Protocol.handle_error(response.error_code)
response.apis
end
end
# Clears the list of target topics.
#
# @see #add_target_topics
# @return [nil]
def clear_target_topics
@target_topics.clear
refresh_metadata!
end
def mark_as_stale!
@stale = true
end
def refresh_metadata!
@cluster_info = nil
cluster_info
end
def refresh_metadata_if_necessary!
refresh_metadata! if @stale
end
# Finds the broker acting as the leader of the given topic and partition.
#
# @param topic [String]
# @param partition [Integer]
# @return [Broker] the broker that's currently leader.
def get_leader(topic, partition)
connect_to_broker(get_leader_id(topic, partition))
end
# Finds the broker acting as the coordinator of the given group.
#
# @param group_id [String]
# @return [Broker] the broker that's currently coordinator.
def get_group_coordinator(group_id:)
@logger.debug "Getting group coordinator for `#{group_id}`"
refresh_metadata_if_necessary!
get_coordinator(Kafka::Protocol::COORDINATOR_TYPE_GROUP, group_id)
end
# Finds the broker acting as the coordinator of the given transaction.
#
# @param transactional_id [String]
# @return [Broker] the broker that's currently coordinator.
def get_transaction_coordinator(transactional_id:)
@logger.debug "Getting transaction coordinator for `#{transactional_id}`"
refresh_metadata_if_necessary!
if transactional_id.nil?
# Get a random_broker
@logger.debug "Transaction ID is not available. Choose a random broker."
return random_broker
else
get_coordinator(Kafka::Protocol::COORDINATOR_TYPE_TRANSACTION, transactional_id)
end
end
def describe_configs(broker_id, configs = [])
options = {
resources: [[Kafka::Protocol::RESOURCE_TYPE_CLUSTER, broker_id.to_s, configs]]
}
info = cluster_info.brokers.find {|broker| broker.node_id == broker_id }
broker = @broker_pool.connect(info.host, info.port, node_id: info.node_id)
response = broker.describe_configs(**options)
response.resources.each do |resource|
Protocol.handle_error(resource.error_code, resource.error_message)
end
response.resources.first.configs
end
def alter_configs(broker_id, configs = [])
options = {
resources: [[Kafka::Protocol::RESOURCE_TYPE_CLUSTER, broker_id.to_s, configs]]
}
info = cluster_info.brokers.find {|broker| broker.node_id == broker_id }
broker = @broker_pool.connect(info.host, info.port, node_id: info.node_id)
response = broker.alter_configs(**options)
response.resources.each do |resource|
Protocol.handle_error(resource.error_code, resource.error_message)
end
nil
end
def partitions_for(topic)
add_target_topics([topic])
refresh_metadata_if_necessary!
cluster_info.partitions_for(topic)
rescue Kafka::ProtocolError
mark_as_stale!
raise
end
def create_topic(name, num_partitions:, replication_factor:, timeout:, config:)
options = {
topics: {
name => {
num_partitions: num_partitions,
replication_factor: replication_factor,
config: config,
}
},
timeout: timeout,
}
broker = controller_broker
@logger.info "Creating topic `#{name}` using controller broker #{broker}"
response = broker.create_topics(**options)
response.errors.each do |topic, error_code|
Protocol.handle_error(error_code)
end
begin
partitions_for(name).each do |info|
Protocol.handle_error(info.partition_error_code)
end
rescue Kafka::LeaderNotAvailable
@logger.warn "Leader not yet available for `#{name}`, waiting 1s..."
sleep 1
retry
rescue Kafka::UnknownTopicOrPartition
@logger.warn "Topic `#{name}` not yet created, waiting 1s..."
sleep 1
retry
end
@logger.info "Topic `#{name}` was created"
end
def delete_topic(name, timeout:)
options = {
topics: [name],
timeout: timeout,
}
broker = controller_broker
@logger.info "Deleting topic `#{name}` using controller broker #{broker}"
response = broker.delete_topics(**options)
response.errors.each do |topic, error_code|
Protocol.handle_error(error_code)
end
@logger.info "Topic `#{name}` was deleted"
end
def describe_topic(name, configs = [])
options = {
resources: [[Kafka::Protocol::RESOURCE_TYPE_TOPIC, name, configs]]
}
broker = controller_broker
@logger.info "Fetching topic `#{name}`'s configs using controller broker #{broker}"
response = broker.describe_configs(**options)
response.resources.each do |resource|
Protocol.handle_error(resource.error_code, resource.error_message)
end
topic_description = response.resources.first
topic_description.configs.each_with_object({}) do |config, hash|
hash[config.name] = config.value
end
end
def alter_topic(name, configs = {})
options = {
resources: [[Kafka::Protocol::RESOURCE_TYPE_TOPIC, name, configs]]
}
broker = controller_broker
@logger.info "Altering the config for topic `#{name}` using controller broker #{broker}"
response = broker.alter_configs(**options)
response.resources.each do |resource|
Protocol.handle_error(resource.error_code, resource.error_message)
end
nil
end
def describe_group(group_id)
response = get_group_coordinator(group_id: group_id).describe_groups(group_ids: [group_id])
group = response.groups.first
Protocol.handle_error(group.error_code)
group
end
def fetch_group_offsets(group_id)
topics = get_group_coordinator(group_id: group_id)
.fetch_offsets(group_id: group_id, topics: nil)
.topics
topics.each do |_, partitions|
partitions.each do |_, response|
Protocol.handle_error(response.error_code)
end
end
topics
end
def create_partitions_for(name, num_partitions:, timeout:)
options = {
topics: [[name, num_partitions, nil]],
timeout: timeout
}
broker = controller_broker
@logger.info "Creating #{num_partitions} partition(s) for topic `#{name}` using controller broker #{broker}"
response = broker.create_partitions(**options)
response.errors.each do |topic, error_code, error_message|
Protocol.handle_error(error_code, error_message)
end
mark_as_stale!
@logger.info "Topic `#{name}` was updated"
end
def resolve_offsets(topic, partitions, offset)
add_target_topics([topic])
refresh_metadata_if_necessary!
partitions_by_broker = partitions.each_with_object({}) {|partition, hsh|
broker = get_leader(topic, partition)
hsh[broker] ||= []
hsh[broker] << partition
}
if offset == :earliest
offset = -2
elsif offset == :latest
offset = -1
end
offsets = {}
partitions_by_broker.each do |broker, broker_partitions|
response = broker.list_offsets(
topics: {
topic => broker_partitions.map {|partition|
{
partition: partition,
time: offset
}
}
}
)
broker_partitions.each do |partition|
offsets[partition] = response.offset_for(topic, partition)
end
end
offsets
rescue Kafka::ProtocolError
mark_as_stale!
raise
end
def resolve_offset(topic, partition, offset)
resolve_offsets(topic, [partition], offset).fetch(partition)
end
def topics
refresh_metadata_if_necessary!
cluster_info.topics.select do |topic|
topic.topic_error_code == 0
end.map(&:topic_name)
end
# Lists all topics in the cluster.
def list_topics
response = random_broker.fetch_metadata(topics: nil)
response.topics.select do |topic|
topic.topic_error_code == 0
end.map(&:topic_name)
end
def list_groups
refresh_metadata_if_necessary!
cluster_info.brokers.map do |broker|
response = connect_to_broker(broker.node_id).list_groups
Protocol.handle_error(response.error_code)
response.groups.map(&:group_id)
end.flatten.uniq
end
def disconnect
@broker_pool.close
end
def cluster_info
@cluster_info ||= fetch_cluster_info
end
private
def get_leader_id(topic, partition)
cluster_info.find_leader_id(topic, partition)
end
# Fetches the cluster metadata.
#
# This is used to update the partition leadership information, among other things.
# The methods will go through each node listed in `seed_brokers`, connecting to the
# first one that is available. This node will be queried for the cluster metadata.
#
# @raise [ConnectionError] if none of the nodes in `seed_brokers` are available.
# @return [Protocol::MetadataResponse] the cluster metadata.
def fetch_cluster_info
errors = []
@seed_brokers.shuffle.each do |node|
(@resolve_seed_brokers ? Resolv.getaddresses(node.hostname).shuffle : [node.hostname]).each do |hostname_or_ip|
node_info = node.to_s
node_info << " (#{hostname_or_ip})" if node.hostname != hostname_or_ip
@logger.info "Fetching cluster metadata from #{node_info}"
begin
broker = @broker_pool.connect(hostname_or_ip, node.port)
cluster_info = broker.fetch_metadata(topics: @target_topics)
if cluster_info.brokers.empty?
@logger.error "No brokers in cluster"
else
@logger.info "Discovered cluster metadata; nodes: #{cluster_info.brokers.join(', ')}"
@stale = false
return cluster_info
end
rescue Error => e
@logger.error "Failed to fetch metadata from #{node_info}: #{e}"
errors << [node_info, e]
ensure
broker.disconnect unless broker.nil?
end
end
end
error_description = errors.map {|node_info, exception| "- #{node_info}: #{exception}" }.join("\n")
raise ConnectionError, "Could not connect to any of the seed brokers:\n#{error_description}"
end
def random_broker
refresh_metadata_if_necessary!
node_id = cluster_info.brokers.sample.node_id
connect_to_broker(node_id)
end
def connect_to_broker(broker_id)
info = cluster_info.find_broker(broker_id)
@broker_pool.connect(info.host, info.port, node_id: info.node_id)
end
def controller_broker
connect_to_broker(cluster_info.controller_id)
end
def get_coordinator(coordinator_type, coordinator_key)
cluster_info.brokers.each do |broker_info|
begin
broker = connect_to_broker(broker_info.node_id)
response = broker.find_coordinator(
coordinator_type: coordinator_type,
coordinator_key: coordinator_key
)
Protocol.handle_error(response.error_code, response.error_message)
coordinator_id = response.coordinator_id
@logger.debug "Coordinator for `#{coordinator_key}` is #{coordinator_id}. Connecting..."
# It's possible that a new broker is introduced to the cluster and
# becomes the coordinator before we have a chance to refresh_metadata.
coordinator = begin
connect_to_broker(coordinator_id)
rescue Kafka::NoSuchBroker
@logger.debug "Broker #{coordinator_id} missing from broker cache, refreshing"
refresh_metadata!
connect_to_broker(coordinator_id)
end
@logger.debug "Connected to coordinator: #{coordinator} for `#{coordinator_key}`"
return coordinator
rescue CoordinatorNotAvailable
@logger.debug "Coordinator not available; retrying in 1s"
sleep 1
retry
rescue ConnectionError => e
@logger.error "Failed to get coordinator info from #{broker}: #{e}"
end
end
raise Kafka::Error, "Failed to find coordinator"
end
end
end
|
module Mud
module Entities
module HasPlayers
#find a player by its identification.
def find_player name
players.find{|p| p.is_named? name}
end
#retrieving the items from this character
def players
(@players ||= []).map{|id| W.find_player id}.freeze
end
#moving players around.
#let players do this
def remove_player p
(@players ||= []).delete p.sym
end
def add_player p
@players << p.sym unless (@players ||= []).include? p.sym
end
#echo
def echo string, list_of_players_to_avoid = [], color = :off
(self.players - list_of_players_to_avoid).each { |p| p.hear_line string, color }
end
end
# A mapping of color symbols to their escape sequences.
class Player < Entity
attr_accessor :hashed_password, :command_groups
# we don't need this, but it needs to be able to do this just in case.
def react_to *args; end
def move_to new_room
self.room.remove_player self
self.room = new_room
new_room.add_player self
end
#the truename of this player
def sym
@name.to_sym
end
#the name that this player is usually displayed by.
# takes into account their wielding, blah blah blah
def display_name
@name.capitalize.freeze
end
#this is what they look like in a "look"
def display_description
@name.capitalize + " stands here" + ((item_for :weapon) ? (", wielding " + item_for(:weapon).short_display_string) : "") + "."
end
# returns if this paleyr is named this string
# it also can take care of other cases?
def is_named? n
n && n.downcase == @name
end
def connection
W.player_connection_map[self]
end
def connection= c
W.player_connection_map[self] = c
end
# create a new player. This should ONLY be called when a player is CREATED, not logged in.
def initialize name,hashed_password
@name = name.downcase
@commands = []
@hashed_password = hashed_password
@pending_output = ""
W.create_player(self)
self.room = W.default_room
@command_groups = []
self.max_hp = 100
self.max_mp = 100
self.hp= max_hp
self.mp= max_mp
@off_balance_timer = {}
end
# when you load the player back into the game from a serialized state, here are some things we
# need to fix.
def on_load
clear_output
end
# When a player logs into the mud, show some default messages, and add them to the room they
# are currently located in. Also, add itself to th list of active players
def login
room.add_player self
room.echo("#{display_name} suddenly appears.", [self], :blue)
hear_line("You fade in to being...", :blue)
W.players << self
end
#inverse of login
def logout
room.remove_player self
room.echo("#{display_name} dissapears.", [self], :blue)
hear_line("You fade out of being...", :blue)
W.players.delete(self)
end
#hear something - message, color, message, color
# this is all followed by a new line
def hear_line *args
raise "must give arguments" if args.size == 0
args << nil if (args.size%2) == 1
hear *args
@pending_output += "\n\r"
end
#hear something - message, color, message, color
def hear *args
raise "must give arguments" if args.size == 0
args << nil if (args.size%2) == 1
(args.size/2).times do |off|
add_output(args[2*off], args[2*off+1])
end
end
private :hear
# Hear is the method for producing output.
def add_output data, color_attr = nil
color_attr ||= []
if data.strip != ""
color_attr = [color_attr] if color_attr.is_a? Symbol
@pending_output += color_attr.map{|a| COLORMAP[a]}.join('')+data+COLORMAP[:off]
end
end
private :add_output
# When a player gets input, it might have a shortcut for say.
# this method will replace a leading ' or " with 'say '
def preprocess_data data
if data[0] == "'" || data[0] == '"'
"say " + data[1,data.length]
else
data
end
end
# When we receive input, do the command with processed version of that
# data
def receive_data data
command preprocess_data(data), @command_groups, true
end
#generates a prompt string.
#adds it via hearline
def add_prompt
hp_percent = 100*hp/max_hp
mp_percent = 100*mp/max_mp
hp_color = case
when hp_percent > 66
:green
when hp_percent > 33
:yellow
else
:red
end
mp_color = case
when mp_percent > 66
:green
when mp_percent > 33
:yellow
else
:red
end
hear_line("#{hp}/#{max_hp} ", [hp_color],
"#{mp}/#{max_mp}", [mp_color],
" #{on_balance?(:balance) ? "x" : " "}#{on_balance?(:equilibrium) ? "e" : " "}-", nil)
end
#this allows simultanious output to be batched together in the same package.
def flush_output
if @pending_output != ""
add_prompt
connection.send_data @pending_output
clear_output
end
end
#remove all output
def clear_output
@pending_output = ""
end
# all the things that should be happening constantly
def tick dt
update_balance dt
flush_output
end
end
end
end
|
class ApplicationController < ActionController::API
before_action :check_headers
private
def check_headers
if request.headers["HEADER"] == "password"
return true
else
render json: { errors: ['Not Authenticated'] }, status: :unauthorized
end
end
end
|
class RemoveRelationshipFromUser < ActiveRecord::Migration
def change
remove_column :users, :relationship
remove_column :users, :user_id
remove_column :users, :name
end
end
|
FactoryGirl.define do
factory :payment_scope do
name {Faker::Name.name}
end
end
|
require 'forwardable'
module TemporalAttributes
@global_time = 0
class << self
def global_time
@global_time
end
def set_global_time(time)
@global_time = time
end
private :set_global_time
def use_global_time(time)
old_time = global_time
set_global_time(time)
ret = yield
set_global_time(old_time)
ret
end
def included(klass)
klass.class_eval do
extend Forwardable
extend TemporalAttributesClassMethods
def_delegators TemporalAttributes, :global_time, :use_global_time
@temporal_attributes = []
@temporal_attribute_settings = {}
end
end
end
module TemporalAttributesClassMethods
attr_reader :temporal_attributes, :temporal_attribute_settings
def temporal_attr(*attrs, type: :historical, history: 2, **opts)
attrs.each do |attr|
@temporal_attributes << attr
@temporal_attribute_settings[attr] = [type, history]
end
end
def temporal_caller(attr, method, history: 2)
@temporal_attributes << attr
@temporal_attribute_settings[attr] = [:caller, history, method]
end
end
def get(key, time = default_time)
key = key.to_sym
return unless valid_temporal_attribute?(key)
case [attr_type(key), time]
when [:caller, 0]
set_value(key, self.send(callee(key)))
else
db[key][time]
end
end
def set(key, val)
key = key.to_sym
return unless valid_temporal_attribute?(key)
case attr_type(key)
when :historical; shift_value(key, val)
when :snapshot; set_value(key, val)
when :caller # do nothing
end
end
def snap
snapshot_attributes.each do |attr|
shift_value(attr, get(attr))
end
end
# magix
def respond_to_missing?(method, priv)
valid_temporal_attribute?(method) || super
end
#TODO: define accessors dynamically vs method_missing
#
def method_missing(method, *args, &block)
meth, setter = /^(.*?)(=?)$/.match(method).values_at(1,2)
if valid_temporal_attribute?(meth.to_sym)
setter.empty? ? get(meth, *args) : set(meth, *args)
else super
end
end
# class property readers
def temporal_settings
@temporal_settings ||= self.class.temporal_attribute_settings
end
def temporal_attributes
@temporal_attributes ||= self.class.temporal_attributes
end
private
def default_time
global_time || 0
end
# initialization
def init
@temporal_mod = TemporalAttributes
@temporal_db = Hash.new { |h,k| h[k] = [nil] }
end
def db
init_proc = method(:init)
body_proc = lambda { @temporal_db }
run_once(:db, init_proc, body_proc)
end
def run_once(name, init, body)
init.call.tap { define_singleton_method(name, &body) }
end
# saving values
def shift_value(key, val)
db[key].unshift(val)
db[key] = db[key][0...history(key)]
val
end
def set_value(key, val)
db[key][default_time] = val
end
# helpers
def valid_temporal_attribute?(attr)
temporal_attributes.include?(attr)
end
def snapshot_attributes
temporal_attributes.select { |attr| !historical?(attr) }
end
def historical?(key); attr_type(key) == :historical end
def snapshot?(key); attr_type(key) == :snapshot end
def caller?(key); attr_type(key) == :caller end
def attr_type(key); temporal_settings[key][0] end
def history(key); temporal_settings[key][1] end
def callee(key); temporal_settings[key][2] end
end
|
require 'spec_helper'
describe "31171525 has_sage_flow_state adds is_saved? is_editable? is in that state" do
before(:each) do
class Foo < Sample
has_sage_flow_states :foo, :zing
end
end
it "Has a method for the first state" do
Foo.method_defined?(:is_foo?).should be_true
end
it "Has a method for the second state" do
Foo.method_defined?(:is_zing?).should be_true
end
it "Does not have a method for states it does not have" do
Foo.method_defined?(:is_bar?).should be_false
end
it "Returns true if object is in specified state" do
f = Foo.new
f.sage_flow_state = 'foo'
f.is_foo?.should be_true
end
it "Returns false if object is not in specified state" do
f = Foo.new
f.sage_flow_state = 'foo'
f.is_zing?.should be_false
end
end
|
class VersioningService
def initialize(migrator = ActiveRecord::Migrator)
@migrator = migrator
end
def current_version
migrator.current_version
end
private
attr_reader :migrator
end
|
json.array!(@port_panels) do |port_panel|
json.extract! port_panel,
json.url port_panel_url(port_panel, format: :json)
end
|
class String
def relative_path?
return !self.start_with?('/')
end
end
|
#
# Specifying rufus-tokyo
#
# Fri Aug 28 08:58:37 JST 2009
#
require File.dirname(__FILE__) + '/spec_base'
require 'rufus/tokyo'
FileUtils.mkdir('tmp') rescue nil
DB_FILE = "tmp/cabinet_btree_spec.tcb"
describe 'Rufus::Tokyo::Cabinet .tcb' do
before do
FileUtils.rm(DB_FILE) if File.exist? DB_FILE
@db = Rufus::Tokyo::Cabinet.new(DB_FILE)
end
after do
@db.close
end
it 'should accept duplicate values' do
@db.putdup('a', 'a0')
@db.putdup('a', 'a1')
@db.getdup('a').should.equal([ 'a0', 'a1' ])
end
it 'should return nul when getdupping a missing key' do
@db.getdup('b').should.equal(nil)
end
it 'should be able to fetch keys for duplicate values' do
[ %w[John Hornbeck],
%w[Tim Gourley],
%w[Grant Schofield],
%w[James Gray],
%w[Dana Gray] ].each do |first, last|
@db.putdup(last, first)
end
@db.keys.should.equal(%w[Gourley Gray Hornbeck Schofield])
@db.keys(:prefix => "G").should.equal(%w[Gourley Gray])
end
end
describe 'Rufus::Tokyo::Cabinet .tcb methods' do
it 'should fail on other structures' do
@db = Rufus::Tokyo::Cabinet.new(DB_FILE.sub(/\.tcb\z/, ".tch"))
lambda { @db.putdup('a', 'a0') }.should.raise(NoMethodError)
@db.close
end
end
describe 'Rufus::Tokyo::Cabinet .tcb order' do
before do
FileUtils.rm(DB_FILE) if File.exist? DB_FILE
end
it 'should default to a lexical order' do
db = Rufus::Tokyo::Cabinet.new(DB_FILE)
fields = [1, 2, 10, 11, 20, 21]
fields.each do |n|
db[n] = n
end
db.keys.should.equal(fields.map { |n| n.to_s }.sort)
db.close
end
it 'should allow an explicit :cmpfunc => :lexical' do
db = Rufus::Tokyo::Cabinet.new(DB_FILE, :cmpfunc => :lexical)
fields = [1, 2, 10, 11, 20, 21]
fields.each do |n|
db[n] = n
end
db.keys.should.equal(fields.map { |n| n.to_s }.sort)
db.close
end
#
# It's not possible to call tcbdbsetcmpfunc() through the abstract API, so
# changing comparison functions are only supported through the Edo interface.
#
end
|
json.array!(@author_requests) do |author_request|
json.extract! author_request, :id, :ois_request_id, :person_id, :old_lastname, :is_teacher, :is_staffteacher, :is_student, :is_postgrad, :details
json.url author_request_url(author_request, format: :json)
end
|
class AddLastObservationToObservations < ActiveRecord::Migration[5.1]
def change
add_column :observations, :last_observation, :text
end
end
|
def caesar_cipher(phrase, shift)
phrase = phrase.to_s if phrase.is_a?(String) == false
puts "Shift should be an integer." if shift.is_a?(Integer) == false
if shift.is_a?(Integer) == true
code = ""
phrase.each_char do |i|
shift.times do
i.next!
i = "a" if i == "aa"
i = "A" if i == "AA"
i = " " if i == "!"
i = "." if i == "/"
i = "!" if i == "\""
i = "(" if i == ")"
i = ")" if i == "*"
end
code += i
end
end
return code
end
|
module TwitterCldr
module Timezones
class Location
attr_reader :tz
def initialize(tz)
@tz = tz
end
def tz_id
tz.identifier
end
def resource
@resource ||= TwitterCldr.get_locale_resource(tz.locale, :timezones)[tz.locale]
end
end
end
end
|
class AddOpponentToGames < ActiveRecord::Migration[5.0]
def change
add_column :games, :opponent, :string
add_column :games, :home, :boolean
end
end
|
class HomesController < ApplicationController
before_action :set_home, only: [:show, :edit, :update, :destroy]
# GET /homes
# GET /homes.json
def index
@php =File.read('./PHP/index.php')
@phphtml =File.read('./PHP/template.html')
@node = File.read('./nodejs/app.js')
@nodehtml = File.read('./nodejs/index.html')
@net = File.read('./net/JWT.cs')
@nethtml = File.read('./net/index.html')
@ror = File.read('./ror/JWT.rb')
@rorhtml = File.read('./ror/index.html')
@django = File.read('./python/views.py')
@djangohtml = File.read('./python/katoTemplate.html')
end
# GET /homes/1
# GET /homes/1.json
def show
end
# GET /homes/new
def new
@home = Home.new
end
# GET /homes/1/edit
def edit
end
# POST /homes
# POST /homes.json
def create
@home = Home.new(home_params)
respond_to do |format|
if @home.save
format.html { redirect_to @home, notice: 'Home was successfully created.' }
format.json { render :show, status: :created, location: @home }
else
format.html { render :new }
format.json { render json: @home.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /homes/1
# PATCH/PUT /homes/1.json
def update
respond_to do |format|
if @home.update(home_params)
format.html { redirect_to @home, notice: 'Home was successfully updated.' }
format.json { render :show, status: :ok, location: @home }
else
format.html { render :edit }
format.json { render json: @home.errors, status: :unprocessable_entity }
end
end
end
# DELETE /homes/1
# DELETE /homes/1.json
def destroy
@home.destroy
respond_to do |format|
format.html { redirect_to homes_url, notice: 'Home was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_home
@home = Home.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def home_params
params[:home]
end
end
|
class AddSubmittedToProduct < ActiveRecord::Migration
def change
add_column :products, :submitter_twitter, :string
add_column :products, :submission_id, :integer
end
end
|
require 'rspec'
require 'card'
describe 'Card class' do
subject (:card) { Card.new(Value.value("ACE"), Suit.suit("CLUB")) }
describe '#initialize' do
it "has a value" do
expect(card.value).to eq(Value.value("ACE"))
end
it "has a suit" do
expect(card.suit).to eq(Suit.suit("CLUB"))
end
end
describe "#<=>" do
it "compares two cards values" do
queen = Card.new(Value.value("QUEEN"), Suit.suit("HEART"))
expect(card <=> queen).to eq(1)
end
it "compares two cards suits" do
ace_spade = Card.new(Value.value("ACE"), Suit.suit("SPADE"))
expect(card <=> ace_spade).to eq(-1)
end
end
end
|
require 'rails_helper'
RSpec.feature 'Products', type: :feature do
def sign_in(user)
visit new_user_session_path
fill_in 'Email', with: user.email
fill_in 'Password', with: user.password
click_button 'Log in'
end
def submit_form
find("form input[value='#{I18n.t('btn_search')}']").click
end
let!(:user) { create :user, status: :normal }
let!(:product) { create(:product, slug: 'my-product') }
let!(:pp_product) { create(:product, slug: 'fifteen-chars-s') }
before { sign_in user }
context 'products exist in db' do
it 'show search form' do
visit products_search_url
expect(page).to have_css('form input#url')
expect(find("form input[value='#{I18n.t('btn_search')}']")).to be_visible
end
it 'display product' do
visit products_search_url
fill_in 'url', with: "#{ENV['URL_BASE_SCRAPPER']}#{product.slug}"
submit_form
page.assert_selector('td', count: 4)
expect(all('tr td')[0]).to have_text(product.slug)
expect(all('tr td')[1]).to have_text(product.title)
expect(all('tr td')[2]).to have_text(product.price_net)
expect(all('tr td')[3]).to have_text(product.price_gross)
end
end
context 'not exist url' do
it 'show message' do
visit products_search_url
fill_in 'url', with: "#{ENV['URL_BASE_SCRAPPER']}something-bad"
submit_form
expect(find('.alert.alert-danger'))
.to have_text(I18n.t('msg_not_found'))
end
end
context 'forbidden url' do
it 'show message' do
visit products_search_url
fill_in 'url', with: "#{ENV['URL_BASE_SCRAPPER']}#{pp_product.slug}"
submit_form
expect(find('.alert.alert-danger'))
.to have_text(I18n.t('msg_prohibited_url'))
end
end
end
|
class ScoresController < ApplicationController
def index
scores = Score.select(:name, :score).order(score: :desc).limit(3)
scores = scores.map { |score| "#{score.name}: #{score.score}" }.join("\n")
render json: scores
end
def save_score
if allow_request?
Score.create(name: params[:name], score: params[:score])
head :ok
else
head :unauthorized
end
end
private
def allow_request?
request.user_agent.start_with?("DragonRuby") ||
request.referer.match?(/.*\.hwcdn\.net/)
end
end
|
class Element < ActiveRecord::Base
has_many :element_assignments, dependent: :destroy
scope :elements, lambda { where(category: 'sentence_element') }
scope :relations, lambda { where(category: 'sentence_relation') }
with_options through: :element_assignments, source: :elementable do |element|
element.has_many :templates, class_name: :ExerciseTemplate, source_type: 'ExerciseTemplate'
element.has_many :exercises, source_type: 'Exercise'
end
end
|
class Show < ApplicationRecord
validates :artist, presence: true
validates :venue, presence: true
validates :event_on, presence: true
belongs_to :artist
belongs_to :venue
end
|
require 'spec_helper'
describe User do
describe "validation" do
context "on update" do
subject { create :user }
it { should validate_presence_of(:username) }
it { should validate_presence_of(:first_name) }
it { should validate_presence_of(:surname) }
end
end
end
|
require 'sinatra'
require 'rack'
require 'github_api'
require 'byebug'
require 'dotenv/load'
require 'faraday'
require 'json'
# start local server with shotgun
# use ngrok to expose
# http://1c4e8b5a.ngrok.io
class App < Sinatra::Base
get '/' do
# this installs the app in a new workspace using Slack's OAuth 2.0
# Slack sends code, app responds with post request, Slack responds with access token
if params['code']
client_id = ENV['CLIENT_ID']
client_secret = ENV['CLIENT_SECRET']
code = params['code']
url = 'https://slack.com/api/oauth.access'
resp = Faraday.post(url, "client_id=#{client_id}&client_secret=#{client_secret}&code=#{code}")
parsed = JSON.parse resp.body
if parsed['access_token']
token = parsed['access_token']
'slack bot added!'
elsif parsed['error']
"something went wrong: #{parsed['error']}"
end
end
end
post '/' do
# TODO: Change to OAuth 2.0 using a GitHub app instead of basic auth
# https://developer.github.com/apps/building-oauth-apps/
username = ENV['GITHUB_USERNAME']
pw = ENV['GITHUB_PASSWORD']
github_api = Github.new basic_auth: "#{username}:#{pw}"
# TODO: Might need to add checks for special characters
if params['text'].length == 0
"Please provide a description of the issue"
else
github_api.issues.create(
user: 'clairemuller',
repo: 'slack_bot_issues',
title: "slack user #{params['user_name']} found a bug",
body: params['text']
)
"Submitted issue: '#{params['text']}'"
end
end
end
|
class Color < ActiveRecord::Base
# has_many :swatches
# validates_presence_of :value
# validates_length_of :value, :within => 4..7
# validates_uniqueness_of :value, :case_sensitive => false
# validates_format_of :value, :with => /^#?([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?$/
end |
require 'test_helper'
class CotizesccamsControllerTest < ActionDispatch::IntegrationTest
setup do
@cotizesccam = cotizesccams(:one)
end
test "should get index" do
get cotizesccams_url
assert_response :success
end
test "should get new" do
get new_cotizesccam_url
assert_response :success
end
test "should create cotizesccam" do
assert_difference('Cotizesccam.count') do
post cotizesccams_url, params: { cotizesccam: { correo: @cotizesccam.correo, nombre: @cotizesccam.nombre } }
end
assert_redirected_to cotizesccam_url(Cotizesccam.last)
end
test "should show cotizesccam" do
get cotizesccam_url(@cotizesccam)
assert_response :success
end
test "should get edit" do
get edit_cotizesccam_url(@cotizesccam)
assert_response :success
end
test "should update cotizesccam" do
patch cotizesccam_url(@cotizesccam), params: { cotizesccam: { correo: @cotizesccam.correo, nombre: @cotizesccam.nombre } }
assert_redirected_to cotizesccam_url(@cotizesccam)
end
test "should destroy cotizesccam" do
assert_difference('Cotizesccam.count', -1) do
delete cotizesccam_url(@cotizesccam)
end
assert_redirected_to cotizesccams_url
end
end
|
module Fauve
module Scheme
# Representation of a section key as part of a wider scheme.
# Holds a section name, which points to a top-level key within
# a colour scheme.
# Takes a section name (string)
class Section
attr_reader :name
def initialize(name)
@name = name.to_s
@colour_map = ColourMap.instance
end
def to_h
return colour_map.map[name] if section_exists?
raise Fauve::UndefinedSectionError.new('Section is not referenced in config')
end
private
attr_reader :colour_map
def section_exists?
!!colour_map.map[name]
end
end
end
end |
require 'spec_helper'
describe Api::V1::InfluencersController, type: :controller do
describe "GET search" do
before { @influencer = Influencer.make! name: "George Michael Bluth" }
it "should assign @documents" do
get :search, q: "George Michael Bluth", format: :json
expect(assigns(:documents)).to eq(PgSearch.multisearch("George Michael Bluth"))
end
it "should render the search template" do
get :search, q: "George Michael Bluth", format: :json
expect(response).to render_template("search")
end
end
end
|
class Geofence < ApplicationRecord
validates_presence_of :description
validates_presence_of :radius
validates_presence_of :lat
validates_presence_of :lng
end
|
require 'rails_helper'
feature 'user sees all existing ideas', js: true do
scenario 'including title, body, and quality for each' do
idea_1 = Idea.create(title: "This is idea #1",
body: "The body of idea #1 should be here")
idea_2 = Idea.create(title: "This is idea #2",
body: "The body of idea #2 should be here",
quality: "genius")
visit root_path
expect(current_path).to eq("/")
expect(page).to have_content(idea_1.title)
expect(page).to have_content(idea_1.body)
expect(page).to have_content("swill")
expect(page).to have_content(idea_2.title)
expect(page).to have_content(idea_2.body)
expect(page).to have_content(idea_2.quality)
end
scenario 'if body is longer than 100 characters it gets truncated' do
idea_1 = Idea.create(title: "This is idea #1",
body: "This is the body of the idea and it is more" \
" than 100 characters long long long long" \
"long long last long")
visit root_path
expect(page).to_not have_content(idea_1.body)
expect(page).to have_content("This is the body of the idea and it is more" \
" than 100 characters long long long long" \
"long long last")
end
end
|
FactoryGirl.define do
factory :hub do
name "Beltrami County"
percent_fee 1.5
end
end
|
class ChangeColumnName < ActiveRecord::Migration[5.2]
def change
rename_column :schools, :school_type, :city
end
end
|
class Role < ActiveRecord::Base
has_paper_trail
has_many :role_users, dependent: :destroy
validates :name, uniqueness: true, presence: true, length: {maximum: 32}
def human()
"Роль: #{self.name}"
end
def Role.models_human_name()
"Роли"
end
end
|
class ReviewStatus < ActiveRecord::Base
include HasValueField
default_value_method :system, :not_reviewed, :reviewed
end
|
require 'rails_helper'
RSpec.describe "admin/topics/edit", type: :view do
before(:each) do
@admin_topic = assign(:admin_topic, Admin::Topic.create!())
end
it "renders the edit admin_topic form" do
render
assert_select "form[action=?][method=?]", admin_topic_path(@admin_topic), "post" do
end
end
end
|
class Timeslot < ApplicationRecord
belongs_to :location
has_many :seatings
end
|
=begin
For added security, yet another system policy has been put in place. Now, a valid passphrase must contain no two words that are anagrams of each other - that is, a passphrase is invalid if any word's letters can be rearranged to form any other word in the passphrase.
For example:
abcde fghij is a valid passphrase.
abcde xyz ecdab is not valid - the letters from the third word can be rearranged to form the first word.
a ab abc abd abf abj is a valid passphrase, because all letters need to be used when forming another word.
iiii oiii ooii oooi oooo is valid.
oiii ioii iioi iiio is not valid - any of these words can be rearranged to form any other word.
Under this new system policy, how many passphrases are valid?
=end
puts File.readlines('input.txt')
.map {|x| x.split.map{ |y| y.chars.sort }}
.reduce(0) { |s, w| w.uniq == w ? s + 1 : s } |
class UsersController < ApplicationController
include ActionController::HttpAuthentication::Token::ControllerMethods
before_action :set_user, only: [:show, :update, :destroy]
before_action :current_user_security, only: [:show, :update, :destroy]
# GET /users
def index
@users = User.all
render json: @users
end
# GET /users/1
def show
render json: @user
end
# POST /users
def create
@user = School.find(params[:school][:id]).users.build(user_params)
if @user.save
render json: @user, status: :created, location: @user
else
render json: @user.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /users/1
def update
if @user.update(user_params)
render json: @user
else
render json: @user.errors, status: :unprocessable_entity
end
end
# DELETE /users/1
def destroy
@user.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def user_params
params.permit(:first_name, :last_name, :email, :password, :password_confirmation)
end
# Auth for resources that only the current user can access.
def current_user_security
authenticate_current_user_token || render_unauthorized
end
# Auth verification for resources that any user can access.
def authenticate_token
authenticate_with_http_token { |token, options| Session.find_by(auth_token: token) }
end
# Auth verification for resources that only the current user can access.
def authenticate_current_user_token
authenticate_with_http_token do |token, options|
return Session.find_by(auth_token: token).user.id != params[:id]
end
end
end
|
json.expenses @expenses.each do |expense|
json.id expense.id
json.created_at time_ago_in_words(expense.created_at) + ' ' + t('datetime.ago') + ' ' + t('datetime.at') + ' ' + expense.created_at.strftime('%H:%M')
json.amount expense.amount
json.comment expense.comment
json.date expense.date.strftime('%d %b %Y')
json.category expense.category.try(:title)
end
json.count @count
|
module ContentManagement
module ViewHelper
include Paths
# 内容 render 系统, 我们使用 render 功能来输出模版,参数与 render 基础版本是一致的,我
# 们仅增加了,with: 参数来声名渲染的对象是谁,With 是一个 Model 对象,
# @param name_or_options String, Hash Render 的参数
# @param options = {} [type] [description]
# @option options ActiveRecord::Base with 内容 Model 对象
# @param &block [type] [description]
#
# @return [type] [description]
def render(name_or_options, options = {}, &block)
if name_or_options.is_a? Hash
options = name_or_options
else
options[:partial] = name_or_options
end
template_class = options[:template_class] || PartialTemplateObject
if with_object = options[:with]
template_object = template_class.new(with_object, options[:partial])
# self.assigns["templable_object"] = template_object
name, type = template_object.view_name
if type == :file && options[:collection]
options[:partial] = template_object.send(:_normalize_path, name)
elsif type == :file
options[:file] = File.join(template_object.path, name)
options.delete(:partial)
else
options[:partial] = name
end
options[:template_object] = template_object.template
# options[:partial] = options[:filename] || template_object.view_name(options[:partial])
template_object.paths.each do |path|
push_view_paths path
end
options.delete(:with)
end
super(options, &block)
end
def render_collection(*args)
super
end
end
end
|
module ApplicationHelper
# @todo get experiments for current user only
#
def current_user_active_experiments
Sliced::Experiment.find_all_in_list(:active)
end
def current_user_pending_experiments
Sliced::Experiment.find_all_in_list(:pending)
end
def facebook_user_image(facebook_uid, size = 'square')
"http://graph.facebook.com/#{facebook_uid}/picture?type=#{size}"
end
def first_name
return unless current_user
current_user.name.split(' ')[0]
end
def last_name
return unless current_user
current_user.name.split(' ')[1]
end
def nice_datetime(time_as_int)
return '' if time_as_int.blank?
t = Time.at(time_as_int)
t.strftime("%d %b, %H:%M")
end
def time_ago_from_int(time_as_int)
return '' if time_as_int.blank?
t = Time.at(time_as_int)
"about #{time_ago_in_words(t)} ago"
end
def specific_css
return "" if @specific_css_list.nil?
links = ""
@specific_css_list.each do |file_name|
links += "#{stylesheet_link_tag file_name.to_s, :media => "all"}\n\t"
end
return links.html_safe
end
def specific_css_mobile
return "" if @specific_mobile_css_list.nil?
links = ""
@specific_mobile_css_list.each do |file_name|
links += "#{stylesheet_link_tag file_name.to_s, :media => "all"}\n\t"
end
return links.html_safe
end
def preview_url(experiment, variation_id)
delimiter = experiment.url.include?("?") ? "&" : "?"
short_type = Sliced::Experiment::SHORT_EXPERIMENT_TYPE[experiment.type]
"#{experiment.url}#{delimiter}sliced_mode=preview&experiment=#{experiment.id}&" <<
"variation=#{variation_id}&experiment_type=#{short_type}" <<
"&experiment_layer=#{experiment.layer}"
end
def impersonate_url(experiment, variation_id)
delimiter = experiment.url.include?("?") ? "&" : "?"
short_type = Sliced::Experiment::SHORT_EXPERIMENT_TYPE[experiment.type]
"#{experiment.url}#{delimiter}sliced_mode=impersonate&experiment=#{experiment.id}&" <<
"variation=#{variation_id}&experiment_type=#{short_type}" <<
"&experiment_layer=#{experiment.layer}"
end
def specific_js
return "" if @specific_js_list.nil?
links = ""
@specific_js_list.each do |file_name|
links += "#{javascript_include_tag file_name.to_s}\n\t"
end
return links.html_safe
end
end
|
class MovieService
class << self
def movie(movie_id)
response = conn.get("3/movie/#{movie_id}")
parse_data(response)
end
def movie_reviews(movie_id)
response = conn.get("3/movie/#{movie_id}/reviews")
parse_data(response)
end
def movie_cast(movie_id)
response = conn.get("3/movie/#{movie_id}/credits")
parse_data(response)
end
def top_rated_movies(page_number)
response = conn.get('3/movie/top_rated') do |req|
req.params['page'] = page_number
end
parse_data(response)
end
def title_search(movie_title)
response = conn.get('3/search/movie') do |req|
req.params['query'] = movie_title
end
parse_data(response)
end
private
def conn
Faraday.new(url: 'https://api.themoviedb.org/') do |faraday|
faraday.headers['Authorization'] = "Bearer #{ENV['movie_db_token']}"
faraday.headers['Accept'] = '*/*'
end
end
def parse_data(response)
JSON.parse(response.body, symbolize_names: true)
end
end
end
|
class UserMailer < ActionMailer::Base
include ActionView::Helpers::TextHelper
default from: "john@phaph.com"
def app_name
Rails.configuration.x.app_name
end
helper_method :app_name
def app_url
Rails.configuration.x.app_url
end
helper_method :app_url
# When someone follows you.
def follow_user_email(follower, user)
@user = user
@follower = follower
mail(to: @user.email, subject: "You have a new follower on #{app_name} ")
end
# When someone follows one of your collections.
def follow_collection_email(follower, collection)
@collection = collection
@follower = follower
mail(to: @collection.user.email, subject: "Your collection '#{@collection.name}' has a new follower!")
end
# When someone follows one of your collectibles.
def follow_collectible_email(follower, collectible)
@collectible = collectible
@follower = follower
mail(to: @collectible.user.email, subject: "'#{@collectible.name}' has a new follower!")
end
# When someone comments on you, or one of your collections or collectibles.
def comment_email(comment, commenter)
@comment = comment
@resource = comment.commentable
@commenter = commenter
mail(to: @comment.user.email, subject: "#{commenter.name} commented on '#{view_context.strip_tags(@comment.commentable.name)}'")
end
# When someone copies one of your collectibles. Called in CollectiblesController#clone
def copy_email(copyable, copier, user)
@user = user
@copier = copier
@copyable = copyable
mail(to: @user.email, subject: "#{@copier.name} copied your #{app_name} #{@copyable.class} \"#{@copyable.name}\"!")
end
def like_comment_email(liker, comment)
end
def new_collectible_email(collectible, follower, user)
@user = user
@follower = follower
@collectible = collectible
mail(to: @user.email, subject: "tk added a new item to #{app_name}!")
end
def new_collection_email(collection, follower, user)
@user = user
@follower = follower
@collection = collection
mail(to: @user.email, subject: "tk added a new collection to #{app_name}!")
end
end
|
require_relative 'library_item'
class Decorator < LibraryItem
def initialize(library_item)
@library_item = library_item
end
def display
@library_item.display
end
end
|
require 'net/http'
require 'rexml/document'
include REXML
Puppet::Type.type(:lm_virtualservice).provide(:ruby) do
def exists?
url = "https://#{resource[:host_ip]}/access/showvs?vs=#{resource[:ip]}&port=#{resource[:port]}&prot=#{resource[:protocol]}"
response = Document.new webrequest(url, resource[:host_username], resource[:host_password])
# response = Document.new <<EOF
# <Response stat="422" code="fail">
# <Error>Unknown VS</Error>
# </Response>
# EOF
if response.root.attributes["code"] == "fail"
raise Puppet::ParseError, "Failed to query load master, response code: #{response.root.attributes["stat"]}" if response.root.attributes["stat"] != "422"
return false
end
return true
end
def create
puts "Creating virtual service '#{resource[:name]}'"
url = "https://#{resource[:host_ip]}/access/addvs?vs=#{resource[:ip]}&port=#{resource[:port]}&prot=#{resource[:protocol]}"
response = Document.new webrequest(url, resource[:host_username], resource[:host_password])
# response = Document.new <<EOF
# <Response stat="422" code="success">
# <Error>Unknown VS</Error>
# </Response>
# EOF
if response.root.attributes["code"] == "fail"
raise Puppet::ParseError, "Failed to create virtual service '#{resource[:name]}', response code: #{response.root.attributes['stat']}"
end
end
def destroy
puts "Deleting virtual service '#{resource[:name]}'"
url = "https://#{resource[:host_ip]}/access/delvs?vs=#{resource[:ip]}&port=#{resource[:port]}&prot=#{resource[:protocol]}"
response = Document.new webrequest(url, resource[:host_username], resource[:host_password])
# response = Document.new <<EOF
# <Response stat="422" code="success">
# <Error>Unknown VS</Error>
# </Response>
# EOF
if response.root.attributes["code"] == "fail"
raise Puppet::ParseError, "Failed to delete virtual service '#{resource[:name]}', response code: #{response.root.attributes['stat']}"
end
end
def webrequest(url, username, password)
puts url
puts "Invoking web request: #{url}"
url = URI.parse(url)
req = Net::HTTP::Get.new(url.to_s)
req.basic_auth(username,password)
res = Net::HTTP.start(url.host, url.port,
:use_ssl => url.scheme == 'https',
:verify_mode => OpenSSL::SSL::VERIFY_NONE) {|http|
http.request(req)
}
puts res.body
end
end
|
require 'pry'
require 'rails'
class Person
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
end
def work(hours, rate)
penalty = block_given? ? yield : 1
{
name: name,
hours: hours,
dollars: hours * rate * penalty.to_f
}
end
def commute(distance, weather)
means = yield(weather)
speed = case means
when 'scooter'
20
when 'train'
30
when 'car'
30
end
rate = case means
when 'scooter'
20
when 'train'
30
when 'car'
50
end
{
minutes: to_minutes(distance.to_f / speed),
cost: distance.to_f * rate / 100
}
end
def self.check
'condition'.present?
end
def to_minutes(hours)
(hours * 60).round
end
end
john = Person.new('john', 25)
phil = Person.new('phil', 24)
john_wages_monday = john.work(8, 50)
# this method is used inside a block. It must be defined above the block in order for the block to know about it
# def check
# 'condition'.present?
# end
john_wages_sunday = john.work(8, 50) do
if Person.check
1.5
else
1.25
end
end
phil_wages = phil.work(8, 50) { 'a pretend conditional thing'.present? ? 2 : 3}
john_commute = john.commute(5, 'sunny') do |weather|
if weather == 'rain'
'train'
else
'scooter'
end
end
phil_commute = phil.commute(25, 'rain') do |weather|
if weather == 'rain'
'car'
else
'train'
end
end
p john_wages_monday
p john_wages_sunday
p phil_wages
p john_commute
p phil_commute |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.