Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Update user_id primary key to bigint | class ChangeUserIdToBigint < ActiveRecord::Migration[6.0]
def up
change_column :users, :id, :bigint
end
def down
change_column :users, :id, :integer
end
end
| |
Add some output formatting to ResultsDecorator | module Discli
class ResultsDecorator
attr_reader :results
def initialize(results)
@results = results
end
def filter(params)
params.inject(results) do |filtered_results, (param, value)|
param, value = param.downcase.to_s, value.downcase.to_s
filtered_results.select do |result|
values = result[param]
if values.respond_to?(:map)
values.map(&:downcase).map(&:split).flatten.include?(value)
elsif values
values.downcase == value
end
end
end
end
end
end
| module Discli
class ResultsDecorator
attr_reader :results
def initialize(results)
@results = results
end
def filter(params)
params.inject(results) do |filtered_results, (param, value)|
param, value = param.downcase.to_s, value.downcase.to_s
filtered_results.select do |result|
values = result[param]
if values.respond_to?(:map)
values.map(&:downcase).map(&:split).flatten.include?(value)
elsif values
values.downcase == value
end
end
end
end
def to_s
results.map do |result|
"%s | %s | %s" % [
result['id'].to_s.rjust(9),
color_type(result['type']).ljust(16),
result['title']]
end.join("\n")
end
private
def color_type(type)
color = {
'release' => :red,
'master' => :green,
'artist' => :blue,
'label' => :yellow
}.fetch(type.strip, :black)
send(color, type)
end
def red(text); colorize(text, 32); end
def blue(text); colorize(text, 34); end
def green(text); colorize(text, 31); end
def black(text); colorize(text, 00); end
def yellow(text); colorize(text, 33); end
def colorize(text, code)
"\e[#{code}m#{text}\e[0m"
end
end
end
|
Use for @debug so it can be caught via replacement. | module Sass
module Tree
# A dynamic node representing a Sass `@debug` statement.
#
# @see Sass::Tree
class DebugNode < Node
# @param expr [Script::Node] The expression to print
def initialize(expr)
@expr = expr
super()
end
protected
# Prints the expression to STDERR.
#
# @param environment [Sass::Environment] The lexical environment containing
# variable and mixin values
def _perform(environment)
res = @expr.perform(environment)
if filename
STDERR.puts "#{filename}:#{line} DEBUG: #{res}"
else
STDERR.puts "Line #{line} DEBUG: #{res}"
end
[]
end
end
end
end
| module Sass
module Tree
# A dynamic node representing a Sass `@debug` statement.
#
# @see Sass::Tree
class DebugNode < Node
# @param expr [Script::Node] The expression to print
def initialize(expr)
@expr = expr
super()
end
protected
# Prints the expression to STDERR.
#
# @param environment [Sass::Environment] The lexical environment containing
# variable and mixin values
def _perform(environment)
res = @expr.perform(environment)
if filename
$stderr.puts "#{filename}:#{line} DEBUG: #{res}"
else
$stderr.puts "Line #{line} DEBUG: #{res}"
end
[]
end
end
end
end
|
Add full_a_path, full_b_path methods on Diff | module Grit
class Diff
attr_reader :repo
def hunks
header_lines.each_with_index
.map { |header, index|
next_header = header_lines[index + 1]
next_line_number = next_header ? next_header[1] : lines.count
DiffHunk.new(header[0], lines[header[1], next_line_number - 1])
}
end
protected
def lines
@lines ||= diff.split("\n")
end
def header_lines
@header_lines ||= lines.each_with_index
.find_all { |line, index| line.start_with?('@@') }
.map { |line, index|
header = DiffHeader.new(line)
[header, index]
}
end
end
end
| module Grit
class Diff
attr_reader :repo
def hunks
header_lines.each_with_index
.map { |header, index|
next_header = header_lines[index + 1]
next_line_number = next_header ? next_header[1] : lines.count
DiffHunk.new(header[0], lines[header[1], next_line_number - 1])
}
end
def full_a_path
File.join(repo.working_dir, a_path)
end
def full_b_path
File.join(repo.working_dir, b_path)
end
protected
def lines
@lines ||= diff.split("\n")
end
def header_lines
@header_lines ||= lines.each_with_index
.find_all { |line, index| line.start_with?('@@') }
.map { |line, index|
header = DiffHeader.new(line)
[header, index]
}
end
end
end
|
Add note about TODO step, updating searchbar data after permissions are adjusted in dashboard | module Admin
class EducatorsController < Admin::ApplicationController
# To customize the behavior of this controller,
# simply overwrite any of the RESTful actions.
def index
@_order = Administrate::Order.new(:full_name)
super
end
def edit
@valid_grades = %w(PK KF SP 1 2 3 4 5 6 7 8 9 10 11 12)
super
end
def resource_params
params["educator"]["grade_level_access"] = params["educator"]["grade_level_access"].try(:keys) || []
params.require("educator").permit(*dashboard.permitted_attributes, grade_level_access: [])
end
end
end
| module Admin
class EducatorsController < Admin::ApplicationController
# To customize the behavior of this controller,
# simply overwrite any of the RESTful actions.
def index
@_order = Administrate::Order.new(:full_name)
super
end
def edit
@valid_grades = %w(PK KF SP 1 2 3 4 5 6 7 8 9 10 11 12)
super
end
def update
# TODO (ARS): re-compute student searchbar JSON once permissions are updated
super
end
def resource_params
params["educator"]["grade_level_access"] = params["educator"]["grade_level_access"].try(:keys) || []
params.require("educator").permit(*dashboard.permitted_attributes, grade_level_access: [])
end
end
end
|
Move minitest/autorun require to stop warning | require 'coveralls'
Coveralls.wear!
ENV['RACK_ENV'] = 'test'
require 'minitest/autorun'
require 'rack/test'
require_relative '../noodle'
# Make sure we don't explode a real index
Node.gateway.index = 'this-is-for-running-noodle-elasticsearch-tests-only'
# TODO: What's the right way to do this?
begin
Node.gateway.delete_index!
rescue
end
# TODO: Enable this via 'rake debug' or something
# Holy cow, log
#Node.gateway.client.transport.logger = Logger.new(STDERR)
# Make sure the index exists
Node.gateway.create_index!
Node.gateway.refresh_index!
require 'minitest/reporters'
Minitest::Reporters.use!
include Rack::Test::Methods
def app
Noodle
end
| require 'coveralls'
Coveralls.wear!
ENV['RACK_ENV'] = 'test'
require 'rack/test'
require_relative '../noodle'
# Make sure we don't explode a real index
Node.gateway.index = 'this-is-for-running-noodle-elasticsearch-tests-only'
# TODO: What's the right way to do this?
begin
Node.gateway.delete_index!
rescue
end
# TODO: Enable this via 'rake debug' or something
# Holy cow, log
#Node.gateway.client.transport.logger = Logger.new(STDERR)
# Make sure the index exists
Node.gateway.create_index!
Node.gateway.refresh_index!
require 'minitest/autorun'
require 'minitest/reporters'
Minitest::Reporters.use!
include Rack::Test::Methods
def app
Noodle
end
|
Add plugin to embed multiple .md files | =begin
Jekyll tag to include Markdown text from _includes directory preprocessing with Liquid.
Usage:
{% markdown <filename> %}
Dependency:
- kramdown
=end
module Jekyll
class MarkdownTag < Liquid::Tag
def initialize(tag_name, text, tokens)
super
@text = text.strip
end
require "kramdown"
def render(context)
tmpl = File.read File.join Dir.pwd, "_includes", @text
site = context.registers[:site]
tmpl = (Liquid::Template.parse tmpl).render site.site_payload
html = Kramdown::Document.new(tmpl).to_html
end
end
end
Liquid::Template.register_tag('markdown', Jekyll::MarkdownTag)
| |
Add staff to user list | ### Configuration
Preference.create(name: 'END_TIME', value: '2013-11-30 22:30:00+1100')
### Data
ImportUsers.import 'public/gala_tables.xlsx'
puts "Imported #{User.count()} users"
ImportItems.import 'public/gala_content.xlsx'
puts "Imported #{Item.count()} items"
# Staff
staff_table = UserGroup.create(name: "Staff", sort_order: UserGroup.maximum(:sort_order) + 1)
User.create(user_group: staff_table, title: '', first_name: 'iPad', last_name: '', pin: 1515, admin: true)
| ### Configuration
Preference.create(name: 'END_TIME', value: '2013-11-30 22:30:00+1100')
### Data
ImportUsers.import 'public/gala_tables.xlsx'
puts "Imported #{User.count()} users"
ImportItems.import 'public/gala_content.xlsx'
puts "Imported #{Item.count()} items"
# Staff
staff_table = UserGroup.create(name: "Staff", sort_order: UserGroup.maximum(:sort_order) + 1)
User.create(user_group: staff_table, title: '', first_name: 'iPad', last_name: '', pin: 1515, admin: true)
User.create(user_group: staff_table, title: 'Mr', first_name: 'Bruno', last_name: 'Chauvet', pin: 1234, admin: true)
User.create(user_group: staff_table, title: 'Mrs', first_name: 'Cecile', last_name: 'Reyes-Chauvet', pin: 1234)
User.create(user_group: staff_table, title: 'Mr', first_name: 'Alexis', last_name: 'Bouvot', pin: 1234)
User.create(user_group: staff_table, title: 'Mr', first_name: 'Nicolas', last_name: 'Teulier', pin: 1234)
User.create(user_group: staff_table, title: 'Mr', first_name: 'Denis', last_name: 'Gittar', pin: 1234)
|
Add card importer to seed.rb | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
| # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
columns = Card.column_names - %w(created_at updated_at)
cards = File.open('../,mytools/collectible_ja.json') {|fp| JSON.load(fp) }
cards.select{|card| card[:id] == 'EX1_066'}.tapp
cards.each do |card|
card['card_type'] = card['type']
card['hearthstone_id'] = card['id']
card.delete('id')
card = card.slice(*columns)
Card.create(card)
end |
Add caveat about using this Bash as login shell | require 'formula'
class Bash < Formula
homepage 'http://www.gnu.org/software/bash/'
url 'http://ftpmirror.gnu.org/bash/bash-4.2.tar.gz'
mirror 'http://ftp.gnu.org/gnu/bash/bash-4.2.tar.gz'
sha256 'a27a1179ec9c0830c65c6aa5d7dab60f7ce1a2a608618570f96bfa72e95ab3d8'
version '4.2.20'
depends_on 'readline'
def patches
patch_level = version.split('.').last.to_i
{'p0' => (1..patch_level).map { |i| "http://ftpmirror.gnu.org/bash/bash-4.2-patches/bash42-%03d" % i }}
end
def install
system "./configure", "--prefix=#{prefix}", "--with-installed-readline"
system "make install"
end
end
| require 'formula'
class Bash < Formula
homepage 'http://www.gnu.org/software/bash/'
url 'http://ftpmirror.gnu.org/bash/bash-4.2.tar.gz'
mirror 'http://ftp.gnu.org/gnu/bash/bash-4.2.tar.gz'
sha256 'a27a1179ec9c0830c65c6aa5d7dab60f7ce1a2a608618570f96bfa72e95ab3d8'
version '4.2.20'
depends_on 'readline'
def patches
patch_level = version.split('.').last.to_i
{'p0' => (1..patch_level).map { |i| "http://ftpmirror.gnu.org/bash/bash-4.2-patches/bash42-%03d" % i }}
end
def install
system "./configure", "--prefix=#{prefix}", "--with-installed-readline"
system "make install"
end
def caveats; <<-EOS.undent
In order to use this build of bash as your login shell,
it must be added to /etc/shells.
EOS
end
end
|
Correct uppercase name on veclibfort | require 'formula'
class Qrupdate < Formula
homepage 'http://sourceforge.net/projects/qrupdate/'
url 'https://downloads.sourceforge.net/qrupdate/qrupdate-1.1.2.tar.gz'
sha1 'f7403b646ace20f4a2b080b4933a1e9152fac526'
option "without-check", "Skip build-time tests (not recommended)"
depends_on :fortran
depends_on "openblas" => :optional
depends_on "veclibfort" if build.without? "openblas"
def install
ENV.j1
blas = (build.with? "openblas") ? "openblas" : "veclibfort"
blas = "-L#{Formula["#{blas}"].opt_lib} -l#{blas}"
make_args = ["FC=#{ENV.fc}", "FFLAGS=#{ENV.fcflags}",
"BLAS=#{blas}", "LAPACK=#{blas}"]
inreplace 'src/Makefile' do |s|
s.gsub! 'install -D', 'install'
end
lib.mkpath
system "make", "lib", "solib", *make_args
system "make", "test", *make_args if build.with? "check"
rm "INSTALL" # Somehow this confuses "make install".
system "make", "install", "PREFIX=#{prefix}"
end
end
| require 'formula'
class Qrupdate < Formula
homepage 'http://sourceforge.net/projects/qrupdate/'
url 'https://downloads.sourceforge.net/qrupdate/qrupdate-1.1.2.tar.gz'
sha1 'f7403b646ace20f4a2b080b4933a1e9152fac526'
option "without-check", "Skip build-time tests (not recommended)"
depends_on :fortran
depends_on "openblas" => :optional
depends_on "veclibfort" if build.without? "openblas"
def install
ENV.j1
blas = (build.with? "openblas") ? "openblas" : "vecLibFort"
blas = "-L#{Formula["#{blas}"].opt_lib} -l#{blas}"
make_args = ["FC=#{ENV.fc}", "FFLAGS=#{ENV.fcflags}",
"BLAS=#{blas}", "LAPACK=#{blas}"]
inreplace 'src/Makefile' do |s|
s.gsub! 'install -D', 'install'
end
lib.mkpath
system "make", "lib", "solib", *make_args
system "make", "test", *make_args if build.with? "check"
rm "INSTALL" # Somehow this confuses "make install".
system "make", "install", "PREFIX=#{prefix}"
end
end
|
Set the mock IP field correctly | module Fog
module Compute
class Octocloud
class Mock
def remote_create_vm(opts)
newid = rand(99999)
opts.merge!({:ip => '127.0.0.1', :state => 'up'})
data[:servers][newid] = opts
opts.merge({:id => newid})
end
end
class Real
def remote_create_vm(opts = {})
%w{type cube memory}.each do |opt|
unless opts.include?(opt) || opts.include?(opt.to_sym)
raise ArgumentError.new("type, template and memory are required options to create a VM")
end
end
remote_request(:method => :post, :expects => [201], :body => opts, :path => "/api/virtual-machines" )
end
end
end
end
end
| module Fog
module Compute
class Octocloud
class Mock
def remote_create_vm(opts)
newid = rand(99999)
opts.merge!({:private_ip_address => '127.0.0.1', :state => 'up'})
data[:servers][newid] = opts
opts.merge({:id => newid})
end
end
class Real
def remote_create_vm(opts = {})
%w{type cube memory}.each do |opt|
unless opts.include?(opt) || opts.include?(opt.to_sym)
raise ArgumentError.new("type, template and memory are required options to create a VM")
end
end
remote_request(:method => :post, :expects => [201], :body => opts, :path => "/api/virtual-machines" )
end
end
end
end
end
|
Add tests for Role model | require 'test_helper'
#
# == Role model test
#
class RoleTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| require 'test_helper'
#
# == Role model test
#
class RoleTest < ActiveSupport::TestCase
setup :initialize_test
test 'should return all roles list if super_administrator' do
roles = Role.allowed_roles_for_user_role(@super_administrator)
assert_equal roles.count, 3
assert roles.exists?(name: 'subscriber')
assert roles.exists?(name: 'administrator')
assert roles.exists?(name: 'super_administrator')
end
test 'should return all roles list except super_administrator if administrator' do
roles = Role.allowed_roles_for_user_role(@administrator)
assert_equal roles.count, 2
assert roles.exists?(name: 'administrator')
assert roles.exists?(name: 'subscriber')
assert_not roles.exists?(name: 'super_administrator')
end
test 'should return nil if subscriber' do
roles = Role.allowed_roles_for_user_role(@subscriber)
assert roles.nil?
end
private
def initialize_test
@super_administrator = users(:anthony)
@administrator = users(:bob)
@subscriber = users(:alice)
end
end
|
Remove reference to guvera core | class Guvera::Dynamodb::BatchWriter
attr_accessor :items
def initialize client, table_name
@changes = []
@table_name = table_name
@client = client
end
def upsert item
@changes << {
put_request: {
item: item.to_hash
}
}
end
def delete item
@changes << {
delete_request: {
key: item.key
}
}
end
def << item
upsert item
end
def save
threads = []
@changes.each_slice(25) do |items|
threads << Guvera::Core.dispatch(method: "batch save", items: items) do
@client.batch_write_item({
request_items: {
"#{@table_name}" => items
}
})
end
end
threads.each {|t| t.join }
end
end
| class Guvera::Dynamodb::BatchWriter
attr_accessor :items
def initialize client, table_name
@changes = []
@table_name = table_name
@client = client
end
def upsert item
@changes << {
put_request: {
item: item.to_hash
}
}
end
def delete item
@changes << {
delete_request: {
key: item.key
}
}
end
def << item
upsert item
end
def save
threads = []
@changes.each_slice(25) do |items|
threads << Thread.new do
@client.batch_write_item({
request_items: {
"#{@table_name}" => items
}
})
end
end
threads.each {|t| t.join }
end
end
|
Remove mongoid logger monkeypatch, since this can now be configured in database.yml. | require "rubygems"
# Setup gem bundler for dependencies.
ENV["BUNDLE_GEMFILE"] = File.expand_path("../../Gemfile", __FILE__)
require "bundler"
Bundler.setup
# Setup the LOGGER constant that ProxyMachine uses if we're not inside
# proxymachine (eg, we're running tests).
if(!defined?(LOGGER))
require "logger"
LOGGER = Logger.new(STDOUT)
end
# Define a constant so we always know the AuthProxy's base location.
AUTH_PROXY_ROOT = File.expand_path("../../", __FILE__)
# Add load paths.
$LOAD_PATH.unshift(File.join(AUTH_PROXY_ROOT, "lib"))
$LOAD_PATH.unshift(File.join(AUTH_PROXY_ROOT, "models"))
# Define the default Rack environment for when we need to interact with models.
ENV["RACK_ENV"] ||= "development"
# Load Mongoid's configuration for this specific environment.
require "mongoid"
# FIXME: Disable MongoDB logging for performance. Currently a simple monkey
# patch.
#
# Mongoid.logger = nil currently doesn't work, but should be fixed in next
# release. https://github.com/mongoid/mongoid/issues/734
#
# Mongoid.logger = nil
module Mongoid
def self.logger
nil
end
end
Mongoid.load!(::File.join(AUTH_PROXY_ROOT, "config", "mongoid.yml"))
| require "rubygems"
# Setup gem bundler for dependencies.
ENV["BUNDLE_GEMFILE"] = File.expand_path("../../Gemfile", __FILE__)
require "bundler"
Bundler.setup
# Setup the LOGGER constant that ProxyMachine uses if we're not inside
# proxymachine (eg, we're running tests).
if(!defined?(LOGGER))
require "logger"
LOGGER = Logger.new(STDOUT)
end
# Define a constant so we always know the AuthProxy's base location.
AUTH_PROXY_ROOT = File.expand_path("../../", __FILE__)
# Add load paths.
$LOAD_PATH.unshift(File.join(AUTH_PROXY_ROOT, "lib"))
$LOAD_PATH.unshift(File.join(AUTH_PROXY_ROOT, "models"))
# Define the default Rack environment for when we need to interact with models.
ENV["RACK_ENV"] ||= "development"
# Load Mongoid's configuration for this specific environment.
require "mongoid"
Mongoid.load!(::File.join(AUTH_PROXY_ROOT, "config", "mongoid.yml"))
|
Add route alias for /pages/:page | Rails.application.routes.draw do
devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth_callbacks' }
devise_scope :user do
get "/users/finish_signup" => "users/omniauth_callbacks#finish_signup"
post "/users/finished_signup" => "users/omniauth_callbacks#finished_signup"
end
scope defaults: { format: :json }, path: "/api" do
resources :maps, only: [:index]
end
# For details on the DSL available within this file, see
# http://guides.rubyonrails.org/routing.html
root to: 'home#index'
end
Rails.application.routes.draw do
get "/pages/:page" => "pages#show"
end
| Rails.application.routes.draw do
devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth_callbacks' }
devise_scope :user do
get "/users/finish_signup" => "users/omniauth_callbacks#finish_signup"
post "/users/finished_signup" => "users/omniauth_callbacks#finished_signup"
end
scope defaults: { format: :json }, path: "/api" do
resources :maps, only: [:index]
end
# For details on the DSL available within this file, see
# http://guides.rubyonrails.org/routing.html
root to: 'home#index'
get "/pages/:page" => "pages#show", as: :page
end
|
Revert "test automated build notification" | require File.dirname(__FILE__) + '/../spec_helper'
describe OptinCostItemsController do
before do
stub_viewer_as_event_group_coordinator
stub_event_group
stub_project
stub_profile
setup_login
@cost_item = stub_model(CostItem)
stub_model_find(:cost_item)
end
it "should update cost item" do
@cost_item.should_receive(:save).and_return(true)
post 'update', :cost_item => {}, :id => @cost_item.id, :profile_id => @profile.id
flash[:notice].should == 'CostItem was successfully updated.'
end
it "should destroy optin cost item" do
@cost_item.should_receive(:destroy).and_return(true)
# list is rendered
@profile.stub!(:project => @project, :profile_cost_items => [])
@project.stub!(:cost_items => [ @cost_item ])
@event_group.stub!(:cost_items => [ ])
post 'destroy', :id => @cost_item.id, :profile_id => @profile.id
response.should be_success
end
it "should send a notification email when this fails" do
"this".should == 'fail'
end
end
| require File.dirname(__FILE__) + '/../spec_helper'
describe OptinCostItemsController do
before do
stub_viewer_as_event_group_coordinator
stub_event_group
stub_project
stub_profile
setup_login
@cost_item = stub_model(CostItem)
stub_model_find(:cost_item)
end
it "should update cost item" do
@cost_item.should_receive(:save).and_return(true)
post 'update', :cost_item => {}, :id => @cost_item.id, :profile_id => @profile.id
flash[:notice].should == 'CostItem was successfully updated.'
end
it "should destroy optin cost item" do
@cost_item.should_receive(:destroy).and_return(true)
# list is rendered
@profile.stub!(:project => @project, :profile_cost_items => [])
@project.stub!(:cost_items => [ @cost_item ])
@event_group.stub!(:cost_items => [ ])
post 'destroy', :id => @cost_item.id, :profile_id => @profile.id
response.should be_success
end
end
|
Clean up the code in WebSocket module | module EventMachine
module WebSocket
# All errors raised by em-websocket should descend from this class
#
class WebSocketError < RuntimeError; end
# Used for errors that occur during WebSocket handshake
#
class HandshakeError < WebSocketError; end
# Used for errors which should cause the connection to close.
# See RFC6455 §7.4.1 for a full description of meanings
#
class WSProtocolError < WebSocketError
def code; 1002; end
end
# 1009: Message too big to process
class WSMessageTooBigError < WSProtocolError
def code; 1009; end
end
def self.start(options, &blk)
EM.epoll
EM.run do
trap("TERM") { stop }
trap("INT") { stop }
run(options, &blk)
end
end
def self.run(options, &blk)
EventMachine::start_server(options[:host], options[:port],
EventMachine::WebSocket::Connection, options) do |c|
blk.call(c)
end
end
def self.stop
puts "Terminating WebSocket Server"
EventMachine.stop
end
class << self
attr_accessor :max_frame_size
end
@max_frame_size = 10 * 1024 * 1024 # 10MB
end
end
| module EventMachine
module WebSocket
class << self
attr_accessor :max_frame_size
end
@max_frame_size = 10 * 1024 * 1024 # 10MB
# All errors raised by em-websocket should descend from this class
class WebSocketError < RuntimeError; end
# Used for errors that occur during WebSocket handshake
class HandshakeError < WebSocketError; end
# Used for errors which should cause the connection to close.
# See RFC6455 §7.4.1 for a full description of meanings
class WSProtocolError < WebSocketError
def code; 1002; end
end
# 1009: Message too big to process
class WSMessageTooBigError < WSProtocolError
def code; 1009; end
end
# Start WebSocket server, including starting eventmachine run loop
def self.start(options, &blk)
EM.epoll
EM.run {
trap("TERM") { stop }
trap("INT") { stop }
run(options, &blk)
}
end
# Start WebSocket server inside eventmachine run loop
def self.run(options)
host, port = options.values_at(:host, :port)
EM.start_server(host, port, Connection, options) do |c|
yield c
end
end
def self.stop
puts "Terminating WebSocket Server"
EM.stop
end
end
end
|
Disable full sync for now as Vagrant already does this | module Vagrant
module Syncer
module Commands
class Syncer < Vagrant.plugin(2, :command)
def self.synopsis
"start auto-rsyncing"
end
def execute
with_target_vms do |machine|
machine = Machine.new(machine)
machine.full_sync
machine.listen
end
0
end
end
end
end
end | module Vagrant
module Syncer
module Commands
class Syncer < Vagrant.plugin(2, :command)
def self.synopsis
"start auto-rsyncing"
end
def execute
with_target_vms do |machine|
machine = Machine.new(machine)
# machine.full_sync
machine.listen
end
0
end
end
end
end
end |
Add rails 6.0 defaults file | # Be sure to restart your server when you modify this file.
#
# This file contains migration options to ease your Rails 6.0 upgrade.
#
# Once upgraded flip defaults one by one to migrate to the new default.
#
# Read the Guide for Upgrading Ruby on Rails for more info on each option.
# see https://guides.rubyonrails.org/autoloading_and_reloading_constants.html
# There is a separate ticket to handle upgrade to zeitwork, we should stick
# to :classic for the time being.
# Rails.application.config.autoloader = :zeitwerk
# Determines whether forms are generated with a hidden tag that forces older versions of Internet Explorer to submit forms encoded in UTF-8.
# Rails.application.config.action_view.default_enforce_utf8 = false
# Embed purpose and expiry metadata inside signed and encrypted
# cookies for increased security.
#
# This option is not backwards compatible with earlier Rails versions.
# It's best enabled when your entire app is migrated and stable on 6.0.
# Rails.application.config.action_dispatch.use_cookies_with_metadata = true
# Send Active Storage analysis and purge jobs to dedicated queues.
# Rails.application.config.active_storage.queues.analysis = :active_storage_analysis
# Rails.application.config.active_storage.queues.purge = :active_storage_purge
# When assigning to a collection of attachments declared via `has_many_attached`, replace existing
# attachments instead of appending. Use #attach to add new attachments without replacing existing ones.
# Rails.application.config.active_storage.replace_on_assign_to_many = true
# Use ActionMailer::MailDeliveryJob for sending parameterized and normal mail.
#
# The default delivery jobs (ActionMailer::Parameterized::DeliveryJob, ActionMailer::DeliveryJob),
# will be removed in Rails 6.1. This setting is not backwards compatible with earlier Rails versions.
# If you send mail in the background, job workers need to have a copy of
# MailDeliveryJob to ensure all delivery jobs are processed properly.
# Make sure your entire app is migrated and stable on 6.0 before using this setting.
# Rails.application.config.action_mailer.delivery_job = "ActionMailer::MailDeliveryJob"
# Enable the same cache key to be reused when the object being cached of type
# `ActiveRecord::Relation` changes by moving the volatile information (max updated at and count)
# of the relation's cache key into the cache version to support recycling cache key.
# Rails.application.config.active_record.collection_cache_versioning = true
| |
Add runtime kernel version to system info fold | require 'travis/build/appliances/base'
require 'shellwords'
module Travis
module Build
module Appliances
class ShowSystemInfo < Base
def apply
sh.fold 'system_info' do
header
show_travis_build_version
show_system_info_file
end
sh.newline
end
private
def header
sh.echo 'Build system information', ansi: :yellow
[:language, :group, :dist].each do |name|
value = data.send(name)
sh.echo "Build #{name}: #{Shellwords.escape(value)}" if value
end
sh.echo "Build id: #{Shellwords.escape(data.build[:id])}"
sh.echo "Job id: #{Shellwords.escape(data.job[:id])}"
end
def show_travis_build_version
if ENV['HEROKU_SLUG_COMMIT']
sh.echo "travis-build version: #{ENV['HEROKU_SLUG_COMMIT']}".untaint
end
end
def show_system_info_file
sh.if "-f #{info_file}" do
sh.cmd "cat #{info_file}"
end
end
def info_file
'/usr/share/travis/system_info'
end
end
end
end
end
| require 'travis/build/appliances/base'
require 'shellwords'
module Travis
module Build
module Appliances
class ShowSystemInfo < Base
def apply
sh.fold 'system_info' do
header
show_travis_build_version
show_system_info_file
end
sh.newline
end
private
def header
sh.echo 'Build system information', ansi: :yellow
[:language, :group, :dist].each do |name|
value = data.send(name)
sh.echo "Build #{name}: #{Shellwords.escape(value)}" if value
end
sh.echo "Build id: #{Shellwords.escape(data.build[:id])}"
sh.echo "Job id: #{Shellwords.escape(data.job[:id])}"
sh.echo "Runtime kernel version: #{`uname -r`.strip}"
end
def show_travis_build_version
if ENV['HEROKU_SLUG_COMMIT']
sh.echo "travis-build version: #{ENV['HEROKU_SLUG_COMMIT']}".untaint
end
end
def show_system_info_file
sh.if "-f #{info_file}" do
sh.cmd "cat #{info_file}"
end
end
def info_file
'/usr/share/travis/system_info'
end
end
end
end
end
|
Add null handler, replacing generic null object | require 'eventmachine'
require 'redis'
require 'multi_json'
require 'bluecap/keys'
require 'bluecap/message'
require 'bluecap/cohort'
require 'bluecap/engagement'
require 'bluecap/server'
require 'bluecap/handlers/attributes'
require 'bluecap/handlers/event'
require 'bluecap/handlers/identify'
require 'bluecap/handlers/report'
require 'bluecap/null_object'
module Bluecap
extend self
# Connect to Redis and store the resulting client.
#
# server - A String of conncetion details in host:port format.
#
# Examples
#
# redis = 'localhost:6379'
#
# Returns nothing.
def redis=(server)
host, port, database = server.split(':')
@redis = Redis.new(host: host, port: port, database: database)
end
# Returns the Redis client, creating a new client if one does not already
# exist.
def redis
return @redis if @redis
self.redis = 'localhost:6379'
self.redis
end
end
| require 'eventmachine'
require 'redis'
require 'multi_json'
require 'bluecap/keys'
require 'bluecap/message'
require 'bluecap/cohort'
require 'bluecap/engagement'
require 'bluecap/server'
require 'bluecap/handlers/attributes'
require 'bluecap/handlers/event'
require 'bluecap/handlers/identify'
require 'bluecap/handlers/null_handler'
require 'bluecap/handlers/report'
module Bluecap
extend self
# Connect to Redis and store the resulting client.
#
# server - A String of conncetion details in host:port format.
#
# Examples
#
# redis = 'localhost:6379'
#
# Returns nothing.
def redis=(server)
host, port, database = server.split(':')
@redis = Redis.new(host: host, port: port, database: database)
end
# Returns the Redis client, creating a new client if one does not already
# exist.
def redis
return @redis if @redis
self.redis = 'localhost:6379'
self.redis
end
end
|
Fix bug with boolean and postgre | class AddBooleanToSettings < ActiveRecord::Migration
def change
add_column :settings, :show_breadcrumb, :boolean, default: 0, after: :show_map
add_column :settings, :show_social, :boolean, default: 1, after: :show_breadcrumb
end
end
| class AddBooleanToSettings < ActiveRecord::Migration
def change
add_column :settings, :show_breadcrumb, :boolean, default: false, after: :show_map
add_column :settings, :show_social, :boolean, default: true, after: :show_breadcrumb
end
end
|
Change redirect after sign up | module SimpleUser
class Users::RegistrationsController < Devise::RegistrationsController
end
end | module SimpleUser
class Users::RegistrationsController < Devise::RegistrationsController
def after_sign_up_path_for(resource)
if ENV['REDIRECT_USER_AFTER_SIGNIN'] == 'false' || !defined?(session[:return_to]) || session[:return_to] == "/" || session[:return_to].nil?
after_sign_in_path_for(resource)
else
return_to = session[:return_to]
return_to
end
end
end
end |
Add code wars (7) down arrow with numbers | # http://www.codewars.com/kata/5645b24e802c6326f7000049/
# iteration 1
def get_a_down_arrow_of(n)
return "" if n < 1
pad_l = (1...n).map{ |x| x % 10 }.join("")
pad_r = pad_l.reverse
result_arr = []
n.downto(1).each do |i|
result_arr << "#{pad_l}#{i%10}#{pad_r}"
pad_l[-1], pad_r[0] = ["", ""] if pad_l.size > 0
end
result_arr.map.with_index{ |x, i| " " * i << x }.join("\n")
end
# iteration 2
def get_a_down_arrow_of(n)
return "" unless n > 0
pad_l = Array.new(n-1){ |i| (i + 1) % 10 }.join("")
pad_r = pad_l.reverse
n.downto(1).map.with_index do |x, i|
str = " " * i + "#{pad_l}#{x%10}#{pad_r}"
pad_l[-1], pad_r[0] = ["", ""] if pad_l.size > 0
str
end.join("\n")
end
| |
Add table tags to list of allowable tags for sanitize. | # Sanitize attributes before validation.
#
# Usage in model:
#
# sanitize_attributes :description, :documentation_description
#
# For now it just allows defaults, mainly harmless formatting tags, see ActionView::Base.sanitized_allowed_tags
# and ActionView::Base.sanitized_allowed_attributes for whole list.
module SanitizableAttributes
def self.included(model)
model.extend(ClassMethods)
end
def sanitize!
self.class.sanitizable_attributes.each do |attr_name|
sanitized_value = ActionController::Base.helpers.sanitize(self.send("#{attr_name}"))
self.send("#{attr_name}=", sanitized_value)
end
end
module ClassMethods
def sanitize_attributes(*attr_names)
cattr_accessor :sanitizable_attributes
self.sanitizable_attributes = attr_names
before_validation :sanitize!
end
end
end | # Sanitize attributes before validation.
#
# Usage in model:
#
# sanitize_attributes :description, :documentation_description
#
module SanitizableAttributes
# based on defaults from ActionView::Base.sanitized_allowed_tags with table tags added
SANITIZED_ALLOWED_TAGS = %w(strong em b i p code pre tt samp kbd var sub sup dfn cite big small
address hr br div span h1 h2 h3 h4 h5 h6 ul ol li dl dt dd abbr acronym a img blockquote del ins
table tr td th)
# based on defaults from ActionView::Base.sanitized_allowed_attributes
SANITIZED_ALLOWED_ATTRIBUTES = %w(href src width height alt cite datetime title class name xml:lang abbr)
def self.included(model)
model.extend(ClassMethods)
end
def sanitize!
self.class.sanitizable_attributes.each do |attr_name|
sanitized_value = ActionController::Base.helpers.sanitize(self.send("#{attr_name}"),
:tags => SANITIZED_ALLOWED_TAGS,
:attributes => SANITIZED_ALLOWED_ATTRIBUTES
)
self.send("#{attr_name}=", sanitized_value)
end
end
module ClassMethods
def sanitize_attributes(*attr_names)
cattr_accessor :sanitizable_attributes
self.sanitizable_attributes = attr_names
before_validation :sanitize!
end
end
end |
Add 'rake' as development dependency | # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require 'ipinfodb/version'
Gem::Specification.new do |s|
s.name = "ipinfodb"
s.version = Ipinfodb::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Tomasz Mazur"]
s.email = ["defkode@gmail.com"]
s.homepage = "http://ipinfodb.com"
s.summary = %q{Free IP address geolocation tools}
s.description = %q{Free IP address geolocation tools}
s.rubyforge_project = "ipinfodb"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
s.add_dependency('httparty', '~> 0.6')
end
| # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require 'ipinfodb/version'
Gem::Specification.new do |gem|
gem.name = "ipinfodb"
gem.version = Ipinfodb::VERSION
gem.platform = Gem::Platform::RUBY
gem.authors = ["Tomasz Mazur"]
gem.email = ["defkode@gmail.com"]
gem.homepage = "http://ipinfodb.com"
gem.summary = %q{Free IP address geolocation tools}
gem.description = %q{Free IP address geolocation tools}
gem.rubyforge_project = "ipinfodb"
gem.files = `git ls-files`.split("\n")
gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
gem.require_paths = ["lib"]
gem.add_dependency('httparty', '~> 0.6')
gem.add_development_dependency('rake')
end
|
Update ruby version in gemspec. | # encoding: UTF-8
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'spree_redbox'
s.version = '2.2'
s.summary = 'Spree extenstion for redbox'
s.required_ruby_version = '>= 1.9.3'
s.author = 'Jakub Kubacki'
s.email = 'kubacki.jk@gmail.com'
s.homepage = 'https://github.com/jkubacki'
#s.files = `git ls-files`.split("\n")
#s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.require_path = 'lib'
s.requirements << 'none'
s.add_dependency 'spree_core', '~> 2.2'
s.add_dependency 'php-serialize'
s.add_development_dependency 'capybara', '~> 2.1'
s.add_development_dependency 'coffee-rails'
s.add_development_dependency 'database_cleaner'
s.add_development_dependency 'factory_girl', '~> 4.4'
s.add_development_dependency 'ffaker'
s.add_development_dependency 'rspec-rails', '~> 2.13'
s.add_development_dependency 'sass-rails'
s.add_development_dependency 'selenium-webdriver'
s.add_development_dependency 'simplecov'
s.add_development_dependency 'sqlite3'
end
| # encoding: UTF-8
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'spree_redbox'
s.version = '2.2'
s.summary = 'Spree extenstion for redbox'
s.required_ruby_version = '>= 2.0.0'
s.author = 'Jakub Kubacki'
s.email = 'kubacki.jk@gmail.com'
s.homepage = 'https://github.com/jkubacki'
#s.files = `git ls-files`.split("\n")
#s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.require_path = 'lib'
s.requirements << 'none'
s.add_dependency 'spree_core', '~> 2.2'
s.add_dependency 'php-serialize'
s.add_development_dependency 'capybara', '~> 2.1'
s.add_development_dependency 'coffee-rails'
s.add_development_dependency 'database_cleaner'
s.add_development_dependency 'factory_girl', '~> 4.4'
s.add_development_dependency 'ffaker'
s.add_development_dependency 'rspec-rails', '~> 2.13'
s.add_development_dependency 'sass-rails'
s.add_development_dependency 'selenium-webdriver'
s.add_development_dependency 'simplecov'
s.add_development_dependency 'sqlite3'
end
|
Add deprecation warning to EmailValidator | # This is a shim for keeping backwards compatibility.
# See the discussion in: https://github.com/lisinge/valid_email2/pull/79
class EmailValidator < ValidEmail2::EmailValidator
end
| # This is a shim for keeping backwards compatibility.
# See the discussion in: https://github.com/lisinge/valid_email2/pull/79
class EmailValidator < ValidEmail2::EmailValidator
def validate_each(record, attribute, value)
warn "DEPRECATION WARNING: The email validator from valid_email2 has been " +
"deprecated in favour of using the namespaced 'valid_email_2/email' validator. " +
"For more information see https://github.com/lisinge/valid_email2#upgrading-to-v200"
super
end
end
|
Add code to fix already-broken databases that would otherwise fail this migration | class UniqueLiveFormTemplate < ActiveRecord::Migration
def self.up
execute "CREATE UNIQUE INDEX unique_live_form_template ON forms (template_id) WHERE status = 'Live'"
end
def self.down
execute 'DROP INDEX unique_live_form_template'
end
end
| class UniqueLiveFormTemplate < ActiveRecord::Migration
def self.up
execute %{
UPDATE forms
SET status = 'Inactive'
FROM (
SELECT DISTINCT ON (template_id) template_id, id
FROM forms
WHERE
status = 'Live' AND
template_id IN (
SELECT template_id
FROM (
SELECT template_id, count(*)
FROM forms
WHERE status = 'Live'
GROUP BY template_id
HAVING count(*) > 1
) foo
)
ORDER BY template_id, version DESC
) bar
WHERE
bar.template_id = forms.template_id AND
bar.id != forms.id AND
forms.status = 'Live'
RETURNING forms.id;
}
execute "CREATE UNIQUE INDEX unique_live_form_template ON forms (template_id) WHERE status = 'Live'"
end
def self.down
execute 'DROP INDEX unique_live_form_template'
end
end
|
Revert "Remove some test parameters" | require 'spec_helper'
require_relative '../../../libraries/consul_installation'
require_relative '../../../libraries/consul_installation_webui'
describe ConsulCookbook::Provider::ConsulInstallationWebui do
step_into(:consul_installation)
before { default_attributes['consul'] ||= {} }
let(:chefspec_options) { {platform: 'ubuntu', version: '14.04'} }
context 'webui installation' do
pending('replace with poise-archive')
recipe do
consul_installation '0.7.0' do
provider :webui
end
end
it do is_expected.to create_directory('/opt/consul-webui/0.7.0')
.with(
recursive: true
)
end
it do is_expected.to create_directory('/var/lib/consul')
.with(
recursive: true
)
end
it do is_expected.to unzip_zipfile('consul_0.7.0_web_ui.zip')
.with(
source: 'https://releases.hashicorp.com/consul/0.7.0/consul_0.7.0_web_ui.zip'
)
end
end
end
| require 'spec_helper'
require_relative '../../../libraries/consul_installation'
require_relative '../../../libraries/consul_installation_webui'
describe ConsulCookbook::Provider::ConsulInstallationWebui do
step_into(:consul_installation)
before { default_attributes['consul'] ||= {} }
let(:chefspec_options) { {platform: 'ubuntu', version: '14.04'} }
context 'webui installation' do
pending('replace with poise-archive')
recipe do
consul_installation '0.7.0' do
provider :webui
end
end
it do is_expected.to create_directory('/opt/consul-webui/0.7.0')
.with(
recursive: true
)
end
it do is_expected.to create_directory('/var/lib/consul')
.with(
recursive: true
)
end
it do is_expected.to unzip_zipfile('consul_0.7.0_web_ui.zip')
.with(
checksum: '42212089c228a73a0881a5835079c8df58a4f31b5060a3b4ffd4c2497abe3aa8',
path: '/opt/consul-webui/0.7.0',
source: 'https://releases.hashicorp.com/consul/0.7.0/consul_0.7.0_web_ui.zip'
)
end
end
end
|
Add check if remore is cloned | require 'securerandom'
require 'erb'
module Skyed
# This module encapsulates all the Git features.
module Git
class << self
def clone_stack_remote(stack, options)
unless Skyed::Settings.current_stack?(stack[:stack_id])
Skyed::Init.opsworks_git_key options
end
ENV['PKEY'] ||= Skyed::Settings.opsworks_git_key
Skyed::Utils.create_template('/tmp', 'ssh-git', 'ssh-git.erb', 0755)
ENV['GIT_SSH'] = '/tmp/ssh-git'
path = "/tmp/skyed.#{SecureRandom.hex}"
r = ::Git.clone(stack[:custom_cookbooks_source][:url], path)
puts "#{stack[:custom_cookbooks_source][:url]} #{r.branch}"
path
end
end
end
end
| require 'securerandom'
require 'erb'
module Skyed
# This module encapsulates all the Git features.
module Git
class << self
def clone_stack_remote(stack, options)
unless Skyed::Settings.current_stack?(stack[:stack_id])
Skyed::Init.opsworks_git_key options
end
ENV['PKEY'] ||= Skyed::Settings.opsworks_git_key
Skyed::Utils.create_template('/tmp', 'ssh-git', 'ssh-git.erb', 0755)
ENV['GIT_SSH'] = '/tmp/ssh-git'
path = "/tmp/skyed.#{SecureRandom.hex}"
::Git.clone(stack[:custom_cookbooks_source][:url], path)
puts Dir[path]
path
end
end
end
end
|
Fix an issue with an accidental backtick in a pod spec summary. | Pod::Spec.new do |spec|
spec.name = 'KSPAutomaticHeightCalculationTableCellView'
spec.version = '1.0.0'
spec.authors = {'Konstantin Pavlikhin' => 'k.pavlikhin@gmail.com'}
spec.social_media_url = 'https://twitter.com/kpavlikhin'
spec.license = {:type => 'MIT', :file => 'License.md'}
spec.homepage = 'https://github.com/konstantinpavlikhin/KSPAutomaticHeightCalculationTableCellView'
spec.source = {:git => 'https://github.com/konstantinpavlikhin/KSPAutomaticHeightCalculationTableCellView.git', :tag => "#{spec.version}"}
spec.summary = 'A useful superclass for a custom view-based NSTableView's cell.'
spec.platform = :osx, "10.7"
spec.osx.deployment_target = "10.7"
spec.requires_arc = true
spec.source_files = '*.{h,m}'
end
| Pod::Spec.new do |spec|
spec.name = 'KSPAutomaticHeightCalculationTableCellView'
spec.version = '1.0.0'
spec.authors = {'Konstantin Pavlikhin' => 'k.pavlikhin@gmail.com'}
spec.social_media_url = 'https://twitter.com/kpavlikhin'
spec.license = {:type => 'MIT', :file => 'License.md'}
spec.homepage = 'https://github.com/konstantinpavlikhin/KSPAutomaticHeightCalculationTableCellView'
spec.source = {:git => 'https://github.com/konstantinpavlikhin/KSPAutomaticHeightCalculationTableCellView.git', :tag => "#{spec.version}"}
spec.summary = 'A useful superclass for a custom view-based NSTableViews cell.'
spec.platform = :osx, "10.7"
spec.osx.deployment_target = "10.7"
spec.requires_arc = true
spec.source_files = '*.{h,m}'
end
|
Update sample to match new ruboto split | require 'ruboto'
# will get called whenever the BroadcastReceiver receives an intent (whenever onReceive is called)
$broadcast_receiver.handle_receive do |context, intent|
Log.v "MYAPP", intent.getExtras.to_s
end
| require 'ruboto/broadcast_receiver'
# will get called whenever the BroadcastReceiver receives an intent (whenever onReceive is called)
RubotoBroadcastReceiver.new_with_callbacks do
def on_receive(context, intent)
Log.v "MYAPP", intent.getExtras.to_s
end
end
|
Add test for CategoryRelationship model | require 'test_helper'
class CategoryRelationshipTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| require 'test_helper'
class CategoryRelationshipTest < ActiveSupport::TestCase
test "CategoryRelationship without child_id should not be valid" do
assert_not CategoryRelationship.new(child_id: nil).valid?
end
end
|
Add a script to check typos | #!/usr/bin/ruby
# -*- coding: utf-8 -*-
# Cited from コードの世界 by Matz
# 典型的なスペル・ミスを探す方法, 図6 文章のミスをチェックするスクリプト
ARGF.each do |line|
print ARGF.file.path, " ",
ARGF.file.lineno, ":",
line if line.gsub!(/([へにおはがでな])\1/s, '[[\&]]')
end
| |
Add float to attribute value | module Moysklad::Entities
class AttributeValue < Virtus::Attribute
def coerce(value)
if value.is_a? String
value
elsif value.is_a? ::Hash
if value['meta']['type'] == 'customentity'
CustomEntity.new value
else
raise "Unknown meta type: #{value['meta']['type']}"
end
else
raise "Unknown value type (#{value}) #{value.class}"
end
end
end
end
| module Moysklad::Entities
class AttributeValue < Virtus::Attribute
def coerce(value)
case value
when String, Float
value
when Hash
if value['meta']['type'] == 'customentity'
CustomEntity.new value
else
raise "Unknown meta type: #{value['meta']['type']}"
end
else
raise "Unknown value type (#{value}) #{value.class}"
end
end
end
end
|
Remove non-existent `:nchar` from attr_reader | # frozen_string_literal: true
module ActiveRecord
module ConnectionAdapters #:nodoc:
module OracleEnhanced
class Column < ActiveRecord::ConnectionAdapters::Column
attr_reader :table_name, :nchar, :virtual_column_data_default, :returning_id #:nodoc:
def initialize(name, default, sql_type_metadata = nil, null = true, table_name = nil, virtual = false, returning_id = nil, comment = nil) #:nodoc:
@virtual = virtual
@virtual_column_data_default = default.inspect if virtual
@returning_id = returning_id
if virtual
default_value = nil
else
default_value = self.class.extract_value_from_default(default)
end
super(name, default_value, sql_type_metadata, null, table_name, comment: comment)
# Is column NCHAR or NVARCHAR2 (will need to use N'...' value quoting for these data types)?
# Define only when needed as adapter "quote" method will check at first if instance variable is defined.
end
def virtual?
@virtual
end
def returning_id?
@returning_id
end
def lob?
self.sql_type =~ /LOB$/i
end
private
def self.extract_value_from_default(default)
case default
when String
default.gsub(/''/, "'")
else
default
end
end
end
end
end
end
| # frozen_string_literal: true
module ActiveRecord
module ConnectionAdapters #:nodoc:
module OracleEnhanced
class Column < ActiveRecord::ConnectionAdapters::Column
attr_reader :table_name, :virtual_column_data_default, :returning_id #:nodoc:
def initialize(name, default, sql_type_metadata = nil, null = true, table_name = nil, virtual = false, returning_id = nil, comment = nil) #:nodoc:
@virtual = virtual
@virtual_column_data_default = default.inspect if virtual
@returning_id = returning_id
if virtual
default_value = nil
else
default_value = self.class.extract_value_from_default(default)
end
super(name, default_value, sql_type_metadata, null, table_name, comment: comment)
# Is column NCHAR or NVARCHAR2 (will need to use N'...' value quoting for these data types)?
# Define only when needed as adapter "quote" method will check at first if instance variable is defined.
end
def virtual?
@virtual
end
def returning_id?
@returning_id
end
def lob?
self.sql_type =~ /LOB$/i
end
private
def self.extract_value_from_default(default)
case default
when String
default.gsub(/''/, "'")
else
default
end
end
end
end
end
end
|
Enable HTTPS handling in caching Rake task. | namespace :exceptionally_beautiful do
desc "Cache all Exceptionally Beautiful error pages in your application's public folder"
task :cache => :environment do
app = ActionDispatch::Integration::Session.new(Rails.application)
ExceptionallyBeautiful.errors.each do |error_code|
app.get "/#{error_code}"
file_path = Rails.root.join('public')
file_name = "/#{error_code}.html"
File.open([file_path, file_name].join, 'w') { |f| f.write(app.response.body) }
end
end
end | namespace :exceptionally_beautiful do
desc "Cache all Exceptionally Beautiful error pages in your application's public folder"
task :cache => :environment do
app = ActionDispatch::Integration::Session.new(Rails.application)
app.https!
ExceptionallyBeautiful.errors.each do |error_code|
app.get "/#{error_code}"
file_path = Rails.root.join('public')
file_name = "/#{error_code}.html"
File.open([file_path, file_name].join, 'w') { |f| f.write(app.response.body) }
end
end
end |
Update Shuttle from version 1.1.1 to 1.1.2 | class Shuttle < Cask
url 'https://github.com/fitztrev/shuttle/releases/download/v1.1.1/Shuttle.dmg'
homepage 'http://fitztrev.github.io/shuttle/'
version '1.1.1'
sha1 '0abd1b042b46d996e5643c21a658ff10877417e6'
link 'Shuttle.app'
end
| class Shuttle < Cask
url 'https://github.com/fitztrev/shuttle/releases/download/v1.1.2/Shuttle.dmg'
homepage 'http://fitztrev.github.io/shuttle/'
version '1.1.2'
sha1 '70ef2c86f6af51621b165bb642c49d0fecf90d90'
link 'Shuttle.app'
end
|
Upgrade Sketch Beta to v3.2.2 | cask :v1 => 'sketch-beta' do
version '3.2.1'
sha256 '75be5326ae7c6d639effb112c5a4f7c93e55e786d7c807a01e80a9479455699c'
url 'https://rink.hockeyapp.net/api/2/apps/0172d48cceec171249a8d850fb16276b/app_versions/64?format=zip&avtoken=772f3a4aa948c0f0ffe925c35a81648c8f40d69d'
homepage 'http://bohemiancoding.com/sketch/beta/'
license :unknown
app 'Sketch Beta.app'
end
| cask :v1 => 'sketch-beta' do
version '3.2.2'
sha256 '275633effb38fa6e2d963efaa8a2fa9e614638fff67db89ab34acc1e7a469a8e'
url 'https://rink.hockeyapp.net/api/2/apps/0172d48cceec171249a8d850fb16276b/app_versions/65?format=zip&avtoken=4cf67d09dadfaa99e993df78664101d36228f5c0'
homepage 'http://bohemiancoding.com/sketch/beta/'
license :unknown
app 'Sketch Beta.app'
end
|
Move factory schema config to initialization | module Pacto
class ContractFactory
attr_reader :preprocessor
def initialize(options = {})
@preprocessor = options[:preprocessor] || NoOpProcessor.new
end
def build_from_file(contract_path, host)
contract_definition = preprocessor.process(File.read(contract_path))
definition = JSON.parse(contract_definition)
schema.validate definition
request = Request.new(host, definition['request'])
response = Response.new(definition['response'])
Contract.new(request, response, contract_path)
end
def schema
@schema ||= MetaSchema.new
end
def load(contract_name, host = nil)
build_from_file(path_for(contract_name), host)
end
private
def path_for(contract)
File.join(Pacto.configuration.contracts_path, "#{contract}.json")
end
end
class NoOpProcessor
def process(contract_content)
contract_content
end
end
end
| module Pacto
class ContractFactory
attr_reader :preprocessor, :schema
def initialize(options = {})
@preprocessor = options[:preprocessor] || NoOpProcessor.new
@schema = options[:schema] || MetaSchema.new
end
def build_from_file(contract_path, host)
contract_definition = preprocessor.process(File.read(contract_path))
definition = JSON.parse(contract_definition)
schema.validate definition
request = Request.new(host, definition['request'])
response = Response.new(definition['response'])
Contract.new(request, response, contract_path)
end
def load(contract_name, host = nil)
build_from_file(path_for(contract_name), host)
end
private
def path_for(contract)
File.join(Pacto.configuration.contracts_path, "#{contract}.json")
end
end
class NoOpProcessor
def process(contract_content)
contract_content
end
end
end
|
Refactor SMS.deliver to use SMS.options | module Cellular
class SMS
attr_accessor :recipient, :sender, :message, :price, :country_code
def initialize(options = {})
@backend = Cellular.config.backend
@recipient = options[:recipient]
@sender = options[:sender] || Cellular.config.sender
@message = options[:message]
@price = options[:price] || Cellular.config.price
@country_code = options[:country_code] || Cellular.config.country_code
@delivered = false
end
def deliver
@delivery_status, @delivery_message = @backend.deliver(
recipient: @recipient,
sender: @sender,
price: @price,
country_code: @country_code,
message: @message
)
@delivered = true
end
def deliver_later
Cellular::Jobs::AsyncMessenger.perform_async options
end
def save(options = {})
raise NotImplementedError
end
def receive(options = {})
raise NotImplementedError
end
def delivered?
@delivered
end
def country
warn "[DEPRECATION] 'country' is deprecated; use 'country_code' instead"
@country_code
end
def country=(country)
warn "[DEPRECATION] 'country' is deprecated; use 'country_code' instead"
@country_code = country
end
private
def options
{
recipient: @recipient,
sender: @sender,
message: @message,
price: @price,
country_code: @country_code
}
end
end
end
| module Cellular
class SMS
attr_accessor :recipient, :sender, :message, :price, :country_code
def initialize(options = {})
@backend = Cellular.config.backend
@recipient = options[:recipient]
@sender = options[:sender] || Cellular.config.sender
@message = options[:message]
@price = options[:price] || Cellular.config.price
@country_code = options[:country_code] || Cellular.config.country_code
@delivered = false
end
def deliver
@delivery_status, @delivery_message = @backend.deliver options
@delivered = true
end
def deliver_later
Cellular::Jobs::AsyncMessenger.perform_async options
end
def save(options = {})
raise NotImplementedError
end
def receive(options = {})
raise NotImplementedError
end
def delivered?
@delivered
end
def country
warn "[DEPRECATION] 'country' is deprecated; use 'country_code' instead"
@country_code
end
def country=(country)
warn "[DEPRECATION] 'country' is deprecated; use 'country_code' instead"
@country_code = country
end
private
def options
{
recipient: @recipient,
sender: @sender,
message: @message,
price: @price,
country_code: @country_code
}
end
end
end
|
Maintain instance variables when raising an aborted exception in the caller context | module Celluloid
# Responses to calls
class Response
attr_reader :call, :value
def initialize(call, value)
@call, @value = call, value
end
end
# Call completed successfully
class SuccessResponse < Response; end
# Call was aborted due to caller error
class ErrorResponse < Response
def value
if super.is_a? AbortError
# Aborts are caused by caller error, so ensure they capture the
# caller's backtrace instead of the receiver's
raise super.cause.class.new(super.cause.message)
else
raise super
end
end
end
end
| module Celluloid
# Responses to calls
class Response
attr_reader :call, :value
def initialize(call, value)
@call, @value = call, value
end
end
# Call completed successfully
class SuccessResponse < Response; end
# Call was aborted due to caller error
class ErrorResponse < Response
def value
if super.is_a? AbortError
# Aborts are caused by caller error, so ensure they capture the
# caller's backtrace instead of the receiver's
raise super.cause.exception(super.cause.message)
else
raise super
end
end
end
end
|
Change usage of DataMapper::Resource::ClassMethods to use Model | # Needed to import datamapper and other gems
require 'rubygems'
require 'pathname'
# Add all external dependencies for the plugin here
gem 'dm-core', '~>0.9.10'
require 'dm-core'
# Require plugin-files
require Pathname(__FILE__).dirname.expand_path / 'dm-is-state_machine' / 'is' / 'state_machine'
require Pathname(__FILE__).dirname.expand_path / 'dm-is-state_machine' / 'is' / 'data' / 'event'
require Pathname(__FILE__).dirname.expand_path / 'dm-is-state_machine' / 'is' / 'data' / 'machine'
require Pathname(__FILE__).dirname.expand_path / 'dm-is-state_machine' / 'is' / 'data' / 'state'
require Pathname(__FILE__).dirname.expand_path / 'dm-is-state_machine' / 'is' / 'dsl' / 'event_dsl'
require Pathname(__FILE__).dirname.expand_path / 'dm-is-state_machine' / 'is' / 'dsl' / 'state_dsl'
# Include the plugin in Resource
module DataMapper
module Resource
module ClassMethods
include DataMapper::Is::StateMachine
end # module ClassMethods
end # module Resource
end # module DataMapper
# An alternative way to do the same thing as above:
# DataMapper::Model.append_extensions DataMapper::Is::StateMachine
| # Needed to import datamapper and other gems
require 'rubygems'
require 'pathname'
# Add all external dependencies for the plugin here
gem 'dm-core', '~>0.9.10'
require 'dm-core'
# Require plugin-files
require Pathname(__FILE__).dirname.expand_path / 'dm-is-state_machine' / 'is' / 'state_machine'
require Pathname(__FILE__).dirname.expand_path / 'dm-is-state_machine' / 'is' / 'data' / 'event'
require Pathname(__FILE__).dirname.expand_path / 'dm-is-state_machine' / 'is' / 'data' / 'machine'
require Pathname(__FILE__).dirname.expand_path / 'dm-is-state_machine' / 'is' / 'data' / 'state'
require Pathname(__FILE__).dirname.expand_path / 'dm-is-state_machine' / 'is' / 'dsl' / 'event_dsl'
require Pathname(__FILE__).dirname.expand_path / 'dm-is-state_machine' / 'is' / 'dsl' / 'state_dsl'
# Include the plugin in Resource
module DataMapper
module Model
include DataMapper::Is::StateMachine
end # module Model
end # module DataMapper
# An alternative way to do the same thing as above:
# DataMapper::Model.append_extensions DataMapper::Is::StateMachine
|
Define PersonTermDecorator for association of people with political_groups vocabulary | # frozen_string_literal: true
module GobiertoPeople
class PersonTermDecorator < BaseDecorator
def initialize(term)
@object = term
end
def people
return GobiertoPeople::Person.none unless association_with_people
GobiertoPeople::Person.where(association_with_people => object)
end
def events
collections_table = GobiertoCommon::Collection.table_name
site.events.distinct.includes(:collection).where(collections_table => { container: people })
end
def site
@site ||= object.vocabulary.site
end
protected
def association_with_people
@association_with_people ||= begin
return unless people_settings.present?
GobiertoPeople::Person.vocabularies.find do |_, setting|
people_settings.send(setting).to_i == object.vocabulary_id.to_i
end&.first
end
end
def people_settings
@people_settings ||= site.gobierto_people_settings
end
end
end
| |
Make sure we included the right URL helpers | class Api::MainstreamCategoryTagPresenter
include Rails.application.routes.url_helpers
include PublicDocumentRoutesHelper
def initialize(categories)
@categories = categories
end
def as_json
{
results: @categories.map { |c| tag_hash(c) }
}
end
private
def tag_hash(mainstream_category)
{
title: mainstream_category.title,
id: mainstream_category.path,
web_url: nil,
details: {
type: 'section',
},
content_with_tag: {
id: mainstream_category.path,
web_url: mainstream_category_path(mainstream_category)
}
}
end
def detailed_guide_url(guide)
h.api_detailed_guide_url guide.document, host: h.public_host
end
def related_json
model.published_related_detailed_guides.map do |guide|
{
id: detailed_guide_url(guide),
title: guide.title,
web_url: h.public_document_url(guide)
}
end
end
end
| class Api::MainstreamCategoryTagPresenter
include Rails.application.routes.url_helpers
include PublicDocumentRoutesHelper
include MainstreamCategoryRoutesHelper
def initialize(categories)
@categories = categories
end
def as_json
{
results: @categories.map { |c| tag_hash(c) }
}
end
private
def tag_hash(mainstream_category)
{
title: mainstream_category.title,
id: mainstream_category.path,
web_url: nil,
details: {
type: 'section',
},
content_with_tag: {
id: mainstream_category.path,
web_url: mainstream_category_path(mainstream_category)
}
}
end
end
|
Add some error catching logic to the version checking call | require_relative "rtasklib/version"
require_relative "rtasklib/models"
require_relative "rtasklib/execute"
require_relative "rtasklib/controller"
require_relative "rtasklib/serializer"
require_relative "rtasklib/taskrc"
require "open3"
module Rtasklib
class TaskWarrior
attr_reader :taskrc, :version
def initialize rc="#{Dir.home}/.taskrc"
# Check TW version, and throw warning
raw_version = Open3.capture2("task _version")
@version = Gem::Version.new(raw_version[0].chomp)
# @version = Gem::Version.new(`task _version`.chomp)
if @version < Gem::Version.new('2.4.0')
warn "#{@version} is untested"
end
# @taskrc =
end
end
end
| require_relative "rtasklib/version"
require_relative "rtasklib/models"
require_relative "rtasklib/execute"
require_relative "rtasklib/controller"
require_relative "rtasklib/serializer"
require_relative "rtasklib/taskrc"
require "open3"
module Rtasklib
class TaskWarrior
attr_reader :taskrc, :version, :rc_location, :data_location
def initialize rc="#{Dir.home}/.taskrc"
@rc_location = rc
# TODO: use taskrc
@data_location = rc.chomp('rc')
# Check TW version, and throw warning
begin
@version = check_version
rescue
warn "Couldn't find the task version"
end
# @taskrc =
end
private
def check_version
raw_version = Open3.capture2(
"task rc.data.location=#{@data_location} _version")
gem_version = Gem::Version.new(raw_version[0].chomp)
if gem_version < Gem::Version.new('2.4.0')
warn "#{@version} is untested"
end
gem_version
end
end
end
|
Add test on HDFS data dir | require File.expand_path('../support/helpers', __FILE__)
describe 'hadoop::hadoop_hdfs_datanode' do
include Helpers::Hadoop
# Example spec tests can be found at http://git.io/Fahwsw
it 'runs no tests by default' do
end
end
| require File.expand_path('../support/helpers', __FILE__)
describe 'hadoop::hadoop_hdfs_datanode' do
include Helpers::Hadoop
it 'ensures HDFS data dirs exist' do
node['hadoop']['hdfs_site']['dfs.data.dir'].each do |dir|
directory(dir)
.must_exist
.with(:owner, 'hdfs')
.and(:group, 'hdfs')
.and(:mode, node['hadoop']['hdfs_site']['dfs.datanode.data.dir.perm'])
end
end
|
Use getit name for PDS :sunflower: | require 'exlibris-aleph'
class UserSession < Authlogic::Session::Base
pds_url Settings.pds.login_url
redirect_logout_url Settings.pds.logout_url
aleph_url Exlibris::Aleph::Config.base_url
calling_system "umlaut"
institution_param_key "umlaut.institution"
# (Re-)Set verification and Aleph permissions to user attributes
def additional_attributes
# Don't do anything unless the record is expired or there are no aleph permissions.
return super unless (attempted_record.expired? or
attempted_record.user_attributes[:aleph_permissions].nil?)
# Reset the aleph permissions
permission_attributes = {}
permission_attributes[:aleph_permissions] = {}
# Get the bor_id and verification
# Use the outdated values if we don't have a PDS user (used for testing).
bor_id = pds_user ? pds_user.id : attempted_record.user_attributes[:nyuidn]
verification = pds_user ? pds_user.verification : attempted_record.user_attributes[:verification]
# Don't do anything unless we get a verification
if (bor_id and verification)
permission_attributes[:verification] = verification
permission_attributes[:aleph_permissions][self.class.aleph_default_sublibrary] =
aleph_bor_auth_permissions(bor_id, verification)
end
return permission_attributes
end
end
| require 'exlibris-aleph'
class UserSession < Authlogic::Session::Base
pds_url Settings.pds.login_url
redirect_logout_url Settings.pds.logout_url
aleph_url Exlibris::Aleph::Config.base_url
calling_system "getit"
institution_param_key "umlaut.institution"
# (Re-)Set verification and Aleph permissions to user attributes
def additional_attributes
# Don't do anything unless the record is expired or there are no aleph permissions.
return super unless (attempted_record.expired? or
attempted_record.user_attributes[:aleph_permissions].nil?)
# Reset the aleph permissions
permission_attributes = {}
permission_attributes[:aleph_permissions] = {}
# Get the bor_id and verification
# Use the outdated values if we don't have a PDS user (used for testing).
bor_id = pds_user ? pds_user.id : attempted_record.user_attributes[:nyuidn]
verification = pds_user ? pds_user.verification : attempted_record.user_attributes[:verification]
# Don't do anything unless we get a verification
if (bor_id and verification)
permission_attributes[:verification] = verification
permission_attributes[:aleph_permissions][self.class.aleph_default_sublibrary] =
aleph_bor_auth_permissions(bor_id, verification)
end
return permission_attributes
end
end
|
Add word 'when' to specs | require 'amarok-stats-common/config'
module AmarokStatsCommon
describe Config do
describe '.filename' do
it 'returns string' do
expect(described_class.filename).to be_a(String)
end
end
describe '.load' do
context "file doesn't exist" do
before :each do
allow(File).to receive(:exists?).with(described_class.filename).and_return(false)
end
it 'returns empty Hash' do
expect(described_class.load).to be_eql({})
end
end
# todo: need clear way to load valid/not-valid data from real files in `spec/`
context 'file exists' do
before :each do
allow(described_class).to receive(:filename).and_return(filename)
end
context 'and contains valid YAML data' do
let(:filename) { 'spec/fake_data/config.yml' }
it "reads the file returned by '.filename'" do
expect(described_class.load).to be_eql({})
end
end
end
end
end
end
| require 'amarok-stats-common/config'
module AmarokStatsCommon
describe Config do
describe '.filename' do
it 'returns string' do
expect(described_class.filename).to be_a(String)
end
end
describe '.load' do
context "when file doesn't exist" do
before :each do
allow(File).to receive(:exists?).with(described_class.filename).and_return(false)
end
it 'returns empty Hash' do
expect(described_class.load).to be_eql({})
end
end
# todo: need clear way to load valid/not-valid data from real files in `spec/`
context 'when file exists' do
before :each do
allow(described_class).to receive(:filename).and_return(filename)
end
context 'and contains valid YAML data' do
let(:filename) { 'spec/fake_data/config.yml' }
it "reads the file returned by '.filename'" do
expect(described_class.load).to be_eql({})
end
end
end
end
end
end
|
Remove rapgenius gem dependency, increment version to 0.1.2 | Gem::Specification.new do |spec|
spec.name = "lita-genius"
spec.version = "0.1.1"
spec.authors = ["Tristan Chong"]
spec.email = ["ong@tristaneuan.ch"]
spec.description = "A Lita handler that returns requested songs from (Rap) Genius."
spec.summary = "A Lita handler that returns requested songs from (Rap) Genius."
spec.homepage = "https://github.com/tristaneuan/lita-genius"
spec.license = "MIT"
spec.metadata = { "lita_plugin_type" => "handler" }
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_runtime_dependency "lita", ">= 4.3"
spec.add_runtime_dependency "rapgenius", "1.0.5"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "pry-byebug"
spec.add_development_dependency "rake"
spec.add_development_dependency "rack-test"
spec.add_development_dependency "rspec", ">= 3.0.0"
spec.add_development_dependency "simplecov"
spec.add_development_dependency "coveralls"
end
| Gem::Specification.new do |spec|
spec.name = "lita-genius"
spec.version = "0.1.2"
spec.authors = ["Tristan Chong"]
spec.email = ["ong@tristaneuan.ch"]
spec.description = "A Lita handler that returns requested songs from (Rap) Genius."
spec.summary = "A Lita handler that returns requested songs from (Rap) Genius."
spec.homepage = "https://github.com/tristaneuan/lita-genius"
spec.license = "MIT"
spec.metadata = { "lita_plugin_type" => "handler" }
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_runtime_dependency "lita", ">= 4.3"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "pry-byebug"
spec.add_development_dependency "rake"
spec.add_development_dependency "rack-test"
spec.add_development_dependency "rspec", ">= 3.0.0"
spec.add_development_dependency "simplecov"
spec.add_development_dependency "coveralls"
end
|
Add schema.rb support to the post gres adapter | require 'foreigner/connection_adapters/sql_2003'
module Foreigner
module ConnectionAdapters
module PostgreSQLAdapter
include Foreigner::ConnectionAdapters::Sql2003
def foreign_keys(table_name)
end
end
end
end
module ActiveRecord
module ConnectionAdapters
PostgreSQLAdapter.class_eval do
include Foreigner::ConnectionAdapters::PostgreSQLAdapter
end
end
end | require 'foreigner/connection_adapters/sql_2003'
module Foreigner
module ConnectionAdapters
module PostgreSQLAdapter
include Foreigner::ConnectionAdapters::Sql2003
def foreign_keys(table_name)
foreign_keys = []
fk_info = select_all %{
select tc.constraint_name as name
,ccu.table_name as to_table
,kcu.column_name as column
,rc.delete_rule as dependency
from information_schema.table_constraints tc
join information_schema.key_column_usage kcu
on tc.constraint_catalog = kcu.constraint_catalog
and tc.constraint_schema = kcu.constraint_schema
and tc.constraint_name = kcu.constraint_name
join information_schema.referential_constraints rc
on tc.constraint_catalog = rc.constraint_catalog
and tc.constraint_schema = rc.constraint_schema
and tc.constraint_name = rc.constraint_name
join information_schema.constraint_column_usage ccu
on tc.constraint_catalog = ccu.constraint_catalog
and tc.constraint_schema = ccu.constraint_schema
and tc.constraint_name = ccu.constraint_name
where tc.constraint_type = 'FOREIGN KEY'
and tc.constraint_catalog = '#{@config[:database]}'
and tc.table_name = '#{table_name}'
}
fk_info.inject([]) do |foreign_keys, row|
options = {:column => row['column'], :name => row['name']}
if row['dependency'] == 'CASCADE'
options[:dependent] = :delete
elsif row['dependency'] == 'SET NULL'
options[:dependent] = :nullify
end
foreign_keys << ForeignKeyDefinition.new(table_name, row['to_table'], options)
end
end
end
end
end
module ActiveRecord
module ConnectionAdapters
PostgreSQLAdapter.class_eval do
include Foreigner::ConnectionAdapters::PostgreSQLAdapter
end
end
end |
Store the operation arg in upcase | require 'optparse'
module SrtShifter
class Options
attr_accessor :options
def initialize(args)
@arguments = args
@operations = ["ADD", "SUB"]
@options = {}
end
def parse_options
@arguments.options do |opts|
opts.banner = "Usage: #{File.basename($PROGRAM_NAME)} [OPTIONS] input_file output_file"
opts.separator ""
opts.separator "Common Options:"
opts.on("-o","--operation (ADD|SUB)", String, "Type ADD to increase time or SUB to decrease time.") do |o|
@options[:operation] = o
end
opts.on("-t","--time (VALUE)", Float, "Time in milliseconds.") do |n|
@options[:time] = n
end
opts.on_tail('-h', '--help', 'Show this help message.') do
puts(opts)
# exit(0)
end
opts.parse!
end
end
def validate_args
begin
raise "Operation option is missing" if @options[:operation].nil?
raise "Unknown operation: #{@options[:operation]}" unless @operations.include? @options[:operation].upcase
raise "Time option is missing" if @options[:time].nil?
raise "Input file is missing" if @arguments[0].nil?
@options[:input] = @arguments[0]
raise "Output file is missing" if @arguments[1].nil?
@options[:output] = @arguments[1]
rescue Exception => ex
puts "#{ex.message}. Please use -h or --help for usage."
# exit(1)
end
end
end
end | require 'optparse'
module SrtShifter
class Options
attr_accessor :options
def initialize(args)
@arguments = args
@operations = ["ADD", "SUB"]
@options = {}
end
def parse_options
@arguments.options do |opts|
opts.banner = "Usage: #{File.basename($PROGRAM_NAME)} [OPTIONS] input_file output_file"
opts.separator ""
opts.separator "Common Options:"
opts.on("-o","--operation (ADD|SUB)", String, "Type ADD to increase time or SUB to decrease time.") do |o|
@options[:operation] = o.upcase
end
opts.on("-t","--time (VALUE)", Float, "Time in milliseconds.") do |n|
@options[:time] = n
end
opts.on_tail('-h', '--help', 'Show this help message.') do
puts(opts)
# exit(0)
end
opts.parse!
end
end
def validate_args
begin
raise "Operation option is missing" if @options[:operation].nil?
raise "Unknown operation: #{@options[:operation]}" unless @operations.include? @options[:operation]
raise "Time option is missing" if @options[:time].nil?
raise "Input file is missing" if @arguments[0].nil?
@options[:input] = @arguments[0]
raise "Output file is missing" if @arguments[1].nil?
@options[:output] = @arguments[1]
rescue Exception => ex
puts "#{ex.message}. Please use -h or --help for usage."
# exit(1)
end
end
end
end |
Purge expired StreamTokens on refresh | class StreamToken < ActiveRecord::Base
class Unauthorized < Exception; end
attr_accessible :token, :target, :expires
def self.find_or_create_session_token(session, target)
result = self.find_or_create_by_token_and_target(session[:session_id], target)
result.renew!
result.token
end
def self.validate_token(value)
raise Unauthorized, "Unauthorized" if value.nil?
(target, token_string) = value.scan(/^(.+)-(.+)$/).first
token = self.find_by_token_and_target(token_string, target)
if token.present? and token.expires > Time.now
token.renew!
return target
else
raise Unauthorized, "Unauthorized"
end
end
def renew!
self.update_attribute :expires, ( Time.now + Avalon::Configuration['streaming']['stream_token_ttl'].minutes )
end
end
| class StreamToken < ActiveRecord::Base
class Unauthorized < Exception; end
attr_accessible :token, :target, :expires
def self.find_or_create_session_token(session, target)
self.purge_expired!
result = self.find_or_create_by_token_and_target(session[:session_id], target)
result.renew!
result.token
end
def self.purge_expired!
self.where("expires <= :now", :now => Time.now).each &:delete
end
def self.validate_token(value)
raise Unauthorized, "Unauthorized" if value.nil?
(target, token_string) = value.scan(/^(.+)-(.+)$/).first
token = self.find_by_token_and_target(token_string, target)
if token.present? and token.expires > Time.now
token.renew!
return target
else
raise Unauthorized, "Unauthorized"
end
end
def renew!
self.update_attribute :expires, ( Time.now + Avalon::Configuration['streaming']['stream_token_ttl'].minutes )
end
end
|
Add a missing test-unit development dependency | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
Gem::Specification.new do |spec|
spec.name = 'fluent-plugin-conditional_filter'
spec.version = '0.0.2'
spec.authors = ['Kentaro Kuribayashi']
spec.email = ['kentarok@gmail.com']
spec.description = %q{A fluent plugin that provides conditional filters}
spec.summary = %q{A fluent plugin that provides conditional filters}
spec.homepage = 'http://github.com/kentaro/fluent-plugin-conditional_filter'
spec.license = 'MIT'
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
spec.add_runtime_dependency 'fluentd'
spec.add_development_dependency 'bundler'
spec.add_development_dependency 'rake'
spec.add_development_dependency 'rspec'
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
Gem::Specification.new do |spec|
spec.name = 'fluent-plugin-conditional_filter'
spec.version = '0.0.2'
spec.authors = ['Kentaro Kuribayashi']
spec.email = ['kentarok@gmail.com']
spec.description = %q{A fluent plugin that provides conditional filters}
spec.summary = %q{A fluent plugin that provides conditional filters}
spec.homepage = 'http://github.com/kentaro/fluent-plugin-conditional_filter'
spec.license = 'MIT'
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
spec.add_runtime_dependency 'fluentd'
spec.add_development_dependency 'bundler'
spec.add_development_dependency 'rake'
spec.add_development_dependency 'rspec'
spec.add_development_dependency 'test-unit'
end
|
Test script for importing a vbox vm. | # TODO: Initial script for importing a vbox vm. Need to refactor.
appliance_filename = 'Ubuntuserver1204-Test.ova'
puts "\nImporting VM...\n\n"
`VBoxManage import #{appliance_filename}`
puts "\nDone importing VM.\n\n"
puts "Modifying VM configuration:"
vms = `VBoxManage list vms`.split("\n")
vm_name = /\"(.*)\"/.match(vms.last)[1]
vm_info_stdout = IO.popen(%Q(VBoxManage showvminfo "#{vm_name}"))
vm_info_stdout.readlines.each do |l|
key, value = l.split(':', 2).map(&:strip)
if !value.nil?
# Remove existing port forwarding rules on Network Adapter 1
if /NIC 1 Rule\(\d\)/.match(key)
rule_name = /^name = (.+?),/.match(value)
`VBoxManage modifyvm "#{vm_name}" --natpf1 delete "#{rule_name[1]}"` if !rule_name.nil? && rule_name.size > 1
# Remove network adapters 3 & 4 to avoid conflict with NAT and Bridged Adapter
elsif other_adapters = /^NIC (3|4)$/.match(key) && value != 'disabled'
`VBoxManage modifyvm "#{vm_name}" --nic#{other_adapters[1]}`
end
end
end
vm_info_stdout.close
puts "Creating NAT on Network Adapter 1 and adding port forwarding..."
`VBoxManage modifyvm "#{vm_name}" --nic1 nat --cableconnected1 on --natpf1 "guestssh,tcp,,2222,,22"`
puts "Creating Bridged Adapter on Network Adapter 2..."
`VBoxManage modifyvm "#{vm_name}" --nic2 bridged --bridgeadapter1 eth0`
puts "\nDone modifying VM.\n\n" | |
Use assert instead of assert_true | require 'helper'
class TestMPEGFile < Test::Unit::TestCase
context "The crash.mp3 file" do
setup do
read_properties = true
@file = TagLib::MPEG::File.new("test/data/crash.mp3", read_properties)
end
context "audio properties" do
setup do
@properties = @file.audio_properties
end
should "be MPEG audio properties" do
assert_equal TagLib::MPEG::Properties, @properties.class
end
should "contain information" do
assert_equal 2, @properties.length
assert_equal 157, @properties.bitrate
assert_equal 44100, @properties.sample_rate
assert_equal 2, @properties.channels
assert_equal TagLib::MPEG::Header::Version1, @properties.version
assert_equal 3, @properties.layer
assert_equal false, @properties.protection_enabled
assert_equal TagLib::MPEG::Header::JointStereo, @properties.channel_mode
assert_equal false, @properties.copyrighted?
assert_equal true, @properties.original?
end
context "Xing header" do
setup do
@xing_header = @properties.xing_header
end
should "exist" do
assert_not_nil @xing_header
end
should "contain information" do
assert_true @xing_header.valid?
assert_equal 88, @xing_header.total_frames
assert_equal 45140, @xing_header.total_size
end
end
end
end
end
| require 'helper'
class TestMPEGFile < Test::Unit::TestCase
context "The crash.mp3 file" do
setup do
read_properties = true
@file = TagLib::MPEG::File.new("test/data/crash.mp3", read_properties)
end
context "audio properties" do
setup do
@properties = @file.audio_properties
end
should "be MPEG audio properties" do
assert_equal TagLib::MPEG::Properties, @properties.class
end
should "contain information" do
assert_equal 2, @properties.length
assert_equal 157, @properties.bitrate
assert_equal 44100, @properties.sample_rate
assert_equal 2, @properties.channels
assert_equal TagLib::MPEG::Header::Version1, @properties.version
assert_equal 3, @properties.layer
assert_equal false, @properties.protection_enabled
assert_equal TagLib::MPEG::Header::JointStereo, @properties.channel_mode
assert_equal false, @properties.copyrighted?
assert_equal true, @properties.original?
end
context "Xing header" do
setup do
@xing_header = @properties.xing_header
end
should "exist" do
assert_not_nil @xing_header
end
should "contain information" do
assert @xing_header.valid?
assert_equal 88, @xing_header.total_frames
assert_equal 45140, @xing_header.total_size
end
end
end
end
end
|
Fix taking version from attributes | include_recipe 'drone::_docker'
docker_image 'drone' do
repo 'drone/drone'
tag '0.4'
action :pull
end
docker_container 'drone' do
repo 'drone/drone'
tag node['drone']['version']
port '80:8000'
env drone_env
volumes ['/var/lib/drone:/var/lib/drone', '/var/run/docker.sock:/var/run/docker.sock']
restart_policy 'always'
sensitive true
end
| include_recipe 'drone::_docker'
docker_image 'drone' do
repo 'drone/drone'
tag node['drone']['version']
action :pull
end
docker_container 'drone' do
repo 'drone/drone'
tag node['drone']['version']
port '80:8000'
env drone_env
volumes ['/var/lib/drone:/var/lib/drone', '/var/run/docker.sock:/var/run/docker.sock']
restart_policy 'always'
sensitive true
end
|
Use `no_checksum` instead of a sha1 when getting `latest` version. | class Mou < Cask
url 'http://mouapp.com/download/Mou.zip'
version 'latest'
homepage 'http://mouapp.com/'
sha1 'e69bc2bbdadea6a2929032506085b6e9501a7fb9'
end
| class Mou < Cask
url 'http://mouapp.com/download/Mou.zip'
version 'latest'
homepage 'http://mouapp.com/'
no_checksum
end
|
Rollback - removed all strips | class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :user_events
validates_uniqueness_of :email, :pfs_number
validates :name, :pfs_number, :email, :presence => true
validates :title, :presence => true, if: :venture_officer?
def long_name
"#{self.name} (#{self.email})".strip!
end
def formal_name
"#{self.title} #{self.name}".strip!
end
def formal_name_with_stars
"#{self.title} #{self.name} #{self.show_stars}".strip!
end
STAR = "\u272F"
def show_stars
star = STAR
star = star.encode('utf-8')
stars = ""
(1..self.gm_stars.to_i).each do
stars = "#{stars}#{star}"
end
stars.strip!
end
def <=> (user)
sort = 0
if user.nil?
sort = -1
else
sort = self.name <=> user.name
end
sort
end
end
| class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :user_events
validates_uniqueness_of :email, :pfs_number
validates :name, :pfs_number, :email, :presence => true
validates :title, :presence => true, if: :venture_officer?
def long_name
"#{self.name} (#{self.email})"
end
def formal_name
"#{self.title} #{self.name}"
end
def formal_name_with_stars
"#{self.title} #{self.name} #{self.show_stars}"
en
STAR = "\u272F"
def show_stars
star = STAR
star = star.encode('utf-8')
stars = ""
(1..self.gm_stars.to_i).each do
stars = "#{stars}#{star}"
end
stars
end
def <=> (user)
sort = 0
if user.nil?
sort = -1
else
sort = self.name <=> user.name
end
sort
end
end
|
Remove with_errors option from Performer | module Eventful
class Performer
include Resource
def self.all(date = nil)
feed_for(:performers, :full, date)
end
def self.updates(date = nil)
feed_for(:performers, :updates, date)
end
def self.find(id, options = {})
options.merge!(id: id)
response = get('performers/get', options)
performer = instantiate(response.body['performer'])
respond_with performer, response, with_errors: true
end
end
end
| module Eventful
class Performer
include Resource
def self.all(date = nil)
feed_for(:performers, :full, date)
end
def self.updates(date = nil)
feed_for(:performers, :updates, date)
end
def self.find(id, options = {})
options.merge!(id: id)
response = get('performers/get', options)
performer = instantiate(response.body['performer'])
respond_with performer, response
end
end
end
|
Select only the constants that are actually Errors | module ZeroMQ
module Errors
ERRORS = Errno.constants.map(&Errno.method(:const_get)).
inject({}) { |map, error| map[error.const_get(:Errno)] = error; map }
private
def check_result!(rc)
return rc if ZMQ::Util.resultcode_ok?(rc)
raise ERRORS.fetch(ZMQ::Util.errno) { ZMQ::Util.error_string }
end
end
end
| module ZeroMQ
module Errors
ERRORS = Errno.constants.map(&Errno.method(:const_get)).
select { |obj| obj.is_a?(Class) && obj < SystemCallError }.
inject({}) { |map, error| map[error.const_get(:Errno)] = error; map }
private
def check_result!(rc)
return rc if ZMQ::Util.resultcode_ok?(rc)
raise ERRORS.fetch(ZMQ::Util.errno) { ZMQ::Util.error_string }
end
end
end
|
Add more defaults to migration | class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :company
t.string :ip_address
t.string :operating_system
t.string :browser
t.string :screen_resolution, default: "N/A"
t.string :window_size, default: "N/A"
t.string :download_speed, default: "N/A"
t.string :flash_version, default: "N/A"
t.string :audio_formats, default: "N/A"
t.string :video_formats, default: "N/A"
t.string :proxy, default: "N/A"
t.boolean :javascript, default: false
t.boolean :cookies
t.boolean :mobile
t.boolean :html5_support
t.boolean :css3_support
t.text :user_agent
t.text :plugins
t.timestamps
end
end
end
| class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :company, default: "N/A"
t.string :ip_address, default: "N/A"
t.string :operating_system, default: "N/A"
t.string :browser, default: "N/A"
t.string :screen_resolution, default: "N/A"
t.string :window_size, default: "N/A"
t.string :download_speed, default: "N/A"
t.string :flash_version, default: "N/A"
t.string :audio_formats, default: "N/A"
t.string :video_formats, default: "N/A"
t.string :proxy, default: "N/A"
t.boolean :javascript, default: false
t.boolean :cookies
t.boolean :mobile
t.boolean :html5_support
t.boolean :css3_support
t.text :user_agent
t.text :plugins
t.timestamps
end
end
end
|
Set missing HD modality HealthCareFacility to site code (eg RJZ) in UKRDC XML | # frozen_string_literal: true
xml = builder
xml.Treatment do
xml.EncounterNumber [treatment.modality_id, treatment.hd_profile_id].compact.join("-")
xml.EncounterType "N"
xml.FromTime treatment.started_on&.iso8601
xml.ToTime(treatment.ended_on&.iso8601) if treatment.ended_on.present?
if treatment.hospital_unit.present?
xml.HealthCareFacility do
xml.CodingStandard "ODS"
xml.Code treatment.hospital_unit.renal_registry_code
end
end
xml.AdmitReason do
xml.CodingStandard "CF_RR7_TREATMENT"
xml.Code treatment.modality_code.txt_code
end
render(
"renalware/api/ukrdc/patients/treatments/discharge_reason",
treatment: treatment,
builder: builder
)
# HD
rr8 = treatment.hospital_unit&.unit_type_rr8
if rr8.present?
xml.Attributes do
xml.QBL05 rr8 # eg HOME
end
end
end
| # frozen_string_literal: true
xml = builder
xml.Treatment do
xml.EncounterNumber [treatment.modality_id, treatment.hd_profile_id].compact.join("-")
xml.EncounterType "N"
xml.FromTime treatment.started_on&.iso8601
xml.ToTime(treatment.ended_on&.iso8601) if treatment.ended_on.present?
xml.HealthCareFacility do
xml.CodingStandard "ODS"
if treatment.hospital_unit.present?
xml.Code treatment.hospital_unit.renal_registry_code
else
xml.Code Renalware.config.ukrdc_site_code
end
end
xml.AdmitReason do
xml.CodingStandard "CF_RR7_TREATMENT"
xml.Code treatment.modality_code.txt_code
end
render(
"renalware/api/ukrdc/patients/treatments/discharge_reason",
treatment: treatment,
builder: builder
)
# HD
rr8 = treatment.hospital_unit&.unit_type_rr8
if rr8.present?
xml.Attributes do
xml.QBL05 rr8 # eg HOME
end
end
end
|
Print log messages to console, add message to ensure script is running | module VirginStats
class NetworkMonitor
@@ping_count = 1
@@server = "www.google.com"
@@sleep_duration = 10
def self.ping_succeeds?
`ping -q -c #{@@ping_count} #{@@server} 2> /dev/null`
$?.exitstatus == 0
end
def initialize
@log_file_name = VirginStats.network_monitor_log_file_name
end
def start
log("Starting monitoring")
@last_network_status_online = NetworkMonitor::ping_succeeds?
log("Initial status: %s" % (@last_network_status_online ? "online" : "OFFline"))
while(1)
sleep(@@sleep_duration)
current_net_status_online = NetworkMonitor::ping_succeeds?
if current_net_status_online != @last_network_status_online
log("Network status changed to: %s" % (current_net_status_online ? "online" : "OFFline"))
@last_network_status_online = current_net_status_online
end
end
end
def formatted_current_time
Time.now.strftime("%Y-%m-%d %H:%M:%S %z")
end
def log(msg)
File.open(@log_file_name, "a") do |f|
f.puts("[%s] %s" % [formatted_current_time, msg])
end
end
end
end
| module VirginStats
class NetworkMonitor
@@ping_count = 1
@@server = "www.google.com"
@@sleep_duration = 10
def self.ping_succeeds?
`ping -q -c #{@@ping_count} #{@@server} 2> /dev/null`
$?.exitstatus == 0
end
def initialize
@log_file_name = VirginStats.network_monitor_log_file_name
end
def start
log("Starting monitoring")
@last_network_status_online = NetworkMonitor::ping_succeeds?
@loop_count = 0
log("Initial status: %s" % (@last_network_status_online ? "online" : "OFFline"))
while(1)
@loop_count += 1
sleep(@@sleep_duration)
current_net_status_online = NetworkMonitor::ping_succeeds?
if current_net_status_online != @last_network_status_online
log("Network status changed to: %s" % (current_net_status_online ? "online" : "OFFline"))
@last_network_status_online = current_net_status_online
else
if @loop_count % 100 == 0
log("Monitoring in progress (%d pings performed)" % @loop_count)
end
end
end
end
def formatted_current_time
Time.now.strftime("%Y-%m-%d %H:%M:%S %z")
end
def log(msg)
File.open(@log_file_name, "a") do |f|
s = "[%s] %s" % [formatted_current_time, msg]
f.puts(s)
puts(s)
end
end
end
end
|
Test that command factory increments command IDs. | require "spec_helper"
include Strut
describe SlimCommandFactory do
it 'increments command IDs' do
sut = SlimCommandFactory.new
import_command = sut.make_import_command(nil, "my_namespace")
make_command = sut.make_make_command(nil, "instance", "class")
expect(import_command.id).to eq("1")
expect(make_command.id).to eq("2")
end
end
| |
Replace keys(processor:*) calls with iteration over set key | module Sidekiq::LimitFetch::Global
module Monitor
extend self
HEARTBEAT_NAMESPACE = 'heartbeat:'
PROCESSOR_NAMESPACE = 'processor:'
HEARTBEAT_TTL = 18
REFRESH_TIMEOUT = 10
def start!(ttl=HEARTBEAT_TTL, timeout=REFRESH_TIMEOUT)
Thread.new do
loop do
update_heartbeat ttl
invalidate_old_processors
sleep timeout
end
end
end
private
def update_heartbeat(ttl)
Sidekiq.redis do |it|
it.pipelined do
it.set processor_key, true
it.set heartbeat_key, true
it.expire heartbeat_key, ttl
end
end
end
def invalidate_old_processors
Sidekiq.redis do |it|
it.keys(PROCESSOR_NAMESPACE + '*').each do |processor|
processor.sub! PROCESSOR_NAMESPACE, ''
next if it.get heartbeat_key processor
it.del processor_key processor
%w(limit_fetch:probed:* limit_fetch:busy:*).each do |pattern|
it.keys(pattern).each do |queue|
it.lrem queue, 0, processor
end
end
end
end
end
def heartbeat_key(processor=Selector.uuid)
HEARTBEAT_NAMESPACE + processor
end
def processor_key(processor=Selector.uuid)
PROCESSOR_NAMESPACE + processor
end
end
end
| module Sidekiq::LimitFetch::Global
module Monitor
extend self
HEARTBEAT_PREFIX = 'heartbeat:'
PROCESS_SET = 'processes'
HEARTBEAT_TTL = 18
REFRESH_TIMEOUT = 10
def start!(ttl=HEARTBEAT_TTL, timeout=REFRESH_TIMEOUT)
Thread.new do
loop do
update_heartbeat ttl
invalidate_old_processors
sleep timeout
end
end
end
private
def update_heartbeat(ttl)
Sidekiq.redis do |it|
it.pipelined do
it.sadd PROCESS_SET, Selector.uuid
it.set heartbeat_key, true
it.expire heartbeat_key, ttl
end
end
end
def invalidate_old_processors
Sidekiq.redis do |it|
it.smembers(PROCESS_SET).each do |processor|
next if it.get heartbeat_key processor
%w(limit_fetch:probed:* limit_fetch:busy:*).each do |pattern|
it.keys(pattern).each do |queue|
it.lrem queue, 0, processor
end
end
it.srem processor
end
end
end
def heartbeat_key(processor=Selector.uuid)
HEARTBEAT_PREFIX + processor
end
end
end
|
Rewrite player move parsing to support entire movement chains | require_relative 'invalid_move_error'
class HumanPlayer
def initialize(board)
self.board = board
end
def take_turn
move = get_move
man = take_man(move.first)
if man.nil?
raise InvalidMoveError.new
end
(man.slide(move.last) || man.jump(move.last)) or raise InvalidMoveError.new
end
protected
attr_accessor :board
def take_man(position)
self.board[position]
end
def get_move
move = gets.chomp
parse_move(move)
end
def parse_move(move)
start, target = move.split(",")
start = start.split("")
target = target.split("")
start.map! {|e| Integer(e) }
target.map! {|e| Integer(e) }
[start, target]
end
end
| require_relative 'invalid_move_error'
class HumanPlayer
def initialize(board)
self.board = board
end
def take_turn
seq = get_move
man = take_man(seq.shift)
if man.nil?
raise InvalidMoveError.new
end
man.move(seq)
end
protected
attr_accessor :board
def take_man(position)
self.board[position]
end
def get_move
move = gets.chomp
parse_input(move)
end
def parse_input(move)
chain = move.split(",")
chain.map { |link| parse_move(link) }
end
def parse_move(move)
move.split("").map { |digit| Integer(digit) }
end
end
|
Exclude spec/ dir from coverage | # frozen_string_literal: true
require 'simplecov'
SimpleCov.start
require 'webmock/rspec'
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'sendgrid_actionmailer_adapter'
| # frozen_string_literal: true
require 'simplecov'
SimpleCov.start do
add_filter('spec')
end
require 'webmock/rspec'
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'sendgrid_actionmailer_adapter'
|
Add IČO for newly linked organizations | PREFIX adms: <http://www.w3.org/ns/adms#>
PREFIX rov: <http://www.w3.org/ns/regorg#>
PREFIX schema: <http://schema.org/>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
WITH <http://linked.opendata.cz/resource/dataset/isvz.cz>
INSERT {
?organization rov:registration ?registration .
?registration a adms:Identifier ;
skos:notation ?ico ;
skos:inScheme <http://linked.opendata.cz/resource/concept-scheme/CZ-ICO> .
}
WHERE {
?organization a schema:Organization .
FILTER STRSTARTS(STR(?organization), "http://linked.opendata.cz/resource/business-entity/CZ")
FILTER NOT EXISTS {
?organization rov:registration [] .
}
BIND (STRAFTER(STR(?organization), "http://linked.opendata.cz/resource/business-entity/CZ") AS ?ico)
BIND (IRI(CONCAT("http://linked.opendata.cz/resource/isvz.cz/identifier/", ?ico)) AS ?registration)
}
| |
Add an explicit virtualenv version to spec facts | require 'puppetlabs_spec_helper/module_spec_helper'
RSpec.configure do |c|
c.default_facts = {
:osfamily => 'RedHat',
:operatingsystem => 'CentOS',
:ipaddress => '172.16.32.42',
:operatingsystemmajrelease => '7',
:operatingsystemrelease => '7.0',
:fqdn => 'patchwork.example.com',
:hostname => 'patchwork',
}
c.hiera_config = File.expand_path(File.join(__FILE__, '../fixtures/hiera.yaml'))
end
at_exit { RSpec::Puppet::Coverage.report! }
| require 'puppetlabs_spec_helper/module_spec_helper'
RSpec.configure do |c|
c.default_facts = {
:osfamily => 'RedHat',
:operatingsystem => 'CentOS',
:ipaddress => '172.16.32.42',
:operatingsystemmajrelease => '7',
:operatingsystemrelease => '7.0',
:fqdn => 'patchwork.example.com',
:hostname => 'patchwork',
:virtualenv_version => '1.10.1'
}
c.hiera_config = File.expand_path(File.join(__FILE__, '../fixtures/hiera.yaml'))
end
at_exit { RSpec::Puppet::Coverage.report! }
|
Convert tests over to should syntax to keep old rspec happy | require 'spec_helper'
describe 'camelCaseFunction' do
it { is_expected.not_to be_nil }
it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /Requires 1 argument/) }
it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, /Argument must be a string/) }
it { is_expected.to run.with_params('test').and_return('test') }
end
| require 'spec_helper'
describe 'camelCaseFunction' do
it { should_not be_nil }
it { should run.with_params().and_raise_error(Puppet::ParseError, /Requires 1 argument/) }
it { should run.with_params(1).and_raise_error(Puppet::ParseError, /Argument must be a string/) }
it { should run.with_params('test').and_return('test') }
end
|
Update geocod.io to use most recent API version | require 'geocoder/lookups/base'
require "geocoder/results/geocodio"
module Geocoder::Lookup
class Geocodio < Base
def name
"Geocodio"
end
def query_url(query)
path = query.reverse_geocode? ? "reverse" : "geocode"
"#{protocol}://api.geocod.io/v1/#{path}?#{url_query_string(query)}"
end
def results(query)
return [] unless doc = fetch_data(query)
return doc["results"] if doc['error'].nil?
if doc['error'] == 'Invalid API key'
raise_error(Geocoder::InvalidApiKey) ||
Geocoder.log(:warn, "Geocodio service error: invalid API key.")
elsif doc['error'].match(/You have reached your daily maximum/)
raise_error(Geocoder::OverQueryLimitError, doc['error']) ||
Geocoder.log(:warn, "Geocodio service error: #{doc['error']}.")
else
raise_error(Geocoder::InvalidRequest, doc['error']) ||
Geocoder.log(:warn, "Geocodio service error: #{doc['error']}.")
end
[]
end
private # ---------------------------------------------------------------
def query_url_params(query)
{
:api_key => configuration.api_key,
:q => query.sanitized_text
}.merge(super)
end
end
end
| require 'geocoder/lookups/base'
require "geocoder/results/geocodio"
module Geocoder::Lookup
class Geocodio < Base
def name
"Geocodio"
end
def query_url(query)
path = query.reverse_geocode? ? "reverse" : "geocode"
"#{protocol}://api.geocod.io/v1.2/#{path}?#{url_query_string(query)}"
end
def results(query)
return [] unless doc = fetch_data(query)
return doc["results"] if doc['error'].nil?
if doc['error'] == 'Invalid API key'
raise_error(Geocoder::InvalidApiKey) ||
Geocoder.log(:warn, "Geocodio service error: invalid API key.")
elsif doc['error'].match(/You have reached your daily maximum/)
raise_error(Geocoder::OverQueryLimitError, doc['error']) ||
Geocoder.log(:warn, "Geocodio service error: #{doc['error']}.")
else
raise_error(Geocoder::InvalidRequest, doc['error']) ||
Geocoder.log(:warn, "Geocodio service error: #{doc['error']}.")
end
[]
end
private # ---------------------------------------------------------------
def query_url_params(query)
{
:api_key => configuration.api_key,
:q => query.sanitized_text
}.merge(super)
end
end
end
|
Add helper methods to JSONDump | require 'inch_ci/worker/build_json/task'
module InchCI
module Worker
module BuildJSON
def self.json(filename)
JSONDump.new(filename)
end
class JSONDump
attr_reader :language, :branch_name, :revision, :nwo, :url
def initialize(filename)
json = JSON[File.read(filename)]
@language = json['language']
@branch_name = json['branch_name'] || json['travis_branch']
@revision = json['revision'] || json['travis_commit']
@nwo = json['nwo'] || json['travis_repo_slug']
@url = json['git_repo_url']
end
end
end
end
end
| require 'inch_ci/worker/build_json/task'
module InchCI
module Worker
module BuildJSON
def self.json(filename)
JSONDump.new(filename)
end
class JSONDump
attr_reader :language, :branch_name, :revision, :nwo, :url
def initialize(filename)
json = JSON[File.read(filename)]
@language = json['language']
@branch_name = json['branch_name'] || json['travis_branch']
@revision = json['revision'] || json['travis_commit']
@nwo = json['nwo'] || json['travis_repo_slug']
@url = json['git_repo_url']
end
def travis?
!json['travis'].nil?
end
def to_h(include_objects: true)
h = json.dup
h.delete('objects') unless include_objects
h
end
end
end
end
end
|
Fix deploy file installation in non-development mode. | def install_deploy_files(file_paths)
remote_paths = file_paths.map { |path| "#{File.join(latest_release, path)}.deploy" }
remote_deploy_file_paths = capture("ls -1 #{remote_paths.join(" ")} 2> /dev/null; true").to_s.split
commands = []
remote_deploy_file_paths.each do |remote_deploy_file_path|
install_remote_path = remote_deploy_file_path.gsub(/\.deploy$/, "")
if(exists?(:rails_env) && rails_env != "development")
# In development mode, don't overwrite any existing files.
commands << "rsync -a --ignore-existing #{remote_deploy_file_path} #{install_remote_path}"
else
commands << "cp #{remote_deploy_file_path} #{install_remote_path}"
end
end
if commands.any?
run commands.join(" && ")
end
end
| def install_deploy_files(file_paths)
remote_paths = file_paths.map { |path| "#{File.join(latest_release, path)}.deploy" }
remote_deploy_file_paths = capture("ls -1 #{remote_paths.join(" ")} 2> /dev/null; true").to_s.split
commands = []
remote_deploy_file_paths.each do |remote_deploy_file_path|
install_remote_path = remote_deploy_file_path.gsub(/\.deploy$/, "")
if(exists?(:rails_env) && rails_env == "development")
# In development mode, don't overwrite any existing files.
commands << "rsync -a --ignore-existing #{remote_deploy_file_path} #{install_remote_path}"
else
commands << "cp #{remote_deploy_file_path} #{install_remote_path}"
end
end
if commands.any?
run commands.join(" && ")
end
end
|
Update spec for new data format. | # == Schema Information
# Schema version: 20100707152350
#
# Table name: alternative_names
#
# id :integer not null, primary key
# name :text
# locality_id :integer
# short_name :text
# qualifier_name :text
# qualifier_locality :text
# qualifier_district :text
# creation_datetime :datetime
# modification_datetime :datetime
# revision_number :string(255)
# modification :string(255)
# created_at :datetime
# updated_at :datetime
#
require 'spec_helper'
describe AlternativeName do
before(:each) do
@valid_attributes = {
:name => "value for name",
:locality_id => 1,
:short_name => "value for short_name",
:qualifier_name => "value for qualifier_name",
:qualifier_locality => "value for qualifier_locality",
:qualifier_district => "value for qualifier_district",
:creation_datetime => Time.now,
:modification_datetime => Time.now,
:revision_number => "value for revision_number",
:modification => "value for modification"
}
end
it "should create a new instance given valid attributes" do
AlternativeName.create!(@valid_attributes)
end
end
| # == Schema Information
# Schema version: 20100707152350
#
# Table name: alternative_names
#
# id :integer not null, primary key
# name :text
# locality_id :integer
# short_name :text
# qualifier_name :text
# qualifier_locality :text
# qualifier_district :text
# creation_datetime :datetime
# modification_datetime :datetime
# revision_number :string(255)
# modification :string(255)
# created_at :datetime
# updated_at :datetime
#
require 'spec_helper'
describe AlternativeName do
before(:each) do
@valid_attributes = {
:alternative_locality_id => 2,
:locality_id => 1,
:creation_datetime => Time.now,
:modification_datetime => Time.now,
:revision_number => "value for revision_number",
:modification => "value for modification"
}
end
it "should create a new instance given valid attributes" do
AlternativeName.create!(@valid_attributes)
end
end
|
Stop Already Login Users From Going Back To Login | class UserSessionsController < ApplicationController
def new
@user = User.new
end
def create
@user = current_user
if @user = login(params[:email], params[:password], params[:remember])
@item = find_next_item(@user)
redirect_back_or_to item_url(@item, notice: 'Login successful')
else
flash.now[:alert] = 'Login failed'
render action: 'new'
end
end
def destroy
logout
redirect_to root_url, notice: 'Logged out!'
end
end
| class UserSessionsController < ApplicationController
def new
if current_user.present?
redirect_back_or_to root_path
else
@user = User.new
end
end
def create
@user = current_user
if @user = login(params[:email], params[:password], params[:remember])
@item = find_next_item(@user)
redirect_back_or_to item_url(@item), notice: 'Login successful'
else
flash.now[:alert] = 'Login failed'
render action: 'new'
end
end
def destroy
logout
redirect_to root_url, notice: 'Logged out!'
end
end
|
Access sass config from context class | require 'sass'
require 'sass/rails/cache_store'
require 'sass/rails/helpers'
require 'sprockets/sass_functions'
require 'tilt'
module Sass
module Rails
class SassTemplate < Tilt::Template
def self.default_mime_type
'text/css'
end
def self.engine_initialized?
true
end
def initialize_engine
end
def prepare
end
def syntax
:sass
end
def evaluate(context, locals, &block)
cache_store = CacheStore.new(context.environment)
options = {
:filename => eval_file,
:line => line,
:syntax => syntax,
:cache_store => cache_store,
:importer => importer_class.new(context, context.pathname.to_s),
:load_paths => context.environment.paths.map { |path| importer_class.new(context, path.to_s) },
:sprockets => {
:context => context,
:environment => context.environment
}
}
sass_config = context.environment.context_class.sass_config.merge(options)
engine = ::Sass::Engine.new(data, sass_config)
css = engine.render
engine.dependencies.map do |dependency|
context.depend_on(dependency.options[:filename])
end
css
rescue ::Sass::SyntaxError => e
context.__LINE__ = e.sass_backtrace.first[:line]
raise e
end
private
def importer_class
SassImporter
end
end
class ScssTemplate < SassTemplate
def syntax
:scss
end
end
end
end
| require 'sass'
require 'sass/rails/cache_store'
require 'sass/rails/helpers'
require 'sprockets/sass_functions'
require 'tilt'
module Sass
module Rails
class SassTemplate < Tilt::Template
def self.default_mime_type
'text/css'
end
def self.engine_initialized?
true
end
def initialize_engine
end
def prepare
end
def syntax
:sass
end
def evaluate(context, locals, &block)
cache_store = CacheStore.new(context.environment)
options = {
:filename => eval_file,
:line => line,
:syntax => syntax,
:cache_store => cache_store,
:importer => importer_class.new(context, context.pathname.to_s),
:load_paths => context.environment.paths.map { |path| importer_class.new(context, path.to_s) },
:sprockets => {
:context => context,
:environment => context.environment
}
}
sass_config = context.class.sass_config.merge(options)
engine = ::Sass::Engine.new(data, sass_config)
css = engine.render
engine.dependencies.map do |dependency|
context.depend_on(dependency.options[:filename])
end
css
rescue ::Sass::SyntaxError => e
context.__LINE__ = e.sass_backtrace.first[:line]
raise e
end
private
def importer_class
SassImporter
end
end
class ScssTemplate < SassTemplate
def syntax
:scss
end
end
end
end
|
Stop Minification to fix JS issues | Rails.application.configure do
config.action_mailer.smtp_settings = {
user_name: ENV['SMTP_USERNAME'],
password: ENV['SMTP_PASSWORD'],
address: ENV['SMTP_HOSTNAME'],
port: ENV['SMTP_PORT'],
domain: ENV['SMTP_DOMAIN'],
authentication: :login,
enable_starttls_auto: true
}
config.cache_classes = true
config.eager_load = true
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
config.assets.js_compressor = :uglifier
config.assets.compile = false
config.assets.digest = true
config.log_level = :info
config.i18n.fallbacks = true
config.active_support.deprecation = :notify
config.log_formatter = ::Logger::Formatter.new
config.active_record.dump_schema_after_migration = false
config.lograge.formatter = Lograge::Formatters::Logstash.new
config.lograge.logger = ActiveSupport::Logger.new \
"#{Rails.root}/log/logstash_#{Rails.env}.json"
config.mx_checker = MxChecker.new
config.active_job.queue_adapter = :sidekiq
end
| Rails.application.configure do
config.action_mailer.smtp_settings = {
user_name: ENV['SMTP_USERNAME'],
password: ENV['SMTP_PASSWORD'],
address: ENV['SMTP_HOSTNAME'],
port: ENV['SMTP_PORT'],
domain: ENV['SMTP_DOMAIN'],
authentication: :login,
enable_starttls_auto: true
}
config.cache_classes = true
config.eager_load = true
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
# config.assets.js_compressor = :uglifier
config.assets.compile = false
config.assets.digest = true
config.log_level = :info
config.i18n.fallbacks = true
config.active_support.deprecation = :notify
config.log_formatter = ::Logger::Formatter.new
config.active_record.dump_schema_after_migration = false
config.lograge.formatter = Lograge::Formatters::Logstash.new
config.lograge.logger = ActiveSupport::Logger.new \
"#{Rails.root}/log/logstash_#{Rails.env}.json"
config.mx_checker = MxChecker.new
config.active_job.queue_adapter = :sidekiq
end
|
Update example use in form spec | require 'spec_helper'
include Support::ResourceExamples
describe Fulcrum::Form do
include_context 'with client'
include_context 'with resource'
let(:resource) { client.forms }
include_examples 'list resource'
include_examples 'find resource'
include_examples 'create resource'
include_examples 'update resource'
include_examples 'delete resource'
end
| require 'spec_helper'
include Support::ResourceExamples
describe Fulcrum::Form do
include_context 'with client'
include_context 'with resource'
let(:resource) { client.forms }
include_examples 'lists resource'
include_examples 'finds resource'
include_examples 'creates resource'
include_examples 'updates resource'
include_examples 'deletes resource'
end
|
Increase link check timeout to 10 seconds | module LocalLinksManager
module CheckLinks
class LinkChecker
TIMEOUT = 5
REDIRECT_LIMIT = 10
def check_link(link)
{
status: fetch_status(link),
checked_at: Time.zone.now,
}
end
private
def fetch_status(link)
begin
response = connection.get(URI.parse(link)) do |request|
request.options[:timeout] = TIMEOUT
request.options[:open_timeout] = TIMEOUT
end
response.status.to_s
rescue Faraday::ConnectionFailed
"Connection failed"
rescue Faraday::TimeoutError
"Timeout Error"
rescue Faraday::SSLError
"SSL Error"
rescue FaradayMiddleware::RedirectLimitReached
"Too many redirects"
rescue URI::InvalidURIError
"Invalid URI"
rescue => e
e.class.to_s
end
end
def connection
@connection ||= Faraday.new(headers: { accept_encoding: 'none' }) do |faraday|
faraday.use FaradayMiddleware::FollowRedirects, limit: REDIRECT_LIMIT
faraday.adapter Faraday.default_adapter
end
end
end
end
end
| module LocalLinksManager
module CheckLinks
class LinkChecker
TIMEOUT = 10
REDIRECT_LIMIT = 10
def check_link(link)
{
status: fetch_status(link),
checked_at: Time.zone.now,
}
end
private
def fetch_status(link)
begin
response = connection.get(URI.parse(link)) do |request|
request.options[:timeout] = TIMEOUT
request.options[:open_timeout] = TIMEOUT
end
response.status.to_s
rescue Faraday::ConnectionFailed
"Connection failed"
rescue Faraday::TimeoutError
"Timeout Error"
rescue Faraday::SSLError
"SSL Error"
rescue FaradayMiddleware::RedirectLimitReached
"Too many redirects"
rescue URI::InvalidURIError
"Invalid URI"
rescue => e
e.class.to_s
end
end
def connection
@connection ||= Faraday.new(headers: { accept_encoding: 'none' }) do |faraday|
faraday.use FaradayMiddleware::FollowRedirects, limit: REDIRECT_LIMIT
faraday.adapter Faraday.default_adapter
end
end
end
end
end
|
Deal with nasty yaml parsing on some rubies | module Pairwise
class InputFile
class << self
def load(filename)
inputs = self.new(filename).load_and_parse
InputData.new(inputs) if valid?(inputs)
end
def valid?(inputs)
inputs && (inputs.is_a?(Array) || inputs.is_a?(Hash))
end
end
def initialize(filename)
@filename = filename
self.extend(input_file_module)
end
private
def input_file_module
type = @filename[/\.(.+)$/, 1]
raise "Cannot determine file type for: #{@filename}" unless type
case type.downcase
when 'yaml', 'yml' then Yaml
else
Pairwise.const_get(type.capitalize) rescue raise "Unsupported file type: #{type}"
end
end
end
module Yaml
def load_and_parse
require 'yaml'
inputs = YAML.load_file(@filename)
end
end
module Csv
def load_and_parse
require 'csv'
csv_data = CSV.read @filename
headers = csv_data.shift.map {|head| head.to_s.strip }
string_data = csv_data.map {|row| row.map {|cell| cell.to_s.strip } }
inputs = Hash.new {|h,k| h[k] = []}
string_data.each do |row|
row.each_with_index { |value, index| inputs[headers[index]] << value }
end
inputs
end
end
end | module Pairwise
class InputFile
class << self
def load(filename)
inputs = self.new(filename).load_and_parse
InputData.new(inputs) if valid?(inputs)
end
def valid?(inputs)
inputs && (inputs.is_a?(Array) || inputs.is_a?(Hash))
end
end
def initialize(filename)
@filename = filename
self.extend(input_file_module)
end
private
def input_file_module
type = @filename[/\.(.+)$/, 1]
raise "Cannot determine file type for: #{@filename}" unless type
case type.downcase
when 'yaml', 'yml' then Yaml
else
Pairwise.const_get(type.capitalize) rescue raise "Unsupported file type: #{type}"
end
end
end
module Yaml
def load_and_parse
require 'yaml'
begin
inputs = YAML.load_file(@filename)
rescue
nil
end
end
end
module Csv
def load_and_parse
require 'csv'
csv_data = CSV.read @filename
headers = csv_data.shift.map {|head| head.to_s.strip }
string_data = csv_data.map {|row| row.map {|cell| cell.to_s.strip } }
inputs = Hash.new {|h,k| h[k] = []}
string_data.each do |row|
row.each_with_index { |value, index| inputs[headers[index]] << value }
end
inputs
end
end
end |
Use double instead of stub_model. | require 'spec_helper'
describe BookingTemplate do
context 'Factory methods' do
describe '.build_booking' do
it 'should raise an exception if no matching template can be found' do
expect {BookingTemplate.build_booking('not found')}.to raise_exception
end
it 'should call build_booking on the matching template' do
template = stub_model(BookingTemplate)
allow(BookingTemplate).to receive(:find_by_code).with('code').and_return(template)
expect(template).to receive(:build_booking).with({:test => 55})
BookingTemplate.build_booking 'code', {:test => 55}
end
end
end
end
| require 'spec_helper'
describe BookingTemplate do
context 'Factory methods' do
describe '.build_booking' do
it 'should raise an exception if no matching template can be found' do
expect {BookingTemplate.build_booking('not found')}.to raise_exception
end
it 'should call build_booking on the matching template' do
template = double(BookingTemplate)
allow(BookingTemplate).to receive(:find_by_code).with('code').and_return(template)
expect(template).to receive(:build_booking).with({:test => 55})
BookingTemplate.build_booking 'code', {:test => 55}
end
end
end
end
|
Simplify testing by returning full error messages from test app | require File.expand_path('../boot', __FILE__)
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
module RailsApp
class Application < Rails::Application
config.eager_load = true
config.root = File.expand_path('../../.', __FILE__)
end
end
| require File.expand_path('../boot', __FILE__)
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
module RailsApp
class Application < Rails::Application
config.eager_load = true
config.root = File.expand_path('../../.', __FILE__)
config.consider_all_requests_local = true
end
end
|
Bring the Client api in line with the Server | class Burrow::Client
attr_reader :message, :connection
def initialize(queue, method, params={})
@connection = Burrow::Connection.new(queue)
@message = Burrow::Message.new(method, params)
end
def self.call(queue, method, params)
new(queue, method, params).call
end
def call
publish
subscribe
end
def publish
connection.exchange.publish(
JSON.generate(message.attributes), {
correlation_id: message.id,
reply_to: connection.return_queue.name,
routing_key: connection.queue.name
}
)
end
def subscribe
response = nil
connection.return_queue.subscribe(block: true) do |delivery_info, properties, payload|
if properties[:correlation_id] == message.id
response = payload
delivery_info.consumer.cancel
end
end
JSON.parse(response)
end
end
| class Burrow::Client
attr_reader :connection
def initialize(queue)
@connection = Burrow::Connection.new(queue)
end
def publish(method, params={})
message = Burrow::Message.new(method, params)
connection.exchange.publish(
JSON.generate(message.attributes), {
correlation_id: message.id,
reply_to: connection.return_queue.name,
routing_key: connection.queue.name
}
)
response = nil
connection.return_queue.subscribe(block: true) do |delivery_info, properties, payload|
if properties[:correlation_id] == message.id
response = payload
delivery_info.consumer.cancel
end
end
JSON.parse(response)
end
end
|
Fix rubocop complaint about Fixnum vs Integer. | require "spec_helper"
describe(GitHubPages) do
it "exposes its version" do
expect(described_class::VERSION).to be_a(Fixnum)
end
end
| require "spec_helper"
describe(GitHubPages) do
it "exposes its version" do
expect(described_class::VERSION).to be_a(Integer)
end
end
|
Add UniFi Controller Beta (version 4.6.4) | cask :v1 => 'unifi-controller-beta' do
version '4.6.4-ade9eed'
sha256 'e2cc1bbef8419320a5a8a52a3fb3cff341746cb78e65ebe92aa03ea03a0fc120'
url "http://dl.ubnt.com/unifi/#{version}/UniFi.pkg"
name 'Unifi Controller Beta'
homepage 'https://community.ubnt.com/t5/UniFi-Wireless-Beta/bd-p/UniFi_Beta'
license :commercial
pkg 'Unifi.pkg'
uninstall :pkgutil => 'com.ubnt.UniFi'
end
| |
Change gem homepage and version number | Gem::Specification.new do |s|
s.name = 'css_views'
s.version = '0.5.2.pre'
s.email = "michael@koziarski.com"
s.author = "Michael Koziarski"
s.description = %q{Allow you to create css.erb views, and use helpers and the like in them}
s.summary = %q{Simple Controller support}
s.homepage = %q{http://www.radionz.co.nz/}
s.add_dependency('actionpack', '>= 3.0.0')
s.files = Dir['lib/**/*']
s.require_path = 'lib'
end | Gem::Specification.new do |s|
s.name = 'css_views'
s.version = '0.5.3'
s.email = "michael@koziarski.com"
s.author = "Michael Koziarski"
s.description = %q{Allow you to create css.erb views, and use helpers and the like in them}
s.summary = %q{Simple Controller support}
s.homepage = %q{http://https://github.com/rhulse/rails-css-views}
s.add_dependency('actionpack', '>= 3.0.0')
s.files = Dir['lib/**/*']
s.require_path = 'lib'
end |
Use Pry as the REPL in the tests | require 'coveralls'
Coveralls.wear!
ENV["RAILS_ENV"] ||= "test"
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require 'authlogic'
require 'authlogic/test_case'
class User
def nyuidn
user_attributes[:nyuidn]
end
def error; end
def uid
username
end
end
class ActiveSupport::TestCase
fixtures :all
def set_dummy_pds_user(user_session)
user_session.instance_variable_set("@pds_user".to_sym, users(:real_user))
end
end
# VCR is used to 'record' HTTP interactions with
# third party services used in tests, and play em
# back. Useful for efficiency, also useful for
# testing code against API's that not everyone
# has access to -- the responses can be cached
# and re-used.
require 'vcr'
require 'webmock'
# To allow us to do real HTTP requests in a VCR.turned_off, we
# have to tell webmock to let us.
WebMock.allow_net_connect!
VCR.configure do |c|
c.cassette_library_dir = 'test/vcr_cassettes'
# webmock needed for HTTPClient testing
c.hook_into :webmock
#c.filter_sensitive_data("localhost") { "" }
end
| require 'coveralls'
Coveralls.wear!
ENV["RAILS_ENV"] ||= "test"
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require 'authlogic'
require 'authlogic/test_case'
require 'pry'
class User
def nyuidn
user_attributes[:nyuidn]
end
def error; end
def uid
username
end
end
class ActiveSupport::TestCase
fixtures :all
def set_dummy_pds_user(user_session)
user_session.instance_variable_set("@pds_user".to_sym, users(:real_user))
end
end
# VCR is used to 'record' HTTP interactions with
# third party services used in tests, and play em
# back. Useful for efficiency, also useful for
# testing code against API's that not everyone
# has access to -- the responses can be cached
# and re-used.
require 'vcr'
require 'webmock'
# To allow us to do real HTTP requests in a VCR.turned_off, we
# have to tell webmock to let us.
WebMock.allow_net_connect!
VCR.configure do |c|
c.cassette_library_dir = 'test/vcr_cassettes'
# webmock needed for HTTPClient testing
c.hook_into :webmock
#c.filter_sensitive_data("localhost") { "" }
end
|
Update the gemspec to include a basic description/etc | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/blimpy/cucumber/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["R. Tyler Croy"]
gem.email = ["tyler@monkeypox.org"]
gem.description = %q{TODO: Write a gem description}
gem.summary = %q{TODO: Write a gem summary}
gem.homepage = ""
gem.files = `git ls-files`.split($\)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.name = "blimpy-cucumber"
gem.require_paths = ["lib"]
gem.version = Blimpy::Cucumber::VERSION
end
| # -*- encoding: utf-8 -*-
require File.expand_path('../lib/blimpy/cucumber/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["R. Tyler Croy"]
gem.email = ["tyler@monkeypox.org"]
gem.description = "Cucumber steps for testing with Blimpy"
gem.summary = "This gem helps spin up and down VMs with Blimpy from within Cucumber tests"
gem.homepage = ""
gem.files = `git ls-files`.split($\)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.name = "blimpy-cucumber"
gem.require_paths = ["lib"]
gem.version = Blimpy::Cucumber::VERSION
end
|
Allow Rails 5.2 in gemspec | $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "canonical-rails/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "canonical-rails"
s.version = CanonicalRails::VERSION
s.authors = ["Denis Ivanov"]
s.email = ["visible@jumph4x.net"]
s.homepage = "https://github.com/jumph4x/canonical-rails"
s.summary = "Simple and configurable Rails canonical ref tag helper"
s.description = "Configurable, but assumes a conservative strategy by default with a goal to solve many search engine index problems: multiple hostnames, inbound links with arbitrary parameters, trailing slashes. "
s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md"]
s.add_dependency 'rails', '>= 4.1', '< 5.2'
s.add_development_dependency 'appraisal'
s.add_development_dependency "sqlite3"
s.add_development_dependency 'rspec-rails', '~> 3.5'
s.add_development_dependency 'pry'
end
| $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "canonical-rails/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "canonical-rails"
s.version = CanonicalRails::VERSION
s.authors = ["Denis Ivanov"]
s.email = ["visible@jumph4x.net"]
s.homepage = "https://github.com/jumph4x/canonical-rails"
s.summary = "Simple and configurable Rails canonical ref tag helper"
s.description = "Configurable, but assumes a conservative strategy by default with a goal to solve many search engine index problems: multiple hostnames, inbound links with arbitrary parameters, trailing slashes. "
s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md"]
s.add_dependency 'rails', '>= 4.1', '< 5.3'
s.add_development_dependency 'appraisal'
s.add_development_dependency "sqlite3"
s.add_development_dependency 'rspec-rails', '~> 3.5'
s.add_development_dependency 'pry'
end
|
Update code to use tap | # frozen_string_literal: true
module TryTo
@handlers = {}
@exceptions = [NoMethodError]
class << self
attr_accessor :default_handler
attr_reader :exceptions, :handlers
def add_handler(exception, handler)
@handlers[exception] = handler
@handlers
end
def remove_handler!(exception)
@handlers.delete(exception)
@handlers
end
def add_exception(exception)
@exceptions << exception
end
def remove_exception!(exception)
@exceptions -= [exception]
end
def reset_exceptions!
@exceptions = [NoMethodError]
end
end
end
module Kernel
private def try_to(handler = nil)
yield if block_given?
rescue *(TryTo.exceptions | TryTo.handlers.keys) => e
handler = handler || TryTo.handlers[e.class] || TryTo.default_handler
handler.respond_to?(:call) ? handler.call(e) : handler
end
end
| # frozen_string_literal: true
module TryTo
@handlers = {}
@exceptions = [NoMethodError]
class << self
attr_accessor :default_handler
attr_reader :exceptions, :handlers
def add_handler(exception, handler)
@handlers.tap { |h| h[exception] = handler }
end
def remove_handler!(exception)
@handlers.tap { |h| h.delete(exception) }
end
def add_exception(exception)
@exceptions << exception
end
def remove_exception!(exception)
@exceptions -= [exception]
end
def reset_exceptions!
@exceptions = [NoMethodError]
end
end
end
module Kernel
private def try_to(handler = nil)
yield if block_given?
rescue *(TryTo.exceptions | TryTo.handlers.keys) => e
handler = handler || TryTo.handlers[e.class] || TryTo.default_handler
handler.respond_to?(:call) ? handler.call(e) : handler
end
end
|
Use address for forward check | shared_examples "provider/network/forwarded_port" do |provider, options|
if !options[:box]
raise ArgumentError,
"box option must be specified for provider: #{provider}"
end
include_context "acceptance"
let(:port){ 8080 }
before do
environment.skeleton("network_forwarded_port")
assert_execute("vagrant", "box", "add", "box", options[:box])
assert_execute("vagrant", "up", "--provider=#{provider}")
end
after do
assert_execute("vagrant", "destroy", "--force")
end
it "properly configures forwarded ports" do
status("Test: TCP forwarded port (default)")
assert_network("http://localhost:#{port}/", port)
end
end
| shared_examples "provider/network/forwarded_port" do |provider, options|
if !options[:box]
raise ArgumentError,
"box option must be specified for provider: #{provider}"
end
include_context "acceptance"
let(:port){ 8080 }
before do
environment.skeleton("network_forwarded_port")
assert_execute("vagrant", "box", "add", "box", options[:box])
assert_execute("vagrant", "up", "--provider=#{provider}")
end
after do
assert_execute("vagrant", "destroy", "--force")
end
it "properly configures forwarded ports" do
status("Test: TCP forwarded port (default)")
assert_network("http://127.0.0.1:#{port}/", port)
end
end
|
Add action to ratings controller so that user can change their rating for a soundtrek, logic to control access in controller and view | class RatingsController < ApplicationController
include RatingsHelper
def create
@sound_trek = SoundTrek.find_by(id: params[:sound_trek_id])
if !already_rated?(@sound_trek)
@rating = @sound_trek.ratings.new(rating_params)
@rating.update_attributes(sound_trek_id: params[:sound_trek_id], trekker_id: session[:user_id])
if @rating.save
flash[:rating_notice] = "Your rating has been recorded."
redirect_to sound_trek_path(@sound_trek)
else
render file: 'public/404.html'
end
else
flash[:already_rated] = "You have already rated this SoundTrek."
redirect_to sound_trek_path(@sound_trek)
end
end
def update
end
private
def rating_params
params.require(:rating).permit(:stars)
end
end
| class RatingsController < ApplicationController
include RatingsHelper
def create
@sound_trek = SoundTrek.find_by(id: params[:sound_trek_id])
if !already_rated?(@sound_trek)
@rating = @sound_trek.ratings.new(rating_params)
@rating.update_attributes(sound_trek_id: params[:sound_trek_id], trekker_id: session[:user_id])
if @rating.save
flash[:rating_notice] = "Your rating has been recorded."
redirect_to sound_trek_path(@sound_trek)
else
render file: 'public/404.html'
end
else
flash[:already_rated] = "You have already rated this SoundTrek."
redirect_to sound_trek_path(@sound_trek)
end
end
def update
@sound_trek = SoundTrek.find(params[:sound_trek_id])
if already_rated?(@sound_trek)
@rating = Rating.find_by(trekker_id: session[:user_id])
@rating.update_attributes(stars: rating_params[:stars])
redirect_to sound_trek_path(@sound_trek)
end
end
private
def rating_params
params.require(:rating).permit(:stars)
end
end
|
Use `replace` rather than `grant` in migration to clear any cruft. | require "delegate"
module Ddr::Auth
class LegacyAuthorization < SimpleDelegator
def to_roles
sources.map(&:to_roles).reduce(&:merge)
end
def clear
sources.each(&:clear)
end
def clear?
sources.all? { |auth| auth.source.empty? }
end
def migrate
migrated = inspect
roles.grant *to_roles
clear
["LEGACY AUTHORIZATION DATA", migrated, "ROLES", roles.serialize.inspect].join("\n\n")
end
def inspect
sources.map { |auth| auth.inspect }.join("\n")
end
private
def sources
wrappers.map { |wrapper| wrapper.new(self) }
end
def wrappers
classes = [ LegacyPermissions, LegacyRoles ]
if respond_to? :default_permissions
classes << LegacyDefaultPermissions
end
classes
end
end
end
| require "delegate"
module Ddr::Auth
class LegacyAuthorization < SimpleDelegator
def to_roles
sources.map(&:to_roles).reduce(&:merge)
end
def clear
sources.each(&:clear)
end
def clear?
sources.all? { |auth| auth.source.empty? }
end
def migrate
migrated = inspect
roles.replace *to_roles
clear
["LEGACY AUTHORIZATION DATA", migrated, "ROLES", roles.serialize.inspect].join("\n\n")
end
def inspect
sources.map { |auth| auth.inspect }.join("\n")
end
private
def sources
wrappers.map { |wrapper| wrapper.new(self) }
end
def wrappers
classes = [ LegacyPermissions, LegacyRoles ]
if respond_to? :default_permissions
classes << LegacyDefaultPermissions
end
classes
end
end
end
|
Add some language to root page on demo site | #!/usr/bin/env/ruby
require 'rubygems'
require 'sinatra/base'
require 'models'
require 'autoforme'
require 'sinatra/flash'
Forme.register_config(:mine, :base=>:default, :serializer=>:html_usa, :labeler=>:explicit, :wrapper=>:div)
Forme.default_config = :mine
class AutoFormeDemo < Sinatra::Base
disable :run
enable :sessions
register Sinatra::Flash
get '/' do
@page_title = 'AutoForme Demo Site'
"Default Page"
end
AutoForme.for(:sinatra, self) do
model_type :sequel
autoforme(Artist)
autoforme(Album)
autoforme(Track) do
columns [:number, :name, :length]
per_page 2
end
autoforme(Tag) do
supported_actions %w'edit update'
end
end
end
class FileServer
def initialize(app, root)
@app = app
@rfile = Rack::File.new(root)
end
def call(env)
res = @rfile.call(env)
res[0] == 200 ? res : @app.call(env)
end
end
| #!/usr/bin/env/ruby
require 'rubygems'
require 'sinatra/base'
require 'models'
require 'autoforme'
require 'sinatra/flash'
Forme.register_config(:mine, :base=>:default, :serializer=>:html_usa, :labeler=>:explicit, :wrapper=>:div)
Forme.default_config = :mine
class AutoFormeDemo < Sinatra::Base
disable :run
enable :sessions
register Sinatra::Flash
get '/' do
@page_title = 'AutoForme Demo Site'
erb <<END
<p>This is the demo site for autoforme, an admin interface for ruby web applications which uses forme to create the related forms.</p>
<p>This demo uses Sinatra as the web framework and Sequel as the database library.</p>
END
end
AutoForme.for(:sinatra, self) do
model_type :sequel
autoforme(Artist)
autoforme(Album)
autoforme(Track) do
columns [:number, :name, :length]
per_page 2
end
autoforme(Tag) do
supported_actions %w'edit update'
end
end
end
class FileServer
def initialize(app, root)
@app = app
@rfile = Rack::File.new(root)
end
def call(env)
res = @rfile.call(env)
res[0] == 200 ? res : @app.call(env)
end
end
|
Fix Tidy platform path and add force-output | module Tidy
class << self
PATH = Rails.root.join('node_modules','htmltidy2','bin','darwin','tidy')
CONFIG = {quiet: true,
show_warnings: false,
enclose_text: true,
drop_empty_elements: true,
hide_comments: true,
tidy_mark: false}
def exec html
IO.popen("#{PATH} #{flags}", 'r+') do |io|
io.write(html)
io.close_write
io.read
end
end
private
def flags
CONFIG.map { |k, v| "--#{k.to_s.gsub('_', '-')} #{v ? 'yes' : 'no'}"}.join(' ')
end
end
end
| module Tidy
class << self
PATH = Rails.root.join('node_modules','htmltidy2','bin',Gem::Platform.local.os,'tidy')
CONFIG = {force_output: true,
quiet: true,
show_errors: 0,
show_warnings: false,
show_info: false,
enclose_text: true,
drop_empty_elements: true,
hide_comments: true,
tidy_mark: false}
def exec html
IO.popen("#{PATH} #{flags}", 'r+') do |io|
io.write(html)
io.close_write
io.read
end
end
private
def flags
CONFIG.map { |k, v|
"--#{k.to_s.gsub('_', '-')} #{v === true ? 'yes' : v === false ? 'no' : v}"
}.join(' ')
end
end
end
|
Add standalone_mogrations gem as dependency | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'p4/chips/version'
Gem::Specification.new do |spec|
spec.name = "p4-chips"
spec.version = P4::Chips::VERSION
spec.authors = ["Zhan Tuaev"]
spec.email = ["zhoran@inbox.ru"]
spec.summary = %q{Provide virtual game chips, handle game and players chips balances, gains and losses}
spec.description = %q{See Readme at https://github.com/Zloy/p4-chips}
spec.homepage = "https://github.com/Zloy/p4-chips"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.6"
spec.add_development_dependency "rspec", "~> 3.1.0"
spec.add_development_dependency "rake"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'p4/chips/version'
Gem::Specification.new do |spec|
spec.name = "p4-chips"
spec.version = P4::Chips::VERSION
spec.authors = ["Zhan Tuaev"]
spec.email = ["zhoran@inbox.ru"]
spec.summary = %q{Provide virtual game chips, handle game and players chips balances, gains and losses}
spec.description = %q{See Readme at https://github.com/Zloy/p4-chips}
spec.homepage = "https://github.com/Zloy/p4-chips"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency "standalone_migrations"
spec.add_development_dependency "bundler", "~> 1.6"
spec.add_development_dependency "rspec", "~> 3.1.0"
spec.add_development_dependency "rake"
end
|
Fix depend lock for mariadb | name 'osl-mysql'
issues_url 'https://github.com/osuosl-cookbooks/osl-mysql/issues'
source_url 'https://github.com/osuosl-cookbooks/osl-mysql'
maintainer 'Oregon State University'
maintainer_email 'systems@osuosl.org'
license 'Apache-2.0'
chef_version '>= 14.0'
description 'Installs/Configures osl-mysql'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '2.3.2'
depends 'firewall'
depends 'git'
# TODO: Remove after chef15 upgrade
depends 'mariadb', '~> 3.2.0'
depends 'mysql', '~> 8.5.1'
depends 'mysql2_chef_gem'
depends 'osl-nrpe'
depends 'osl-munin'
depends 'osl-postfix'
depends 'percona', '~> 0.16.1'
depends 'yum-epel'
supports 'centos', '~> 6.0'
supports 'centos', '~> 7.0'
| name 'osl-mysql'
issues_url 'https://github.com/osuosl-cookbooks/osl-mysql/issues'
source_url 'https://github.com/osuosl-cookbooks/osl-mysql'
maintainer 'Oregon State University'
maintainer_email 'systems@osuosl.org'
license 'Apache-2.0'
chef_version '>= 14.0'
description 'Installs/Configures osl-mysql'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '2.3.2'
depends 'firewall'
depends 'git'
# TODO: Remove after chef15 upgrade
depends 'mariadb', '< 4.0.0'
depends 'mysql', '~> 8.5.1'
depends 'mysql2_chef_gem'
depends 'osl-nrpe'
depends 'osl-munin'
depends 'osl-postfix'
depends 'percona', '~> 0.16.1'
depends 'yum-epel'
supports 'centos', '~> 6.0'
supports 'centos', '~> 7.0'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.