text stringlengths 10 2.61M |
|---|
class VendorDatesController < ApplicationController
before_action :set_vendor_date, only: [:show, :edit, :update, :destroy]
# GET /vendor_dates
# GET /vendor_dates.json
def index
@vendor_dates = VendorDate.all
end
# GET /vendor_dates/1
# GET /vendor_dates/1.json
def show
end
# GET /vendor_dates/new
def new
@vendor_date = VendorDate.new
end
# GET /vendor_dates/1/edit
def edit
end
# POST /vendor_dates
# POST /vendor_dates.json
def create
puts vendor_date_params
@vendor_date = VendorDate.new(vendor_date_params)
respond_to do |format|
if @vendor_date.save
format.html { redirect_to @vendor_date, notice: 'Venue date was successfully created.' }
format.json { render :show, status: :created, location: @vendor_date }
else
format.html { render :new }
format.json { render json: @vendor_date.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /vendor_dates/1
# PATCH/PUT /vendor_dates/1.json
def update
respond_to do |format|
if @vendor_date.update(vendor_date_params)
format.html { redirect_to @vendor_date, notice: 'Venue date was successfully updated.' }
format.json { render :show, status: :ok, location: @vendor_date }
else
format.html { render :edit }
format.json { render json: @vendor_date.errors, status: :unprocessable_entity }
end
end
end
# DELETE /vendor_dates/1
# DELETE /vendor_dates/1.json
def destroy
@vendor_date.destroy
respond_to do |format|
format.html { redirect_to vendor_dates_url, notice: 'Venue date was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_vendor_date
@vendor_date = VendorDate.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def vendor_date_params
params.require(:vendor_date).permit(:vendor_id, :date, :service_id)
end
end
|
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :email
t.string :github_access_token
t.string :github_id
t.string :twitter_oauth_token
t.string :twitter_oauth_token_secret
t.string :twitter_id
t.string :remember_me_token
t.timestamps
end
add_index :users, :email, unique: true
add_index :users, :github_access_token
add_index :users, :github_id, unique: true
add_index :users, :twitter_oauth_token
add_index :users, :twitter_oauth_token_secret
add_index :users, :twitter_id, unique: true
add_index :users, :remember_me_token
end
end
|
module Pacer
module Routes
module RouteOperations
def range(from, to)
args = { :filter => :range }
args[:begin] = from if from
args[:end] = to if to
chain_route args
end
def limit(max)
chain_route :filter => :range, :limit => max
end
alias take limit
def offset(amount)
chain_route :filter => :range, :offset => amount
end
alias drop offset
def at(pos)
chain_route :filter => :range, :index => pos
end
end
end
module Filter
module RangeFilter
def limit(n = nil)
@limit = n
if range.begin == -1
@range = range.begin...n
else
@range = range.begin...(range.begin + n)
end
self
end
def limit=(n)
limit n
n
end
def offset(n = nil)
s = n
s += 1 if range.begin == -1
if range.end == -1
@range = (range.begin + s)..-1
elsif range.exclude_end?
@range = (range.begin + s)...(range.end + n)
else
@range = (range.begin + s)..(range.end + n)
end
self
end
alias drop offset
def offset=(n)
offset n
n
end
def range=(range)
@range = range
end
def begin=(n)
@range = n..range.end
end
def end=(n)
@range = range.begin..n
end
def index=(index)
@range = index..index
end
def range
@range ||= -1..-1
end
protected
def attach_pipe(end_pipe)
from = @range.begin
to = @range.end
if @range.exclude_end?
if to == 0
pipe = Pacer::Pipes::NeverPipe.new
pipe.set_starts end_pipe if end_pipe
return pipe
elsif to > 0
to -= 1
end
end
pipe = Pacer::Pipes::RangeFilterPipe.new from, to
pipe.set_starts end_pipe if end_pipe
pipe
end
def inspect_string
"#{ inspect_class_name }(#{ range.inspect })"
end
end
end
end
|
# frozen_string_literal: true
module Utility
# for posting slack
module Slack
extend ActiveSupport::Concern
# class method
module ClassMethods
def notify_slack(message)
return if Rails.application.config.slack_webhook_url.blank?
notifier = ::Slack::Notifier.new(Rails.application.config.slack_webhook_url)
notifier.ping(message, parse: 'full')
end
end
def notify_slack(message)
self.class.notify_slack(message)
end
end
end
|
module IOTA
module Multisig
class Address
def initialize(digests = nil)
# Initialize kerl instance
@kerl = IOTA::Crypto::Kerl.new
# Add digests if passed
absorb(digests) if digests
end
def absorb(digest)
# Construct array
digests = digest.class == Array ? digest : [digest]
# Add digests
digests.each do |d|
# Get trits of digest
digestTrits = IOTA::Crypto::Converter.trits(d)
# Absorb
@kerl.absorb(digestTrits, 0, digestTrits.length)
end
self
end
def finalize(digest = nil)
# Absorb last digest if passed
absorb(digest) if digest
# Squeeze the address trits
addressTrits = []
@kerl.squeeze(addressTrits, 0, IOTA::Crypto::Kerl::HASH_LENGTH)
# Convert trits into trytes and return the address
IOTA::Crypto::Converter.trytes(addressTrits)
end
end
end
end
|
describe ::PPC::API::Sm::Keyword do
auth = $sm_auth
keyword_service = ::PPC::API::Sm::Keyword
test_keyword_id = 0
test_plan_id = ::PPC::API::Sm::Plan.ids(auth)[:result][0]
test_group_id = ::PPC::API::Sm::Group.search_id_by_plan_id(auth, test_plan_id)[:result][0][:group_ids][0]
it "can get ids by group id" do
response = keyword_service.search_id_by_group_id(auth, test_group_id)
p response
expect(response[:succ]).to be true
group_id = response[:result][0][:group_id]
expect(group_id == test_group_id).to be true
expect(response[:result][0][:keyword_ids].is_a? Array).to be true
end
it "can get by group id" do
response = keyword_service.search_by_group_id(auth, test_group_id)
p response
expect(response[:succ]).to be true
expect(response[:succ]).to be true
group_id = response[:result][0][:group_id]
expect(group_id == test_group_id).to be true
expect(response[:result][0][:keywords].is_a? Array).to be true
end
it "can add a new keyword" do
response = keyword_service.add(auth, {group_id: test_group_id, keyword: 'testtest1', mobile_destination: 'http://m.elong.com', match_type: 'exact', pause: true, price: 1.2})
p response
expect(response[:succ]).to be true
expect(response[:succ]).to be true
expect(response[:result][0][:id]).to be > 0
test_keyword_id = response[:result][0][:id]
end
it "can update a keyword" do
response = keyword_service.update(auth, {id: test_keyword_id, price: 2})
p response
expect(response[:succ]).to be true
expect(response[:succ]).to be true
expect(response[:result][0][:price] == 2).to be true
end
it "can get by id" do
response = keyword_service.get(auth, test_keyword_id)
p response
expect(response[:succ]).to be true
expect(response[:succ]).to be true
expect(response[:result][0][:keyword]).to eql 'testtest1'
end
it "can delete by id" do
response = keyword_service.delete(auth, test_keyword_id)
p response
expect(response[:succ]).to be true
expect(response[:succ]).to be true
expect(response[:result]).to eql 0
end
end
|
# encoding: UTF-8
module OmniSearch
# we create this as a singleton
# so that only one connection to the cache exists
#
class Cache < ActiveSupport::Cache::MemCacheStore
include ::Singleton
attr_accessor :timestamp
def initialize
server = OmniSearch.configuration.memcache_server
@namespace = OmniSearch.configuration.memcache_namespace
@timestamp = new_timestamp
super(server, namespace: Proc.new{stamped_namespace})
end
def self.refresh
self.instance.refresh
end
def refresh
@timestamp = new_timestamp
end
def new_timestamp
Time.now.to_i
end
def stamped_namespace
"#{@namespace}_#{@timestamp}"
end
end
end
|
# Фильмы
# :title
# :year
# :slogan
# :director_id
# :budget
# :rating
# :our_rating
# :duration
# :is_viewed
class Film < ActiveRecord::Base
mount_uploader :image, ImageUploader
scope :has_image, -> { where.not(image: nil) }
scope :viewed, -> { where(is_viewed: true) }
scope :unviewed, -> { where(is_viewed: false) }
attr_accessor :directors
# Режиссеры, актеры
acts_as_taggable_on :directors, :actors
has_many :film_countries, dependent: :destroy
has_many :countries, through: :film_countries
accepts_nested_attributes_for :countries, allow_destroy: true, reject_if: proc{|att| att[:country_id].blank? }
# Просмотры
# Пока убираем
# has_many :views, as: :viewable, dependent: :destroy
# Уникальное имя по году
validates :title, uniqueness: { scope: :year }
class << self
def search(q)
self.where("title LIKE ?", "%#{q}%")
end
end
def countries_in_words
countries.map(&:title).join(", ")
end
end
|
class PublicationUnpublished < ActiveRecord::Base
belongs_to :publication
belongs_to :unpublished
end
|
class FixOutboards < ActiveRecord::Migration
def change
Boat.inactive.where('created_at > ?', 2.weeks.ago).each do |boat|
boat.save
end
end
end
|
class TiplineNewsletterType < DefaultObject
description "TiplineNewsletter type"
implements GraphQL::Types::Relay::Node
field :dbid, GraphQL::Types::Int, null: true
field :introduction, GraphQL::Types::String, null: true
field :header_type, GraphQL::Types::String, null: true
field :header_file_url, GraphQL::Types::String, null: true
field :header_overlay_text, GraphQL::Types::String, null: true
field :content_type, GraphQL::Types::String, null: true
field :rss_feed_url, GraphQL::Types::String, null: true
field :first_article, GraphQL::Types::String, null: true
field :second_article, GraphQL::Types::String, null: true
field :third_article, GraphQL::Types::String, null: true
field :number_of_articles, GraphQL::Types::Int, null: true
field :send_every, JsonStringType, null: true
field :send_on, GraphQL::Types::String, null: true
def send_on
object.send_on ? object.send_on.strftime("%Y-%m-%d") : nil
end
field :timezone, GraphQL::Types::String, null: true
field :time, GraphQL::Types::String, null: true
def time
object.time.strftime("%H:%M")
end
field :subscribers_count, GraphQL::Types::Int, null: true
field :footer, GraphQL::Types::String, null: true
field :language, GraphQL::Types::String, null: true
field :enabled, GraphQL::Types::Boolean, null: true
field :team, TeamType, null: true
field :last_scheduled_at, GraphQL::Types::Int, null: true
field :last_scheduled_by, UserType, null: true
field :last_sent_at, GraphQL::Types::Int, null: true
field :last_delivery_error, GraphQL::Types::String, null: true
end
|
class User < ApplicationRecord
devise :database_authenticatable, :registerable, :confirmable,
:recoverable, :rememberable, :trackable, :validatable, :lockable,
:omniauthable, omniauth_providers: [:google_oauth2]
validates :first_name, :second_name, presence: true
has_many :authentication_methods, dependent: :destroy
has_many :permissions, dependent: :destroy
def full_name
"#{first_name} #{second_name}"
end
end
|
require 'spec_helper'
require 'kibana'
describe ::Kibana do
include Rack::Test::Methods
def app
::Kibana.new
end
it 'returns kibana stuff on GET /' do
responses = ['/', '', '//', 'index.html'].map { |url|
get(url)
}
# Should all be a 200 and the same
responses.each do |r|
expect(r.status).to eql(200)
expect(r.body).to eql(responses.first.body)
expect(r.headers).to include(
'Cache-Control' => 'max-age=0, '\
'must-revalidate'
)
end
# Should have our header in it
expect(responses.first.body).to include('/logout')
end
it 'returns 404 on non-existant' do
expect(get('404').status).to eql(404)
end
end
|
class ChangeIsCompletedToCompleted < ActiveRecord::Migration
def change
remove_column :todos, :is_completed, :boolean
add_column :todos, :completed, :boolean, null: false, default: false
end
end
|
class CreateFeedbackTickets < ActiveRecord::Migration
def change
create_table :feedback_tickets do |t|
t.integer :ticket_id
t.float :ticket_rating
t.float :user_rating
end
end
end
|
require 'test_helper'
require 'redis'
require 'me_redis'
# safety for Redis class, prevents to run test if base is not empty
class RedisSafety < Redis
def initialize(options = {})
options[:db] = ENV['REDIS_TEST_DB'] || 5
super(options).tap do
# preventing accidental connect to existing DB!
raise "Redis DB contains keys! Check if the TEST_REDIS_DB ENV is appropriate and flushdb before running test" if self.keys('*').length > 0
end
end
end
class MeRedisTest < Minitest::Test
extend ActiveSupport::Testing::Declarative
def redis; @clear_redis ||= RedisSafety.new end
def setup; redis end
def teardown; redis.flushdb end
def check_me_methods(me_redis, redis, key, split)
me_redis.me_incr(key)
assert(me_redis.me_get(key) == '1')
assert (redis.hget(*split) == '1')
assert(redis.hget(*split) == me_redis.me_get(key))
me_redis.me_set(key, 'it works')
assert(me_redis.me_get(key) == 'it works')
assert(redis.hget(*split) == me_redis.me_get(key))
assert(me_redis.me_getset(key, 'Cool!') == 'it works')
assert(me_redis.me_get(key) == 'Cool!')
assert(redis.hget(*split) == me_redis.me_get(key))
assert(redis.hexists(*split))
assert(me_redis.me_exists?(key))
me_redis.me_del(key)
assert(!me_redis.me_exists?(key))
assert(!redis.hexists(*split))
me_redis.me_setnx(key, 'start')
assert(me_redis.me_get(key) == 'start')
me_redis.me_setnx(key, 'finish')
assert(me_redis.me_get(key) == 'start')
end
def check_me_multi_methods(me_redis, keys, splits)
me_redis.me_mset(keys[0], 'one', keys[1], 'two',)
assert(me_redis.me_get(keys[1]) == 'two')
assert(me_redis.hget(*splits[1]) == me_redis.me_get(keys[1]))
assert(me_redis.me_mget(*keys) == [me_redis.hget(*splits[0]), me_redis.hget(*splits[1])])
assert(me_redis.me_mget(*keys) == %w[one two])
end
def check_key_zipping(kz_redis)
kz_redis.class.configure do |c|
c.zip_crumbs = 'some/long/key/construct'.split('/')
end
key = 'some/long/construct/1'
kz_key = 's/l/c/1'
kz_redis.incr(key)
assert(kz_redis.get(key) == redis.get(kz_key))
assert(kz_redis.exists(key) == redis.exists(kz_key))
assert(kz_redis.type(key) == redis.type(kz_key))
kz_redis.decr(key)
assert(kz_redis.get(key) == '0')
kz_redis.decrby(key, 2)
assert(kz_redis.get(key) == '-2')
kz_redis.set(key, 'string')
assert(kz_redis.get(key) == redis.get(kz_key))
kz_redis.getset(key, {hash: true})
assert(kz_redis.get(key) == redis.get(kz_key))
kz_redis.del('some/long/construct/1')
assert(!kz_redis.exists('some/long/construct/1'))
kz_redis.incr('some/long/construct/1')
kz_redis.incr('some/long/construct/2')
kz_redis.rename('some/long/construct/1', 'some/long/construct/3')
assert(redis.exists('s/l/c/3'))
assert(!redis.exists('s/l/c/1'))
kz_redis.renamenx('some/long/construct/2', 'some/long/construct/3')
assert(redis.exists('s/l/c/2'))
end
def check_future(redis, must_be)
ftr = nil
redis.pipelined {ftr = yield}
assert(ftr.value == must_be)
end
test 'MeRedis configure' do
MeConfigureTest = Class.new(RedisSafety)
MeConfigureTest.include(MeRedis)
MeConfigureTest.configure {|c|
c.hash_max_ziplist_value = 100
c.hash_max_ziplist_entries = 100
c.compress_namespaces = [:key, :hkey]
c.zip_crumbs = 'test|test_me'.split('|')
}
redis = MeConfigureTest.new
assert( redis.config(:get, 'hash-max-ziplist-*')['hash-max-ziplist-entries'].to_i == 100 )
assert( redis.config(:get, 'hash-max-ziplist-*')['hash-max-ziplist-value'].to_i == 100 )
assert(MeConfigureTest.me_config.default_compressor == MeRedis::ZipValues::ZlibCompressor)
assert(MeConfigureTest.zip_ns_finder == {
string_ns: /\A(hkey|key)/,
rgxps_ns: nil,
rgxps_arr: []
})
assert(MeConfigureTest.key_zip_regxp == /(test_me|test)/)
assert(MeConfigureTest.me_config.zip_crumbs == {'test_me' => 't1', 'test' => 't'})
MeConfigureTest.configure {|c|
c.compress_namespaces = :key
c.zip_crumbs = 'test'
}
assert(MeConfigureTest.zip_ns_finder == {
string_ns: /\A(key)/,
rgxps_ns: nil,
rgxps_arr: []
})
assert(MeConfigureTest.key_zip_regxp == /(test)/)
assert(MeConfigureTest.me_config.zip_crumbs == {'test' => 't'})
MeConfigureTest.configure(
compress_namespaces: :key,
zip_crumbs: {test: :ts}
)
assert(MeConfigureTest.me_config.compress_namespaces == {'key' => MeConfigureTest.me_config.default_compressor})
assert(MeConfigureTest.key_zip_regxp == /(test)/)
assert(MeConfigureTest.me_config.zip_crumbs == {'test' => 'ts'})
key_rgxp = /key:[\d]+:/
MeConfigureTest.configure(
compress_namespaces: {
key_rgxp => MeRedis::ZipValues::EmptyCompressor,
hkey: MeRedis::ZipValues::EmptyCompressor
},
zip_crumbs: {hkey: :ts}
)
assert( MeConfigureTest.zip_ns_finder == {
string_ns: /\A(ts)/,
rgxps_ns: /\A(#{key_rgxp})/,
rgxps_arr: [key_rgxp]
})
assert(MeConfigureTest.me_config.compress_namespaces == {
key_rgxp => MeRedis::ZipValues::EmptyCompressor,
'ts' => MeRedis::ZipValues::EmptyCompressor
})
MeConfigureTest.configure(compress_namespaces: key_rgxp)
assert_raises(ArgumentError) do
MeConfigureTest.configure(compress_namespaces: MeRedis::ZipValues::EmptyCompressor)
end
assert_raises(ArgumentError) do
MeConfigureTest.configure(zip_crumbs: MeRedis::ZipValues::EmptyCompressor)
end
assert_raises(ArgumentError) do
MeConfigureTest.configure(zip_crumbs: {user: :u, user_preview: :u})
end
end
test "Test MeRedis base me_methods" do
me_redis = Class.new(RedisSafety)
.include(MeRedis::ZipToHash)
.configure(
hash_max_ziplist_entries: 64,
integers_to_base62: true
).new
key, key2 = 'user:100', 'user:101'
# 100 / 64 == 1, ( 100 % 64 ).to_base62 == 'A'
split, split2 = ['user:1', 'A'], ['user:1', 'B']
check_me_methods(me_redis, redis, key, split)
check_me_multi_methods(me_redis, [key, key2], [split, split2])
end
test "Test MeRedis base me_methods + Key zipping" do
me_redis = Class.new(RedisSafety)
.include(MeRedis::ZipToHash)
.prepend(MeRedis::ZipKeys)
.configure(
zip_crumbs: :user,
hash_max_ziplist_entries: 64,
integers_to_base62: true
).new
key, key2 = 'user:100', 'user:101'
# 100 / ( hash_max_ziplist_entries = 64 ) == 1, ( 100 % 64 ).to_base62 == 'A'
split, split2 = ['u:1', 'A'], ['u:1', 'B']
check_me_methods(me_redis, redis, key, split)
check_me_multi_methods(me_redis, [key, key2], [split, split2])
end
test "Test MeRedis " do
me_redis = Class.new(RedisSafety)
.include(MeRedis::ZipToHash)
.prepend(MeRedis::ZipKeys)
.configure(
zip_crumbs: [:user, :user_inside],
hash_max_ziplist_entries: 64,
integers_to_base62: true
).new
# test that sub crumb doesn't overthrow longer crumb
key = 'user_inside:100'
# 100 / 64 == 1, ( 100 % 64 ).to_base62 == 'A'
split = ['u1:1', 'A']
me_redis.me_incr(key)
assert(me_redis.me_get(key) == '1')
assert(redis.hget(*split) == me_redis.me_get(key))
# but in case of only shorter crumb present all goes also well
key, key2 = 'user:100', 'user:101'
# 100 / 64 == 1, ( 100 % 64 ).to_base62 == 'A'
split, split2 = ['u:1', 'A'], ['u:1', 'B']
redis.flushdb
check_me_methods(me_redis, redis, key, split)
check_me_multi_methods(me_redis, [key, key2], [split, split2])
end
test 'Key zipping' do
check_key_zipping(Class.new(RedisSafety).prepend(MeRedis::ZipKeys).new)
end
test 'Value zipping compressor matchig' do
gz_redis = Class.new(RedisSafety)
.prepend(MeRedis::ZipValues)
.configure(compress_namespaces: {
key: 1,
/org:[\d]+:hkey/ => 2
} ).new
gz_redis.class.get_compressor_for_key('org:123:hkey')
assert(gz_redis.class.get_compressor_for_key('org:123:hkey') == 2)
assert(gz_redis.class.get_compressor_for_key('org::hkey').nil?)
assert(gz_redis.class.get_compressor_for_key('key:1') == 1)
end
test 'Value zipping' do
gz_redis = Class.new(RedisSafety)
.prepend(MeRedis::ZipValues)
.configure(compress_namespaces: [:key, /hkey_[\d]+/]).new
str, str2 = 'Zip me string', {str: 'str'}
gz_redis.set(:key, str)
assert(Zlib.inflate(redis.get(:key)) == str)
assert(gz_redis.get(:key) == str)
gz_redis.hset(:hkey_1, 1, str)
assert(Zlib.inflate(redis.hget(:hkey_1, 1)) == str)
assert(gz_redis.hget(:hkey_1, 1) == str)
gz_redis.mset(:key, str2, :key1, str)
assert(redis.mget(:key, :key1).map! {|vl| Zlib.inflate(vl)} == [str2.to_s, str])
assert(gz_redis.mget(:key, :key1) == [str2.to_s, str])
gz_redis.hmset(:hkey_1, 1, str2, 2, str)
assert(redis.hmget(:hkey_1, 1, 2).map! {|vl| Zlib.inflate(vl)} == [str2.to_s, str])
assert(gz_redis.hmget(:hkey_1, 1, 2) == [str2.to_s, str])
end
test 'GZ pipelined' do
gz_redis = Class.new(RedisSafety)
.prepend(MeRedis::ZipValues)
.configure(compress_namespaces: :gz).new
str, str2 = 'Zip me string', {str: str}
gz_redis.set(:gz_key, str)
check_future(gz_redis, str) {gz_future = gz_redis.get(:gz_key)}
assert(Zlib.inflate(redis.get(:gz_key)) == str)
gz_redis.pipelined {gz_redis.hset(:gz_hkey, 1, str)}
assert(Zlib.inflate(redis.hget(:gz_hkey, 1)) == str)
check_future(gz_redis, str) {gz_future = gz_redis.hget(:gz_hkey, 1)}
gz_redis.pipelined {gz_redis.mset(:gz_key, str2, :gz_key1, str)}
assert(redis.mget(:gz_key, :gz_key1).map {|vl| Zlib.inflate(vl)} == [str2.to_s, str])
check_future(gz_redis, [str2.to_s, str]) {gz_redis.mget(:gz_key, :gz_key1)}
gz_redis.pipelined {gz_redis.hmset(:gz_hkey, 1, str2, 2, str)}
assert(redis.hmget(:gz_hkey, 1, 2).map {|vl| Zlib.inflate(vl)} == [str2.to_s, str])
assert(gz_redis.hmget(:gz_hkey, 1, 2) == [str2.to_s, str])
end
test 'Key gzipping + GZ' do
check_key_zipping(Class.new(RedisSafety)
.prepend(MeRedis::ZipValues)
.prepend(MeRedis::ZipKeys)
.new)
end
test 'Check gz and kz intersection' do
gzkz_redis = Class.new(RedisSafety)
.prepend(MeRedis::ZipValues)
.prepend(MeRedis::ZipKeys)
.configure {|c|
c.compress_namespaces = :gz_kz
c.zip_crumbs = c.compress_namespaces
}.new
str = 'Key zipped and also gzipped'
gzkz_redis.set(:gz_kz_me, str)
assert(Zlib::Inflate.inflate(redis.get(:g_me)) == gzkz_redis.get(:gz_kz_me))
assert(Zlib::Inflate.inflate(redis.get(:g_me)) == str)
end
test 'Check gz and kz regexp intersection' do
gzkz_redis = Class.new(RedisSafety)
.prepend(MeRedis::ZipValues)
.prepend(MeRedis::ZipKeys)
.configure(
zip_crumbs: :gz_kz,
compress_namespaces: /g:[\d]+/
).new
str = 'Key zipped and also gzipped'
gzkz_redis.set('gz_kz:100', str)
assert(Zlib::Inflate.inflate(redis.get('g:100')) == gzkz_redis.get('gz_kz:100'))
assert(Zlib::Inflate.inflate(redis.get('g:100')) == str)
gzkz_redis.class.configure(
zip_crumbs: :gz_kz,
compress_namespaces: /g:[\d]+/,
integers_to_base62: true
)
gzkz_redis.flushdb
# now compression would broke
gzkz_redis.set('gz_kz:50', str)
assert(redis.get('g:O') == str)
gzkz_redis.class.configure(
zip_crumbs: :gz_kz,
compress_namespaces: /g:[a-zA-Z\d]+/,
integers_to_base62: true
)
gzkz_redis.flushdb
gzkz_redis.set('gz_kz:100', str)
assert(Zlib::Inflate.inflate(redis.get('g:1C')) == gzkz_redis.get('gz_kz:100'))
assert(Zlib::Inflate.inflate(redis.get('g:1C')) == str)
end
test 'Full House Intersection' do
fh_redis = Class.new(RedisSafety)
.include(MeRedis)
.configure do |c|
c.compress_namespaces = 'user'
c.zip_crumbs = c.compress_namespaces
c.hash_max_ziplist_entries = 64
c.integers_to_base62 = true
end.new
str = 'Key zipped and also value gzipped'
key, key2 = 'user:100', 'user:101'
# 100 / 64 == 1, ( 100 % 64 ).to_base62 == 'A'
split, split2 = ['u:1', 'A'], ['u:1', 'B']
# it's a bad idea to use GZ COmpressor on integers, but for testing purpose
fh_redis.me_incr(key)
assert(fh_redis.me_get(key) == '1')
assert (redis.hget(*split) == '1')
assert(redis.hget(*split) == fh_redis.me_get(key))
fh_redis.me_set(key, str)
assert(Zlib::Inflate.inflate(redis.hget(*split)) == fh_redis.me_get(key))
assert(Zlib::Inflate.inflate(redis.hget(*split)) == str)
assert(fh_redis.me_getset(key, 'Cool!') == str)
assert(fh_redis.me_get(key) == 'Cool!')
assert(Zlib::Inflate.inflate(redis.hget(*split)) == fh_redis.me_get(key))
assert(redis.hexists(*split))
assert(fh_redis.me_exists?(key))
fh_redis.me_del(key)
assert(!fh_redis.me_exists?(key))
assert(!redis.hexists(*split))
fh_redis.me_setnx(key, 'start')
assert(fh_redis.me_get(key) == 'start')
fh_redis.me_setnx(key, 'finish')
assert(fh_redis.me_get(key) == 'start')
check_me_multi_methods(fh_redis, [key, key2], [split, split2])
end
test 'Migrator fallbacks' do
hm_redis = Class.new(RedisSafety)
.include(MeRedisHotMigrator)
.configure(
hash_max_ziplist_entries: 64,
integers_to_base62: true,
zip_crumbs: :user).new
assert(!hm_redis.me_get('user:100'))
redis.set('user:100', 1)
assert(!redis.hget(*hm_redis.send(:split_key, 'user:100')))
assert(hm_redis.me_get('user:100') == '1')
# fallback to long keys and hash methods before set
redis.mset('user:100', 1, 'user:101', 2)
assert(hm_redis.get('user:100') == '1')
assert(hm_redis.exists('user:100'))
assert(hm_redis.type('user:100') == 'none')
assert(hm_redis.mget('user:100', 'user:101') == %w[1 2])
assert(hm_redis.me_mget('user:100', 'user:101') == %w[1 2])
assert(hm_redis.getset('user:100', 3) == '1')
hm_redis.mset('user:101', 4)
assert(redis.mget('user:100', 'user:101') == %w[3 2])
assert(redis.mget('u:1C', 'u:1D') == %w[3 4])
assert(hm_redis.mget('user:100', 'user:101') == %w[3 4])
redis.flushdb
hm_redis.me_mset('user:100', 5, 'user:101', 6)
assert(hm_redis.me_mget('user:100', 'user:101') == %w[5 6])
redis.flushdb
redis.hset('user', 'A', 1)
assert(hm_redis.hget('user', 'A') == '1')
assert(hm_redis.hgetall('user') == {"A" => "1"})
end
test 'Migrator fallbacks with pipelines' do
hm_redis = Class.new(RedisSafety)
.include(MeRedisHotMigrator)
.configure(
hash_max_ziplist_entries: 64,
integers_to_base62: true,
zip_crumbs: :user
).new
redis.set('user:100', 1)
check_future(hm_redis, '1') {hm_redis.me_get('user:100')}
check_future(hm_redis, '1') {hm_redis.get('user:100')}
# fallback to long keys and hash methods before set
redis.mset('user:100', 1, 'user:101', 2)
check_future(hm_redis, true) {hm_redis.exists('user:100')}
check_future(hm_redis, 'none') {hm_redis.type('user:100')}
check_future(hm_redis, %w[1 2]) {hm_redis.mget('user:100', 'user:101')}
ftr = nil
hm_redis.pipelined {ftr = hm_redis.me_mget_p('user:100', 'user:101')}
assert(ftr.map(&:value) == %w[1 2])
check_future(hm_redis, '1') {hm_redis.getset('user:100', 3)}
hm_redis.mset('user:101', 4)
assert(redis.mget('user:100', 'user:101') == %w[3 2])
assert(redis.mget('u:1C', 'u:1D') == %w[3 4])
check_future(hm_redis, %w[3 4]) {hm_redis.mget('user:100', 'user:101')}
redis.flushdb
redis.hset('user', 'A', 1)
check_future(hm_redis, '1') {hm_redis.hget('user', 'A')}
check_future(hm_redis, {"A" => "1"}) {hm_redis.hgetall('user')}
redis.flushdb
hm_redis.me_mset('user:100', 5, 'user:101', 6)
assert(hm_redis.me_mget('user:100', 'user:101') == %w[5 6])
end
test 'AwsConfigBlocker' do
aws_redis = Class.new(RedisSafety)
aws_redis.send(:define_method, :config) {|*_| raise "AWS raise emulation" }
aws_redis.include(MeRedis)
assert_raises(StandardError) { aws_redis.new }
assert(
aws_redis.configure(
hash_max_ziplist_entries: 256,
hash_max_ziplist_value: 1024,
integers_to_base62: true,
zip_crumbs: :user )
)
aws_redis.prepend(MeRedis::AwsConfigBlocker)
assert( aws_redis.new.config == {} )
end
end
|
# frozen_string_literal: true
require "active_support/core_ext/hash/except"
require "active_support/core_ext/hash/slice"
module ActionController
# This module provides a method which will redirect the browser to use the secured HTTPS
# protocol. This will ensure that users' sensitive information will be
# transferred safely over the internet. You _should_ always force the browser
# to use HTTPS when you're transferring sensitive information such as
# user authentication, account information, or credit card information.
#
# Note that if you are really concerned about your application security,
# you might consider using +config.force_ssl+ in your config file instead.
# That will ensure all the data is transferred via HTTPS, and will
# prevent the user from getting their session hijacked when accessing the
# site over unsecured HTTP protocol.
module ForceSSL
extend ActiveSupport::Concern
include AbstractController::Callbacks
ACTION_OPTIONS = [:only, :except, :if, :unless]
URL_OPTIONS = [:protocol, :host, :domain, :subdomain, :port, :path]
REDIRECT_OPTIONS = [:status, :flash, :alert, :notice]
module ClassMethods
# Force the request to this particular controller or specified actions to be
# through the HTTPS protocol.
#
# If you need to disable this for any reason (e.g. development) then you can use
# an +:if+ or +:unless+ condition.
#
# class AccountsController < ApplicationController
# force_ssl if: :ssl_configured?
#
# def ssl_configured?
# !Rails.env.development?
# end
# end
#
# ==== URL Options
# You can pass any of the following options to affect the redirect url
# * <tt>host</tt> - Redirect to a different host name
# * <tt>subdomain</tt> - Redirect to a different subdomain
# * <tt>domain</tt> - Redirect to a different domain
# * <tt>port</tt> - Redirect to a non-standard port
# * <tt>path</tt> - Redirect to a different path
#
# ==== Redirect Options
# You can pass any of the following options to affect the redirect status and response
# * <tt>status</tt> - Redirect with a custom status (default is 301 Moved Permanently)
# * <tt>flash</tt> - Set a flash message when redirecting
# * <tt>alert</tt> - Set an alert message when redirecting
# * <tt>notice</tt> - Set a notice message when redirecting
#
# ==== Action Options
# You can pass any of the following options to affect the before_action callback
# * <tt>only</tt> - The callback should be run only for this action
# * <tt>except</tt> - The callback should be run for all actions except this action
# * <tt>if</tt> - A symbol naming an instance method or a proc; the
# callback will be called only when it returns a true value.
# * <tt>unless</tt> - A symbol naming an instance method or a proc; the
# callback will be called only when it returns a false value.
def force_ssl(options = {})
action_options = options.slice(*ACTION_OPTIONS)
redirect_options = options.except(*ACTION_OPTIONS)
before_action(action_options) do
force_ssl_redirect(redirect_options)
end
end
end
# Redirect the existing request to use the HTTPS protocol.
#
# ==== Parameters
# * <tt>host_or_options</tt> - Either a host name or any of the url and
# redirect options available to the <tt>force_ssl</tt> method.
def force_ssl_redirect(host_or_options = nil)
unless request.ssl?
options = {
protocol: "https://",
host: request.host,
path: request.fullpath,
status: :moved_permanently
}
if host_or_options.is_a?(Hash)
options.merge!(host_or_options)
elsif host_or_options
options[:host] = host_or_options
end
secure_url = ActionDispatch::Http::URL.url_for(options.slice(*URL_OPTIONS))
flash.keep if respond_to?(:flash) && request.respond_to?(:flash)
redirect_to secure_url, options.slice(*REDIRECT_OPTIONS)
end
end
end
end
|
module ZombieApocalypse
class Input
@@creatures = File.readlines("input.txt")[2].scan(/\d+/).map(&:to_i).each_slice(2).to_a
attr_accessor :grid_size, :zombie_origin_x, :zombie_origin_y, :path
def initialize(options={})
inputs = File.readlines("input.txt")
@grid_size = options[:grid_size] || inputs[0].chomp.to_i #4
@zombie_origin_x = options[:zombie_origin_x] || inputs[1].scan(/\d+/).map(&:to_i)[0]
@zombie_origin_y = options[:zombie_origin_y] || inputs[1].scan(/\d+/).map(&:to_i)[1]
@path = options[:path] || inputs[3].upcase.split("") #["U","D","L",..]
end
def self.creatures
@@creatures
end
def self.kill_creature(creature)
@@creatures.delete(creature)
end
end
end |
# frozen_string_literal: true
# exchange_rates.rb
# Author: William Woodruff
# ------------------------
# A Cinch plugin that provides USD currency exchange rates for yossarian-bot.
# Data courtesy of Open Exchange Rates: https://openexchangerates.org/
# ------------------------
# This code is licensed by William Woodruff under the MIT License.
# http://opensource.org/licenses/MIT
require "json"
require "open-uri"
require_relative "yossarian_plugin"
class ExchangeRates < YossarianPlugin
include Cinch::Plugin
use_blacklist
KEY = ENV["OEX_API_KEY"]
URL = "https://openexchangerates.org/api/latest.json?app_id=%{key}"
def usage
"!rate <code [code2...]> - Get the currency exchange rate between USD and one or more currencies."
end
def match?(cmd)
cmd =~ /^(!)?rate$/
end
match /rate (.+)/, method: :exchange_rate, strip_colors: true
def exchange_rate(m, code)
if KEY
url = URL % { key: KEY }
codes = code.upcase.split
begin
hash = JSON.parse(URI.open(url).read)
hash["rates"].default = "?"
rates = codes.map do |curr|
"USD/#{curr}: #{hash['rates'][curr]}"
end.join(", ")
m.reply rates, true
rescue Exception => e
m.reply e.to_s, true
end
else
m.reply "#{self.class.name}: Internal error (missing API key)."
end
end
end
|
module WeatherApi
class Units
FAHRENHEIT = 'f'
CELSIUS = 'c'
attr_reader :temperature,
:distance,
:pressure,
:speed
def initialize(payload)
@temperature = payload[:temperature]&.strip
@distance = payload[:distance]&.strip
@pressure = payload[:pressure]&.strip
@speed = payload[:speed]&.strip
end
end
end
|
#
# Cookbook Name:: mysql
# Recipe:: default
#
# Copyright (c) 2015 The Authors, All Rights Reserved.
#package 'mysql-server' do
# action :install
#end
#service 'mysqld' do
# action [:start, :enable]
#end
#package "gcc"
#package "gcc-c++"
#package "make"
#package "openssl-devel"
#package "pcre-devel"
mysql_root_pwd = "ADMINPASSWORD"
mysql_default_db = "waman"
mysql_config_file = "/etc/mysql/my.cnf"
#version = "5.6.26-1"
#bash "install_mysql_from_source" do
# cwd Chef::Config['file_cache_path']
# code <<-EOH
# wget http://dev.mysql.com/get/Downloads/MySQL-5.6/MySQL-#{version}.el6.src.rpm
# rpm -Uvh MySQL-5.6/MySQL-#{version}.el6.src.rpm
# cd /home/vagrant/rpmbuild/SOURCES/mysql-5.6.26
# ./configure && make && make install
# EOH
# not_if "test -f /usr/local/nginx/sbin/nginx"
#end
package "mysql-server" do
action :install
end
service "mysqld" do
service_name "mysqld"
supports [:restart, :reload, :status]
action [:start, :enable]
end
# set the root password
execute "/usr/bin/mysqladmin -uroot password #{mysql_root_pwd}" do
not_if "/usr/bin/mysqladmin -uroot -p#{mysql_root_pwd} status"
end
# create the default database
execute "/usr/bin/mysql -uroot -p#{mysql_root_pwd} -e 'CREATE DATABASE IF NOT EXISTS #{mysql_default_db}'"
# grant privileges to the user so that he can get access from the host machine
execute "/usr/bin/mysql -uroot -p#{mysql_root_pwd} -e \"GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '#{mysql_root_pwd}' WITH GRANT OPTION;\""
#execute "sed -i 's/127.0.0.1/0.0.0.0/g' #{mysql_config_file}" do
#not_if "cat #{mysql_config_file} | grep 0.0.0.0"
#end
service "mysqld" do
action :restart
end |
# coding: utf-8
require 'rspec'
require './arangodb.rb'
describe ArangoDB do
api = "/_api/collection"
prefix = "api-collection"
context "dealing with collections:" do
################################################################################
## reading all collections
################################################################################
context "all collections:" do
before do
for cn in ["units", "employees", "locations" ] do
ArangoDB.drop_collection(cn)
@cid = ArangoDB.create_collection(cn)
end
end
after do
for cn in ["units", "employees", "locations" ] do
ArangoDB.drop_collection(cn)
end
end
it "returns all collections" do
cmd = api
doc = ArangoDB.log_get("#{prefix}-all-collections", cmd)
doc.code.should eq(200)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(false)
doc.parsed_response['code'].should eq(200)
collections = doc.parsed_response['collections']
names = doc.parsed_response['names']
# filter out system collections
realCollections = [ ]
collections.each { |collection|
if collection['name'].slice(0, 1) != "_"
realCollections.push(collection)
end
}
realNames = { }
names.each do |name, collection|
if name.slice(0, 1) != '_'
realNames[name] = collection
end
end
realCollections.length.should eq(3)
realNames.length.should eq(3)
for collection in realCollections do
realNames[collection['name']].should eq(collection)
end
end
end
################################################################################
## error handling
################################################################################
context "error handling:" do
it "returns an error if collection identifier is unknown" do
cmd = api + "/123456"
doc = ArangoDB.log_get("#{prefix}-bad-identifier", cmd)
doc.code.should eq(404)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(true)
doc.parsed_response['errorNum'].should eq(1203)
doc.parsed_response['code'].should eq(404)
end
it "creating a collection without name" do
cmd = api
doc = ArangoDB.log_post("#{prefix}-create-missing-name", cmd)
doc.code.should eq(400)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(true)
doc.parsed_response['code'].should eq(400)
doc.parsed_response['errorNum'].should eq(1208)
end
it "creating a collection with an illegal name" do
cmd = api
body = "{ \"name\" : \"1\" }"
doc = ArangoDB.log_post("#{prefix}-create-illegal-name", cmd, :body => body)
doc.code.should eq(400)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(true)
doc.parsed_response['code'].should eq(400)
doc.parsed_response['errorNum'].should eq(1208)
end
it "creating a collection with a duplicate name" do
cn = "UnitTestsCollectionBasics"
cid = ArangoDB.create_collection(cn)
cmd = api
body = "{ \"name\" : \"#{cn}\" }"
doc = ArangoDB.log_post("#{prefix}-create-illegal-name", cmd, :body => body)
doc.code.should eq(400)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(true)
doc.parsed_response['code'].should eq(400)
doc.parsed_response['errorNum'].should eq(1207)
end
it "creating a collection with an illegal body" do
cmd = api
body = "{ name : world }"
doc = ArangoDB.log_post("#{prefix}-create-illegal-body", cmd, :body => body)
doc.code.should eq(400)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(true)
doc.parsed_response['code'].should eq(400)
doc.parsed_response['errorNum'].should eq(600)
doc.parsed_response['errorMessage'].should eq("SyntaxError: Unexpected token n")
end
it "creating a collection with a null body" do
cmd = api
body = "null"
doc = ArangoDB.log_post("#{prefix}-create-null-body", cmd, :body => body)
doc.code.should eq(400)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(true)
doc.parsed_response['code'].should eq(400)
doc.parsed_response['errorNum'].should eq(1208)
end
end
################################################################################
## reading a collection
################################################################################
context "reading:" do
before do
@cn = "UnitTestsCollectionBasics"
ArangoDB.drop_collection(@cn)
@cid = ArangoDB.create_collection(@cn)
end
after do
ArangoDB.drop_collection(@cn)
end
# get
it "finds the collection by identifier" do
cmd = api + "/" + String(@cid)
doc = ArangoDB.log_get("#{prefix}-get-collection-identifier", cmd)
doc.code.should eq(200)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(false)
doc.parsed_response['code'].should eq(200)
doc.parsed_response['id'].should eq(@cid)
doc.parsed_response['name'].should eq(@cn)
doc.parsed_response['status'].should eq(3)
doc.headers['location'].should eq(api + "/" + String(@cid))
cmd2 = api + "/" + String(@cid) + "/unload"
doc = ArangoDB.put(cmd2)
doc = ArangoDB.log_get("#{prefix}-get-collection-identifier", cmd)
doc.code.should eq(200)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(false)
doc.parsed_response['code'].should eq(200)
doc.parsed_response['id'].should eq(@cid)
doc.parsed_response['name'].should eq(@cn)
[2,4].include?(doc.parsed_response['status']).should be_true
doc.headers['location'].should eq(api + "/" + String(@cid))
end
# get
it "finds the collection by name" do
cmd = api + "/" + String(@cn)
doc = ArangoDB.log_get("#{prefix}-get-collection-name", cmd)
doc.code.should eq(200)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(false)
doc.parsed_response['code'].should eq(200)
doc.parsed_response['id'].should eq(@cid)
doc.parsed_response['name'].should eq(@cn)
doc.parsed_response['status'].should eq(3)
doc.headers['location'].should eq(api + "/" + String(@cid))
cmd2 = api + "/" + String(@cid) + "/unload"
doc = ArangoDB.put(cmd2)
doc = ArangoDB.log_get("#{prefix}-get-collection-name", cmd)
doc.code.should eq(200)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(false)
doc.parsed_response['code'].should eq(200)
doc.parsed_response['id'].should eq(@cid)
doc.parsed_response['name'].should eq(@cn)
[2,4].include?(doc.parsed_response['status']).should be_true
doc.headers['location'].should eq(api + "/" + String(@cid))
end
# get count
it "checks the size of a collection" do
cmd = api + "/" + String(@cid) + "/count"
doc = ArangoDB.log_get("#{prefix}-get-collection-count", cmd)
doc.code.should eq(200)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(false)
doc.parsed_response['code'].should eq(200)
doc.parsed_response['id'].should eq(@cid)
doc.parsed_response['name'].should eq(@cn)
doc.parsed_response['status'].should eq(3)
doc.parsed_response['count'].should be_kind_of(Integer)
doc.headers['location'].should eq(api + "/" + String(@cid) + "/count")
end
# get count
it "checks the properties of a collection" do
cmd = api + "/" + String(@cid) + "/properties"
doc = ArangoDB.log_get("#{prefix}-get-collection-properties", cmd)
doc.code.should eq(200)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(false)
doc.parsed_response['code'].should eq(200)
doc.parsed_response['id'].should eq(@cid)
doc.parsed_response['name'].should eq(@cn)
doc.parsed_response['status'].should eq(3)
doc.parsed_response['waitForSync'].should eq(true)
doc.parsed_response['journalSize'].should be_kind_of(Integer)
doc.headers['location'].should eq(api + "/" + String(@cid) + "/properties")
end
# get figures
it "extracting the figures for a collection" do
cmd = api + "/" + String(@cid) + "/figures"
doc = ArangoDB.log_get("#{prefix}-get-collection-figures", cmd)
doc.code.should eq(200)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(false)
doc.parsed_response['code'].should eq(200)
doc.parsed_response['id'].should eq(@cid)
doc.parsed_response['name'].should eq(@cn)
doc.parsed_response['status'].should eq(3)
doc.parsed_response['count'].should be_kind_of(Integer)
doc.parsed_response['figures']['alive']['count'].should be_kind_of(Integer)
doc.parsed_response['count'].should eq(doc.parsed_response['figures']['alive']['count'])
doc.parsed_response['journalSize'].should be_kind_of(Integer)
doc.headers['location'].should eq(api + "/" + String(@cid) + "/figures")
end
end
################################################################################
## deleting of collection
################################################################################
context "deleting:" do
before do
@cn = "UnitTestsCollectionBasics"
end
it "delete an existing collection by identifier" do
cid = ArangoDB.create_collection(@cn)
cmd = api + "/" + String(cid)
doc = ArangoDB.log_delete("#{prefix}-delete-collection-identifier", cmd)
doc.code.should eq(200)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(false)
doc.parsed_response['code'].should eq(200)
doc.parsed_response['id'].should eq(cid)
cmd = api + "/" + String(cid)
doc = ArangoDB.get(cmd)
doc.parsed_response['error'].should eq(true)
doc.parsed_response['code'].should eq(404)
end
it "delete an existing collection by name" do
cid = ArangoDB.create_collection(@cn)
cmd = api + "/" + @cn
doc = ArangoDB.log_delete("#{prefix}-delete-collection-name", cmd)
doc.code.should eq(200)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(false)
doc.parsed_response['code'].should eq(200)
doc.parsed_response['id'].should eq(cid)
cmd = api + "/" + String(cid)
doc = ArangoDB.get(cmd)
doc.parsed_response['error'].should eq(true)
doc.parsed_response['code'].should eq(404)
end
end
################################################################################
## creating a collection
################################################################################
context "creating:" do
before do
@cn = "UnitTestsCollectionBasics"
end
it "create a collection" do
cmd = api
body = "{ \"name\" : \"#{@cn}\" }"
doc = ArangoDB.log_post("#{prefix}-create-collection", cmd, :body => body)
doc.code.should eq(200)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(false)
doc.parsed_response['code'].should eq(200)
doc.parsed_response['id'].should be_kind_of(Integer)
doc.parsed_response['name'].should eq(@cn)
doc.parsed_response['waitForSync'].should == false
cmd = api + "/" + String(@cn) + "/figures"
doc = ArangoDB.get(cmd)
doc.parsed_response['waitForSync'].should == false
ArangoDB.drop_collection(@cn)
end
it "create a collection, sync" do
cmd = api
body = "{ \"name\" : \"#{@cn}\", \"waitForSync\" : true }"
doc = ArangoDB.log_post("#{prefix}-create-collection-sync", cmd, :body => body)
doc.code.should eq(200)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(false)
doc.parsed_response['code'].should eq(200)
doc.parsed_response['id'].should be_kind_of(Integer)
doc.parsed_response['name'].should eq(@cn)
doc.parsed_response['waitForSync'].should == true
cmd = api + "/" + String(@cn) + "/figures"
doc = ArangoDB.get(cmd)
doc.parsed_response['waitForSync'].should == true
ArangoDB.drop_collection(@cn)
end
it "create a collection, using a collection id" do
ArangoDB.drop_collection(@cn)
cmd = api
body = "{ \"name\" : \"#{@cn}\", \"_id\" : 12345678 }"
doc = ArangoDB.log_post("#{prefix}-create-collection-id", cmd, :body => body)
doc.code.should eq(200)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(false)
doc.parsed_response['code'].should eq(200)
doc.parsed_response['id'].should be_kind_of(Integer)
doc.parsed_response['id'].should eq(12345678)
doc.parsed_response['name'].should eq(@cn)
ArangoDB.drop_collection(@cn)
end
it "create a collection, using duplicate collection id" do
ArangoDB.drop_collection(@cn)
ArangoDB.drop_collection(123456789)
cmd = api
body = "{ \"name\" : \"#{@cn}\", \"_id\" : 123456789 }"
doc = ArangoDB.log_post("#{prefix}-create-collection-id-dup", cmd, :body => body)
doc.code.should eq(200)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(false)
doc.parsed_response['code'].should eq(200)
doc.parsed_response['id'].should be_kind_of(Integer)
doc.parsed_response['id'].should eq(123456789)
doc.parsed_response['name'].should eq(@cn)
body = "{ \"name\" : \"#{@cn}2\", \"_id\" : 123456789 }"
doc = ArangoDB.log_post("#{prefix}-create-collection-id-dup", cmd, :body => body)
doc.code.should eq(400)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(true)
doc.parsed_response['code'].should eq(400)
ArangoDB.drop_collection(@cn)
end
it "create a collection, invalid name" do
cmd = api
body = "{ \"name\" : \"_invalid\" }"
doc = ArangoDB.log_post("#{prefix}-create-collection-invalid", cmd, :body => body)
doc.code.should eq(400)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(true)
doc.parsed_response['code'].should eq(400)
end
it "create a collection, already existing" do
ArangoDB.drop_collection(@cn)
cmd = api
body = "{ \"name\" : \"#{@cn}\" }"
doc = ArangoDB.log_post("#{prefix}-create-collection-existing", cmd, :body => body)
doc.code.should eq(200)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(false)
doc.parsed_response['code'].should eq(200)
body = "{ \"name\" : \"#{@cn}\" }"
doc = ArangoDB.log_post("#{prefix}-create-collection-existing", cmd, :body => body)
doc.code.should eq(400)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(true)
doc.parsed_response['code'].should eq(400)
ArangoDB.drop_collection(@cn)
end
end
################################################################################
## load a collection
################################################################################
ArangoDB.drop_collection(@cn)
context "loading:" do
before do
@cn = "UnitTestsCollectionBasics"
end
it "load a collection by identifier" do
ArangoDB.drop_collection(@cn)
cid = ArangoDB.create_collection(@cn)
cmd = api + "/" + String(cid) + "/load"
doc = ArangoDB.log_put("#{prefix}-identifier-load", cmd)
doc.code.should eq(200)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(false)
doc.parsed_response['code'].should eq(200)
doc.parsed_response['id'].should eq(cid)
doc.parsed_response['name'].should eq(@cn)
doc.parsed_response['status'].should eq(3)
doc.parsed_response['count'].should be_kind_of(Integer)
ArangoDB.drop_collection(@cn)
end
it "load a collection by name" do
ArangoDB.drop_collection(@cn)
cid = ArangoDB.create_collection(@cn)
cmd = api + "/" + @cn + "/load"
doc = ArangoDB.log_put("#{prefix}-name-load", cmd)
doc.code.should eq(200)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(false)
doc.parsed_response['code'].should eq(200)
doc.parsed_response['id'].should eq(cid)
doc.parsed_response['name'].should eq(@cn)
doc.parsed_response['status'].should eq(3)
doc.parsed_response['count'].should be_kind_of(Integer)
ArangoDB.drop_collection(@cn)
end
end
################################################################################
## unloading a collection
################################################################################
context "unloading:" do
before do
@cn = "UnitTestsCollectionBasics"
end
it "unload a collection by identifier" do
ArangoDB.drop_collection(@cn)
cid = ArangoDB.create_collection(@cn)
cmd = api + "/" + String(cid) + "/unload"
doc = ArangoDB.log_put("#{prefix}-identifier-unload", cmd)
doc.code.should eq(200)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(false)
doc.parsed_response['code'].should eq(200)
doc.parsed_response['id'].should eq(cid)
doc.parsed_response['name'].should eq(@cn)
[2,4].include?(doc.parsed_response['status']).should be_true
ArangoDB.drop_collection(@cn)
end
it "unload a collection by name" do
ArangoDB.drop_collection(@cn)
cid = ArangoDB.create_collection(@cn)
cmd = api + "/" + @cn + "/unload"
doc = ArangoDB.log_put("#{prefix}-name-unload", cmd)
doc.code.should eq(200)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(false)
doc.parsed_response['code'].should eq(200)
doc.parsed_response['id'].should eq(cid)
doc.parsed_response['name'].should eq(@cn)
[2,4].include?(doc.parsed_response['status']).should be_true
ArangoDB.drop_collection(@cn)
end
end
################################################################################
## truncate a collection
################################################################################
context "truncating:" do
before do
@cn = "UnitTestsCollectionBasics"
@cid = ArangoDB.create_collection(@cn)
end
after do
ArangoDB.drop_collection(@cn)
end
it "truncate a collection by identifier" do
cmd = "/_api/document?collection=#{@cid}"
body = "{ \"Hallo\" : \"World\" }"
for i in ( 1 .. 10 )
doc = ArangoDB.post(cmd, :body => body)
end
ArangoDB.size_collection(@cid).should eq(10)
cmd = api + "/" + String(@cid) + "/truncate"
doc = ArangoDB.log_put("#{prefix}-identifier-truncate", cmd)
doc.code.should eq(200)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(false)
doc.parsed_response['code'].should eq(200)
doc.parsed_response['id'].should eq(@cid)
doc.parsed_response['name'].should eq(@cn)
doc.parsed_response['status'].should eq(3)
ArangoDB.size_collection(@cid).should eq(0)
ArangoDB.drop_collection(@cn)
end
end
################################################################################
## renames a collection
################################################################################
context "renaming:" do
it "rename a collection by identifier" do
cn = "UnitTestsCollectionBasics"
ArangoDB.drop_collection(cn)
cid = ArangoDB.create_collection(cn)
cmd = "/_api/document?collection=#{cid}"
body = "{ \"Hallo\" : \"World\" }"
for i in ( 1 .. 10 )
doc = ArangoDB.post(cmd, :body => body)
end
ArangoDB.size_collection(cid).should eq(10)
ArangoDB.size_collection(cn).should eq(10)
cn2 = "UnitTestsCollectionBasics2"
ArangoDB.drop_collection(cn2)
body = "{ \"name\" : \"#{cn2}\" }"
cmd = api + "/" + String(cid) + "/rename"
doc = ArangoDB.log_put("#{prefix}-identifier-rename", cmd, :body => body)
doc.code.should eq(200)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(false)
doc.parsed_response['code'].should eq(200)
doc.parsed_response['id'].should eq(cid)
doc.parsed_response['name'].should eq(cn2)
doc.parsed_response['status'].should eq(3)
ArangoDB.size_collection(cid).should eq(10)
ArangoDB.size_collection(cn2).should eq(10)
cmd = api + "/" + String(cn)
doc = ArangoDB.get(cmd)
doc.code.should eq(404)
doc.parsed_response['error'].should eq(true)
doc.parsed_response['errorNum'].should eq(1203)
cmd = api + "/" + String(cn2)
doc = ArangoDB.get(cmd)
doc.code.should eq(200)
doc.parsed_response['error'].should eq(false)
doc.parsed_response['name'].should eq(cn2)
doc.parsed_response['status'].should eq(3)
ArangoDB.drop_collection(cn)
ArangoDB.drop_collection(cn2)
end
it "rename a collection by identifier with conflict" do
cn = "UnitTestsCollectionBasics"
ArangoDB.drop_collection(cn)
cid = ArangoDB.create_collection(cn)
cn2 = "UnitTestsCollectionBasics2"
ArangoDB.drop_collection(cn2)
cid2 = ArangoDB.create_collection(cn2)
body = "{ \"Hallo\" : \"World\" }"
cmd = "/_api/document?collection=#{cid}"
for i in ( 1 .. 10 )
doc = ArangoDB.post(cmd, :body => body)
end
ArangoDB.size_collection(cid).should eq(10)
ArangoDB.size_collection(cn).should eq(10)
cmd = "/_api/document?collection=#{cid2}"
for i in ( 1 .. 20 )
doc = ArangoDB.post(cmd, :body => body)
end
ArangoDB.size_collection(cid2).should eq(20)
ArangoDB.size_collection(cn2).should eq(20)
body = "{ \"name\" : \"#{cn2}\" }"
cmd = api + "/" + String(cid) + "/rename"
doc = ArangoDB.log_put("#{prefix}-identifier-rename-conflict", cmd, :body => body)
doc.code.should eq(400)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(true)
doc.parsed_response['code'].should eq(400)
doc.parsed_response['errorNum'].should eq(1207)
ArangoDB.size_collection(cid).should eq(10)
ArangoDB.size_collection(cn).should eq(10)
ArangoDB.size_collection(cid2).should eq(20)
ArangoDB.size_collection(cn2).should eq(20)
ArangoDB.drop_collection(cn)
ArangoDB.drop_collection(cn2)
end
it "rename a new-born collection by identifier" do
cn = "UnitTestsCollectionBasics"
ArangoDB.drop_collection(cn)
cid = ArangoDB.create_collection(cn)
cn2 = "UnitTestsCollectionBasics2"
ArangoDB.drop_collection(cn2)
body = "{ \"name\" : \"#{cn2}\" }"
cmd = api + "/" + String(cid) + "/rename"
doc = ArangoDB.log_put("#{prefix}-identifier-rename-new-born", cmd, :body => body)
doc.code.should eq(200)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(false)
doc.parsed_response['code'].should eq(200)
doc.parsed_response['id'].should eq(cid)
doc.parsed_response['name'].should eq(cn2)
doc.parsed_response['status'].should eq(3)
cmd = api + "/" + String(cn)
doc = ArangoDB.get(cmd)
doc.code.should eq(404)
doc.parsed_response['error'].should eq(true)
doc.parsed_response['errorNum'].should eq(1203)
cmd = api + "/" + String(cn2)
doc = ArangoDB.get(cmd)
doc.code.should eq(200)
doc.parsed_response['error'].should eq(false)
doc.parsed_response['name'].should eq(cn2)
doc.parsed_response['status'].should eq(3)
ArangoDB.drop_collection(cn)
ArangoDB.drop_collection(cn2)
end
it "rename a new-born collection by identifier with conflict" do
cn = "UnitTestsCollectionBasics"
ArangoDB.drop_collection(cn)
cid = ArangoDB.create_collection(cn)
cn2 = "UnitTestsCollectionBasics2"
ArangoDB.drop_collection(cn2)
cid2 = ArangoDB.create_collection(cn2)
cmd = "/_api/document?collection=#{cid2}"
body = "{ \"name\" : \"#{cn2}\" }"
cmd = api + "/" + String(cid) + "/rename"
doc = ArangoDB.log_put("#{prefix}-identifier-rename-conflict", cmd, :body => body)
doc.code.should eq(400)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(true)
doc.parsed_response['code'].should eq(400)
doc.parsed_response['errorNum'].should eq(1207)
ArangoDB.drop_collection(cn)
ArangoDB.drop_collection(cn2)
end
end
################################################################################
## properties of a collection
################################################################################
context "properties:" do
it "changing the properties of a collection by identifier" do
cn = "UnitTestsCollectionBasics"
ArangoDB.drop_collection(cn)
cid = ArangoDB.create_collection(cn)
cmd = "/_api/document?collection=#{cid}"
body = "{ \"Hallo\" : \"World\" }"
for i in ( 1 .. 10 )
doc = ArangoDB.post(cmd, :body => body)
end
ArangoDB.size_collection(cid).should eq(10)
ArangoDB.size_collection(cn).should eq(10)
cmd = api + "/" + String(cid) + "/properties"
body = "{ \"waitForSync\" : true }"
doc = ArangoDB.log_put("#{prefix}-identifier-properties-sync", cmd, :body => body)
doc.code.should eq(200)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(false)
doc.parsed_response['code'].should eq(200)
doc.parsed_response['id'].should eq(cid)
doc.parsed_response['name'].should eq(cn)
doc.parsed_response['status'].should eq(3)
doc.parsed_response['waitForSync'].should eq(true)
cmd = api + "/" + String(cid) + "/properties"
body = "{ \"waitForSync\" : false }"
doc = ArangoDB.log_put("#{prefix}-identifier-properties-no-sync", cmd, :body => body)
doc.code.should eq(200)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(false)
doc.parsed_response['code'].should eq(200)
doc.parsed_response['id'].should eq(cid)
doc.parsed_response['name'].should eq(cn)
doc.parsed_response['status'].should eq(3)
doc.parsed_response['waitForSync'].should eq(false)
ArangoDB.drop_collection(cn)
end
end
end
end
|
require "socket"
require "timeout"
class Lxi_device < TCPSocket
# attr_accessor :timeout_seconds
# def initialize()
# @timeout_seconds = 0.1
# end
public :gets
def send_ascii_line(line)
line.chomp
#puts writes each of its arguments, adding a newline after each
self.puts(line)
end
def read_response()
#v=0.1
timeout_seconds=0.1
result=String.new
begin
timeout(timeout_seconds){
while (true) do
result=result + self.getc.chr
end
}
rescue TimeoutError => my_err
#we do nothing, just trap the err
##if you are going to print, this class has a print,puts
## and printf method, so be careful!
#STDOUT.print "\n_____Timeout_________(" + my_err.to_s + ")\n"
end
return result
end
def send_command(line)
send_ascii_line(line)
return read_response
end
# def get_possible_commands()
# response=send_command("help")
# lines=response.split("\n")
# ### we ignore the first three lines and the last one
# possible_commands=lines[3..lines.size-2]
# return possible_commands
# end
def reconnect(server_name,server_port)
end
end
|
class CreateTiles < ActiveRecord::Migration
def self.up
create_table :tiles do |t|
t.integer :user_id
t.integer :x,:null=>false
t.integer :y,:null=>false
t.integer :page_id,:null=>false
t.boolean :activated
t.integer :points,:null=>false,:default=>0
t.timestamps
end
end
def self.down
drop_table :tiles
end
end
|
class ComunesController < ApplicationController
# GET /comunes
# GET /comunes.json
def index
@comunes = Comune.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @comunes }
end
end
# GET /comunes/1
# GET /comunes/1.json
def show
@comune = Comune.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @comune }
end
end
# GET /comunes/new
# GET /comunes/new.json
def new
@comune = Comune.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @comune }
end
end
# GET /comunes/1/edit
def edit
@comune = Comune.find(params[:id])
end
# POST /comunes
# POST /comunes.json
def create
@comune = Comune.new(params[:comune])
respond_to do |format|
if @comune.save
format.html { redirect_to @comune, notice: 'Comune was successfully created.' }
format.json { render json: @comune, status: :created, location: @comune }
else
format.html { render action: "new" }
format.json { render json: @comune.errors, status: :unprocessable_entity }
end
end
end
# PUT /comunes/1
# PUT /comunes/1.json
def update
@comune = Comune.find(params[:id])
respond_to do |format|
if @comune.update_attributes(params[:comune])
format.html { redirect_to @comune, notice: 'Comune was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @comune.errors, status: :unprocessable_entity }
end
end
end
# DELETE /comunes/1
# DELETE /comunes/1.json
def destroy
@comune = Comune.find(params[:id])
@comune.destroy
respond_to do |format|
format.html { redirect_to comunes_url }
format.json { head :no_content }
end
end
end
|
require 'spec_helper'
module Strumbar
module Instrumentation
module Mongoid
describe RuntimeTracker do
%w(runtime count).each do |attribute|
describe ".#{attribute}" do
it "is a class attribute" do
RuntimeTracker.send("#{attribute}=", 100)
RuntimeTracker.send(attribute).should == 100
end
end
end
end
describe ".reset" do
it "returns the current runtime" do
RuntimeTracker.runtime = 1500
RuntimeTracker.reset.should == 1500
end
it "resets the count and runtime attributes" do
RuntimeTracker.runtime = 1000
RuntimeTracker.count = 2
RuntimeTracker.reset
RuntimeTracker.runtime.should == 0
RuntimeTracker.count.should == 0
end
end
end
end
end
|
require 'test_helper'
class V1::OrdersControllerTest < ActionDispatch::IntegrationTest
setup do
@order = orders(:one)
@user = @order.user
@access_token = @user.tokens.where(kind: 'access').first.uuid
end
test 'should get index' do
get v1_orders_url(access_token: @access_token), as: :json
assert_response :success
end
test 'should create order' do
order_params = { status: 'created' }
assert_difference('Order.count') do
post v1_orders_url(access_token: @access_token),
params: order_params, as: :json
end
assert_response :created
end
test 'should show order' do
get v1_order_url(@order, access_token: @access_token), as: :json
assert_response :success
end
test 'should update order' do
patch v1_order_url(@order, access_token: @access_token),
params: { status: 'packed' }, as: :json
assert_response :ok
end
test 'should destroy order' do
assert_difference('Order.count', -1) do
delete v1_order_url(@order, access_token: @access_token), as: :json
end
assert_response :no_content
end
end
|
class Guide::Fixture
# Fixtures are used to generate content for your Living Guide
# that would otherwise be repetitive, such as view models that are used
# from multiple components. Declaring these in a single place is useful
# because it helps keep a consistent interface between the fake view models
# in the Living Guide and the real view models in your application.
#
# Feel free to override or redeclare this class if you want.
# Nothing in the Guide gem depends on it.
private
def self.image_path(image_name, extension)
Guide::Photographer.new(image_name, extension).image_path
end
end
|
require 'spec_helper'
require 'tempfile'
RSpec.describe FlickrCollage::FileLoader do
before do
FlickRaw.api_key = 'api_key'
FlickRaw.shared_secret = 'shared_secret'
allow_any_instance_of(FlickRaw::Flickr).to receive(:call).and_return([])
allow_any_instance_of(FlickRaw::Flickr).to receive_message_chain('photos.search')
.and_return(['photos.search return'])
allow(FlickRaw).to receive(:url_b).and_return('url://dummy')
allow_any_instance_of(FlickrCollage::FileLoader).to receive(:open).and_yield(Tempfile.new)
allow(Magick::Image).to receive(:from_blob).and_return([random_image])
end
it 'contains FLICK_RAW_URL_METHODS constant' do
expect(FlickrCollage::FileLoader::FLICK_RAW_URL_METHODS)
.to eq(%w(url url_m url_s url_t url_b url_z url_q url_n url_c url_o))
end
context '#load_flickr_files' do
it 'returns a Magick::ImageList' do
expect(FlickrCollage::FileLoader.image_list(['test']).first).to be_a(Magick::ImageList)
end
it 'raises Errors::NoFlickRawURLMethod for unknown FlickRaw url method' do
expect { subject.load_flickr_files(['test'], url_method: 'unknown') }
.to raise_error(FlickrCollage::Errors::NoFlickRawURLMethod)
end
context 'without flickr.photos.search response item' do
before do
allow(FlickrCollage::Dictionary).to receive(:words).and_return(['word'])
allow_any_instance_of(FlickRaw::Flickr).to receive_message_chain('photos.search')
.with(tags: ['test'], sort: 'interestingness-desc', content_type: 1, per_page: 1) { [] }
allow_any_instance_of(FlickRaw::Flickr).to receive_message_chain('photos.search')
.with(tags: ['word'], sort: 'interestingness-desc', content_type: 1, per_page: 1) { ['photos.search return'] }
end
it 'raises Errors::NoImageFound and retries with a dictionary word' do
image_list, unsuccessful_keywords = subject.load_flickr_files(['test'])
expect(image_list).to be_a(Magick::ImageList)
expect(unsuccessful_keywords).to eq('test' => 'word')
end
end
end
context '.image_list' do
it 'calls load_flickr_files on a new instance' do
allow_any_instance_of(FlickrCollage::FileLoader).to receive(:load_flickr_files)
.with(['keyword']).and_return('called')
expect(FlickrCollage::FileLoader.image_list(['keyword'])).to eq('called')
end
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure(2) do |config|
NodeCount = 4
(1..NodeCount).each do |i|
config.vm.define "test#{i}" do |demo|
demo.vm.box = "centos/7"
demo.vm.hostname = "temp#{i}"
demo.vm.network "private_network", ip: "10.10.10.1#{i}"
demo.vm.network "forwarded_port", guest: "80", host: "8#{i}",
auto_correct: true
demo.vm.network "forwarded_port", guest: "8080", host: "808#{i}",
auto_correct: true
demo.vm.provider "virtualbox" do |vb|
vb.cpus = 2
vb.memory = 1024
end
demo.vm.provision "shell", inline: <<-SHELL
yum update
yum install wget vim
yum install centos-release-gluster -y
yum install epel-release -y
yum install glusterfs-server -y
systemctl enable glusterd
systemctl start glusterd
echo "[TASK 11] Enable ssh password authentication"
sed -i 's/^PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config
systemctl reload sshd
echo "[TASK 12] Set root password"
echo "test" | passwd --stdin root >/dev/null 2>&1
SHELL
end
end
end
|
class Sprite < Draco::Component
attribute :path
attribute :flip_vertically, default: false
attribute :flip_horizontally, default: false
attribute :color, default: nil
attribute :source_w
attribute :source_h
attribute :source_x
attribute :source_y
end
|
module Orocos
module RemoteProcesses
# Representation of a remote process started with ProcessClient#start
class Process < ProcessBase
# The ProcessClient instance that gives us access to the remote process
# server
attr_reader :process_client
# A string describing the host. It can be used to check if two processes
# are running on the same host
def host_id; process_client.host_id end
# True if this process is located on the same machine than the ruby
# interpreter
def on_localhost?; process_client.host == 'localhost' end
# The process ID of this process on the machine of the process server
attr_reader :pid
def initialize(name, deployment_model, process_client, pid)
@process_client = process_client
@pid = pid
@alive = true
super(name, deployment_model)
end
# Retunging the Process name of the remote process
def process
self
end
# Called to announce that this process has quit
def dead!
@alive = false
end
# Returns the task context object for the process' task that has this
# name
def task(task_name)
process_client.name_service.get(task_name, process: self)
end
# Cleanly stop the process
#
# @see kill!
def kill(wait = true, cleanup: true, hard: false)
process_client.stop(name, wait, cleanup: cleanup, hard: hard)
end
# Wait for the
def join
process_client.join(name)
end
# True if the process is running. This is an alias for running?
def alive?; @alive end
# True if the process is running. This is an alias for alive?
def running?; @alive end
# Resolve all tasks within the deployment
#
# A deployment is usually considered ready when all its tasks can be
# resolved successfully
def resolve_all_tasks(cache = Hash.new)
Orocos::Process.resolve_all_tasks(self, cache) do |task_name|
task(task_name)
end
end
# Waits for the deployment to be ready. +timeout+ is the number of
# milliseconds we should wait. If it is nil, will wait indefinitely
def wait_running(timeout = nil)
Orocos::Process.wait_running(self, timeout)
end
end
end
end
|
Locate the ruby documentation for methods File::path and File#path. How are they different?
Answer:
Both found here: https://ruby-doc.org/core-2.5.0/File.html#method-c-path
File::path returns the string representation of the path
File#path returns the pathname used to create file as a string |
class AddConstraintsToResearchUsers < ActiveRecord::Migration[5.2]
def change
add_index :research_users, [:user_id, :research_id], unique: true
end
end
|
require 'spec_helper'
describe TagsController, :type => :controller do
before(:each) do
c1 = FactoryGirl.create(:character, name: 'Sherlock Holmes')
c2 = FactoryGirl.create(:character, name: 'Catwoman')
c3 = FactoryGirl.create(:character, name: 'Bast')
c4 = FactoryGirl.create(:character, name: 'Batman')
c1.tag_list = 'detectives, sherlock holmes'
c2.tag_list = 'batman, cats'
c3.tag_list = 'egyptian gods, deities, cats'
c4.tag_list = 'batman, detectives'
c1.save!
c2.save!
c3.save!
c4.save!
end
describe "GET index" do
it "renders the index template" do
get :index
expect(response).to render_template('index')
end
it "sets the character tags ordered by name" do
get :index
tag_names = assigns(:character_tags).map { |t| t.name }
expect(tag_names).to eq(['batman', 'cats', 'deities', 'detectives', 'egyptian gods', 'sherlock holmes'])
end
end
describe "GET view" do
it "renders the view template" do
get :view, :tag => 'batman'
expect(response).to render_template('view')
end
it "sets the tag" do
get :view, :tag => 'batman'
expect(assigns(:tag)).to eq('batman')
end
it "sets the characters" do
get :view, :tag => 'batman'
expect(assigns(:characters)).to eq([Character.find(4), Character.find(2)])
end
it "deals with non-existing tags" do
get :view, :tag => 'dogs'
expect(assigns(:characters).size).to eq(0)
end
end
end
|
class CreateHeadachesExistingIllnessesJoinTable < ActiveRecord::Migration
def self.up
create_table :headaches_existing_illnesses, :id => false do |t|
t.references :headache, :existing_illness
end
end
def self.down
drop_table :headaches_existing_illnesses
end
end
|
class AddCommonToUsers < ActiveRecord::Migration
def change
add_column :users, :common, :boolean
end
end
|
require 'process/roulette/croupier/controller_socket'
module Process
module Roulette
module Croupier
# The JoinPending class encapsulates the handling of pending connections
# during the 'join' phase of the croupier state machine. It explicitly
# handles new player and new controller connections, moving them from
# the pending list to the appropriate collections of the croupier itself,
# depending on their handshake.
class JoinPending < Array
def initialize(driver)
super()
@driver = driver
end
def reap!
delete_if(&:dead?)
end
def cleanup!
return unless any?
puts 'closing pending connections'
each(&:close)
end
def process(socket, packet)
_handle_nil(socket, packet) ||
_handle_new_player(socket, packet) ||
_handle_new_controller(socket, packet, @driver.password) ||
_handle_new_controller(socket, packet, 'OK') ||
_handle_ping(socket, packet) ||
_handle_unexpected(socket, packet)
end
def _handle_nil(socket, packet)
return false unless packet.nil?
puts 'pending socket closed'
delete(socket)
true
end
def _handle_new_player(socket, packet)
return false unless /^OK:(?<username>.*)/ =~ packet
socket.username = username
delete(socket)
if @driver.players.any? { |p| p.username == socket.username }
_player_username_taken(socket)
else
_player_accepted(socket)
end
true
end
def _handle_new_controller(socket, packet, password)
return false unless packet == password
socket.extend(ControllerSocket)
socket.spectator! if password == 'OK'
puts format('accepting new %s',
socket.spectator? ? 'spectator' : 'controller')
socket.send_packet('OK')
delete(socket)
@driver.controllers << socket
true
end
def _handle_ping(_socket, packet)
return false unless packet == 'PING'
true
end
def _handle_unexpected(_socket, packet)
puts "unexpected input from pending socket (#{packet.inspect})"
true
end
def _player_username_taken(socket)
puts 'rejecting: username already taken'
socket.send_packet('username already taken')
socket.close
end
def _player_accepted(socket)
puts "accepting new player #{socket.username}"
socket.send_packet('OK')
@driver.players << socket
@driver.broadcast_update(
"player '#{socket.username}' added" \
" (#{@driver.players.length} total)")
end
end
end
end
end
|
class TravelersController < ApplicationController
def index
@travelers = Traveler.all
end
def show
@traveler = Traveler.find(params[:id])
@favorite_countries = @traveler.vacations.where(favorite: true).map(&:country)
end
end |
# encoding: utf-8
describe Faceter::Coercers, ".prefix" do
subject { described_class[:prefix] }
it "coerces arguments" do
expect(subject[:foo]).to eql(
prefix: :foo,
separator: "_",
nested: false,
selector: nil
)
end
it "coerces arguments" do
attributes = subject[:foo, separator: ".", nested: true, only: /foo/]
expect(attributes).to eq(
prefix: :foo,
separator: ".",
nested: true,
selector: Selector.new(only: /foo/)
)
end
it "coerces arguments" do
attributes = subject[:foo, separator: ".", nested: true, except: /foo/]
expect(attributes).to eq(
prefix: :foo,
separator: ".",
nested: true,
selector: Selector.new(except: /foo/)
)
end
end # describe Faceter::Coercers.prefix
|
# encoding: UTF-8
require_relative 'Damage'
require_relative 'SpecificDamageToUI'
module Deepspace
class SpecificDamage < Damage
def initialize (wl, s) # wl: Array<WeaponType>, s: int
super(s)
@weapons = wl
end
attr_reader :weapons
def self.newCopy (d) # d: SpecificDamage
new(Array.new(d.weapons), d.nShields)
end
def newCopy # "contructor de copia" de instancia
self.class.newCopy(self)
end
def getUIversion
SpecificDamageToUI.new(self)
end
def to_s
getUIversion.to_s
end
def arrayContainsType (w, t) # arrayContainsType (w: Array<Weapon>, t: WeaponType) : int
for i in 0 .. w.length-1
if(w[i].type == t)
return i
end
end
-1
end
def adjust (weapons, s) # adjust (w: Array<Weapon>, s: Array<ShieldBooster>) : Damage
wCopy = @weapons.clone # Creamos copia para no modificar atributo
adjustedWeapons = weapons.map do |w|
wCopy.delete_at(wCopy.index(w.type) || wCopy.length)
end
adjustedWeapons.compact! # Elimina nils
self.class.new(adjustedWeapons, adjustNShields(s))
end
def discardWeapon(w) # discardWeapon (w: Weapon) : void
@weapons.delete_if {|x| x == w.type}
end
def hasNoEffect
super && (@weapons == nil || @weapons.length == 0)
end
# Especificación de acceso a métodos privados
# private :arrayContainsType
end
end
if $0 == __FILE__
require_relative 'Weapon'
require_relative 'WeaponType'
require_relative 'ShieldBooster'
arrayWT = Array.new(3){Deepspace::WeaponType::LASER}
d = Deepspace::SpecificDamage.new(arrayWT,4)
puts d
d2 = Deepspace::SpecificDamage.newCopy(d)
puts d2
arrayW = Array.new(2){Deepspace::Weapon.new("hola1",Deepspace::WeaponType::LASER,1)}
puts d.arrayContainsType(arrayW, Deepspace::WeaponType::LASER)
arrayS = Array.new(3){Deepspace::ShieldBooster.new("hola2", 2.0, 1)}
puts d.adjust(arrayW,arrayS)
d.discardWeapon(Deepspace::Weapon.new("hola1",Deepspace::WeaponType::LASER,1))
puts d
puts d.hasNoEffect
end
|
class ContactFormsController < ApplicationController
before_filter :authenticate_user!, :check_authorization, :except => [ :create ]
def new
@contact_form = ContactForm.new
end
def create
@contact_form = ContactForm.new( params[:contact_form] )
if verify_recaptcha( :model => @contact_form, :message => 'Recaptcha error' ) && @contact_form.valid?
flash[:success] = "Your email has been sent."
ContactMailer.deliver_contact_email( @contact_form )
redirect_to root_url
else
flash[:error] = "You have failed to prive all the required information. Please start over."
@contact = Section.find_by_name('contacto')
redirect_to params[:return_page]
end
end
end
|
require 'rails_helper'
describe 'User OAuth tokens' do
describe 'should be properly encrypted with the attr_encrypted gem' do
before do
@user = User.create(email: 'test01@test.com',
password: '123456',
password_confirmation: '123456')
end
it 'should save an OAuth token when persisted' do
@user.github_token = 'aldfjaoeunfo2i3j2j2l3j'
@user.save
expect(@user.github_token).to eql('aldfjaoeunfo2i3j2j2l3j')
end
it 'should be properly encrypted' do
@user.github_token = 'aldfjaoeunfo2i3j2j2l3j'
@user.save
expect(@user.encrypted_github_token).not_to be_nil
end
it 'should create an iv when the token is persisted' do
@user.github_token = 'aldfjaoeunfo2i3j2j2l3j'
@user.save
expect(@user.encrypted_github_token_iv).not_to be_nil
end
end
end
|
#========================================================================
#
# init settings
#
#========================================================================
class Game_Config
attr_accessor :debug_info
attr_accessor :flag_output_info
attr_accessor :clean_output_data # clean file every time open the game?
attr_accessor :configs # Current applied comfigs
attr_accessor :shared_items # Royal Supplies
#============================================================
# *)Initalize
#============================================================
def initialize
@debug_info = []
@flag_output_info = true
@clean_output_data = true
@configs = []
@shared_items = []
init_debug_info
end
#============================================================
# *)Init debug info & file
#============================================================
def init_debug_info
return if !@flag_output_info
if clean_output_data
file = File.new("Debug_Info.dat","w")
file.write("")
file.close
end
file = File.new("Debug_Info.dat","a")
file.write("\n")
file.write("=============================================================\n")
file.write(" Game Launched Time : #{Time.now}\n")
file.write("=============================================================\n")
if !$pre_output_debug_infos.nil?
file.write("---------------------------------------------\n")
file.write(" Load game world setting \n")
file.write("---------------------------------------------\n")
for str in $pre_output_debug_infos
file.write(str)
@configs.push(str)
file.write("\n")
end
end
file.close
output_debug_info("\\\\\\\\\\\\\\\\\\~~!Hello World!~~///////////////")
end
#============================================================
# *) Output debug information
#============================================================
def output_debug_info(str,show_time = true)
return if !@flag_output_info
file = File.new("Debug_Info.dat","a")
str = str.to_s
str = sprintf("[%s] | %s\n",Time.now.to_s,str) if show_time
file.write(str)
file.write("---------------------------------------------------------------------------------------\n")
file.close
end
#============================================================
# *)Load Configs
#============================================================
def read_configs
#================================================
# Game World Settings
#================================================
file = File.new("001_Configs.rvdata2")
puts "--------------------------------------------------"
puts " Load game world setting"
puts "--------------------------------------------------"
#================================================
# encode : n*4 + 1 ; decode: (n-1) / 4
#================================================
if file
@configs = []
infos = []
str = ""
i = 0
line = file.gets
while i < line.size
code = 0
mul = 100
if line[i] == '0' # end of line
i += 1
infos.push(str)
str = ""
end # end of line
i += 1
break if i > line.size # prevent overflow
for j in 0...3
char = line[i+j].to_i
code += char * mul
mul /= 10
end #load encoded char
code = (code-1) /4
str += (code.chr)
i += 3
end # while i < line.size
for i in infos
puts "#{i}"
@configs.push(i)
end
file.close
end # if file
end # def read_configs
#============================================================
# *)Show current applied configs
#============================================================
def show_configs
puts "-------- Read configs -------"
for i in 0...@configs.size
p sprintf("Line %3d: %s\n",i,@configs[i])
end
puts " ------- End of Configs -------"
end
#============================================================
# *) Encode config
#============================================================
def encode_config(cmd)
encoded_str = ""
ascii_str = []
cmd.each_byte do |c|
ascii_str.push(c)
end
for ch in ascii_str
distract = (rand(8) + 1).to_s
encrypt_ch = (ch * 4 + 1).to_s
encoded_str += distract + encrypt_ch
end
encoded_str += '0'
return encoded_str
end
#============================================================
# *) REWRITE current applied configs
#============================================================
def update_config(type,str = "")
#---------------------------------
# Attach or rewrite all configs
#---------------------------------
if type.upcase != "W" && type.upcase != "D" || str.size < 5
msgbox("Config Error:\n" + "Invalied config assignment")
return
end
file = File.new("001_Configs.rvdata2","w")
puts "--------------------------------------------------"
puts " Rewrite game world setting"
puts "--------------------------------------------------"
#------------------------------------------------
# Add new config
#------------------------------------------------
new_configs = ""
if type.upcase == "W"
encoded_str = encode_config(str)
insert_position = @configs.size - 1
@configs.insert(insert_position,str)
for config in @configs
new_configs += encode_config(config)
end
#------------------------------------------------
# Remove config
#------------------------------------------------
elsif type.upcase == "D"
for config in @configs
next if config.include?(str)
new_configs += encode_config(config)
end
end
file.write(new_configs)
file.close
end
#============================================================
# *) load_shared_items
#============================================================
def load_shared_items(item_class = RPG::Item)
container = $game_party.item_container(item_class)
file = File.new("000_MLP_Shared.rvdata2","r")
counter = 0
@shared_items = []
while (line = file.gets)
counter += 1
if counter == 11
data = line.split('|')
data.delete_at(3)
data.delete_at(0)
puts "Shared Data Index:\n#{data}"
puts "----------------------------------------------"
end
end
file.close
index = data[0].split(':').at(1)
if !index.nil?
index[0] = index[index.length - 1] = ""
index = index.split(',')
index.each do |item|
item = item.split("=>")
id = item[0].to_i
num = item[1].to_i
@shared_items.push([id,num])
end
end
puts "#{@shared_items}"
end
#============================================================
# *) write_shared_items
#============================================================
def update_shared_items(item_class = RPG::Item)
load_shared_items if @shared_items.size < 1
msgbox("Save the shared data will take about 1~3 minutes\n" +
"And it will execute updater twice in process,\n" +
"just press any key to close the updater when it's done ^^\n" +
"To prevent the error, please don't close the program while its still working."
)
original_cmd = ["Item:","Recipe:"]
file = File.new("000_MLP_Shared.rvdata2","w")
file.close()
system('start /wait shared_data_updater.exe 10')
file = File.new("000_MLP_Shared.rvdata2","a")
#-----output real shared data------------------------
prng = $game_system.make_rand
str = get_distract_words(prng.rand(5000...8000))
str += '|' + original_cmd[0]
str += "{"
cnt = 0
for item in @shared_items
cnt += 1
str += sprintf("%d=>%d",item[0],item[1])
str += ',' if cnt != @shared_items.length
end
str += "}"
str += '|' + original_cmd[1] + '|'
str += get_distract_words(prng.rand(5000...8000))
str += '\n'
file.write(str)
file.close
#------------------------------------------------------
system('start /wait shared_data_updater.exe 10')
msgbox("Update Successfully!")
end
#============================================================
# *) Get shared items
#============================================================
def get_shared_items
for item in @shared_items
$game_party.gain_item($data_items[item[0]],item[1])
end
end
#============================================================
# *) Get bullshits
#============================================================
def get_distract_words(len = 1000)
signs = "0Q6WqE7R!T8YwU9I@O0PeL#KrJ$HtG%FyD^SuA&ZiX*CoV(BpN)Ma_s+d}f{g<hj>k?l:m~n`b,v.c/x;z'1[2]3\4=5"
str = ""
while len > 0
len -= 1
prng = $game_system.make_rand
str += signs[prng.rand(0...signs.length)]
end
return str
end
end
|
# -*- encoding: utf-8 -*-
# stub: image-inspector-client 2.0.0 ruby lib
Gem::Specification.new do |s|
s.name = "image-inspector-client".freeze
s.version = "2.0.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["Mooli Tayer".freeze]
s.date = "2018-05-28"
s.description = "A client for image_inspector REST API".freeze
s.email = ["mtayer@redhat.com".freeze]
s.homepage = "https://github.com/openshift/image-inspector-client-ruby".freeze
s.licenses = ["MIT".freeze]
s.required_ruby_version = Gem::Requirement.new(">= 2.2.0".freeze)
s.rubygems_version = "2.6.14.1".freeze
s.summary = "A client for image_inspector REST API".freeze
s.installed_by_version = "2.6.14.1" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_development_dependency(%q<bundler>.freeze, ["~> 1.6"])
s.add_development_dependency(%q<rake>.freeze, ["~> 12.0"])
s.add_development_dependency(%q<minitest>.freeze, [">= 0"])
s.add_development_dependency(%q<webmock>.freeze, ["~> 3.0.1"])
s.add_development_dependency(%q<rubocop>.freeze, ["~> 0.49.1"])
s.add_runtime_dependency(%q<json>.freeze, [">= 0"])
s.add_runtime_dependency(%q<recursive-open-struct>.freeze, ["~> 1.0"])
s.add_runtime_dependency(%q<rest-client>.freeze, ["~> 2.0"])
else
s.add_dependency(%q<bundler>.freeze, ["~> 1.6"])
s.add_dependency(%q<rake>.freeze, ["~> 12.0"])
s.add_dependency(%q<minitest>.freeze, [">= 0"])
s.add_dependency(%q<webmock>.freeze, ["~> 3.0.1"])
s.add_dependency(%q<rubocop>.freeze, ["~> 0.49.1"])
s.add_dependency(%q<json>.freeze, [">= 0"])
s.add_dependency(%q<recursive-open-struct>.freeze, ["~> 1.0"])
s.add_dependency(%q<rest-client>.freeze, ["~> 2.0"])
end
else
s.add_dependency(%q<bundler>.freeze, ["~> 1.6"])
s.add_dependency(%q<rake>.freeze, ["~> 12.0"])
s.add_dependency(%q<minitest>.freeze, [">= 0"])
s.add_dependency(%q<webmock>.freeze, ["~> 3.0.1"])
s.add_dependency(%q<rubocop>.freeze, ["~> 0.49.1"])
s.add_dependency(%q<json>.freeze, [">= 0"])
s.add_dependency(%q<recursive-open-struct>.freeze, ["~> 1.0"])
s.add_dependency(%q<rest-client>.freeze, ["~> 2.0"])
end
end
|
# frozen_string_literal: true
class AddIsPublishedToBooks < ActiveRecord::Migration[5.2]
def change
add_column :books, :is_published, :boolean, default: true
end
end
|
# frozen_string_literal: true
module Dotloop
class Authenticate
include HTTParty
base_uri 'https://auth.dotloop.com/oauth/'
attr_accessor :app_id
attr_accessor :app_secret
attr_accessor :application
def initialize(app_id:, app_secret:, application: 'dotloop')
@app_id = app_id
@app_secret = app_secret
@application = application
raise 'Please enter an APP id' unless @app_id
raise 'Please enter an APP secret' unless @app_secret
end
def acquire_access_and_refresh_token(code, options = {})
params = {
grant_type: 'authorization_code',
code: code,
redirect_uri: options[:redirect_uri]
}
raw('/token', params)
end
def refresh_access_token(refresh_token)
params = {
grant_type: 'refresh_token',
refresh_token: refresh_token
}
raw('/token', params)
end
def revoke_access(access_token)
params = {
token: access_token
}
raw('/token/revoke', params)
end
def raw(page, params = {})
response = self.class.post(page, query: params, headers: headers, timeout: 60)
handle_dotloop_error(response.code) if response.code != 200
response.parsed_response
end
def handle_dotloop_error(response_code)
error = case response_code
when 400
Dotloop::BadRequest
when 401
Dotloop::Unauthorized
when 403
Dotloop::Forbidden
else
StandardError
end
raise error, "Error communicating: Response code #{response_code}"
end
def url_for_authentication(redirect_uri, options = {})
params = {
client_id: @app_id,
response_type: 'code',
redirect_uri: redirect_uri
}
options.key?(:state) && params[:state] = options[:state]
options.key?(:redirect_on_deny) && params[:redirect_on_deny] = options[:redirect_on_deny]
"https://auth.dotloop.com/oauth/authorize?#{params.to_query}"
end
private
def headers
encode = Base64.encode64("#{app_id}:#{app_secret}").gsub(/\n/, '')
{
'Authorization' => "Basic #{encode}",
'User-Agent' => @application,
'Accept' => '*/*'
}
end
end
end
|
class Splam::Rules::Fuzz < Splam::Rule
class << self
attr_accessor :bad_word_score
end
self.bad_word_score = 10
def run
patterns = [/^(\d[a-z])/, /(\d[a-z][A-Z]\w+)/, /(\b\w+\d\.txt)/, /(;\d+;)/ ]
ignore_if = [%r{vendor/rails}, /EXC_BAD_ACCESS/, /JavaAppLauncher/, %r{Contents/MacOS}, %r{/Library/}]
matches = 0
# looks like a stack trace
ignore_if.each do |pattern|
return if @body.scan(pattern)
end
patterns.each do |pattern|
results = @body.scan(pattern)
if results && results.size > 0
add_score((self.class.bad_word_score * results.size), "bad pattern match: '#{$1}'")
end
matches += results.size
end
add_score matches.size ** 4, "Aggregate number of bad patterns was #{matches}." if matches > 1
end
end |
# frozen_string_literal: true
# == Schema Information
#
# Table name: thermostats
#
# id :bigint not null, primary key
# household_token :string not null
# location :string
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_thermostats_on_household_token (household_token) UNIQUE
#
class Thermostat < ApplicationRecord
has_many :readings
end
|
module Anticipate
module DSL
def trying_every(amount)
anticipation.trying_every(amount)
end
def failing_after(amount)
anticipation.failing_after(amount)
end
def sleeping(amount)
anticipation.sleeping(amount)
end
def default_tries
@default_tries ||= 1
end
def default_interval
@default_interval ||= 0.1
end
private
def anticipator
Anticipator.new(Kernel)
end
def anticipation
Anticipation.new(anticipator, default_interval, default_tries)
end
class Term
def initialize(anticipator, interval, timeout)
@anticipator, @interval, @timeout = anticipator, interval, timeout
end
private
def exec
@anticipator.anticipate(@interval, @timeout) do
yield
end
end
def chain
Anticipation.new(@anticipator, @interval, @timeout)
end
end
class TryingEvery < Term
def seconds
block_given? ? exec { yield } : chain
end
end
class FailingAfter < Term
def tries
block_given? ? exec { yield } : chain
end
end
class AfterSleep < Term
def between_tries
block_given? ? exec { yield } : chain
end
end
class Sleeping < Term
def seconds
AfterSleep.new(@anticipator, @interval, @timeout)
end
end
class Anticipation < Term
def trying_every(amount)
TryingEvery.new(@anticipator, amount, @timeout)
end
def failing_after(amount)
FailingAfter.new(@anticipator, @interval, amount)
end
def sleeping(amount)
Sleeping.new(@anticipator, amount, @timeout)
end
end
end
end |
# encoding: UTF-8
namespace :omnisearch do
desc 'builds all indexes'
task build: :environment do
OmniSearch::Indexes.build
end
desc 'rebuilds all indexes, clears memcache'
task reindex: :environment do
OmniSearch::Indexes.destroy
OmniSearch::Indexes.build
OmniSearch::Cache.refresh
end
desc 'clears memcache'
task refresh_cache: :environment do
OmniSearch::Cache.refresh
end
desc 'searches every two letter combination of a-z (aa, ab..)'
task warm_cache: :environment do
first_letter = ('a'..'z').to_a
second_letter = ('a'..'z').to_a
first_letter.product(second_letter) do |first, second|
OmniSearch::Search::Cached.find "#{first}#{second}"
end
end
desc 'tests certain matches against the index'
task test_searches: :environment do
here = File.expand_path(File.dirname(__FILE__))
load File.join(here, '../string_tests.rb')
end
end
|
module Pages
class NewTodo
include Capybara::DSL
include Formulaic::Dsl
def initialize(attributes)
@attributes = attributes
end
def create
fill_form_and_submit :todo, attributes
end
private
attr_reader :attributes
end
end
|
class IssuesController < ApplicationController
def index
@client = Octokit::Client.new(access_token: ENV["github_token"])
@issues = @client.issues("#{ENV["org_name"]}/#{ENV["repo_name"]}", state: "all")
@projects = @client.org_projects(ENV["org_name"])
@project = @projects.first
@columns = @client.project_columns(@project.id)
@columns.map! {|column|
{
name: column[:name],
cards: @client.column_cards(column.id).map {|card|
issue_number = card[:content_url].split("/").last.to_i
@issues.select {|issue| issue[:number] == issue_number }.first
# @client.issue(repo_name, issue_number)
}.compact
}
}
end
end
|
# require 'scraperwiki'
require 'mechanize'
require File.dirname(__FILE__) + '/lib_icon_rest_xml/scraper'
starting_url = "https://www2.bmcc.nsw.gov.au/DATracking/Pages/XC.Track/SearchApplication.aspx"
case ENV['MORPH_PERIOD']
when 'lastmonth'
period = "lastmonth"
when 'thismonth'
period = "thismonth"
when
period = "thisweek"
else
period = "last14days"
end
puts "Getting data in `" + period + "`, changable via MORPH_PERIOD environment"
agent = Mechanize.new
doc = agent.get(starting_url)
form = doc.forms.first
button = form.button_with(value: "I Agree")
raise "Can't find agree button" if button.nil?
doc = form.submit(button)
scrape_icon_rest_xml(starting_url, "d=" + period + "&k=LodgementDate&o=xml", false, agent)
|
require 'rails_helper'
describe League::Match::CommEdit do
before(:all) { create(:league_match_comm_edit) }
it { should belong_to(:comm).class_name('League::Match::Comm') }
it { should belong_to(:created_by).class_name('User') }
it { should validate_presence_of(:content) }
end
|
module Cosy
module Event
class Note
attr_accessor :pitch, :velocity, :duration, :channel
def initialize(pitch, velocity, duration, channel=nil)
@pitch, @velocity, @duration, @channel = pitch.to_i, velocity.to_i, duration.to_i, channel
end
def eql?(other)
self == other
end
def ==(other)
other.is_a? NoteEvent and other.pitch==@pitch and other.velocity==@velocity and
other.duration==@duration and other.channel==@channel
end
def to_s
inspect
end
def pvdc
return pitch, velocity, duration, channel
end
def inspect
s = '{pitch:' + @pitch.inspect
s += ',velocity:' + @velocity.inspect
s += ',duration:' + @duration.inspect
s += ',channel:' + @channel.inspect if channel
s += '}'
return s
end
end
class ProgramChange
attr_accessor :program_number, :channel
def initialize(program_number, channel=nil)
@program_number, @channel = program_number, channel
end
end
class Rest
attr_accessor :duration
def initialize(duration)
@duration = duration
end
end
class ControlChange
attr_accessor :controller_number, :value, :channel
def initialize(controller_number, value, channel=nil)
@controller_number, @value, @channel = controller_number, value, channel
end
end
class PitchBend
attr_accessor :amount, :channel
def initialize(amount, channel=nil)
@amount, @channel = amount, channel
end
def midi
# assume range -1.0 to 1.0
if @amount == -1.0
0
else
# pitch bends go from 0 (lowest) to 16383 (highest) with 8192 in the center
(@amount * 8191 + 8192).to_i
end
end
end
class Tempo
attr_accessor :bpm
def initialize(bpm)
@bpm = bpm
end
end
class OscMessage
attr_accessor :host, :port, :path, :args
def initialize(host,port,path,*args)
@host,@port,@path,@args = host,port,path,args
end
def to_s
"osc://#{host}:#{port}#{path} #{args}"
end
end
end
end |
module Fog
module Google
class SQL < Fog::Service
autoload :Mock, File.expand_path("../sql/mock", __FILE__)
autoload :Real, File.expand_path("../sql/real", __FILE__)
requires :google_project
recognizes(
:app_name,
:app_version,
:google_application_default,
:google_auth,
:google_client,
:google_client_options,
:google_key_location,
:google_key_string,
:google_json_key_location,
:google_json_key_string
)
GOOGLE_SQL_API_VERSION = "v1beta4".freeze
GOOGLE_SQL_BASE_URL = "https://www.googleapis.com/sql/".freeze
GOOGLE_SQL_API_SCOPE_URLS = %w(https://www.googleapis.com/auth/sqlservice.admin
https://www.googleapis.com/auth/cloud-platform).freeze
##
# MODELS
model_path "fog/google/models/sql"
# Backup Run
model :backup_run
collection :backup_runs
# Flag
model :flag
collection :flags
# Instance
model :instance
collection :instances
# Operation
model :operation
collection :operations
# SSL Certificate
model :ssl_cert
collection :ssl_certs
# Tier
model :tier
collection :tiers
# User
model :user
collection :users
##
# REQUESTS
request_path "fog/google/requests/sql"
# Backup Run
request :delete_backup_run
request :get_backup_run
request :insert_backup_run
request :list_backup_runs
# Flag
request :list_flags
# Instance
request :clone_instance
request :delete_instance
request :export_instance
request :get_instance
request :import_instance
request :insert_instance
request :list_instances
request :reset_instance_ssl_config
request :restart_instance
request :restore_instance_backup
request :update_instance
# Operation
request :get_operation
request :list_operations
# SSL Certificate
request :delete_ssl_cert
request :get_ssl_cert
request :insert_ssl_cert
request :list_ssl_certs
# Tier
request :list_tiers
# User
request :insert_user
request :update_user
request :list_users
request :delete_user
end
end
end
|
class Groups::PostsController < GroupsController
before_action :find_group
before_action :check_privileges
def create
@post = current_user.posts.build(post_params)
@post.group = @group
respond_to do |format|
if @post.save
@posts = @group.posts.order('created_at DESC').paginate(page: params[:page], per_page: 10)
format.js
else
@posts = @group.posts.order('created_at DESC').paginate(page: params[:page], per_page: 10)
format.js
end
end
end
private
def check_privileges
render status: 401 unless current_user.groups.include?(@group)
end
def find_group
@group = Group.find(params[:group_id])
end
def post_params
params.require(:post).permit(:content, :user_id, :group_id)
end
end
|
require 'rails_helper'
module V1
RSpec.describe TargetsController, type: :controller do
describe 'GET #most_targeted' do
it 'returns a collection of targets' do
target = create :target, :with_club
get :most_targeted, format: :json
first = assigns(:targets)[:targets].first
expect(first.object).to eq(target.targetable)
expect(first.scope[:quantity]).to eq(1)
end
it 'only 5 targets' do
target2 = create :target, :with_club
create :target, targetable: target2.targetable
create :target, targetable: target2.targetable
create :target, targetable: target2.targetable
target3 = create :target, :with_club
create :target, targetable: target3.targetable
create :target, :with_club
create :target, :with_club
create :target, :with_club
create :target, :with_club
get :most_targeted, format: :json
targets = assigns(:targets)[:targets]
first = targets.first
second = targets.second
expect(targets.count).to eq(5)
expect(first.object).to eq(target2.targetable)
expect(first.scope[:quantity]).to eq(4)
expect(second.object).to eq(target3.targetable)
expect(second.scope[:quantity]).to eq(2)
end
end
end
end
|
module Users
class UserRepository
UserNotFound = Class.new(StandardError)
attr_reader :adapter
def initialize adapter: Users::Model
@adapter = adapter
end
def create_user params
adapter.create(params)
end
def destroy_user id
user = adapter.find(id)
user.destroy
end
def fetch offset, limit
adapter.limit(limit).offset(offset)
end
def fetch_all
adapter.all
end
def find_by_id id
adapter.find(id)
rescue ActiveRecord::RecordNotFound
raise UserNotFound
end
def update_user id, params
user = adapter.find(id)
user.update!(params)
end
end
end
|
#
# Be sure to run `pod lib lint TGLPullToRefresh.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'TGLPullToRefresh'
s.version = '0.1.0'
s.summary = 'A flexible pull-to-refresh for UIScrollView.'
s.description = <<-DESC
TGLPullToRefresh provides a light, flexible implementation of the pull-to-refresh paradigm. Unlike UIRefreshControl, it lets you use any "progress" view you want. It also handles dynamically changing content offsets. You can see it in action in the list views of Pyfl (https://getpyfl.com/download).
DESC
s.homepage = 'https://github.com/bvirlet/TGLPullToRefresh'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'bvirlet' => 'bruno.virlet@gmail.com' }
s.source = { :git => 'https://github.com/bvirlet/TGLPullToRefresh.git', :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/bvirlet'
s.ios.deployment_target = '9.0'
s.source_files = 'TGLPullToRefresh/Classes/**/*'
end
|
# Copyright © 2011-2019 MUSC Foundation for Research Development~
# All rights reserved.~
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:~
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.~
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following~
# disclaimer in the documentation and/or other materials provided with the distribution.~
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products~
# derived from this software without specific prior written permission.~
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,~
# BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT~
# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL~
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS~
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR~
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.~
require 'rails_helper'
RSpec.describe 'dashboard/documents/documents_table', type: :view do
def render_documents_for(protocol, permission_to_edit=false)
render 'dashboard/documents/documents_table',
protocol: protocol,
protocol_type: protocol.type,
permission_to_edit: permission_to_edit
end
let_there_be_lane
context 'User has permission to edit' do
it 'should render documents_table' do
protocol = build(:unarchived_study_without_validations, primary_pi: jug2)
render_documents_for(protocol, true)
expect(response).to have_selector('#document-new:not(.disabled)')
end
end
context 'User does not have permission to edit' do
it 'should not render documents_table' do
protocol = build(:unarchived_study_without_validations, primary_pi: jug2)
render_documents_for(protocol)
expect(response).to have_selector('#document-new.disabled')
end
end
end
|
require 'line/bot'
class Sugarcoat::BotController < BaseController
protect_from_forgery
def callback
case request.method_symbol
when :get
if params["hub.verify_token"] == "taptappun"
render json: params["hub.challenge"]
else
render json: "Error, wrong validation token"
end
when :post
apiconfig = YAML.load(File.open(Rails.root.to_s + "/config/apiconfig.yml"))
message = params["entry"][0]["messaging"][0]
if message.include?("message")
#ユーザーの発言
sender = message["sender"]["id"]
text = message["message"]["text"]
endpoint_uri = "https://graph.facebook.com/v2.6/me/messages?access_token=" + apiconfig["facebook_bot"]["access_token"]
sugarcoated = Sugarcoat::Seed.to_sugarcoat(text).join("")
voice = VoiceWord.generate_and_upload_voice(nil, ApplicationRecord.reading(sugarcoated), "aoi", VoiceWord::VOICE_S3_SUGARCOAT_FILE_ROOT, "public-read", VoiceWord::SUGARCOAT_VOICE_PARAMS)
request_content = {
recipient: {
id:sender
},
message: {
text: sugarcoated
}
}
request_voice_content = {
recipient: {
id:sender
},
message: {
attachment: {
type: "audio",
payload: {
url: "https://taptappun.s3.amazonaws.com/" + VoiceWord::VOICE_S3_SUGARCOAT_FILE_ROOT + voice.file_name
}
}
}
}
http_client = http_client = HTTPClient.new
res = http_client.post(endpoint_uri, request_content.to_json, {'Content-Type' => 'application/json; charset=UTF-8'})
logger.info res.body
#http_client = http_client = HTTPClient.new
#res = http_client.post(endpoint_uri, request_voice_content.to_json, {'Content-Type' => 'application/json; charset=UTF-8'})
#logger.info res.body
head(:ok)
else
#botの発言
head(:ok)
end
end
end
def linebot_callback
apiconfig = YAML.load(File.open(Rails.root.to_s + "/config/apiconfig.yml"))
client = Line::Bot::Client.new {|config|
config.channel_secret = apiconfig["line_bot"]["sugarcoat"]["channel_secret"]
config.channel_token = apiconfig["line_bot"]["sugarcoat"]["channel_token"]
}
body = request.body.read
logger.info "-----------------------------------"
logger.info body
signature = request.env['HTTP_X_LINE_SIGNATURE']
unless client.validate_signature(body, signature)
render status: 400, json: { message: "BadRequest" }.to_json and return
end
events = client.parse_events_from(body)
logger.info "-----------------------------------"
logger.info events
events.each do |event|
case event
when Line::Bot::Event::Message
line_user_id = event["source"]["userId"]
case event.type
when Line::Bot::Event::MessageType::Text
logger.info event.message
logger.info event['replyToken']
message = {
type: 'text',
text: event.message['text']
}
logger.info event["source"]
user = client.get_profile(event["source"]["userId"])
logger.info user.body
res = client.reply_message(event['replyToken'], message)
when Line::Bot::Event::MessageType::Image, Line::Bot::Event::MessageType::Video, Line::Bot::Event::MessageType::Audio
response = client.get_message_content(event.message['id'])
File.open(Rails.root.to_s +"/tmp/" + SecureRandom.hex, 'wb'){|f| f.write(response.body) }
end
when Line::Bot::Event::Follow
Sugarcoat::LinebotFollowerUser.generate_profile!(line_client: client, line_user_id: event["source"]["userId"], isfollow: true)
when Line::Bot::Event::Unfollow
Sugarcoat::LinebotFollowerUser.generate_profile!(line_client: client, line_user_id: event["source"]["userId"], isfollow: false)
end
end
head(:ok)
end
end
|
class JobLiteSerializer < ActiveModel::Serializer
attributes :name, :environment
has_many :steps, serializer: JobStepLiteSerializer
def name
object.job_template.name
end
def environment
return nil unless object.environment
object.environment.each_with_object([]) do |env_vars, arr|
arr << env_vars.each_with_object({}) do |(key, value), result|
result[key] = value.to_s
end
end
end
end
|
module RailsAdmin
module Config
module Actions
class Delete < RailsAdmin::Config::Actions::Base
RailsAdmin::Config::Actions.register(self)
register_instance_option :member do
true
end
register_instance_option :route_fragment do
'delete'
end
register_instance_option :http_methods do
[:get, :delete]
end
register_instance_option :authorization_key do
:destroy
end
register_instance_option :controller do
proc do
RailsAdmin::MainController.class_eval { respond_to :html, :js }
if (@object.is_a?(Dynamic) && @object.annotation_type == 'smooch_user') || request.delete? # DESTROY
RequestStore.store[:ability] = :admin
redirect_path = nil
@auditing_adapter && @auditing_adapter.delete_object(@object, @abstract_model, _current_user)
if @object.is_a?(Team)
@object.update_column(:inactive, true)
TeamDeletionWorker.perform_async(@object.id, current_api_user.id)
flash[:info] = t('admin.flash.delete_team_scheduled', team: @object.name)
redirect_path = index_path
else
if @object.destroy
flash[:success] = t('admin.flash.successful', name: @model_config.label, action: t('admin.actions.delete.done'))
redirect_path = index_path
else
flash[:error] = t('admin.flash.error', name: @model_config.label, action: t('admin.actions.delete.done'))
redirect_path = back_or_index
end
end
redirect_to redirect_path
elsif request.get? # DELETE
respond_with(@object)
end
end
end
register_instance_option :link_icon do
'icon-remove'
end
end
end
end
end
|
require 'time'
require_relative './string/str_paint.rb'
# Returns foreground id for color given.
def get_fg(str)
return Color.get_t("fg")[str]
end
class Logger
@software_version = "v1.0"
@_24HourTime = Time.new.strftime("%H:%M")
def self.get_head()
return "[Logger #{@_24HourTime.to_s}]"
end
#TODO: Metaprogramming, get line and file from caller.
def self.error(info)
puts "#{self.get_head()} " + "ERROR".str_paint(get_fg("red")) + ": Line '#{__LINE__}' in #{__FILE__} (#{info})."
end
def self.warning(info)
puts "#{self.get_head()} " + " WARNING".str_paint(get_fg("brown")) + ": #{info}."
end
def self.log(message)
puts "#{self.get_head()}: " + "#{message}".str_paint(get_fg("blue"))
end
def self.success(message)
puts "#{self.get_head()} " + "Success: ".str_paint(get_fg("green")) + message.str_paint(get_fg("green"))
end
def self.plog(message)
print "#{self.get_head()}: " + "#{message}".str_paint(get_fg("blue"))
end
def self.log_data(data, length)
loop do
if data.length > length
self.plog("Data about to me printed is over #{length} chararacters, continue? (Y/N): ")
case gets.chomp.downcase
when "y"
self.log(data)
break
when "n"
break
else
next
end
else
self.log(data)
break
end
end
end
end
|
class Follower < ActiveRecord::Base
has_many :user_followers
has_many :users, through: :user_followers
end
|
require 'spec_helper'
describe ValidationsController do
describe '#last_digit_valid?' do
it 'should return a boolean' do
expect(ValidationsController.new.last_digit_valid?(9782895406976)).to eq(true||false)
end
it 'should return true if the last digit is valid ISBN' do
expect(ValidationsController.new.last_digit_valid?(9782895406976)).to eq(true)
end
end
end
|
require 'rails_helper'
feature 'User attmpts to create a paste', js: true do
context 'with valid attributes' do
scenario 'when clicking on the save button on the homepage' do
ruby_code = load_fixture 'ruby.rb'
visit root_path
fill_in 'Try some code', with: ruby_code
click_button(t('helpers.submit.paste.create'))
expect(page).to have_content('Ruby')
expect(page).to have_content(ruby_code)
end
end
end
|
module Humble
class DefaultDataRowMapper
def initialize(configuration)
@configuration = configuration
end
def map_from(row)
result = @configuration.type.new
row.each do |key, value|
result.send("#{key}=", value)
end
result
end
end
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Tag do
let(:tag_object) { tag }
let(:subject) { described_class.new(tag_object) }
it 'should create a tag object' do
expect(subject).to be_kind_of(Tag)
end
it 'should have an id attribute' do
expect(subject.id).to be_truthy
end
it 'should have a name attribute' do
expect(subject.name).to be_truthy
end
it 'should save the raw attribute' do
expect(subject.raw).to eq tag_object
end
end
|
class CorrectFirstNameForUser < ActiveRecord::Migration[5.0]
def change
remove_column :users, :firts_name
add_column :users, :first_name, :text
end
end
|
class ApplicationMailer < ActionMailer::Base
default reply_to: Settings.mailer.default_reply_to, from: Settings.mailer.default_from, bcc: Settings.mailer.try(:bcc_email) || []
layout 'mailer'
end
|
class CreateCourses < ActiveRecord::Migration[5.2]
def change
create_table :courses do |t|
t.string :title
t.monetize :price
t.integer :status, null: false, default: 0
t.integer :period, null: false, default: 30
t.text :slug, index: { unique: true }
t.text :description
t.belongs_to :category, foreign_key: true
t.timestamps
end
end
end
|
colors = 'blue pink yellow orange'
if colors.include? 'yellow'
puts true
else
puts false
end
if colors.include? 'purple'
puts true
else
puts false
end
# Much easier and most simple way
# colors = 'blue pink yellow orange'
# puts colors.include?('yellow')
# puts colors.include?('purple') |
class AddInUser < ActiveRecord::Migration[6.1]
def change
add_column :users,'room_no','string'
add_column :users,'role','string'
end
end
|
require 'spec_helper'
module OCR
describe CheckSum do
Given(:checker) { CHECKER }
describe "#checksum" do
Then { checker.check_sum("000000000").should == 0 }
Then { checker.check_sum("777777777").should == 7 }
Then { checker.check_sum("123456789").should == 0 }
Then { checker.check_sum("000000002").should == (2*1) % 11 }
Then { checker.check_sum("000000020").should == (2*2) % 11 }
Then { checker.check_sum("000000200").should == (2*3) % 11 }
Then { checker.check_sum("000002000").should == (2*4) % 11 }
Then { checker.check_sum("000020000").should == (2*5) % 11 }
Then { checker.check_sum("000200000").should == (2*6) % 11 }
Then { checker.check_sum("002000000").should == (2*7) % 11 }
Then { checker.check_sum("020000000").should == (2*8) % 11 }
Then { checker.check_sum("200000000").should == (2*9) % 11 }
end
describe "#check?" do
context "when the account number is good" do
# good account numbers were taken from the user story specs
Then { checker.check?("000000000").should be_true }
Then { checker.check?("000000051").should be_true }
Then { checker.check?("123456789").should be_true }
Then { checker.check?("200800000").should be_true }
Then { checker.check?("333393333").should be_true }
Then { checker.check?("490867715").should be_true }
Then { checker.check?("664371485").should be_true }
Then { checker.check?("711111111").should be_true }
Then { checker.check?("777777177").should be_true }
end
context "when the account number is bad" do
# bad account numbers were taken from the user story specs
Then { checker.check?("111111111").should_not be_true }
Then { checker.check?("490067715").should_not be_true }
Then { checker.check?("664371495").should_not be_true }
Then { checker.check?("00000000").should_not be_true }
Then { checker.check?("0000000000").should_not be_true }
end
end
end
end
|
class Order < ActiveRecord::Base
has_many :line_items, dependent: :destroy
belongs_to :user
accepts_nested_attributes_for :line_items
validates :firstname, :lastname, :street_address, :city, :zipcode, :state, :country, :email, :user_id, :status, presence: true
validates :state, inclusion: ::STATES, if: :is_usa?
validates :state, inclusion: ::PROVINCES, if: :is_canada?
scope :pending, -> { where(:status => "Submitted")}
def is_usa?
(country == 'United States')
end
def is_canada?
(country == 'Canada')
end
def add_line_items_from_cart(cart)
cart.line_items.each do |item|
item.cart_id = nil
line_items << item
end
end
def is_complete?
if (self.status == "Shipped")
true
end
end
def current_color
if (self.status == "Submitted")
return :warn
elsif (self.status == "Shipped")
return :ok
elsif (self.status == "Offline-Purchased")
return :offline_purchased
elsif (self.status == "Purchased")
return :error
end
end
def self.total_grouped_by_day(start)
orders = where(created_at: start.beginning_of_day..Time.zone.now)
orders = orders.group("date(created_at)")
orders = orders.select("date(created_at) as created_at, count(*) as count")
#orders.group_by { |o| o.created_at.to_date }
orders.each_with_object({}) do |order, counts|
counts[order.created_at.to_date] = order.count
end
end
def self.created_between(start_date, end_date)
where("created_at >= ? AND created_at <= ?", start_date, end_date)
end
end
|
require 'test/unit'
require 'pp'
require 'miw/layout/box'
require 'miw/rectangle'
require 'miw/size'
require 'miw/view'
class Test_Layout_Box < ::Test::Unit::TestCase
def test_vbox_do_layout_item1_resize_both
box = MiW::Layout::VBox.new
items = [
[ MiW::Rectangle.new(0, 0, 100, 100), resize: [true, true] ]
]
rect = MiW::Rectangle.new 0, 0, 200, 200
box.do_layout items, rect
assert_equal rect.width, items[0][0].width
assert_equal rect.height, items[0][0].height
assert_equal rect.x, items[0][0].x
assert_equal rect.y, items[0][0].y
end
def test_vbox_do_layout_item1_resize_vertical
box = MiW::Layout::VBox.new
item = MiW::Rectangle.new 0, 0, 100, 100
items = [
[ item, resize: [false, true] ]
]
rect = MiW::Rectangle.new 0, 0, 200, 200
box.do_layout items, rect
assert_equal 50, items[0][0].x
assert_equal 0, items[0][0].y
assert_equal 100, items[0][0].width
assert_equal 200, items[0][0].height
end
# item: 1
# resize: V
# align: [:top, :center]
def test_vbox_do_layout_item1_resize_vertical_top
box = MiW::Layout::VBox.new
item = MiW::Rectangle.new 0, 0, 100, 100
items = [
[ item, resize: [false, true], align: [:top, :center] ]
]
rect = MiW::Rectangle.new 0, 0, 200, 200
box.do_layout items, rect
assert_equal 0, items[0][0].x
assert_equal 0, items[0][0].y
assert_equal 100, items[0][0].width
assert_equal 200, items[0][0].height
end
def test_vbox_do_layout_item1_resize_vertical_top
box = MiW::Layout::VBox.new
item = MiW::Rectangle.new 0, 0, 100, 100
items = [
[ item, resize: [false, true], align: [:top, :center] ]
]
rect = MiW::Rectangle.new 0, 0, 200, 200
box.do_layout items, rect
assert_equal 0, items[0][0].x
assert_equal 0, items[0][0].y
assert_equal 100, items[0][0].width
assert_equal 200, items[0][0].height
end
def test_vbox_do_layout_item2_resize_both
box = MiW::Layout::VBox.new
items = [
[ MiW::Rectangle.new(0, 0, 100, 100), resize: [true, true] ],
[ MiW::Rectangle.new(0, 0, 100, 100), resize: [true, true] ]
]
exp = [
[ 0, 0, 200, 100 ],
[ 0, 100, 200, 100 ]
]
rect = MiW::Rectangle.new 0, 0, 200, 200
box.do_layout items, rect
items.each_with_index do |item, i|
assert_equal exp[i][0], item[0].x
assert_equal exp[i][1], item[0].y
assert_equal exp[i][2], item[0].width
assert_equal exp[i][3], item[0].height
end
end
end
|
def is_multiple_of_3_or_5?(i)
i % 3 == 0 || i % 5 == 0
end
p (0..999).inject { |sum, n| is_multiple_of_3_or_5?(n) ? n + sum : sum }
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
@bella = User.create!(email: 'bella@dog.com', password: 'pass123', name: 'Bella')
@vik = User.create!(email: 'vik@dog.com', password: 'pass123', name: 'Vik')
@bunny = User.create!(email: 'bunbun@dog.com', password: 'pass123', name: 'BunBun')
@dog = Tag.create!(tag: 'dog')
@cute = Tag.create!(tag: 'cute')
@fluffy = Tag.create!(tag: 'fluffy')
@coding = Tag.create!(tag: 'coding')
@bikes = Tag.create!(tag: 'bikes')
@birds = Tag.create!(tag: 'birds')
@poetry = Tag.create!(tag: 'poetry')
@flowers = Tag.create!(tag: 'flowers')
@belgian = Tag.create!(tag: 'belgian beer')
@canals = Tag.create!(tag: 'canals')
@a = Tag.create!(tag: 'art')
@b = Tag.create!(tag: 'music')
@c = Tag.create!(tag: 'avant garde')
@g = Tag.create!(tag: 'cats')
@f = Tag.create!(tag: 'loudness')
@e = Tag.create!(tag: 'quietness')
@d = Tag.create!(tag: 'dreams')
titles = [
"it won’t suit me",
"it was not the right thing to do",
"stop playing poker",
"any amount will be greatly appreciated",
"perhaps compensates for the loss of a true metaphysics",
"loud voice",
"The waves were crashing on the shore",
"it was a lovely sight",
"I often see the time 11:11 or 12:34 on clocks",
"come back at once",
"I'd rather be a bird than a fish",
"glittering gem",
"Abstraction",
"The sky is clear",
"not noisy"
]
urls = [
"www.modernpoetry.org.uk/blinks.html",
"www.avantgardemusic.com",
"https://webflow.com/blog/10-brutalist-websites",
"https://filmquarterly.org/2009/09/01/the-avant-garde-archive-online",
"www.modernpoetry.org.uk/blinks.html",
"https://www.poetryfoundation.org/",
"https://allpoetry.com/poems",
"poetrysociety.org.uk/",
"https://fleursdumal.org/",
"https://www.hafizonlove.com/",
"www.thesongsofhafiz.com/hafizpoetry.htm",
"terminaliafestival.org",
"https://mappingweirdstuff.wordpress.com",
"surrealism.website",
"www.surrealists.co.uk",
"www.surrealismart.org/websites.html"
]
# Bookmark.all.each do |bookmark|
# #bookmark.screenshot.attach(io: File.open('app/assets/images/tempScreen.png'), filename: 'tempScreen.png')
# bookmark.screenshot.attach(io: File.open('app/assets/images/screens/defaultScreen.jpg'), filename: 'defaultScreen.jpg')
# end
@b2 = Bookmark.create!(url: 'http://blogpaws.com',title: 'blogpaws',user: @bella)
@b3 = Bookmark.create!(url: 'http://www.allthingsdogblog.com',title: 'dogggs',user: @bella)
@b5 = Bookmark.create!(url: 'http://www.bringingupbella.com',title: 'WARNING YOU SHOULD NOT SEE ME UNLESS YOU ARE VIK!!!!',user: @vik)
@b6 = Bookmark.create!(url: urls.sample, title: titles.sample, user: @bella)
@b7 = Bookmark.create!(url: urls.sample, title: titles.sample, user: @bella)
@b8 = Bookmark.create!(url: urls.sample, title: titles.sample, user: @bella)
@b9 = Bookmark.create!(url: urls.sample, title: titles.sample, user: @bella)
@b10 = Bookmark.create!(url: urls.sample, title: titles.sample, user: @bella)
@b11 = Bookmark.create!(url: urls.sample, title: titles.sample, user: @bella)
@b12 = Bookmark.create!(url: urls.sample, title: titles.sample, user: @bella)
@aa = Bookmark.create!(url: urls.sample, title: titles.sample, user: @bella)
@bb = Bookmark.create!(url: urls.sample, title: titles.sample, user: @bella)
@cc = Bookmark.create!(url: urls.sample, title: titles.sample, user: @bella)
@dd = Bookmark.create!(url: urls.sample, title: titles.sample, user: @bella)
@ee = Bookmark.create!(url: urls.sample, title: titles.sample, user: @bella)
@wegot = Bookmark.create!(url: 'https://www.wegotcoders.com/',title: '
We Got Coders | Web Development Courses & Developers For Hire',user: @bella)
@ff = Bookmark.create!(url: urls.sample, title: titles.sample, user: @bella)
@kk = Bookmark.create!(url: urls.sample, title: titles.sample, user: @bella)
@jj = Bookmark.create!(url: urls.sample, title: titles.sample, user: @bella)
@ii = Bookmark.create!(url: urls.sample, title: titles.sample, user: @bella)
@hh = Bookmark.create!(url: urls.sample, title: titles.sample, user: @bella)
@gg = Bookmark.create!(url: urls.sample, title: titles.sample, user: @bella)
@boxt = Bookmark.create!(url: 'https://boxt.co.uk/', title: 'Buy a Worcester Bosch boiler online with installation | BOXT.co.uk', user: @bella)
@b4 = Bookmark.create!(url: 'http://www.bringingupbella.com',title: 'A dog named bella!',user: @bella)
@kerrSite = Bookmark.create!(url: 'https://kerrimaru.github.io/#main',title: 'Really cool site!!',user: @bella)
Bookmark.all.each do |bookmark|
x = Tag.all.shuffle
random_tag = [x[0],x[1], x[2], x[3], x[4]]
bookmark.tags << random_tag
end
@bb.screenshot.attach(io: File.open('app/assets/images/screens/dolelol.png'), filename: 'dolelol.png')
@cc.screenshot.attach(io: File.open('app/assets/images/screens/images.jfif'), filename: 'images.jfif')
@dd.screenshot.attach(io: File.open('app/assets/images/screens/scree5.png'), filename: 'scree5.png')
@ee.screenshot.attach(io: File.open('app/assets/images/screens/screen1.jpg'), filename: 'screen1.jpg')
@aa.screenshot.attach(io: File.open('app/assets/images/screens/defaultScreen.jpg'), filename: 'defaultScreen.jpg')
@ff.screenshot.attach(io: File.open('app/assets/images/screens/screen2.jfif'), filename: 'screen2.jfif')
@kk.screenshot.attach(io: File.open('app/assets/images/screens/screen3.png'), filename: 'screen3.png')
@jj.screenshot.attach(io: File.open('app/assets/images/screens/screen6.jfif'), filename: 'screen6.jfif')
@ii.screenshot.attach(io: File.open('app/assets/images/screens/screen7.jpg'), filename: 'screen7.jpg')
@hh.screenshot.attach(io: File.open('app/assets/images/screens/screen8.jpg'), filename: 'screen8.jpg')
@gg.screenshot.attach(io: File.open('app/assets/images/screens/yum.jpg'), filename: 'yum.jpg')
@b6.screenshot.attach(io: File.open('app/assets/images/screens/screen3.png'), filename: 'screen3.png')
@b7.screenshot.attach(io: File.open('app/assets/images/screens/dolelol.png'), filename: 'dolelol.png')
@b8.screenshot.attach(io: File.open('app/assets/images/screens/images.jfif'), filename: 'images.jfif')
@b9.screenshot.attach(io: File.open('app/assets/images/screens/screen2.jfif'), filename: 'screen2.jfif')
@b10.screenshot.attach(io: File.open('app/assets/images/screens/screen6.jfif'), filename: 'screen6.jfif')
@b11.screenshot.attach(io: File.open('app/assets/images/screens/screen1.jpg'), filename: 'screen1.jpg')
@b12.screenshot.attach(io: File.open('app/assets/images/screens/screen7.jpg'), filename: 'screen7.jpg')
@b4.screenshot.attach(io: File.open('app/assets/images/screens/scree5.png'), filename: 'scree5.png')
@kerrSite.screenshot.attach(io: File.open('app/assets/images/screens/kerri.jfif'), filename: 'kerri.jfif')
@wegot.screenshot.attach(io: File.open('app/assets/images/screens/coders.jfif'), filename: 'coders.jfif')
@boxt.screenshot.attach(io: File.open('app/assets/images/screens/boxt.jfif'), filename: 'boxt.jfif')
@b2.screenshot.attach(io: File.open('app/assets/images/screens/dolelol.png'), filename: 'dolelol.png')
@b3.screenshot.attach(io: File.open('app/assets/images/screens/images.jfif'), filename: 'images.jfif')
@b5.screenshot.attach(io: File.open('app/assets/images/screens/scree5.png'), filename: 'scree5.png')
|
# :nocov:
module GraphqlDoc
extend ActiveSupport::Concern
included do
swagger_controller :graphql, 'GraphQL'
swagger_api :create do
summary 'GraphQL interface'
notes 'Use this method in order to send queries to the GraphQL server'
param :query, :query, :string, :required, 'GraphQL query'
# response(code, message, exampleRequest)
# "exampleRequest" should be: { query: {}, headers: {}, body: {} }
authed = { CheckConfig.get('authorization_header') => 'test' }
response :ok, 'GraphQL result', { query: { query: 'query Query { about { name, version } }' }, headers: authed }
response 401, 'Access denied', { query: { query: 'query Query { about { name, version } }' } }
end
end
end
# :nocov:
|
# code here!
class School
attr_reader :roster
def initialize(school)
@school = school
@roster = Hash.new { |h, k| h[k] = []}
end
def add_student(name, grade)
@roster[grade] << name
end
def grade(student_grade)
@roster[student_grade]
end
def sort
@roster.each { |grade, names| names.sort! }
end
end
|
module Treasury
class DelayedIncrementJob
include Resque::Integration
queue :base
retrys
# Public: Отложенный инкремент поля
#
# params - Hash:
# 'object' - Integer идентификатор
# 'field_name' - String название поля
# 'field_class' - String класс поля
# 'by' - Integer приращение
#
# Returns nothing
def self.perform(params)
object = params.fetch('object')
field_name = params.fetch('field_name')
increment = params.fetch('by')
field = Treasury::Fields::Base.create_by_class(params.fetch('field_class'))
new_value = field.raw_value(object, field_name).to_i + increment
field.write_data({object => {field_name => new_value}}, true)
end
end
end
|
require 'rails_helper'
RSpec.describe 'Passenger show page', type: :feature do
before(:each) do
@airline = Airline.create!(name: "Delta")
@flight1 = @airline.flights.create!(number: "1727", date: "08-03-20", time: "3:30pm MST", departure_city: "Denver", arrival_city: "Reno")
@flight2 = @airline.flights.create!(number: "7777", date: "08-03-20", time: "8:30pm MST", departure_city: "Reno", arrival_city: "Seattle")
@flight3 = @airline.flights.create!(number: "1776", date: "08-04-20", time: "8:30am PST", departure_city: "Seattle", arrival_city: "Houston")
@joe = Passenger.create!(name: "Joe", age: "7")
@bob = Passenger.create!(name: "Bob", age: "77")
FlightPassenger.create!(flight: @flight1, passenger: @joe)
FlightPassenger.create!(flight: @flight1, passenger: @bob)
FlightPassenger.create!(flight: @flight2, passenger: @joe)
FlightPassenger.create!(flight: @flight2, passenger: @bob)
end
it 'shows passenger info' do
visit "/passengers/#{@bob.id}"
expect(page).to have_content("Bob")
expect(page).to have_link(@flight1.number)
expect(page).to have_link(@flight2.number)
end
it "allows flight assignment" do
visit "/passengers/#{@bob.id}"
fill_in 'Flight number', with: '1776'
click_button 'Submit'
expect(current_path).to eq("/passengers/#{@bob.id}")
expect(page).to have_link(@flight3.number)
end
end
|
class Ranking < ActiveRecord::Base
belongs_to :option
belongs_to :user
end
|
Rails.application.routes.draw do
get "/user_recipes" => "user_recipes#index"
get "/user_recipes/new" => "user_recipes#new"
post "/user_recipes" => "user_recipes#create"
get "/user_recipes/:id" => "user_recipes#show"
get "/user_recipes/:id/edit" => "user_recipes#edit"
patch "/user_recipes/:id" => "user_recipes#update"
delete "/user_recipes/:id" => "user_recipes#destroy"
get "/parent_recipes" => "parent_recipes#index"
get "/parent_recipes/new" => "parent_recipes#new"
post "/parent_recipes" => "parent_recipes#create"
get "/parent_recipes/:id" => "parent_recipes#show"
get "/parent_recipes/:id/edit" => "parent_recipes#edit"
patch "/parent_recipes/:id" => "parent_recipes#update"
delete "/parent_recipes/:id" => "parent_recipes#destroy"
get "/categories" => "categories#index"
get "/categories/:id" => "categories#show"
post "/categories" => "categories#create"
post "/users" => "users#create"
namespace :api do
get "/parent_recipes" => "parent_recipes#index"
get "/parent_recipes/:id" => "parent_recipes#show"
post "/parent_recipes" => "parent_recipes#create"
patch "/parent_recipes/:id" => "parent_recipes#update"
delete "/parent_recipes/:id" => "parent_recipes#destroy"
get "/user_recipes" => "user_recipes#index"
get "/user_recipes/:id" => "user_recipes#show"
post "/user_recipes" => "user_recipes#create"
patch "/user_recipes/:id" => "user_recipes#update"
delete "/user_recipes/:id" => "user_recipes#destroy"
get "/categories" => "categories#index"
get "/categories/:id" => "categories#show"
post "/categories" => "categories#create"
post "/users" => "users#create"
post "/sessions" => "sessions#create"
end
end
|
class GroupMembership < ApplicationRecord
belongs_to :user
belongs_to :group
# after_create :create_notifications
private
# def recipients
# membership = current_user.group_memberships
# groups = Group.where(language: self.card_set.language).to_set.superset?(self.to_set)
# recipients = User.where(group_membership: membership)
# end
# def create_notifications
# recipients.each do |recipient|
# Notification.create(recipient: recipient, actor: current_user,
# action: 'joined', notifiable: self)
# end
# end
end
|
class PagerGroupDestinationSerializer < ActiveModel::Serializer
embed :ids, :include => true
end
|
require 'csv'
require 'bigdecimal'
require_relative '../lib/invoice_item'
require_relative '../lib/modules/findable'
require_relative '../lib/modules/crudable'
class InvoiceItemRepository
include Findable
include Crudable
attr_reader :all
def initialize(path)
@all = []
create_items(path)
end
def create_items(path)
CSV.foreach(path, headers: true, header_converters: :symbol) do |row|
invoice_item = InvoiceItem.new(row)
@all << invoice_item
end
end
def inspect
"#<#{self.class} #{@invoice_items.size} rows>"
end
def find_all_by_item_id(item_id)
@all.find_all do |invoice_item|
invoice_item.item_id == item_id
end
end
def find_all_by_invoice_id(invoice_id)
@all.find_all do |invoice_item|
invoice_item.invoice_id == invoice_id
end
end
def find_revenue_by_invoice_id(invoice_id)
find_all_by_invoice_id(invoice_id).sum do |invoice_item|
invoice_item.quantity * invoice_item.unit_price
end
end
def create(attributes)
create_new(attributes, InvoiceItem)
end
def update(id, attributes)
update_new(id, attributes)
end
def delete(id)
delete_new(id)
end
end
|
require 'socket'
module SocketSpecs
# helper to get the hostname associated to 127.0.0.1
def self.hostname
# Calculate each time, without caching, since the result might
# depend on things like do_not_reverse_lookup mode, which is
# changing from test to test
Socket.getaddrinfo("127.0.0.1", nil)[0][2]
end
def self.hostnamev6
Socket.getaddrinfo("::1", nil)[0][2]
end
def self.port
40001
end
def self.local_port
40002
end
def self.sockaddr_in(port, host)
Socket::SockAddr_In.new(Socket.sockaddr_in(port, host))
end
def self.socket_path
tmp("unix_server_spec.socket")
end
def self.start_tcp_server(remote_host = nil)
thread = Thread.new do
if remote_host
server = TCPServer.new(remote_host, SocketSpecs.port)
else
server = TCPServer.new(SocketSpecs.port)
end
server.accept
server.close
end
Thread.pass until thread.status == 'sleep' or thread.status == nil
thread.status.should_not be_nil
thread
end
end
|
Rails.application.routes.draw do
root 'books#index'
resources books, only: [:index, :new, :create]
resources authors, except: [:destroy]
end
|
#!/usr/bin/env ruby
#
# Author: z0mbix (zombie@zombix.org)
#
# Description:
# zup is a wrapper for unison to easily sync a directory recursively
# with a remote host usually over ssh.
#
# Requirements:
# unison, rsync, openssh, ruby
#
# Version: 0.1.1
#
require 'fileutils'
# Main user config file:
$CONFIG_FILE=ENV['HOME'] + '/.zup.conf'
# Unison command to run
$SYNC_COMMAND="unison \
-logfile=.zup/zup.log \
-auto \
-times \
-sortnewfirst \
-confirmbigdel \
-copyprog='rsync --inplace' \
-copyprogrest='rsync --partial --inplace' \
-contactquietly \
-terse \
-ignore='Path .zup'"
#$ZUP_DEBUG=true
# Set unison directory to .zup in pwd instead of ~/.unison
ENV['UNISON'] = '.zup'
class Zup
def initialize
if ARGV.length < 1
output_help
exit 0
end
# Check that config file exists
unless File.exist?($CONFIG_FILE)
puts "Config file " + $CONFIG_FILE + " does not exist!\n\n"
puts "Please create one with at least the following settings:\n\n"
puts "server=[hostname|ip]"
puts "remote_dir=[remote directory to sync with]"
exit 0
end
# Import configuration from ~/.zup.conf
# Set some defaults
@conf = { 'port' => '22', 'protocol' => 'ssh', 'batch' => 'no' }
File.foreach($CONFIG_FILE) do |line|
line.strip!
# Skip commented and blank lines
if (line[0] != ?# and line =~ /\S/)
i = line.index('=')
if (i)
# Strip keys and convert to lowercase, and strip values
key = line[0..i - 1].strip.downcase
value = line[i + 1..-1].strip
@conf[key] = value
else
@conf[line.downcase] = ''
end
end
end
# Enable unison's batch mode
# See http://www.cis.upenn.edu/~bcpierce/unison/download/releases/stable/unison-manual.html
# for full details
if @conf['batch'] == 'yes'
$SYNC_COMMAND = $SYNC_COMMAND + ' -batch'
end
case ARGV[0]
when 'help'
output_help
when 'showconfig'
output_config
when 'init'
enable_zup_dir
when 'sync'
sync_zup_dir
when 'uninit'
disable_zup_dir
end
end
# Output the config settings
def output_config
puts 'Using config file: ' + $CONFIG_FILE
@conf.each { |key, value| puts key + " = " + value }
end
def output_help
puts "usage: zup <command>\n\n"
puts "Commands:"
puts " help This help output"
puts " init Initialise the current directory for sync remote sync"
puts " uninit Uninitialise the current directory for remote sync"
puts " sync Synchronise the current directory with remove host"
puts " showconfig Output the configuration settings"
end
# Check if the pwd is zup enabled
def zup_dir_enabled?
if File.exist?('.zup/enabled')
return true
else
return false
end
end
# Enable the pwd so it can sync with the remote host
def enable_zup_dir
unless zup_dir_enabled?
puts ' * Adding current directory'
# Create .zup directory
FileUtils.mkdir('.zup') unless File.directory?('.zup')
# Create file to enable zup
File.open(".zup/enabled", 'w') { |f| f.close }
else
puts ' * Directory already initialised'
return false
end
end
# Disable the pwd so it no-longer syncs with the remote host
def disable_zup_dir
if zup_dir_enabled?
puts ' * Uninitialising current directory'
# TODO: Fix uninitialising a directory
# Removing .zup directory breaks syncing if it's ever re-initialised
#FileUtils.rm_rf(".zup") if File.directory?('.zup')
FileUtils.rm('.zup/enabled')
exit 0
else
puts ' * Directory not initialised'
return false
exit 0
end
end
# Run unison to sync with remote host if enabled
def sync_zup_dir
if zup_dir_enabled?
local_dir = File.basename(Dir.pwd)
# Output the full unison command if debugging enabled
puts($SYNC_COMMAND + ' . ' + @conf['protocol'] + '://' \
+ @conf['server'] + '/' + @conf['remote_dir'] + '/' \
+ local_dir) if $ZUP_DEBUG
# Run unison
system($SYNC_COMMAND + ' . ' + @conf['protocol'] + '://' \
+ @conf['server'] + '/' + @conf['remote_dir'] + '/' \
+ local_dir)
else
puts " * Current directory not initialised (Run 'zup init' to add it)"
exit 0
end
end
end
zup = Zup.new
|
#
# Cookbook Name:: chef_dotfiles
# Recipe:: default
#
node["dotfiles"]["users"].each do |username|
home_path = File.expand_path("~#{username}")
install_path = "#{home_path}/dotfiles"
git install_path do
repository node["dotfiles"]["repo"]
user username
group username
reference "master"
action :sync
enable_submodules true
end
node["dotfiles"]["files"].each do |file|
directory "#{home_path}/.#{file}" do
recursive true
action :delete
not_if {File.symlink?("#{home_path}/.#{file}")}
end
file "#{home_path}/.#{file}" do
not_if {File.directory?("#{home_path}/.#{file}")}
action :delete
end
link "#{home_path}/.#{file}" do
owner username
group username
to "#{install_path}/#{file}"
end
end
end
|
class Booking < ApplicationRecord
belongs_to :pool
belongs_to :user
end
|
require 'eb_ruby_client/configuration'
RSpec.describe EbRubyClient::Configuration do
subject(:configuration) { EbRubyClient::Configuration.new }
before do
config_file_path = File.expand_path("../../../config/eventbrite.yml", __FILE__)
EbRubyClient::Configuration.config_file_path = config_file_path
end
it "returns the base_url" do
expect(configuration.base_url).to eq("https://test.eventbrite.url/api")
end
it "returns the auth_token" do
expect(configuration.auth_token).to eq("test-auth-token")
end
end
|
module SwProjectCustomerQnax
class RoleAccessRight < ActiveRecord::Base
attr_accessor :user_role_name
attr_accessible :action, :brief_note, :last_updated_by_id, :resource, :user_role_id, :processed,
:user_role_name,
:as => :role_new
attr_accessible :action, :brief_note, :last_updated_by_id, :resource, :processed,
:user_role_name,
:as => :role_updated
attr_accessor :start_date_s, :end_date_s, :action_s, :resource_s, :user_role_id_s, :processed_s, :customer_id_s, :project_id_s
attr_accessible :start_date_s, :end_date_s, :action_s, :resource_s, :user_role_id_s, :processed_s, :customer_id_s, :project_id_s,
:as => :role_search_stats
belongs_to :last_updated_by, :class_name => 'Authentify::User'
belongs_to :user_role, :class_name => 'SwProjectCustomerQnax::UserRole'
validates :user_role_id, :presence => true,
:numericality => {:only_integer => true, :greater_than => 0}
validates :action, :resource, :presence => true
validates :action, :uniqueness => {:scope => [:resource, :user_role_id], :case_sensitive => false, :message => 'Duplicate Action!'}
validate :dynamic_validate
def dynamic_validate
wf = Authentify::AuthentifyUtility.find_config_const('dynamic_validate_role_access_right', 'sw_project_customer_qnaxx')
eval(wf) if wf.present?
end
end
end
|
require 'rails_helper'
RSpec.describe Stock, type: :model do
context 'when defining the model' do
it { is_expected.to belong_to :product }
it { is_expected.to validate_presence_of :amount }
end
context 'when saving the model' do
subject(:stock) { create(:stock) }
it 'saving a valid stock' do
expect(stock.save!).to be_truthy
end
end
end
|
require("spec_helper")
describe(Store) do
it{ should have_and_belong_to_many(:brands) }
it { should validate_presence_of(:name) }
describe('#capitalize_name') do
it "capitalizes the name of a store" do
store = Store.create({:name => "demo store"})
expect(store.name()).to (eq("Demo store"))
end
end
end
|
class Poll < ActiveRecord::Base
# attr_accessible :title, :body
attr_accessible :micropost_id, :poll_type, :question
# Associations
belongs_to :micropost
has_many :proposals
# Validations
validates_presence_of :poll_type
validates_presence_of :question
validates_presence_of :micropost_id
def to_mobile
mobile_proposals = []
proposals.each do |proposal|
mobile_proposals << proposal.to_mobile
end
{ id: self.id, micropost_id: micropost_id, poll_type: poll_type, question: question, proposals: mobile_proposals }
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.