Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Include the compiled native gem. | require "consistent_hash/version"
module ConsistentHash
# Your code goes here...
end
| require "consistent_hash/version"
require 'consistent_hash.so'
module ConsistentHash
# Your code goes here...
end
|
Add a unit test for `solo clean` | require 'test_helper'
require 'support/validation_helper'
require 'chef/knife/solo_clean'
class SoloCleanTest < TestCase
include ValidationHelper::ValidationTests
def command(*args)
knife_command(Chef::Knife::SoloClean, *args)
end
end
| require 'test_helper'
require 'support/validation_helper'
require 'chef/knife/solo_clean'
class SoloCleanTest < TestCase
include ValidationHelper::ValidationTests
def test_removes_provision_path
cmd = command('somehost', '--provisioning-path=/foo/bar')
cmd.expects(:run_command).with('rm -rf /foo/bar').returns(SuccessfulResult.new)
cmd.run
end
def command(*args)
knife_command(Chef::Knife::SoloClean, *args)
end
end
|
Simplify discussion locked checking on comment policy | class CommentPolicy < ApplicationPolicy
delegate :writable?, to: :discussion_policy
def index?
true
end
def show?
discussion_policy.show?
end
def create?
logged_in? && !locked? && writable?
end
def update?
owner? && !locked? && writable?
end
def destroy?
owner? && !locked? && writable?
end
def move?
!locked? && (owner? || moderator? || admin?) && writable?
end
def upvote?
logged_in? && !owner? && writable?
end
def remove_upvote?
logged_in? && !owner? && writable?
end
def locked?
Array.wrap(record).any? do |comment|
comment.discussion.locked?
end
end
def discussion_policy
DiscussionPolicy.new user, discussions
end
def discussions
Array.wrap(record).compact.collect &:discussion
end
class Scope < Scope
delegate :zooniverse_admin?, :permissions, to: :@discussion_scope
def initialize(user, scope)
@discussion_scope = DiscussionPolicy::Scope.new user, Discussion
super
end
def resolve
return scope.all if zooniverse_admin?
scope.joins(discussion: :board).where permissions.join(' or ')
end
def discussion_scope
DiscussionPolicy::Scope.new user, Discussion
end
end
end
| class CommentPolicy < ApplicationPolicy
delegate :writable?, to: :discussion_policy
def index?
true
end
def show?
discussion_policy.show?
end
def create?
logged_in? && !locked? && writable?
end
def update?
owner? && !locked? && writable?
end
def destroy?
owner? && !locked? && writable?
end
def move?
!locked? && (owner? || moderator? || admin?) && writable?
end
def upvote?
logged_in? && !owner? && writable?
end
def remove_upvote?
logged_in? && !owner? && writable?
end
def locked?
discussions.any? &:locked?
end
def discussion_policy
DiscussionPolicy.new user, discussions
end
def discussions
@_discussions ||= Array.wrap(record).compact.collect(&:discussion)
end
class Scope < Scope
delegate :zooniverse_admin?, :permissions, to: :@discussion_scope
def initialize(user, scope)
@discussion_scope = DiscussionPolicy::Scope.new user, Discussion
super
end
def resolve
return scope.all if zooniverse_admin?
scope.joins(discussion: :board).where permissions.join(' or ')
end
def discussion_scope
DiscussionPolicy::Scope.new user, Discussion
end
end
end
|
Add subcommands 'site', 'member', 'song'. | require "sexy_zone"
require "thor"
module SexyZone
class CLI < Thor
# example for using command, and , abstract.
desc "red WORD", "red words print."
# define command as method.
def red(word)
say(word, :red)
end
end
end
| require "sexy_zone"
require "thor"
module SexyZone
class CLI < Thor
desc "site", "Open SexyZone offcial site."
def site()
uri = "http://sexyzone.ponycanyon.co.jp/"
command = "open"
system "#{command} #{uri}"
end
desc "member [option]", "Let's join the members of SexyZone!"
option :add, :type => :string, :aliases => '-a', :desc => "Join new member."
option :list, :type => :boolean, :aliases => '-l', :desc => "Show all member's name."
def member
names = Array[
"Shori Sato",
"Kento Nakajima",
"Fuma Kikuchi",
"So Matsushima",
"Marius Yo"
]
if options[:add]
message = "'#{options[:add]}' is not suitable as a new member of SexyZone."
say("ERROR: #{message}", :red)
else
names.each do |name|
say(name)
end
end
end
desc "song [option]", "Let's release a new song of SexyZone!"
option :add, :type => :string, :aliases => '-a', :desc => "Release new song."
option :list, :type => :boolean, :aliases => '-l', :desc => "Show all song's name."
def song
songs = Array[
"BAD BOYS"
]
if options[:add]
message = "'#{options[:add]}' is not suitable as a new song of SexyZone."
say("ERROR: #{message}", :red)
else
songs.each do |song|
say(song)
end
end
end
end
end
|
Add an index on `host_id` and `expires_at` | #!/usr/bin/env ruby
module Hotdog
module Commands
class Init < BaseCommand
def run(args=[])
execute(<<-EOS)
CREATE TABLE IF NOT EXISTS hosts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(255) NOT NULL
);
EOS
execute(<<-EOS)
CREATE UNIQUE INDEX IF NOT EXISTS hosts_name ON hosts ( name );
EOS
execute(<<-EOS)
CREATE TABLE IF NOT EXISTS tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(200) NOT NULL,
value VARCHAR(200) NOT NULL DEFAULT ""
);
EOS
execute(<<-EOS)
CREATE UNIQUE INDEX IF NOT EXISTS tags_name_value ON tags ( name, value );
EOS
execute(<<-EOS)
CREATE TABLE IF NOT EXISTS hosts_tags (
host_id INTEGER NOT NULL,
tag_id INTEGER NOT NULL,
expires_at INTEGER NOT NULL
);
EOS
execute(<<-EOS)
CREATE UNIQUE INDEX IF NOT EXISTS hosts_tags_host_id_tag_id ON hosts_tags ( host_id, tag_id );
EOS
execute(<<-EOS)
CREATE INDEX IF NOT EXISTS hosts_tags_expires_at ON hosts_tags ( expires_at );
EOS
application.run_command("update")
end
end
end
end
# vim:set ft=ruby :
| #!/usr/bin/env ruby
module Hotdog
module Commands
class Init < BaseCommand
def run(args=[])
execute(<<-EOS)
CREATE TABLE IF NOT EXISTS hosts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(255) NOT NULL
);
EOS
execute(<<-EOS)
CREATE UNIQUE INDEX IF NOT EXISTS hosts_name ON hosts ( name );
EOS
execute(<<-EOS)
CREATE TABLE IF NOT EXISTS tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(200) NOT NULL,
value VARCHAR(200) NOT NULL DEFAULT ""
);
EOS
execute(<<-EOS)
CREATE UNIQUE INDEX IF NOT EXISTS tags_name_value ON tags ( name, value );
EOS
execute(<<-EOS)
CREATE TABLE IF NOT EXISTS hosts_tags (
host_id INTEGER NOT NULL,
tag_id INTEGER NOT NULL,
expires_at INTEGER NOT NULL
);
EOS
execute(<<-EOS)
CREATE UNIQUE INDEX IF NOT EXISTS hosts_tags_host_id_tag_id ON hosts_tags ( host_id, tag_id );
EOS
execute(<<-EOS)
CREATE INDEX IF NOT EXISTS hosts_tags_expires_at ON hosts_tags ( expires_at );
EOS
execute(<<-EOS)
CREATE INDEX IF NOT EXISTS hosts_tags_host_id_expires_at ON hosts_tags ( host_id, expires_at );
EOS
application.run_command("update")
end
end
end
end
# vim:set ft=ruby :
|
Add multi_json as a runtime dependency for JSON file-based models | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'whisky/version'
Gem::Specification.new do |spec|
spec.name = "whisky"
spec.version = Whisky::VERSION
spec.authors = ["Sonny Scroggin"]
spec.email = ["scrogson@gmail.com"]
spec.description = %q{Whisky is a micro-framework built upon Rack.}
spec.summary = %q{Another Rack Micro-Framework.}
spec.homepage = "http://github.com/scrogson/whisky"
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_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rspec"
spec.add_development_dependency "rake"
spec.add_development_dependency "rack-test"
spec.add_runtime_dependency "rack"
spec.add_runtime_dependency "erubis"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'whisky/version'
Gem::Specification.new do |spec|
spec.name = "whisky"
spec.version = Whisky::VERSION
spec.authors = ["Sonny Scroggin"]
spec.email = ["scrogson@gmail.com"]
spec.description = %q{Whisky is a micro-framework built upon Rack.}
spec.summary = %q{Another Rack Micro-Framework.}
spec.homepage = "http://github.com/scrogson/whisky"
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_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rspec"
spec.add_development_dependency "rake"
spec.add_development_dependency "rack-test"
spec.add_runtime_dependency "rack"
spec.add_runtime_dependency "erubis"
spec.add_runtime_dependency "multi_json"
end
|
Fix race condition bug, when background and realtime workers tried to check achievements for same user at once | class CheckNewAchievements
@queue = :cron
def self.perform
User.all.each{|u| u.earn_achievements }
end
end
| class CheckNewAchievements
@queue = :cron
def self.perform
User.where(User.arel_table[:achievements_fetched_at].not_eq(nil)).each{|u| u.earn_achievements }
end
end
|
Add test for queue time calc accounting for network time | # frozen_string_literal: true
require "test_helper"
require "judoscale/request"
require "judoscale/config"
module Judoscale
describe Request do
let(:request) { Request.new(env, config) }
let(:env) { {} }
let(:config) { Config.instance }
describe "#queue_time" do
it "handles X_REQUEST_START in integer milliseconds (Heroku)" do
started_at = Time.now - 2
ended_at = started_at + 1
env["HTTP_X_REQUEST_START"] = (started_at.to_f * 1000).to_i.to_s
_(request.queue_time(ended_at)).must_be_within_delta 1000, 1
end
it "handles X_REQUEST_START in seconds with fractional milliseconds (nginx)" do
started_at = Time.now - 2
ended_at = started_at + 1
env["HTTP_X_REQUEST_START"] = "t=#{format "%.3f", started_at.to_f}"
_(request.queue_time(ended_at)).must_be_within_delta 1000, 1
end
end
end
end
| # frozen_string_literal: true
require "test_helper"
require "judoscale/request"
require "judoscale/config"
module Judoscale
describe Request do
let(:request) { Request.new(env, config) }
let(:env) { {} }
let(:config) { Config.instance }
describe "#queue_time" do
it "handles X_REQUEST_START in integer milliseconds (Heroku)" do
started_at = Time.now - 2
ended_at = started_at + 1
env["HTTP_X_REQUEST_START"] = (started_at.to_f * 1000).to_i.to_s
_(request.queue_time(ended_at)).must_be_within_delta 1000, 1
end
it "handles X_REQUEST_START in seconds with fractional milliseconds (nginx)" do
started_at = Time.now - 2
ended_at = started_at + 1
env["HTTP_X_REQUEST_START"] = "t=#{format "%.3f", started_at.to_f}"
_(request.queue_time(ended_at)).must_be_within_delta 1000, 1
end
it "subtracts the network time / request body wait available in puma from the queue time" do
started_at = Time.now - 2
ended_at = started_at + 1
env["HTTP_X_REQUEST_START"] = (started_at.to_f * 1000).to_i.to_s
env["puma.request_body_wait"] = 50
_(request.queue_time(ended_at)).must_be_within_delta 950, 1
end
end
end
end
|
Test file created in class with Peter's syntax. | require ('test/unit')
require ('mocha')
require ('httparty')
require (json_file)
class MockExampleTest < Test::Unit::TestCase
def test_example_mocking
file_name = File.expand_path('../json/gaga.json'_FILE_)
response = stub('first test ever', :body => File.read(file_name))
HTTParty.expects(:get).returns(response)
end
end
| |
Add search functionality to VendorPayments | module NetSuite
module Records
class VendorPayment
include Support::Fields
include Support::RecordRefs
include Support::Records
include Support::Actions
include Namespaces::TranPurch
actions :get, :get_list, :initialize, :add, :delete, :update, :upsert
fields :address, :balance, :bill_pay, :created_at, :credit_list, :currency_name, :exchange_rate, :last_modified_date,
:memo, :print_voucher, :status, :to_ach, :to_be_printed, :total, :tran_date, :tran_id, :transaction_number
field :apply_list, VendorPaymentApplyList
field :custom_field_list, CustomFieldList
record_refs :account, :ap_acct, :currency, :custom_form, :department, :entity, :klass, :location, :posting_period,
:subsidiary, :void_journal
attr_reader :internal_id
attr_accessor :external_id
def initialize(attributes = {})
@internal_id = attributes.delete(:internal_id) || attributes.delete(:@internal_id)
@external_id = attributes.delete(:external_id) || attributes.delete(:@external_id)
initialize_from_attributes_hash(attributes)
end
def to_record
rec = super
if rec["#{record_namespace}:customFieldList"]
rec["#{record_namespace}:customFieldList!"] = rec.delete("#{record_namespace}:customFieldList")
end
rec
end
end
end
end
| module NetSuite
module Records
class VendorPayment
include Support::Fields
include Support::RecordRefs
include Support::Records
include Support::Actions
include Namespaces::TranPurch
actions :get, :get_list, :initialize, :add, :delete, :update, :upsert, :search
fields :address, :balance, :bill_pay, :created_at, :credit_list, :currency_name, :exchange_rate, :last_modified_date,
:memo, :print_voucher, :status, :to_ach, :to_be_printed, :total, :tran_date, :tran_id, :transaction_number
field :apply_list, VendorPaymentApplyList
field :custom_field_list, CustomFieldList
record_refs :account, :ap_acct, :currency, :custom_form, :department, :entity, :klass, :location, :posting_period,
:subsidiary, :void_journal
attr_reader :internal_id
attr_accessor :external_id
def initialize(attributes = {})
@internal_id = attributes.delete(:internal_id) || attributes.delete(:@internal_id)
@external_id = attributes.delete(:external_id) || attributes.delete(:@external_id)
initialize_from_attributes_hash(attributes)
end
def to_record
rec = super
if rec["#{record_namespace}:customFieldList"]
rec["#{record_namespace}:customFieldList!"] = rec.delete("#{record_namespace}:customFieldList")
end
rec
end
def self.search_class_name
"Transaction"
end
def self.search_class_namespace
'tranSales'
end
end
end
end
|
Remove hidden secret injection into stackfile | require 'yaml'
module KumoDockerCloud
module StackFile
def self.create_from_template(stack_template, config, env_vars)
parsed = YAML.load(ERB.new(stack_template).result(config.get_binding))
parsed[config.app_name]['environment'] ||= {}
parsed[config.app_name]['environment'].merge!(config.plain_text_secrets)
parsed[config.app_name]['environment'].merge!(env_vars.fetch(config.app_name, {}))
converted_env_vars = make_all_root_level_keys_strings(env_vars)
env_vars.each do |key, _|
key_string = key.to_s
parsed[key_string]['environment'].merge!(converted_env_vars.fetch(key_string))
end
parsed
end
def self.make_all_root_level_keys_strings(env_vars)
env_vars.keys.reduce({}) { |acc, key| acc[key.to_s] = env_vars[key]; acc }
end
private_class_method :make_all_root_level_keys_strings
end
end
| require 'yaml'
module KumoDockerCloud
module StackFile
def self.create_from_template(stack_template, config, env_vars)
parsed = YAML.load(ERB.new(stack_template).result(config.get_binding))
converted_env_vars = make_all_root_level_keys_strings(env_vars)
env_vars.each do |key, _|
key_string = key.to_s
parsed[key_string]['environment'].merge!(converted_env_vars.fetch(key_string))
end
parsed
end
def self.make_all_root_level_keys_strings(env_vars)
env_vars.keys.reduce({}) { |acc, key| acc[key.to_s] = env_vars[key]; acc }
end
private_class_method :make_all_root_level_keys_strings
end
end
|
Simplify the Rails 3 detection | module SitemapGenerator
module Utilities
extend self
# Copy templates/sitemap.rb to config if not there yet.
def install_sitemap_rb(verbose=false)
if File.exist?(File.join(RAILS_ROOT, 'config/sitemap.rb'))
puts "already exists: config/sitemap.rb, file not copied" if verbose
else
FileUtils.cp(
SitemapGenerator.templates.template_path(:sitemap_sample),
File.join(RAILS_ROOT, 'config/sitemap.rb'))
puts "created: config/sitemap.rb" if verbose
end
end
# Remove config/sitemap.rb if exists.
def uninstall_sitemap_rb
if File.exist?(File.join(RAILS_ROOT, 'config/sitemap.rb'))
File.rm(File.join(RAILS_ROOT, 'config/sitemap.rb'))
end
end
# Clean sitemap files in output directory.
def clean_files
FileUtils.rm(Dir[File.join(RAILS_ROOT, 'public/sitemap*.xml.gz')])
end
# Returns whether this environment is using ActionPack
# version 3.0.0 or greater.
#
# @return [Boolean]
def self.rails3?
# The ActionPack module is always loaded automatically in Rails >= 3
return false unless defined?(ActionPack) && defined?(ActionPack::VERSION)
version =
if defined?(ActionPack::VERSION::MAJOR)
ActionPack::VERSION::MAJOR
else
# Rails 1.2
ActionPack::VERSION::Major
end
# 3.0.0.beta1 acts more like ActionPack 2
# for purposes of this method
# (checking whether block helpers require = or -).
# This extra check can be removed when beta2 is out.
version >= 3 &&
!(defined?(ActionPack::VERSION::TINY) &&
ActionPack::VERSION::TINY == "0.beta")
end
end
end | module SitemapGenerator
module Utilities
extend self
# Copy templates/sitemap.rb to config if not there yet.
def install_sitemap_rb(verbose=false)
if File.exist?(File.join(RAILS_ROOT, 'config/sitemap.rb'))
puts "already exists: config/sitemap.rb, file not copied" if verbose
else
FileUtils.cp(
SitemapGenerator.templates.template_path(:sitemap_sample),
File.join(RAILS_ROOT, 'config/sitemap.rb'))
puts "created: config/sitemap.rb" if verbose
end
end
# Remove config/sitemap.rb if exists.
def uninstall_sitemap_rb
if File.exist?(File.join(RAILS_ROOT, 'config/sitemap.rb'))
File.rm(File.join(RAILS_ROOT, 'config/sitemap.rb'))
end
end
# Clean sitemap files in output directory.
def clean_files
FileUtils.rm(Dir[File.join(RAILS_ROOT, 'public/sitemap*.xml.gz')])
end
# Returns a boolean indicating whether this environment is Rails 3
#
# @return [Boolean]
def self.rails3?
Rails.version.to_f >= 3
end
end
end |
Add license in gem package | # encoding: utf-8
require "./lib/injectable/version"
Gem::Specification.new do |s|
s.name = "injectable"
s.version = Injectable::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Durran Jordan"]
s.email = ["durran@gmail.com"]
s.summary = "Dead simple Ruby dependency injection"
s.description = s.summary
s.files = Dir.glob("lib/**/*") + %w(README.md Rakefile)
s.require_path = "lib"
end
| # encoding: utf-8
require "./lib/injectable/version"
Gem::Specification.new do |s|
s.name = "injectable"
s.version = Injectable::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Durran Jordan"]
s.email = ["durran@gmail.com"]
s.summary = "Dead simple Ruby dependency injection"
s.description = s.summary
s.files = Dir.glob("lib/**/*") + %w(README.md LICENSE Rakefile)
s.require_path = "lib"
end
|
Add rake files for rubocop runner | Cch::Runner.configure :rubocop do |runner|
runner.watch(/\.rb$/)
end
Cch::Runner.configure :haml_lint, gem: 'haml-lint' do |runner|
runner.watch(/\.haml$/)
end
Cch::Runner.configure :rspec do |runner|
runner.watch(/_spec\.rb$/)
runner.watch(%r{^spec/spec_helper.rb$}, proc { %w(spec) })
runner.watch(%r{^spec/rails_helper.rb$}, proc { %w(spec) })
runner.watch(%r{^config/routes.rb$}, proc { %w(spec/routing) })
runner.watch(%r{^app/controllers/application_controller.rb$}, proc { %w(spec/controllers) })
runner.watch(%r{^lib/(.+)\.rb$}, proc { |m| %W(spec/#{m[1]}_spec.rb spec/lib/#{m[1]}_spec.rb) })
runner.watch(%r{^app/(.+)\.rb$}, proc { |m| %W(spec/#{m[1]}_spec.rb) })
runner.watch(
%r{^app/controllers/(.+)_(controller)\.rb$},
proc do |m|
%W(spec/routing/#{m[1]}_routing_spec.rb spec/requests/#{m[1]}_spec.rb spec/features/#{m[1]}_spec.rb)
end
)
end
| Cch::Runner.configure :rubocop do |runner|
runner.watch(/\.rb$/)
runner.watch(/\.rake$/)
end
Cch::Runner.configure :haml_lint, gem: 'haml-lint' do |runner|
runner.watch(/\.haml$/)
end
Cch::Runner.configure :rspec do |runner|
runner.watch(/_spec\.rb$/)
runner.watch(%r{^spec/spec_helper.rb$}, proc { %w(spec) })
runner.watch(%r{^spec/rails_helper.rb$}, proc { %w(spec) })
runner.watch(%r{^config/routes.rb$}, proc { %w(spec/routing) })
runner.watch(%r{^app/controllers/application_controller.rb$}, proc { %w(spec/controllers) })
runner.watch(%r{^lib/(.+)\.rb$}, proc { |m| %W(spec/#{m[1]}_spec.rb spec/lib/#{m[1]}_spec.rb) })
runner.watch(%r{^app/(.+)\.rb$}, proc { |m| %W(spec/#{m[1]}_spec.rb) })
runner.watch(
%r{^app/controllers/(.+)_(controller)\.rb$},
proc do |m|
%W(spec/routing/#{m[1]}_routing_spec.rb spec/requests/#{m[1]}_spec.rb spec/features/#{m[1]}_spec.rb)
end
)
end
|
Add migration to create SpreePurchaseOrder | class CreateSpreePurchaseOrder < ActiveRecord::Migration
def change
create_table :spree_purchase_order_documents do |t|
t.string :number
t.date :invoice_date
t.string :contact_name
t.string :contact_email
t.string :attachment_file_name
t.string :attachment_content_type
t.string :attachment_file_size
t.timestamps
end
add_index :spree_purchase_order_documents, [:number, :invoice_date]
end
end
| |
Fix migration so travis is happy | class PopulateFeedbacksToRedis < ActiveRecord::Migration[5.2]
def change
Feedback.populate_redis_meta
end
end
| class PopulateFeedbacksToRedis < ActiveRecord::Migration[5.2]
def change
# If this line isn't here, travis thinks we died
ActiveRecord::Base.logger = Logger.new(STDOUT)
Feedback.populate_redis_meta
end
end
|
Tweak the name of the plugin to match the patch. | require 'redmine'
require 'dispatcher'
Dispatcher.to_prepare :forward_to_diffs do
require_dependency 'application_helper'
ApplicationHelper.send(:include, DiffForwardPluginPatch) unless ApplicationHelper.included_modules.include?(DiffForwardPluginPatch)
end
Redmine::Plugin.register :forward_to_diffs do
name 'Forward to diffs'
author 'Jon McManus'
url 'http://github.com/jmcb/forward-to-diffs'
author_url 'http://github.com/jmcb'
description 'Link users directly to diffs of revisions, rather than to the overview.'
version '0.1'
requires_redmine :version_or_higher => '0.8.0'
end
| require 'redmine'
require 'dispatcher'
Dispatcher.to_prepare :diff_forward do
require_dependency 'application_helper'
ApplicationHelper.send(:include, DiffForwardPluginPatch) unless ApplicationHelper.included_modules.include?(DiffForwardPluginPatch)
end
Redmine::Plugin.register :diff_forward do
name 'Forward to diffs'
author 'Jon McManus'
url 'http://github.com/jmcb/forward-to-diffs'
author_url 'http://github.com/jmcb'
description 'Link users directly to diffs of revisions, rather than to the overview.'
version '0.1'
requires_redmine :version_or_higher => '0.8.0'
end
|
Rename AdminUser to Admin in admin. | ActiveAdmin.register AdminUser do
index do
selectable_column
id_column
column :email
column :current_sign_in_at
column :sign_in_count
column :created_at
actions
end
filter :email
filter :current_sign_in_at
filter :sign_in_count
filter :created_at
form do |f|
f.inputs "Admin Details" do
f.input :email
f.input :password
f.input :password_confirmation
end
f.actions
end
end
| ActiveAdmin.register AdminUser, as: 'Admin' do
index do
selectable_column
id_column
column :email
column :current_sign_in_at
column :sign_in_count
column :created_at
actions
end
filter :email
filter :current_sign_in_at
filter :sign_in_count
filter :created_at
form do |f|
f.inputs "Admin Details" do
f.input :email
f.input :password
f.input :password_confirmation
end
f.actions
end
end
|
Add small doc to hook class. | module RedmineRecurringTasks
module Hooks
class IssueSidebarHook < Redmine::Hook::ViewListener
render_on :view_issues_sidebar_planning_bottom, partial: 'weekly_schedules/issues/sidebar'
end
end
end
| module RedmineRecurringTasks
module Hooks
# Issue sidebar hook for show weekly schedule on issue page
class IssueSidebarHook < Redmine::Hook::ViewListener
render_on :view_issues_sidebar_planning_bottom, partial: 'weekly_schedules/issues/sidebar'
end
end
end
|
Set Cocoapods version to 0.2.0 | #
# Be sure to run `pod lib lint cf-jsmn.podspec' to ensure this is a
# valid spec before submitting.
#
Pod::Spec.new do |s|
s.name = "cf-jsmn"
s.version = "0.1.0"
s.summary = "CF (OS X and iOS) version of jsmn"
s.description = <<-DESC
A Core Foundation compatible version of the awesome lightweight JSON parser
"jsmn", with support for unicode strings.
DESC
s.homepage = "https://github.com/luckymarmot/cf-jsmn"
s.license = 'MIT'
s.author = { "Micha Mazaheri" => "micha@mazaheri.me" }
s.source = { :git => "https://github.com/luckymarmot/cf-jsmn.git", :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/luckymarmot'
s.ios.deployment_target = '7.0'
s.osx.deployment_target = '10.9'
s.requires_arc = false
s.source_files = 'src/*'
s.public_header_files = 'src/*.h'
end
| #
# Be sure to run `pod lib lint cf-jsmn.podspec' to ensure this is a
# valid spec before submitting.
#
Pod::Spec.new do |s|
s.name = "cf-jsmn"
s.version = "0.2.0"
s.summary = "CF (OS X and iOS) version of jsmn"
s.description = <<-DESC
A Core Foundation compatible version of the awesome lightweight JSON parser
"jsmn", with support for unicode strings.
DESC
s.homepage = "https://github.com/luckymarmot/cf-jsmn"
s.license = 'MIT'
s.author = { "Micha Mazaheri" => "micha@mazaheri.me" }
s.source = { :git => "https://github.com/luckymarmot/cf-jsmn.git", :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/luckymarmot'
s.ios.deployment_target = '7.0'
s.osx.deployment_target = '10.9'
s.requires_arc = false
s.source_files = 'src/*'
s.public_header_files = 'src/*.h'
end
|
Use the contents method, not the @contents variable. | module Salt
module Renderable
def render(site, body, context = {})
context[:site] ||= site
begin
output = Erubis::Eruby.new(@contents).evaluate(context) { body }
rescue Exception => e
output = body
end
output = site.templates[@layout].render(site, output, context) if @layout && site.templates[@layout]
output
end
end
end | module Salt
module Renderable
def render(site, body, context = {})
context[:site] ||= site
begin
output = Erubis::Eruby.new(self.contents).evaluate(context) { body }
rescue Exception => e
output = body
end
output = site.templates[@layout].render(site, output, context) if @layout && site.templates[@layout]
output
end
end
end |
Update aptitude before installing ppa | package :apt_sources do
description "Setup custom repositories"
apt "python-software-properties" do
post :install, "add-apt-repository -y ppa:git-core/ppa"
post :install, "add-apt-repository -y ppa:svn/ppa"
post :install, "apt-get update -y"
end
verify do
has_apt "python-software-properties"
end
end | package :apt_sources do
description "Setup custom repositories"
runner "apt-get update -y"
apt "python-software-properties" do
post :install, "add-apt-repository -y ppa:git-core/ppa"
post :install, "add-apt-repository -y ppa:svn/ppa"
post :install, "apt-get update -y"
end
verify do
has_apt "python-software-properties"
end
end |
Include environment for pings task | desc "pings oursolution.is every 10 minutes"
task :pings do
require 'net/http'
uri = URI("http://oursolution.is")
Net::HTTP.get_response(uri)
end | desc "pings oursolution.is every 10 minutes"
task :pings => :environment do
puts "oursolution.is must not idle"
require 'net/http'
uri = URI("http://oursolution.is")
Net::HTTP.get_response(uri)
end |
Update Active Admins permitted params to include unisex and accessibility. | ActiveAdmin.register Restroom do
permit_params :name, :street, :city, :state, :access, :bath_type, :directions, :comment, :latitude, :longitude, :country
# See permitted parameters documentation:
# https://github.com/gregbell/active_admin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters
#
# permit_params :list, :of, :attributes, :on, :model
#
# or
#
# permit_params do
# permitted = [:permitted, :attributes]
# permitted << :other if resource.something?
# permitted
# end
end
| ActiveAdmin.register Restroom do
permit_params :name, :street, :city, :state, :accessible, :unisex, :directions,
:comment, :latitude, :longitude, :country
end
|
Change usage of DataMapper::Resource::ClassMethods to use Model | require 'pathname'
require 'rubygems'
gem 'dm-core', '~>0.9.10'
require 'dm-core'
require Pathname(__FILE__).dirname.expand_path / 'dm-is-remixable' / 'is' / 'remixable'
module DataMapper
module Resource
module ClassMethods
include DataMapper::Is::Remixable
end # module ClassMethods
end # module Resource
end # module DataMapper
| require 'pathname'
require 'rubygems'
gem 'dm-core', '~>0.9.10'
require 'dm-core'
require Pathname(__FILE__).dirname.expand_path / 'dm-is-remixable' / 'is' / 'remixable'
module DataMapper
module Model
include DataMapper::Is::Remixable
end # module Model
end # module DataMapper
|
Remove the nginx attribute that breaks nginx on Windows nodes | # instead of using hard-coded path for passenger root, we should be using the following:
#%x{passenger-config --root}.chomp
#
node.default["nginx"]["passenger"]["version"] = "3.0.12"
node.default["nginx"]["passenger"]["root"] = "/usr/lib/ruby/gems/1.8/gems/passenger-3.0.12"
node.default["nginx"]["passenger"]["ruby"] = %x{which ruby}.chomp
node.default["nginx"]["passenger"]["max_pool_size"] = 10
| # instead of using hard-coded path for passenger root, we should be using the following:
#%x{passenger-config --root}.chomp
#
node.default["nginx"]["passenger"]["version"] = "3.0.12"
node.default["nginx"]["passenger"]["root"] = "/usr/lib/ruby/gems/1.8/gems/passenger-3.0.12"
node.default["nginx"]["passenger"]["ruby"] = ""
node.default["nginx"]["passenger"]["max_pool_size"] = 10
|
Initialize solution - yay green specs | class ResistorColorDuo
def self.value(colors)
number = "#{ColorValues[colors[0]]}" + "#{ColorValues[colors[1]]}"[0]
number.to_i
end
ColorValues = {
"black" => 0,
"brown" => 10,
"blue" => 6,
"grey" => 8,
"yellow" => 4,
"violet" => 7,
"orange" => 3,
"green" => 5
}
end
| class ResistorColorDuo
def self.value(colors)
number = "#{ColorValues[colors[0]]}" + "#{ColorValues[colors[1]]}"
number[0..1].to_i
end
ColorValues = {
"black" => 0,
"brown" => 10,
"blue" => 6,
"grey" => 8,
"yellow" => 4,
"violet" => 7,
"orange" => 3,
"green" => 5
}
end
|
Whitelist allow Crazy Egg to jump over the check terms | class ApplicationController < ActionController::Base
helper_method :watch_cookie?
protect_from_forgery with: :exception
before_filter :check_browser
before_filter :check_terms
def not_found
raise ActionController::RoutingError.new('Not Found')
end
def accept_terms
session[:return_to] = params[:return_to] unless params[:return_to].nil?
@title = 'Terms of Service'
end
private
Browser = Struct.new(:browser, :version)
SupportedBrowsers = [
Browser.new('Safari', '5.0.5'),
Browser.new('Firefox', '12.0'),
Browser.new('Internet Explorer', '10.0'),
Browser.new('Chrome', '19.0.1036.7'),
Browser.new('Opera', '11.00')
]
def check_browser
user_agent = UserAgent.parse(request.user_agent)
redirect_to "/notsupportedbrowser" unless SupportedBrowsers.detect { |browser| user_agent >= browser } || user_agent.bot?
end
def check_terms
session[:return_to] = request.fullpath
redirect_to accept_terms_path unless watch_cookie?
end
def watch_cookie?
cookies.permanent[ENV['TERMS_COOKIE'].to_sym] || controller_name == 'embed' || UserAgent.parse(request.user_agent).bot?
end
end
| class ApplicationController < ActionController::Base
helper_method :watch_cookie?
protect_from_forgery with: :exception
before_filter :check_browser
before_filter :check_terms
def not_found
raise ActionController::RoutingError.new('Not Found')
end
def accept_terms
session[:return_to] = params[:return_to] unless params[:return_to].nil?
@title = 'Terms of Service'
end
private
Browser = Struct.new(:browser, :version)
SupportedBrowsers = [
Browser.new('Safari', '5.0.5'),
Browser.new('Firefox', '12.0'),
Browser.new('Internet Explorer', '10.0'),
Browser.new('Chrome', '19.0.1036.7'),
Browser.new('Opera', '11.00')
]
def check_browser
user_agent = UserAgent.parse(request.user_agent)
redirect_to "/notsupportedbrowser" unless SupportedBrowsers.detect { |browser| user_agent >= browser } || user_agent.bot?
end
def check_terms
session[:return_to] = request.fullpath
@whitelist = [
'80.74.134.135',
# '127.0.0.1'
]
if not @whitelist.include? request.remote_ip
redirect_to accept_terms_path unless watch_cookie?
end
end
def watch_cookie?
cookies.permanent[ENV['TERMS_COOKIE'].to_sym] || controller_name == 'embed' || UserAgent.parse(request.user_agent).bot?
end
end
|
Create script for generating sponsor files | require "yaml"
print "Enter the event in YYYY-city format: "
cityname = gets.chomp
config = YAML.load_file("data/events/#{cityname}.yml")
sponsors = config['sponsors']
sponsors.each {|s|
if File.exist?("data/sponsors/#{s['id']}.yml")
puts "The file for #{s['id']} totally exists already"
else
puts "I need to make a file for #{s['id']}"
puts "What is the sponsor URL?"
sponsor_url = gets.chomp
sponsorfile = File.open("data/sponsors/#{s['id']}.yml", "w")
sponsorfile.write "name: #{s['id']}\n"
sponsorfile.write "url: #{sponsor_url}\n"
sponsorfile.close
puts "It will be data/sponsors/#{s['id']}.yml"
end
}
| |
Remove uneeded 'self.' from User::before_save | class User < ActiveRecord::Base
validates :name, presence: true, length: { maximum: 50 }
validates :email, presence: true, format: { with: /@/ },
uniqueness: { case_sensitive: false }
before_save { self.email.downcase! }
has_secure_password
validates :password, length: { minimum: 6 }
end
| class User < ActiveRecord::Base
validates :name, presence: true, length: { maximum: 50 }
validates :email, presence: true, format: { with: /@/ },
uniqueness: { case_sensitive: false }
before_save { email.downcase! }
has_secure_password
validates :password, length: { minimum: 6 }
end
|
Add route for 504 error | Static::Application.routes.draw do
match "/templates/wrapper.html.erb", :to => "root#wrapper"
match "/templates/print.html.erb", :to => "root#print"
match "/templates/related.raw.html.erb", :to => "root#related"
match "/templates/homepage.html.erb", :to => "root#homepage"
match "/templates/admin.html.erb", :to => "root#admin"
match "/templates/404.html.erb", :to => "root#404"
match "/templates/406.html.erb", :to => "root#406"
match "/templates/418.html.erb", :to => "root#418"
match "/templates/500.html.erb", :to => "root#500"
match "/templates/501.html.erb", :to => "root#501"
match "/templates/503.html.erb", :to => "root#503"
end
| Static::Application.routes.draw do
match "/templates/wrapper.html.erb", :to => "root#wrapper"
match "/templates/print.html.erb", :to => "root#print"
match "/templates/related.raw.html.erb", :to => "root#related"
match "/templates/homepage.html.erb", :to => "root#homepage"
match "/templates/admin.html.erb", :to => "root#admin"
match "/templates/404.html.erb", :to => "root#404"
match "/templates/406.html.erb", :to => "root#406"
match "/templates/418.html.erb", :to => "root#418"
match "/templates/500.html.erb", :to => "root#500"
match "/templates/501.html.erb", :to => "root#501"
match "/templates/503.html.erb", :to => "root#503"
match "/templates/504.html.erb", :to => "root#504"
end
|
Use old way to create a test class, Rubinius only has Minitest 4.x | require 'minitest/autorun'
require "#{__dir__}/quizbot"
class TestQuestionpool < Minitest::Test
def setup
@questionpool = Questionpool.new
# Load our actual questions as fixtures
@questionpool.load
end
def test_load
assert !@questionpool.instance_variable_get(:@questions).empty?
end
def test_any_key_has_value?
assert @questionpool.any_key_has_value?('dontcare', 'all')
assert @questionpool.any_key_has_value?('Category', 'Werkstoffe')
assert !@questionpool.any_key_has_value?('NonExistingCategory', 'dontcare')
assert !@questionpool.any_key_has_value?('Category', 'NonExisting')
end
def test_number_of_questions_per
qp = Questionpool.new
qp.instance_variable_set :@questions, [
{'Category' => 'category1'}, {'Category' => 'category1'},
{ 'Category' => 'category2'}, {'Answer' => '42'},
]
assert_equal "category1 (2), category2 (1)",
qp.number_of_questions_per('Category')
end
end
| require 'minitest/autorun'
require "#{__dir__}/quizbot"
class TestQuestionpool < Minitest::Unit::TestCase
def setup
@questionpool = Questionpool.new
# Load our actual questions as fixtures
@questionpool.load
end
def test_load
assert !@questionpool.instance_variable_get(:@questions).empty?
end
def test_any_key_has_value?
assert @questionpool.any_key_has_value?('dontcare', 'all')
assert @questionpool.any_key_has_value?('Category', 'Werkstoffe')
assert !@questionpool.any_key_has_value?('NonExistingCategory', 'dontcare')
assert !@questionpool.any_key_has_value?('Category', 'NonExisting')
end
def test_number_of_questions_per
qp = Questionpool.new
qp.instance_variable_set :@questions, [
{'Category' => 'category1'}, {'Category' => 'category1'},
{ 'Category' => 'category2'}, {'Answer' => '42'},
]
assert_equal "category1 (2), category2 (1)",
qp.number_of_questions_per('Category')
end
end
|
Check in code from other projects | # Use like this:
# QuickConfig.api(:spreedly, 'SPREEDLY_CORE_LOGIN', 'SPREEDLY_CORE_SECRET') do
# SpreedlyCore.configure(ENV['SPREEDLY_CORE_LOGIN'],
# ENV['SPREEDLY_CORE_SECRET'],
# SPREEDLY_CORE[Rails.env]['token'])
# end
#
# or
#
# QuickConfig.api(:janrain, 'JANRAIN_API_KEY')
#
# Looks for a file in the project root, e.g. .spreedly, or .janrain in the
# above cases, and loads it to optionally set env vars for local development
#
# e.g.:
# ENV['SPREEDLY_CORE_LOGIN'] = 'asdfasdf'
# ENV['SPREEDLY_CORE_SECRET'] = 'fdsafdsa'
#
# Otherwise just defaults to using environment variables. Set your variables
# in your Heroku config to keep them out of your code.
class QuickConfig
def self.api(name, *vars)
Rails.root.join(".#{name}").tap do |local_config|
load local_config if File.exist?(local_config)
end
if vars.all?{|var|ENV[var].present?}
yield if block_given?
else
Rails.logger.warn <<-WARNING
You must configure your #{name.to_s.titleize} credentials in the following environment variables:
#{vars.join("\n ")}
WARNING
end
end
end
| |
Add spec for package recipe | require 'chefspec'
describe 'tdi-example-vim::package' do
package_checks = {
'ubuntu' => {
'12.04' => ['vim'],
'14.04' => ['vim']
},
'debian' => {
'7.0' => ['vim'],
'7.1' => ['vim']
},
'redhat' => {
'6.3' => ['vim-minimal', 'vim-enhanced']
}
}
package_checks.each do |platform, versions|
versions.each do |version, packages|
packages.each do |package_name|
it "should install #{package_name} on #{platform} #{version}" do
chef_runner = ChefSpec::SoloRunner.new(platform: platform, version: version)
chef_runner.converge(described_recipe)
expect(chef_runner).to install_package(package_name)
end
end
end
end
end
| |
Add a hash method to Mark | module TicTacToe
class Mark
attr_reader :symbol
def initialize(symbol = " ")
@symbol = symbol
end
def ==(o)
o.class == self.class && o.symbol == self.symbol
end
def mark(symbol)
Mark.new(symbol)
end
def blank?
symbol == " "
end
def to_s
@symbol
end
end
end
| module TicTacToe
class Mark
attr_reader :symbol
def initialize(symbol = " ")
@symbol = symbol
end
def ==(o)
o.class == self.class && o.symbol == self.symbol
end
def hash
@symbol.hash
end
def mark(symbol)
Mark.new(symbol)
end
def blank?
symbol == " "
end
def to_s
@symbol
end
end
end
|
Change AddressBR to use NameBR instead of Name | # encoding: utf-8
require 'ffaker/address'
module Faker
module AddressBR
include Faker::Address
extend ModuleUtils
extend self
def zip_code
Faker.numerify '#####-###'
end
def state
STATE.rand
end
def state_abbr
STATE_ABBR.rand
end
def city
CITY.rand
end
def street_prefix
STREET_PREFIX.rand
end
def street
case rand(1)
when 0 then "#{street_prefix} #{Name.name}"
when 1 then "#{street_prefix} #{Name.first_name} #{Name.last_name} #{Name.last_name}"
end
end
STREET_PREFIX = k %w( Rua Avenida Travessa Alameda )
end
end
| # encoding: utf-8
require 'ffaker/address'
module Faker
module AddressBR
include Faker::Address
extend ModuleUtils
extend self
def zip_code
Faker.numerify '#####-###'
end
def state
STATE.rand
end
def state_abbr
STATE_ABBR.rand
end
def city
CITY.rand
end
def street_prefix
STREET_PREFIX.rand
end
def street
case rand(1)
when 0 then "#{street_prefix} #{NameBR.name}"
when 1 then "#{street_prefix} #{NameBR.first_name} #{NameBR.last_name} #{NameBR.last_name}"
end
end
STREET_PREFIX = k %w( Rua Avenida Travessa Alameda )
end
end
|
Fix aesthetic parens in PrivatePub::Utils | class PrivatePub
module Utils
class << self
def symbolize_keys arg
case arg
when Array
arg.map { |elem| symbolize_keys elem }
when Hash
Hash[
arg.map { |key, value|
k = key.is_a?(String) ? key.to_sym : key
v = symbolize_keys value
[k,v]
}]
else
arg
end
end
end
end
end
| class PrivatePub
module Utils
class << self
def symbolize_keys(arg)
case arg
when Array
arg.map { |elem| symbolize_keys elem }
when Hash
Hash[
arg.map { |key, value|
k = key.is_a?(String) ? key.to_sym : key
v = symbolize_keys value
[k,v]
}]
else
arg
end
end
end
end
end
|
Make sure we check the correct instance. | module RFunk
class Option
include Enumerable
def each(&block)
return enum_for(:enum) if block.nil?
enum.each { |v| block.call(v) }
end
end
def Option(value)
if [Some, None].map { |t| value.is_a?(t) }.any?
value
elsif nothing?(value)
None.instance
else
Some.new(value)
end
end
private
def nothing?(value)
value.nil? || (value.respond_to?(:empty?) && value.empty?) || value.is_a?(None)
end
end
| module RFunk
class Option
include Enumerable
def each(&block)
return enum_for(:enum) if block.nil?
enum.each { |v| block.call(v) }
end
end
def Option(value)
if [Some, None].map { |t| value.is_a?(t) }.any?
value
elsif nothing?(value)
None.instance
else
Some.new(value)
end
end
private
def nothing?(value)
value.nil? || (value.respond_to?(:empty?) && value.empty?) || value == None.instance
end
end
|
Update category_id primary and foreign keys to bigint | class ChangeCategoryIdToBigint < ActiveRecord::Migration[6.0]
def up
change_column :categories, :id, :bigint
change_column :broadcasts, :category_id, :bigint
end
def down
change_column :categories, :id, :integer
change_column :broadcasts, :category_id, :integer
end
end
| |
Fix copier spec (use real objects) | # encoding: utf-8
require_relative '../../spec_helper'
require_relative '../../../app/models/map/copier'
require_relative '../../../app/models/layer'
describe CartoDB::Map::Copier do
before do
@user_id = UUIDTools::UUID.timestamp_create.to_s
@map = OpenStruct.new(
user_id: @user_id,
to_hash: { user_id: @user_id },
layers: (1..5).map { Layer.new(kind: 'carto') }
)
@copier = CartoDB::Map::Copier.new
end
describe '#copy' do
it 'returns a copy of the original map' do
new_map = @copier.copy(@map)
new_map.should be_an_instance_of Map
new_map.user_id.should == @user_id
end
it 'copies all layers from the original map' do
new_map = @copier.copy(@map)
new_map.layers.length.should == @map.layers.length
end
end #copy
end # CartoDB::Map::Copier
| # encoding: utf-8
require_relative '../../spec_helper'
require_relative '../../../app/models/map/copier'
require_relative '../../../app/models/layer'
describe CartoDB::Map::Copier do
before do
@user_id = UUIDTools::UUID.timestamp_create.to_s
@map = Map.new(user_id: @user_id)
@map.stubs(:layers).returns((1..5).map { Layer.new(kind: 'carto') })
@copier = CartoDB::Map::Copier.new
end
describe '#copy' do
it 'returns a copy of the original map' do
new_map = @copier.copy(@map)
new_map.should be_an_instance_of Map
new_map.user_id.should == @user_id
end
it 'copies all layers from the original map' do
new_map = @copier.copy(@map)
new_map.layers.length.should == 5
end
end #copy
end # CartoDB::Map::Copier
|
Update podspec to support tvOS | Pod::Spec.new do |s|
s.name = "OROpenSubtitleDownloader"
s.version = "1.1.1"
s.summary = "An Obj-C API for Searching and Downloading Subtitles from OpenSubtitles."
s.homepage = "https://github.com/orta/OROpenSubtitleDownloader"
s.license = { :type => 'BSD', :file => 'LICENSE' }
s.author = { "orta" => "orta.therox@gmail.com" }
s.source = { :git => "https://github.com/orta/OROpenSubtitleDownloader.git", :commit => :head }
s.source_files = 'OROpenSubtitleDownloader.{h,m}'
s.library = 'z'
s.requires_arc = true
s.ios.deployment_target = '7.0'
s.osx.deployment_target = '10.9'
s.dependency 'AFNetworking'
s.dependency 'xmlrpc'
end
| Pod::Spec.new do |s|
s.name = "OROpenSubtitleDownloader"
s.version = "2.0.0"
s.summary = "An Obj-C API for Searching and Downloading Subtitles from OpenSubtitles."
s.homepage = "https://github.com/orta/OROpenSubtitleDownloader"
s.license = { :type => 'BSD', :file => 'LICENSE' }
s.author = { "orta" => "orta.therox@gmail.com" }
s.source = { :git => "https://github.com/orta/OROpenSubtitleDownloader.git", :commit => :head }
s.source_files = 'OROpenSubtitleDownloader.{h,m}'
s.library = 'z'
s.requires_arc = true
s.ios.deployment_target = '7.0'
s.osx.deployment_target = '10.9'
s.tvos.deployment_target = '9.0'
s.dependency 'AFNetworking'
s.dependency 'xmlrpc'
end
|
Create functionality so that only logged_in users may make new responses | class ResponsesController < ApplicationController
def new
@parent = parent_object
@parent_name = @parent.class.name.downcase.pluralize
@response = Response.new
end
def create
@parent = parent_object
@response = @parent.responses.build(responder_id: current_user.id, content: params[:response][:content])
if @response.save
redirect_to parent_url(@parent)
else
flash[:message] = "Failed to comment successfully."
render :new
end
end
private
def parent_object
case
when params[:question_id] then Question.find(params[:question_id])
when params[:answer_id] then Answer.find(params[:answer_id])
end
end
def parent_url(parent)
case
when params[:question_id] then question_path(parent)
when params[:answer_id] then question_path(parent.question_id)
end
end
end
| class ResponsesController < ApplicationController
def new
if logged_in?
@parent = parent_object
@parent_name = @parent.class.name.downcase.pluralize
@response = Response.new
else
redirect_to login_path
end
end
def create
@parent = parent_object
@response = @parent.responses.build(responder_id: current_user.id, content: params[:response][:content])
if @response.save
redirect_to parent_url(@parent)
else
flash[:message] = "Failed to comment successfully."
render :new
end
end
private
def parent_object
case
when params[:question_id] then Question.find(params[:question_id])
when params[:answer_id] then Answer.find(params[:answer_id])
end
end
def parent_url(parent)
case
when params[:question_id] then question_path(parent)
when params[:answer_id] then question_path(parent.question_id)
end
end
end
|
Add tests for existing Logging functionality | require File.expand_path(File.join(File.dirname(__FILE__), "test_helper"))
require 'onelogin/ruby-saml/logging'
class LoggingTest < Minitest::Test
describe "Logging" do
before do
ENV.delete('ruby-saml/testing')
end
after do
ENV['ruby-saml/testing'] = '1'
end
describe "given no specific logging setup" do
it "prints to stdout" do
OneLogin::RubySaml::Logging.expects(:puts).with('hi mom')
OneLogin::RubySaml::Logging.debug('hi mom')
end
end
describe "given a Rails app" do
let(:logger) { mock('Logger') }
before do
::Rails = mock('Rails module')
::Rails.stubs(:logger).returns(logger)
end
after do
Object.instance_eval { remove_const(:Rails) }
end
it "delegates to Rails" do
logger.expects(:debug).with('hi mom')
logger.expects(:info).with('sup?')
OneLogin::RubySaml::Logging.debug('hi mom')
OneLogin::RubySaml::Logging.info('sup?')
end
end
end
end
| |
Use let vs instance vars in Media requests spec | require "rails_helper"
RSpec.describe "Media requests", type: :request do
describe "requesting an asset that doesn't exist" do
it "should respond with file not found" do
get "/media/34/test.jpg"
expect(response.status).to eq(404)
end
end
describe "request an asset that does exist" do
before do
@asset = FactoryGirl.create(:clean_asset)
get "/media/#{@asset.id}/asset.png", nil, "HTTP_X_SENDFILE_TYPE" => "X-Accel-Redirect",
"HTTP_X_ACCEL_MAPPING" => "#{Rails.root}/tmp/test_uploads/assets/=/raw/"
end
it "should set the X-Accel-Redirect header" do
expect(response).to be_success
id = @asset.id.to_s
expect(response.headers["X-Accel-Redirect"]).to eq("/raw/#{id[2..3]}/#{id[4..5]}/#{id}/#{@asset.file.identifier}")
end
it "should set the correct content headers" do
expect(response.headers["Content-Type"]).to eq("image/png")
expect(response.headers["Content-Disposition"]).to eq('inline; filename="asset.png"')
end
end
end
| require "rails_helper"
RSpec.describe "Media requests", type: :request do
describe "requesting an asset that doesn't exist" do
it "should respond with file not found" do
get "/media/34/test.jpg"
expect(response.status).to eq(404)
end
end
describe "request an asset that does exist" do
let(:asset) { FactoryGirl.create(:clean_asset) }
before do
get "/media/#{asset.id}/asset.png", nil, "HTTP_X_SENDFILE_TYPE" => "X-Accel-Redirect",
"HTTP_X_ACCEL_MAPPING" => "#{Rails.root}/tmp/test_uploads/assets/=/raw/"
end
it "should set the X-Accel-Redirect header" do
expect(response).to be_success
id = asset.id.to_s
expect(response.headers["X-Accel-Redirect"]).to eq("/raw/#{id[2..3]}/#{id[4..5]}/#{id}/#{asset.file.identifier}")
end
it "should set the correct content headers" do
expect(response.headers["Content-Type"]).to eq("image/png")
expect(response.headers["Content-Disposition"]).to eq('inline; filename="asset.png"')
end
end
end
|
Update gemspec with min ruby version | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'bagit/version'
Gem::Specification.new do |spec|
spec.name = "bagit"
spec.version = BagIt::VERSION
spec.summary = "BagIt package generation and validation"
spec.description = "Ruby Library and Command Line tools for bagit"
spec.email = "jamie@jamielittle.org"
spec.homepage = 'http://github.com/tipr/bagit'
spec.authors = ["Tom Johnson, Francesco Lazzarino, Jamie Little"]
spec.license = "MIT"
spec.add_dependency 'validatable', '~> 1.6'
spec.add_dependency 'docopt', '~> 0.5.0'
spec.add_development_dependency 'bundler'
spec.add_development_dependency 'rake', '~> 10.4'
spec.add_development_dependency 'rspec', '~> 3'
spec.add_development_dependency 'coveralls'
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"]
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'bagit/version'
Gem::Specification.new do |spec|
spec.name = "bagit"
spec.version = BagIt::VERSION
spec.summary = "BagIt package generation and validation"
spec.description = "Ruby Library and Command Line tools for bagit"
spec.email = "jamie@jamielittle.org"
spec.homepage = 'http://github.com/tipr/bagit'
spec.authors = ["Tom Johnson, Francesco Lazzarino, Jamie Little"]
spec.license = "MIT"
spec.required_ruby_version = '~> 2.0'
spec.add_dependency 'validatable', '~> 1.6'
spec.add_dependency 'docopt', '~> 0.5.0'
spec.add_development_dependency 'bundler'
spec.add_development_dependency 'rake', '~> 10.4'
spec.add_development_dependency 'rspec', '~> 3'
spec.add_development_dependency 'coveralls'
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"]
end
|
Handle parentheses in strings correctly in REPL | require "lasp"
require "readline"
module Lasp
module_function
def repl
trap("SIGINT") { puts "\n\nBye!"; exit }
puts "((( Läsp v#{Lasp::VERSION} REPL (ctrl+c to exit) )))\n\n"
loop do
begin
history = true
input = Readline.readline("lasp> ", history).to_s
input = autoclose_parentheses(input)
result = Lasp::execute(input)
puts " => #{result.inspect}"
rescue
puts " !> #{$!}"
end
end
end
def autoclose_parentheses(input)
num_opens = input.chars.select { |c| c == "(" }.count
num_closes = input.chars.select { |c| c == ")" }.count
if num_opens > num_closes
missing_closes = num_opens - num_closes
puts " ?> Appending #{missing_closes} missing closing parentheses:"
corrected_input = input + (")" * missing_closes)
puts " ?> #{corrected_input}"
corrected_input
else
input
end
end
end
| require "lasp"
require "lasp/parser"
require "readline"
module Lasp
module_function
def repl
trap("SIGINT") { puts "\n\nBye!"; exit }
puts "((( Läsp v#{Lasp::VERSION} REPL (ctrl+c to exit) )))\n\n"
loop do
begin
history = true
input = Readline.readline("lasp> ", history).to_s
input = autoclose_parentheses(input)
result = Lasp::execute(input)
puts " => #{result.inspect}"
rescue
puts " !> #{$!}"
end
end
end
def autoclose_parentheses(input)
tokens = Lasp::tokenize(input)
num_opens = tokens.select { |t| t == "(" }.count
num_closes = tokens.select { |t| t == ")" }.count
if num_opens > num_closes
missing_closes = num_opens - num_closes
puts " ?> Appending #{missing_closes} missing closing parentheses:"
corrected_input = input + (")" * missing_closes)
puts " ?> #{corrected_input}"
corrected_input
else
input
end
end
end
|
Add supports info, hostsfile dependency | name 'dirsrv'
maintainer 'Alan Willis'
maintainer_email 'alwillis@riotgames.com'
license 'All rights reserved'
description 'Installs/Configures 389ds'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version lambda { IO.read(File.join(File.dirname(__FILE__), 'VERSION')) rescue "0.0.1" }.call
depends 'yum', '~> 3.0'
| name 'dirsrv'
maintainer 'Alan Willis'
maintainer_email 'alwillis@riotgames.com'
license 'All rights reserved'
description 'Installs/Configures 389ds'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version lambda { IO.read(File.join(File.dirname(__FILE__), 'VERSION')) rescue "0.0.1" }.call
depends 'yum', '~> 3.0'
depends 'hostsfile'
supports 'centos'
supports 'fedora'
supports 'oracle'
supports 'redhat'
supports 'scientific'
supports 'debian'
supports 'ubuntu'
|
Fix embarrassing grammatical error in Gemspec description/summary. | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/lazy_resource/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Andrew Latimer"]
gem.email = ["andrew@elpasoera.com"]
gem.description = %q{ActiveResource with it's feet up. The write less, do more consumer of delicious APIs.}
gem.summary = %q{ActiveResource with it's feet up. The write less, do more consumer of delicious APIs.}
gem.homepage = "http://github.com/ahlatimer/lazy_resource"
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 = "lazy_resource"
gem.require_paths = ["lib"]
gem.version = LazyResource::VERSION
gem.add_dependency 'activemodel', '>= 3.1.0'
gem.add_dependency 'activesupport', '>= 3.1.0'
gem.add_dependency 'json', '>= 1.5.2'
gem.add_dependency 'typhoeus', '0.4.2'
end
| # -*- encoding: utf-8 -*-
require File.expand_path('../lib/lazy_resource/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Andrew Latimer"]
gem.email = ["andrew@elpasoera.com"]
gem.description = %q{ActiveResource with its feet up. The write less, do more consumer of delicious APIs.}
gem.summary = %q{ActiveResource with its feet up. The write less, do more consumer of delicious APIs.}
gem.homepage = "http://github.com/ahlatimer/lazy_resource"
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 = "lazy_resource"
gem.require_paths = ["lib"]
gem.version = LazyResource::VERSION
gem.add_dependency 'activemodel', '>= 3.1.0'
gem.add_dependency 'activesupport', '>= 3.1.0'
gem.add_dependency 'json', '>= 1.5.2'
gem.add_dependency 'typhoeus', '0.4.2'
end
|
Add testing code for lib/table.rb | require_relative 'test_helper'
require 'table'
class TableTest < TC
include Table
def test_context
t1 = Main.new(:template=>"Hi <%= m %> and <%= n %>", :context=>{"m"=>"a", "n"=>"b"})
assert_equal(t1.m, "a")
assert_equal(t1.n, "b")
assert(t1.inspect != "c")
t2 = Main.new(:template=>"Hi <%= m %> and <%= n %>", :context=>{"m"=>"a", "n"=>"b", "inspect"=>"c"})
assert_equal(t2.m, "a")
assert_equal(t2.n, "b")
assert_equal(t2.inspect, "c")
end
def test_context_is_only_on_instance
t1 = Main.new(:template=>"<%= m %>", :context=>{"m"=>"a"})
t2 = Main.new(:template=>"<%= n %>", :context=>{"n"=>"a"})
assert(t1.respond_to?(:m))
assert(!t1.respond_to?(:n))
assert(!t2.respond_to?(:m))
assert(t2.respond_to?(:n))
end
def test_render
expected = "Hi a and b"
actual = Main.new(:template=>"Hi <%= m %> and <%= n %>", :context=>{"m"=>"a", "n"=>"b"}).render
assert_equal(actual, expected)
expected = "Hi a"
actual = Main.new(:template=>"Hi <%= inspect %>", :context=>{"inspect"=>"a"}).render
assert_equal(actual, expected)
end
end
| require_relative 'test_helper'
require 'table'
require 'template'
class TableTest < TC
include Table
def test_context
t1 = Main.new(:context=>{"m"=>"a", "n"=>"b"})
assert_equal(t1.m, "a")
assert_equal(t1.n, "b")
assert(t1.inspect != "c")
t2 = Main.new(:context=>{"m"=>"a", "n"=>"b", "inspect"=>"c"})
assert_equal(t2.m, "a")
assert_equal(t2.n, "b")
assert_equal(t2.inspect, "c")
end
def test_context_is_only_on_instance
t1 = Main.new(:context=>{"m"=>"a"})
t2 = Main.new(:context=>{"n"=>"a"})
assert(t1.respond_to?(:m))
assert(!t1.respond_to?(:n))
assert(!t2.respond_to?(:m))
assert(t2.respond_to?(:n))
end
def test_render
b = Main.new(:context=>{"m"=>"a", "n"=>"b"}).get_binding
expected = "Hi a and b"
actual = Template::RenderWithErb.("Hi <%= m %> and <%= n %>", b)
assert_equal(actual, expected)
b = Main.new(:context=>{"inspect"=>"a"}).get_binding
expected = "Hi a"
actual = Template::RenderWithErb.("Hi <%= inspect %>", b)
assert_equal(actual, expected)
end
end
|
Include auth token in snapshot post | require 'curb'
module Snapme
class Snapper
attr_reader :command, :host, :interval
def initialize(host, interval, command = ImagesnapCommand.new)
@command = command
@host = host
@interval = interval
end
def run(looping = true)
loop do
take_snapshot
post_snapshot
break unless looping
sleep(interval)
end
end
def endpoint_url
"#{host}/snapshot"
end
def filename
'/tmp/snapshot.jpg'
end
private
def take_snapshot
command.call(filename)
end
def post_snapshot
curl.http_post(file)
end
def curl
@curl ||= Curl::Easy.new(endpoint_url).tap do |curl|
curl.multipart_form_post = true
end
end
def file
Curl::PostField.file('snapshot', filename)
end
end
end
| require 'curb'
module Snapme
class Snapper
attr_reader :command, :host, :interval
def initialize(host, interval, command = ImagesnapCommand.new)
@command = command
@host = host
@interval = interval
end
def run(looping = true)
loop do
take_snapshot
post_snapshot
break unless looping
sleep(interval)
end
end
def endpoint_url
"#{host}/snapshot"
end
def filename
'/tmp/snapshot.jpg'
end
private
def take_snapshot
command.call(filename)
end
def post_snapshot
curl.http_post(file, auth_token)
end
def curl
@curl ||= Curl::Easy.new(endpoint_url).tap do |curl|
curl.multipart_form_post = true
end
end
def auth_token
Curl::PostField.content('auth_token', ENV['AUTH_TOKEN'])
end
def file
Curl::PostField.file('snapshot', filename)
end
end
end
|
Test code for pad array | =begin
pseudocode
#create destructive + non-destructive methods
#input for those methods is an array, mn-len, value to pad with
#compare the array length with the min-size to check if we need padding
# if we need padding apply (min-size - array.len ) = number
# value * print it number of times
#return array
#lookup binding.pry
=end
def pad!(array, min_size, value = nil)
if array.length < min_size
binding.pry
array.concat([value]*(min_size - array.length))
end
return array
end
def pad(array, min_size, value = nil)
if array.length < min_size
diff = (min_size)-(array.length)
new_arr = array + [value]*diff
else
new_arr = Array.new(array)
end
return new_arr
end
# def pad!(array, min_size, value = nil) #destructive
# if min_size <= array.length
# #checking if input of min_size is less than th length of array
# return array
# elsif min_size == 0
# return array
# else
# counter = array.length
# until counter == min_size
# array.push(value)
# counter +=1
# end
# end
# return array
# end
# pad!([1,2,3], 9, "apple")
# def pad(array, min_size, value = nil) #non-destructive
# new_array = Array.new(array)
# if min_size <= array.length
# return array
# elsif min_size == 0
# return array
# else
# counter = array.length
# until counter == min_size
# new_array.push(value)
# counter +=1
# end
# end
# return new_array
# end
pad([1,2,3,], 9, "apple")
# # Your previous JavaScript content is preserved below:
#
# # This pad is reserved for a member of the Sea Lions 2016
| |
Fix terms of service feature test. | require 'spec_helper'
describe "Uploading files via web form", :type => :feature do
before do
sign_in :user
click_link "Upload"
end
it "should have an ingest screen" do
expect(page).to have_content "Select files"
expect(page).to have_content "Start upload"
expect(page).to have_content "Cancel upload"
expect(page).to have_xpath '//input[@type="file"]'
end
context "the terms of service", :js do
it "should be required to be checked" do
attach_file("files[]", File.dirname(__FILE__)+"/../../spec/fixtures/image.jp2")
attach_file("files[]", File.dirname(__FILE__)+"/../../spec/fixtures/jp2_fits.xml")
expect(page).to have_css("button#main_upload_start[disabled]")
find('#main_upload_start_span').hover do
expect(page).to have_content "Please accept Deposit Agreement before you can upload."
end
end
end
end
| require 'spec_helper'
describe "Uploading files via web form", :type => :feature do
before do
sign_in :user
click_link "Upload"
end
it "should have an ingest screen" do
expect(page).to have_content "Select files"
expect(page).to have_content "Start upload"
expect(page).to have_content "Cancel upload"
expect(page).to have_xpath '//input[@type="file"]'
end
context "the terms of service", :js do
it "should be required to be checked" do
attach_file("files[]", File.dirname(__FILE__)+"/../../spec/fixtures/image.jp2")
attach_file("files[]", File.dirname(__FILE__)+"/../../spec/fixtures/jp2_fits.xml")
expect(page).to have_css("button#main_upload_start[disabled]")
find('#main_upload_start_span').hover
expect(page).to have_content "Please accept Deposit Agreement before you can upload."
end
end
end
|
Update to using Realm lower than 2.0.3. | Pod::Spec.new do |s|
s.name = "JYObjectModule"
s.version = "0.0.25"
s.summary = "A module of models definition."
s.description = <<-DESC
A module of models definition on iOS platform for jiangyou tec. only.
DESC
s.homepage = "https://github.com/jiangtour/JYObjectModule"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "aiXing" => "862099730@qq.com" }
s.platform = :ios, "7.0"
s.source = { :git => "https://github.com/jiangtour/JYObjectModule.git", :tag => "0.0.25" }
s.source_files = "JYObjectModule/Models/*.{h,m}", "JYObjectModule/Models/Normal/*.{h,m}", "JYObjectModule/Models/Storage/*.{h,m}"
s.frameworks = "Foundation"
s.requires_arc = true
s.dependency "Realm"
s.dependency "MJExtension"
s.dependency "SDWebImage"
s.dependency "CocoaSecurity"
s.dependency "UICKeyChainStore"
end
| Pod::Spec.new do |s|
s.name = 'JYObjectModule'
s.version = '0.0.26'
s.summary = 'A module of models definition.'
s.description = <<-DESC
A module of models definition on iOS platform for jiangyou tec. only.
DESC
s.homepage = 'https://github.com/jiangtour/JYObjectModule'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'aiXing' => '862099730@qq.com' }
s.platform = :ios, '7.0'
s.source = { :git => 'https://github.com/jiangtour/JYObjectModule.git', :tag => '0.0.26' }
s.source_files = 'JYObjectModule/Models/*.{h,m}', 'JYObjectModule/Models/Normal/*.{h,m}', 'JYObjectModule/Models/Storage/*.{h,m}'
s.frameworks = 'Foundation'
s.requires_arc = true
s.dependency 'Realm', '<= 1.0.7'
s.dependency 'MJExtension'
s.dependency 'SDWebImage'
s.dependency 'CocoaSecurity'
s.dependency 'UICKeyChainStore'
end
|
Create a location where database drivers can be downloaded | #
# Copyright 2012, Peter Donald
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
include_recipe 'java::default'
a = archive 'sqlshell' do
url node['sqlshell']['package']['url']
version node['sqlshell']['package']['version']
end
node.override['sqlshell']['base_directory'] = a.base_directory
node.override['sqlshell']['package']['local_archive'] = a.target_artifact
| #
# Copyright 2012, Peter Donald
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
include_recipe 'java::default'
a = archive 'sqlshell' do
url node['sqlshell']['package']['url']
version node['sqlshell']['package']['version']
end
node.override['sqlshell']['base_directory'] = a.base_directory
node.override['sqlshell']['lib'] = "#{a.base_directory}/lib"
directory node['sqlshell']['lib']
node.override['sqlshell']['package']['local_archive'] = a.target_artifact
|
Use a lock in CreateGame service | class CreateGame
AI_NAMES = [
'Bill',
'John',
'Sally',
'Andy',
'Joseph',
"Tony",
"Jim",
"Ella",
"Amy",
"Eric",
]
def initialize(player_count, player_name=nil)
@player_count = player_count
@player_name = player_name
end
def call
Game.transaction do
players = [ Player.create!(:name => player_name) ]
ai_count = @player_count - 1
players += ai_count.times.map do
Player.create!(:name => AI_NAMES.sample)
end
Game.create!(:players => players,
:initial_dealer_id => random_player(players).id,
:initial_trump => random_suit)
end
end
private
def player_name
if @player_name.nil? || @player_name.strip.empty?
AI_NAMES.sample
else
@player_name.capitalize
end
end
def random_player(players)
players.sample
end
def random_suit
Card::SUITS.sample
end
end
| class CreateGame
AI_NAMES = [
'Bill',
'John',
'Sally',
'Andy',
'Joseph',
"Tony",
"Jim",
"Ella",
"Amy",
"Eric",
]
def initialize(player_count, player_name=nil)
@player_count = player_count
@player_name = player_name
end
def call
ai_count = @player_count - 1
ai_count.times.map { create_ai }
game = Game.create!(:players => players,
:initial_dealer_id => random_player(players).id,
:initial_trump => random_suit)
game.with_lock do
game.players.create!(:name => AI_NAMES.sample)
end
end
private
def player_name
if @player_name.nil? || @player_name.strip.empty?
AI_NAMES.sample
else
@player_name.capitalize
end
end
def random_player(players)
players.sample
end
def random_suit
Card::SUITS.sample
end
end
|
Add type and value_for attributes to user hash | # frozen_string_literal: true
module ActivityValuesModel
extend ActiveSupport::Concern
# rubocop:disable Style/ClassVars
@@default_values = HashWithIndifferentAccess.new
# rubocop:enable Style/ClassVars
included do
serialize :values, JsonbHashSerializer
after_initialize :init_default_values, if: :new_record?
before_create :add_user
end
class_methods do
def default_values(dfs)
@@default_values.merge!(dfs)
end
end
protected
def init_default_values
self.values = @@default_values
end
def add_user
message_items.merge!(user: { id: owner.id, value: owner.full_name })
end
end
| # frozen_string_literal: true
module ActivityValuesModel
extend ActiveSupport::Concern
# rubocop:disable Style/ClassVars
@@default_values = HashWithIndifferentAccess.new
# rubocop:enable Style/ClassVars
included do
serialize :values, JsonbHashSerializer
after_initialize :init_default_values, if: :new_record?
before_create :add_user
end
class_methods do
def default_values(dfs)
@@default_values.merge!(dfs)
end
end
protected
def init_default_values
self.values = @@default_values
end
def add_user
message_items.merge!(user: { id: owner.id,
value: owner.full_name,
type: 'User',
value_for: 'full_name' })
end
end
|
Check if models_config exists to support migrations of existing systems. | # update settings for searchable models
if ActiveRecord::Base.connection.tables.include?('settings')
models_current = Models.searchable.map(&:to_s)
models_config = Setting.get('models_searchable')
if models_current != models_config
Setting.set('models_searchable', models_current)
end
end
| # update settings for searchable models
if ActiveRecord::Base.connection.tables.include?('settings')
models_current = Models.searchable.map(&:to_s)
models_config = Setting.get('models_searchable')
if models_config && models_current != models_config
Setting.set('models_searchable', models_current)
end
end
|
Add refactored concatenate arrays solution | # Concatenate Two Arrays
# I worked on this challenge by myself.
# Your Solution Below
def array_concat(array_1, array_2)
# Your code here
if (array_1.length == 0) && (array_2.length == 0)
return []
else
return array_1 + array_2
end
end | # Concatenate Two Arrays
# I worked on this challenge by myself.
# Your Solution Below
=begin Initial Solution
def array_concat(array_1, array_2)
# Your code here
if (array_1.length == 0) && (array_2.length == 0)
return []
else
return array_1 + array_2
end
end
=end
#Refactored Solution
def array_concat(array_1, array_2)
# Your code here
return array_1.concat(array_2)
end |
Remove unnecessary references to "self" | class LoadProfilesController < ResourceController
RESOURCE_ACTIONS = %i(show edit update destroy)
before_filter :fetch_load_profile, only: self::RESOURCE_ACTIONS
before_filter :authorize_generic, except: self::RESOURCE_ACTIONS
respond_to :html
respond_to :json, only: :show
def index
skip_policy_scope
@load_profile_categories = LoadProfileCategory.where(parent_id: nil)
end
# GET /load_profiles
def show
end
# GET /load_profiles/new
def new
@load_profile = LoadProfile.new
end
# POST /load_profiles
def create
@load_profile = current_user.load_profiles.create(load_profile_params)
respond_with(@load_profile)
end
# GET /load_profiles/:id/edit
def edit
end
# PATCH /load_profiles/:id
def update
@load_profile.update_attributes(load_profile_params)
respond_with(@load_profile)
end
# DELETE /load_profiles/:id
def destroy
@load_profile.destroy
redirect_to(load_profiles_url)
end
#######
private
#######
def fetch_load_profile
@load_profile = LoadProfile.find(params[:id])
authorize @load_profile
end
def load_profile_params
params.require(:load_profile).permit(
:key, :name, :curve, :load_profile_category_id,
{ technology_profiles_attributes: [:id, :technology, :_destroy] }
)
end
end
| class LoadProfilesController < ResourceController
RESOURCE_ACTIONS = %i(show edit update destroy)
before_filter :fetch_load_profile, only: RESOURCE_ACTIONS
before_filter :authorize_generic, except: RESOURCE_ACTIONS
respond_to :html
respond_to :json, only: :show
def index
skip_policy_scope
@load_profile_categories = LoadProfileCategory.where(parent_id: nil)
end
# GET /load_profiles
def show
end
# GET /load_profiles/new
def new
@load_profile = LoadProfile.new
end
# POST /load_profiles
def create
@load_profile = current_user.load_profiles.create(load_profile_params)
respond_with(@load_profile)
end
# GET /load_profiles/:id/edit
def edit
end
# PATCH /load_profiles/:id
def update
@load_profile.update_attributes(load_profile_params)
respond_with(@load_profile)
end
# DELETE /load_profiles/:id
def destroy
@load_profile.destroy
redirect_to(load_profiles_url)
end
#######
private
#######
def fetch_load_profile
@load_profile = LoadProfile.find(params[:id])
authorize @load_profile
end
def load_profile_params
params.require(:load_profile).permit(
:key, :name, :curve, :load_profile_category_id,
{ technology_profiles_attributes: [:id, :technology, :_destroy] }
)
end
end
|
Add additional solution to concatenate challenge | # Concatenate Two Arrays
# I worked on this challenge [by myself].
# Your Solution Below
def array_concat(array_1, array_2)
array_1 + array_2
end
| # Concatenate Two Arrays
# I worked on this challenge [by myself].
# Your Solution Below
def array_concat(array_1, array_2)
array_1 + array_2
end
|
Add spec for Devise configuration | require 'spec_helper'
require 'rails_app_helper'
RSpec.describe 'rails_app project' do
describe 'Rails.root' do
it 'contains project path in sub directory' do
expect(Rails.root.to_s).to match(/spec\/rails_app/)
end
end
end
| require 'spec_helper'
require 'rails_app_helper'
RSpec.describe 'rails_app project' do
describe 'Rails.root' do
it 'contains project path in sub directory' do
expect(Rails.root.to_s).to match(/spec\/rails_app/)
end
end
describe 'Devise settings' do
subject { Devise.mappings[:user] }
it { should be_truthy }
end
end
|
Add a spec for validation error message | require 'spec_helper'
describe "password" do
it "should accept nil password" do
u = User.new(:name => 'alice', :password => nil)
u.should be_valid
end
it "should reject blank password" do
u = User.new(:name => 'alice', :password => '')
u.should_not be_valid
u.should have(1).error_on(:password)
end
end
| require 'spec_helper'
describe "password" do
it "should accept nil password" do
u = User.new(:name => 'alice', :password => nil)
u.should be_valid
end
it "should reject blank password" do
u = User.new(:name => 'alice', :password => '')
u.should_not be_valid
u.should have(1).error_on(:password)
u.errors[:password].first.should == "can't be blank"
end
end
|
Add util to merge identical party memberships | module Hdo
module Utils
class PartyMembershipMerger
def duplicates
dups = {}
reps = Representative.joins(:party_memberships).where('(select count(*) from party_memberships where representative_id = representatives.id) > 1').all
reps.each do |r|
memberships = r.party_memberships
dups[r] = memberships if memberships.map(&:party_id).uniq.size == 1
end
dups
end
def print
duplicates.each do |rep, memberships|
puts rep.name
memberships.each { |ms| print_membership ms }
end
end
def merge!
duplicates.each do |rep, memberships|
party = memberships.first.party
start_date = memberships.map(&:start_date).min
end_date = memberships.any?(&:open_ended?) ? nil : memberships.map(&:end_date).max
puts "merging memberships for #{rep.name}"
puts "from"
memberships.each { |ms| print_membership ms }
rep.party_memberships.clear
ms = rep.party_memberships.create!(start_date: start_date, end_date: end_date, party: party)
puts "to"
print_membership(ms)
end
end
private
def print_membership(ms)
puts "\t#{ms.party.name}: #{ms.start_date} .. #{ms.end_date}"
end
end
end
end | |
Implement to_s for pretty messages in the log. | # -*- encoding: utf-8 -*-
require 'watch_tower/appscript'
module WatchTower
module Editor
module BaseAppscript
def self.included(base)
base.send :include, InstanceMethods
end
module InstanceMethods
def self.included(base)
base.class_eval <<-END, __FILE__, __LINE__ + 1
# Include AppScript
include ::Appscript
# Is the editor running ?
#
# @return [Boolean]
def is_running?
editor.is_running? if editor
end
# Returns the name of the editor
#
# Child class should implement this method
def name
editor.try(:name).try(:get)
end
# Returns the version of the editor
#
# Child class should implement this method
def version
editor.try(:version).try(:get)
end
# Return the path of the document being edited
# Child classes can override this method if the behaviour is different
#
# @return [String] path to the document currently being edited
def current_path
current_paths.try(:first)
end
# Return the pathes of the documents being edited
# Child classes can override this method if the behaviour is different
#
# @return [Array] pathes to the documents currently being edited
def current_paths
if is_running? && editor.respond_to?(:document)
editor.document.get.collect(&:path).collect(&:get)
end
end
END
end
end
end
end
end | # -*- encoding: utf-8 -*-
require 'watch_tower/appscript'
module WatchTower
module Editor
module BaseAppscript
def self.included(base)
base.send :include, InstanceMethods
end
module InstanceMethods
def self.included(base)
base.class_eval <<-END, __FILE__, __LINE__ + 1
# Include AppScript
include ::Appscript
# Is the editor running ?
#
# @return [Boolean]
def is_running?
editor.is_running? if editor
end
# Returns the name of the editor
#
# Child class should implement this method
def name
editor.try(:name).try(:get)
end
# Returns the version of the editor
#
# Child class should implement this method
def version
editor.try(:version).try(:get)
end
# Return the path of the document being edited
# Child classes can override this method if the behaviour is different
#
# @return [String] path to the document currently being edited
def current_path
current_paths.try(:first)
end
# Return the pathes of the documents being edited
# Child classes can override this method if the behaviour is different
#
# @return [Array] pathes to the documents currently being edited
def current_paths
if is_running? && editor.respond_to?(:document)
editor.document.get.collect(&:path).collect(&:get)
end
end
# The editor's name for the log
# Child classes can overwrite this method
#
# @return [String]
def to_s
"\#{self.class.to_s.split('::').last} Editor"
end
END
end
end
end
end
end |
Add period for summary in podspec. | Pod::Spec.new do |s|
name = "SHMessageUIBlocks"
url = "https://github.com/seivan/#{name}"
git_url = "#{url}.git"
s.name = name
version = "1.0.0"
source_files = "#{name}/**/*.{h,m}"
s.version = version
s.summary = "CompletionBlocks for MFMailComposeViewController and MFMessageComposeViewController (MessageUI framework)"
s.description = <<-DESC
* Swizzle and junk free
* No need to clean up after - The control blocks are self maintained.
* The controllers are referenced in a map with weak properties
* Prefixed selectors.
* Minimum clutter on top of the public interface.
DESC
s.homepage = url
s.license = 'MIT'
s.author = { "Seivan Heidari" => "seivan.heidari@icloud.com" }
s.source = { :git => git_url, :tag => version}
s.ios.framework = 'MessageUI'
s.platform = :ios, "6.0"
s.source_files = source_files
s.requires_arc = true
end
| Pod::Spec.new do |s|
name = "SHMessageUIBlocks"
url = "https://github.com/seivan/#{name}"
git_url = "#{url}.git"
s.name = name
version = "1.0.0"
source_files = "#{name}/**/*.{h,m}"
s.version = version
s.summary = "CompletionBlocks for MFMailComposeViewController and MFMessageComposeViewController (MessageUI framework)."
s.description = <<-DESC
* Swizzle and junk free
* No need to clean up after - The control blocks are self maintained.
* The controllers are referenced in a map with weak properties
* Prefixed selectors.
* Minimum clutter on top of the public interface.
DESC
s.homepage = url
s.license = 'MIT'
s.author = { "Seivan Heidari" => "seivan.heidari@icloud.com" }
s.source = { :git => git_url, :tag => version}
s.ios.framework = 'MessageUI'
s.platform = :ios, "6.0"
s.source_files = source_files
s.requires_arc = true
end
|
Update Google Play Music Manager (1.0.243.1116) | cask 'music-manager' do
version '1.0.216.5719'
sha256 '948967d9325bde3e7344504e965dbcd9f94bee01512f4c49ad3e4d9425798f11'
url "https://dl.google.com/dl/androidjumper/mac/#{version.sub(%r{^\d+\.\d+\.}, '').delete('.')}/musicmanager.dmg"
name 'Google Play Music Manager'
homepage 'https://play.google.com/music/'
license :unknown # TODO: change license and remove this comment; ':unknown' is a machine-generated placeholder
# Renamed for consistency: app name is different in the Finder and in a shell.
# Original discussion: https://github.com/caskroom/homebrew-cask/pull/4282
app 'MusicManager.app', target: 'Music Manager.app'
end
| cask 'music-manager' do
version '1.0.243.1116'
sha256 'e425d1724d092ae5ddfb28ad4304439754394b91ab3ff3063b66196d2ffe4bee'
url "https://dl.google.com/dl/androidjumper/mac/#{version.sub(%r{^\d+\.\d+\.}, '').delete('.')}/musicmanager.dmg"
name 'Google Play Music Manager'
homepage 'https://play.google.com/music/'
license :unknown # TODO: change license and remove this comment; ':unknown' is a machine-generated placeholder
# Renamed for consistency: app name is different in the Finder and in a shell.
# Original discussion: https://github.com/caskroom/homebrew-cask/pull/4282
app 'MusicManager.app', target: 'Music Manager.app'
end
|
Add rspec-puppet-facts (omitted from a previos commit), and set a puppetversion fact from an environment variable | require 'puppetlabs_spec_helper/module_spec_helper'
| require 'puppetlabs_spec_helper/module_spec_helper'
require 'rspec-puppet-facts'
include RspecPuppetFacts
RSpec.configure do |c|
c.default_facts = {
:puppetversion => ENV['PUPPET_VERSION'] || '3.7.0'
}
end
|
Replace manual accessor with attr_reader | module Prezzo
module Calculator
def initialize(context = {})
@context = validated!(context)
end
def calculate
raise "Calculate not implemented"
end
private
def validated!(context)
raise "Empty Context" if context.nil?
raise "Invalid Context" if context.respond_to?(:valid?) && !context.valid?
context
end
def context
@context
end
end
end
| module Prezzo
module Calculator
def initialize(context = {})
@context = validated!(context)
end
def calculate
raise "Calculate not implemented"
end
private
attr_reader :context
def validated!(context)
raise "Empty Context" if context.nil?
raise "Invalid Context" if context.respond_to?(:valid?) && !context.valid?
context
end
end
end
|
Add a little test for the helper | require 'rails_helper'
describe ApplicationHelper do
describe '.up_downify' do
it 'adds a down arrow icon for negative starts' do
expect(helper.up_downify('+10%')).to include('<i')
expect(helper.up_downify('+10%')).to include('up')
end
it 'adds an up arrow icon for positive starts' do
expect(helper.up_downify('-10%')).to include('<i')
expect(helper.up_downify('-10%')).to include('down')
end
it 'does not add other strings' do
expect(helper.up_downify('hello')).to_not include('<i')
expect(helper.up_downify('hello + goodbye')).to_not include('<i')
end
end
end
| require 'rails_helper'
describe ApplicationHelper do
describe '.up_downify' do
it 'adds a down arrow icon for negative starts' do
expect(helper.up_downify('+10%')).to include('<i')
expect(helper.up_downify('+10%')).to include('up')
end
it 'adds an up arrow icon for positive starts' do
expect(helper.up_downify('-10%')).to include('<i')
expect(helper.up_downify('-10%')).to include('down')
end
it 'does not add other strings' do
expect(helper.up_downify('hello')).to_not include('<i')
expect(helper.up_downify('hello + goodbye')).to_not include('<i')
end
end
describe 'last signed in helper' do
it 'shows a message if a user has never signed in' do
expect(display_last_signed_in_as(build(:user))).to eq 'Never signed in'
end
it 'shows the last time as user signed in' do
last_sign_in_at = DateTime.new(2001,2,3,4,5,6)
expect(display_last_signed_in_as(build(:user, last_sign_in_at: last_sign_in_at))).to eq nice_date_times(last_sign_in_at)
end
end
end
|
Add index to users root_account_ids | #
# Copyright (C) 2020 - present Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3 of the License.
#
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
class AddIndexToUsersRootAccountIds < ActiveRecord::Migration[5.2]
tag :postdeploy
disable_ddl_transaction!
def change
add_index :users, :root_account_ids, algorithm: :concurrently, using: :gin, if_not_exists: true
end
end
| |
Add a minor optimization, don't bother bootstrapping Puppet if it's already in our PATH | require 'blimpy/livery/base'
require 'blimpy/livery/cwd'
module Blimpy
module Livery
class Puppet < CWD
attr_accessor :module_path, :manifest_path, :options
def initialize(*args)
super
@module_path = './modules'
@manifest_path = 'manifests/site.pp'
@options = '--verbose'
end
def script
'puppet.sh'
end
def flight(box)
# This should get our puppet.sh bootstrap script run
super(box)
# At this point we should be safe to actually invoke Puppet
command = "puppet apply --modulepath=#{module_path} #{options} #{manifest_path}"
if use_sudo?(box)
box.ssh_into("sudo #{command}")
else
box.ssh_into(command)
end
end
def postflight(box)
end
def bootstrap_script
File.expand_path(File.dirname(__FILE__) + "/../../../scripts/#{script}")
end
def self.configure(&block)
if block.nil?
raise Blimpy::InvalidLiveryException, "Puppet livery must be given a block in order to configure itself"
end
instance = self.new
yield instance
instance
end
end
end
end
| require 'blimpy/livery/base'
require 'blimpy/livery/cwd'
module Blimpy
module Livery
class Puppet < CWD
attr_accessor :module_path, :manifest_path, :options
def initialize(*args)
super
@module_path = './modules'
@manifest_path = 'manifests/site.pp'
@options = '--verbose'
@puppet_exists = false
end
def script
'puppet.sh'
end
def preflight(box)
# If we find Puppet in our default path, we don't really need to send
# the bootstrap script again
@puppet_exists = box.ssh_into('which puppet > /dev/null')
unless @puppet_exists
super(box)
end
end
def flight(box)
unless @puppet_exists
# This should get our puppet.sh bootstrap script run
super(box)
end
# At this point we should be safe to actually invoke Puppet
command = "puppet apply --modulepath=#{module_path} #{options} #{manifest_path}"
run_sudo = ''
run_sudo = 'sudo' if use_sudo?(box)
box.ssh_into("cd #{dir_name} && #{run_sudo} #{command}")
end
def postflight(box)
end
def bootstrap_script
File.expand_path(File.dirname(__FILE__) + "/../../../scripts/#{script}")
end
def self.configure(&block)
if block.nil?
raise Blimpy::InvalidLiveryException, "Puppet livery must be given a block in order to configure itself"
end
instance = self.new
yield instance
instance
end
end
end
end
|
Remove moped dependency as Mongoid should fetch it | # encoding: utf-8
lib = File.expand_path('../lib/', __FILE__)
$:.unshift lib unless $:.include?(lib)
require "kiqstand/version"
Gem::Specification.new do |s|
s.name = "kiqstand"
s.version = Kiqstand::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Durran Jordan"]
s.email = ["durran@gmail.com"]
s.homepage = "http://mongoid.org"
s.summary = "Mongoid Middleware for Sidekiq"
s.description = s.summary
s.required_rubygems_version = ">= 1.3.6"
s.rubyforge_project = "kiqstand"
s.add_dependency("mongoid", ["~> 4.0"])
s.add_dependency("moped", ["~> 1.4"])
s.files = Dir.glob("lib/**/*") + %w(CHANGELOG.md LICENSE README.md Rakefile)
s.require_path = 'lib'
end
| # encoding: utf-8
lib = File.expand_path('../lib/', __FILE__)
$:.unshift lib unless $:.include?(lib)
require "kiqstand/version"
Gem::Specification.new do |s|
s.name = "kiqstand"
s.version = Kiqstand::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Durran Jordan"]
s.email = ["durran@gmail.com"]
s.homepage = "http://mongoid.org"
s.summary = "Mongoid Middleware for Sidekiq"
s.description = s.summary
s.required_rubygems_version = ">= 1.3.6"
s.rubyforge_project = "kiqstand"
s.add_dependency("mongoid", ["~> 4.0"])
s.files = Dir.glob("lib/**/*") + %w(CHANGELOG.md LICENSE README.md Rakefile)
s.require_path = 'lib'
end
|
Remove deprecated has_key method. Replace for key? | class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :set_locale
private
# Set locale from URI param. When not available, default to english.
# If already set and not present on URI, use the one set in session.
def set_locale
if params.has_key?(:lang) && session[:locale] != params[:lang]
case params[:lang]
when 'en'
locale = :en
when 'es'
locale = :es
else
locale = :en
end
session[:locale] = locale
end
I18n.locale = session[:locale]
end
end
| class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :set_locale
private
# Set locale from URI param. When not available, default to english.
# If already set and not present on URI, use the one set in session.
def set_locale
if params.key?(:lang) && session[:locale] != params[:lang]
case params[:lang]
when 'en'
locale = :en
when 'es'
locale = :es
else
locale = :en
end
session[:locale] = locale
end
I18n.locale = session[:locale]
end
end
|
Add deprecation warning when using the Runit init system | # include helper methods
class ::Chef::Recipe
include ::Opscode::ChefClient::Helpers
end
# libraries/helpers.rb method to DRY directory creation resources
client_bin = find_chef_client
Chef::Log.debug("Found chef-client in #{client_bin}")
node.default['chef_client']['bin'] = client_bin
create_directories
include_recipe 'runit' # ~FC007: runit is only required when using the runit_service recipe
runit_service 'chef-client'
| # include helper methods
class ::Chef::Recipe
include ::Opscode::ChefClient::Helpers
end
Chef::Log.warn("Running chef-client under the Runit init system is deprecated. Please consider running under your native init system instead.")
# libraries/helpers.rb method to DRY directory creation resources
client_bin = find_chef_client
Chef::Log.debug("Found chef-client in #{client_bin}")
node.default['chef_client']['bin'] = client_bin
create_directories
include_recipe 'runit' # ~FC007: runit is only required when using the runit_service recipe
runit_service 'chef-client'
|
Use chef conditionals for tzdata package selection | #
# Cookbook Name:: timezone
# Recipe:: default
#
# Copyright 2010, James Harton <james@sociable.co.nz>
#
# Apache 2.0 License.
#
case node.platform
when ['debian','ubuntu']
# Make sure it's installed. It would be a pretty broken system
# that didn't have it.
platform_version = node.platform_version.to_f
if platform_version >= 12.04 && platform_version < 14.04
package "tzdata" do
version "2012b-1"
options "--force-yes"
end
else
package "tzdata"
end
template "/etc/timezone" do
source "timezone.conf.erb"
owner 'root'
group 'root'
mode 0644
notifies :run, 'bash[dpkg-reconfigure tzdata]'
end
bash 'dpkg-reconfigure tzdata' do
user 'root'
code "/usr/sbin/dpkg-reconfigure -f noninteractive tzdata"
action :nothing
end
end
| #
# Cookbook Name:: timezone
# Recipe:: default
#
# Copyright 2010, James Harton <james@sociable.co.nz>
#
# Apache 2.0 License.
#
case node.platform
when ['debian','ubuntu']
package "tzdata" do
version "2012b-1"
options "--force-yes"
only_if { node['lsb']['codename'] == 'precise' }
end
package "tzdata" do
not_if { node['lsb']['codename'] == 'precise' }
end
template "/etc/timezone" do
source "timezone.conf.erb"
owner 'root'
group 'root'
mode 0644
notifies :run, 'bash[dpkg-reconfigure tzdata]'
end
bash 'dpkg-reconfigure tzdata' do
user 'root'
code "/usr/sbin/dpkg-reconfigure -f noninteractive tzdata"
action :nothing
end
end
|
Fix reversed logic in auth | class ExercismApp < Sinatra::Base
get '/' do
if current_user.guest?
erb :index
else
pending = Submission.pending.select do |submission|
current_user.may_nitpick?(submission.exercise)
end
unstarted = Exercism.current_curriculum.unstarted_trails(current_user.current_languages)
if current_user.admin?
erb :admin, locals: {pending: pending, unstarted: unstarted}
else
erb :dashboard, locals: {pending: pending, unstarted: unstarted}
end
end
end
get '/account' do
unless current_user.guest?
flash[:error] = 'You must log in to go there.'
redirect '/'
end
erb :account
end
end
| class ExercismApp < Sinatra::Base
get '/' do
if current_user.guest?
erb :index
else
pending = Submission.pending.select do |submission|
current_user.may_nitpick?(submission.exercise)
end
unstarted = Exercism.current_curriculum.unstarted_trails(current_user.current_languages)
if current_user.admin?
erb :admin, locals: {pending: pending, unstarted: unstarted}
else
erb :dashboard, locals: {pending: pending, unstarted: unstarted}
end
end
end
get '/account' do
if current_user.guest?
flash[:error] = 'You must log in to go there.'
redirect '/'
end
erb :account
end
end
|
Update Minco app to latest version: 2.0.23 | cask :v1 => 'minco' do
version '2.0.22'
sha256 'bf98d80e0273552559ae7b98ba411d62ccdca66ddd9f2f274bd2aa2cdcd44c58'
# webpack.com is the official download host per the appcast feed
url "https://ssl.webpack.de/celmaro.com/updates/minco2/Minco#{version.delete('.')}.zip"
appcast 'https://ssl.webpack.de/celmaro.com/updates/minco2/minco.xml',
:sha256 => '3ab9e6d0a6e9ebecfeab805c399a7194fe2a88bdcc1b096446e9f8be7e7195f8'
name 'Minco'
homepage 'http://www.celmaro.com/minco/'
license :commercial
depends_on :macos => '>= :yosemite'
depends_on :arch => :x86_64
app 'Minco.app'
end
| cask :v1 => 'minco' do
version '2.0.23'
sha256 'e8acbfb029f8df05f62164168653f0605aa0a11207c0b0fa255454ec033dea26'
# webpack.com is the official download host per the appcast feed
url "https://ssl.webpack.de/celmaro.com/updates/minco2/Minco#{version.delete('.')}.zip"
appcast 'https://ssl.webpack.de/celmaro.com/updates/minco2/minco.xml',
:sha256 => 'e8acbfb029f8df05f62164168653f0605aa0a11207c0b0fa255454ec033dea26'
name 'Minco'
homepage 'http://www.celmaro.com/minco/'
license :commercial
depends_on :macos => '>= :yosemite'
depends_on :arch => :x86_64
app 'Minco.app'
end
|
Make sure podspec requires arc | Pod::Spec.new do |s|
s.name = 'ZWEmoji'
s.version = '0.3.0'
s.license = 'MIT'
s.summary = 'Objective-C library for using unicode emoji based on emoji codes used in Campfire/GitHub'
s.homepage = 'https://github.com/zachwaugh/ZWEmoji'
s.authors = { 'Zach Waugh' => 'zwaugh@gmail.com'}
s.source = { :git => 'https://github.com/zachwaugh/ZWEmoji.git', :tag => '0.3.0'}
s.source_files = 'lib'
end | Pod::Spec.new do |s|
s.name = 'ZWEmoji'
s.version = '0.3.1'
s.license = 'MIT'
s.summary = 'Objective-C library for using unicode emoji based on emoji codes used in Campfire/GitHub'
s.homepage = 'https://github.com/zachwaugh/ZWEmoji'
s.authors = { 'Zach Waugh' => 'zwaugh@gmail.com'}
s.source = { :git => 'https://github.com/zachwaugh/ZWEmoji.git', :tag => "#{s.version}"}
s.source_files = 'lib'
s.requires_arc = true
end |
Set content type to text to avoid rending HTML | require "sinatra"
require "sqlite3"
set(:startup_hook) do
database_file = "#{environment}.db"
first_run = !File.exist?(database_file)
set(:db, SQLite3::Database.new(database_file))
if first_run
db.execute <<-SQL
CREATE TABLE pastes (
name VARCHAR(30),
body BLOB
)
SQL
end
end
configure do
Sinatra::Application.startup_hook
end
helpers do
def execute(sql, bindings)
Sinatra::Application.db.execute(sql, bindings)
end
def create_paste(name, body)
execute("INSERT INTO PASTES (name, body) VALUES (?, ?)", [name, body])
end
def find_paste(name)
execute("SELECT body FROM pastes WHERE name = ?", [name]).flatten.first
end
end
get "/" do
erb :usage
end
post "/" do
name = SecureRandom.uuid
create_paste(name, request.body.read)
"#{request.base_url}/#{name}"
end
get "/:paste_name" do
body = find_paste(params["paste_name"])
body
end
| require "sinatra"
require "sqlite3"
set(:startup_hook) do
database_file = "#{environment}.db"
first_run = !File.exist?(database_file)
set(:db, SQLite3::Database.new(database_file))
if first_run
db.execute <<-SQL
CREATE TABLE pastes (
name VARCHAR(30),
body BLOB
)
SQL
end
end
configure do
Sinatra::Application.startup_hook
end
helpers do
def execute(sql, bindings)
Sinatra::Application.db.execute(sql, bindings)
end
def create_paste(name, body)
execute("INSERT INTO PASTES (name, body) VALUES (?, ?)", [name, body])
end
def find_paste(name)
execute("SELECT body FROM pastes WHERE name = ?", [name]).flatten.first
end
end
get "/" do
erb :usage
end
post "/" do
name = SecureRandom.uuid
create_paste(name, request.body.read)
"#{request.base_url}/#{name}"
end
get "/:paste_name" do
content_type :text
body = find_paste(params["paste_name"])
body
end
|
Change search implementation, in case an hash arrives it means that is looking for an specific repository | module TicketMaster::Provider
module Github
# Project class for ticketmaster-github
#
#
class Project < TicketMaster::Provider::Base::Project
attr_accessor :prefix_options
API = Octopi::Repository
# declare needed overloaded methods here
def self.find(*options)
first, attributes = options
if first.class == Hash
self::API.find(first)
else
super(first, attributes)
end
end
def self.search(options = {}, limit = 100)
raise "Please supply arguments for search" if options.blank?
self::API.find_all(options)[0...limit]
end
# copy from this.copy(that) copies that into this
def copy(project)
project.tickets.each do |ticket|
copy_ticket = self.ticket!(:title => ticket.title, :description => ticket.description)
ticket.comments.each do |comment|
copy_ticket.comment!(:body => comment.body)
sleep 1
end
end
end
end
end
end
| module TicketMaster::Provider
module Github
# Project class for ticketmaster-github
#
#
class Project < TicketMaster::Provider::Base::Project
attr_accessor :prefix_options
API = Octopi::Repository
# declare needed overloaded methods here
def self.search(options = {}, limit = 100)
raise "Please supply arguments for search" if options.blank?
if options.is_a? Hash
self::API.find(options).to_a
else
self::API.find_all(options)[0...limit]
end
end
# copy from this.copy(that) copies that into this
def copy(project)
project.tickets.each do |ticket|
copy_ticket = self.ticket!(:title => ticket.title, :description => ticket.description)
ticket.comments.each do |comment|
copy_ticket.comment!(:body => comment.body)
sleep 1
end
end
end
end
end
end
|
Add test to check that progress.fraction= doesn't set selection when real is disposed | require 'swt_shoes/spec_helper'
describe Shoes::Swt::Progress do
let(:text) { "TEXT" }
let(:dsl) { double('dsl').as_null_object }
let(:parent) { double('parent') }
let(:real) { double('real', :disposed? => false).as_null_object }
subject { Shoes::Swt::Progress.new dsl, parent }
before :each do
parent.stub(:real)
::Swt::Widgets::ProgressBar.stub(:new) { real }
end
it_behaves_like "movable element"
it "should have a method called fraction=" do
subject.should respond_to :fraction=
end
it "should multiply the value by 100 when calling real.selection" do
real.should_receive(:selection=).and_return(55)
subject.fraction = 0.55
end
it "should round up correctly" do
real.should_receive(:selection=).and_return(100)
subject.fraction = 0.999
end
end
| require 'swt_shoes/spec_helper'
describe Shoes::Swt::Progress do
let(:text) { "TEXT" }
let(:dsl) { double('dsl').as_null_object }
let(:parent) { double('parent') }
let(:real) { double('real', :disposed? => false).as_null_object }
subject { Shoes::Swt::Progress.new dsl, parent }
before :each do
parent.stub(:real)
::Swt::Widgets::ProgressBar.stub(:new) { real }
end
it_behaves_like "movable element"
it "should have a method called fraction=" do
subject.should respond_to :fraction=
end
it "should multiply the value by 100 when calling real.selection" do
real.should_receive(:selection=).and_return(55)
subject.fraction = 0.55
end
it "should round up correctly" do
real.should_receive(:selection=).and_return(100)
subject.fraction = 0.999
end
context "with disposed real element" do
before :each do
real.stub(:disposed?) { true }
end
it "shouldn't set selection" do
real.should_not_receive(:selection=)
subject.fraction = 0.55
end
end
end
|
Fix IterativeProcess early exit (nil transformation). | module Furnace
module Transform
class IterativeProcess
def initialize(stages)
@stages = stages
end
def transform(*sequence)
loop do
changed = false
@stages.each do |stage|
break if stage.nil?
if new_sequence = stage.transform(*sequence)
changed = true
sequence = new_sequence
end
end
return sequence unless changed
end
end
end
end
end
| module Furnace
module Transform
class IterativeProcess
def initialize(stages)
@stages = stages
end
def transform(*sequence)
loop do
changed = false
@stages.each do |stage|
return sequence if stage.nil?
if new_sequence = stage.transform(*sequence)
changed = true
sequence = new_sequence
end
end
return sequence unless changed
end
end
end
end
end
|
Revert "reverted conversations controller to bao's version" | class ConversationsController < ApplicationController
def index
if current_user
@conversations = current_user.conversations
else
flash[:info] = 'Please sign in'
redirect_to new_student_session_path
end
end
def new
end
def create
conversation = Conversation.new
conversation.create_student(id: current_user.id)
# TODO: Match to random, active mentor instead of first mentor
conversation.create_mentor(id: Mentor.first.id)
conversation.save!
# reloads the page
redirect_to :back
end
def show
@conversation = Conversation.find_by(id: params[:slug])
@messages = @conversation.messages
@message = Message.new
end
end
| class ConversationsController < ApplicationController
def index
if current_user
@conversations = current_user.conversations
else
flash[:info] = 'Please sign in'
redirect_to new_student_session_path
end
end
def new
end
def create
if current_user.instance_of? Mentor
flash[:danger] = "A student will initiate conversation."
else
if Mentor.mentor_available_chat?
conversation = Conversation.new
conversation.create_student(id: current_student.id)
mentor = Mentor.first_mentor_available_chat
byebug
mentor.is_available = 0
mentor.save!
conversation.create_mentor(id: mentor.id)
conversation.save!
flash[:success] = "Congradulations! You have been paird with #{mentor.email}"
else
flash[:danger] = "Mentor is not available at the moment"
end
end
redirect_to :back
end
def show
@conversation = Conversation.find_by(id: params[:slug])
@messages = @conversation.messages
@message = Message.new
end
end
|
Set a longer timeout for aruba | require 'cucumber'
require 'rspec'
require 'aruba/cucumber'
Before do
@aruba_timeout_seconds = 10
end
| require 'cucumber'
require 'rspec'
require 'aruba/cucumber'
Before do
@aruba_timeout_seconds = 30
end
|
Update gemspec with readme project description | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/newrelic_moped/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Stephen Bartholomew", "Piotr Sokolowski"]
gem.email = ["stephenbartholomew@gmail.com"]
gem.description = %q{New Relic Instrumentation for Moped & Mongoid 3}
gem.summary = %q{New Relic Instrumentation for Moped & Mongoid 3}
gem.homepage = "https://github.com/stevebartholomew/newrelic_moped"
gem.license = "MIT"
gem.files = Dir["{lib}/**/*.rb", "LICENSE", "*.md"]
gem.name = "newrelic_moped"
gem.require_paths = ["lib"]
gem.version = NewrelicMoped::VERSION
gem.add_dependency 'newrelic_rpm', '~> 3.11'
gem.add_dependency 'moped'
gem.add_development_dependency 'rake'
gem.add_development_dependency 'test-unit'
end
| # -*- encoding: utf-8 -*-
require File.expand_path('../lib/newrelic_moped/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Stephen Bartholomew", "Piotr Sokolowski"]
gem.email = ["stephenbartholomew@gmail.com"]
gem.description = %q{New Relic instrumentation for Moped (1.x, 2.0) / Mongoid (3.x, 4.0)}
gem.summary = %q{New Relic instrumentation for Moped (1.x, 2.0) / Mongoid (3.x, 4.0)}
gem.homepage = "https://github.com/stevebartholomew/newrelic_moped"
gem.license = "MIT"
gem.files = Dir["{lib}/**/*.rb", "LICENSE", "*.md"]
gem.name = "newrelic_moped"
gem.require_paths = ["lib"]
gem.version = NewrelicMoped::VERSION
gem.add_dependency 'newrelic_rpm', '~> 3.11'
gem.add_dependency 'moped'
gem.add_development_dependency 'rake'
gem.add_development_dependency 'test-unit'
end
|
Add redesign summary feature spec | require 'spec_helper'
RSpec.feature "Faculty Redesign Management" do
feature "add new redesign summary" do
let(:redesign_summaries) { create(:redesign_summaries) }
let(:redesign_summaries_admin) { create(:redesign_summaries_admin_user) }
before(:each) do
#login
visit "/login"
fill_in "Email", with: redesign_summaries_admin.email
fill_in "Password", with: redesign_summaries_admin.password
click_button "Log In"
end
context "with principle technique and Redesign process addressed" do
scenario "add new summary" do
visit "/profiles/1/redesign-summaries/new"
fill_in "ReDesign Process:", with: "This is the ReDesign Process"
check "Multiple Means of Representation"
click_button "Save redesign summary"
expect(page).to have_text("Redesign summary created successfully.")
end
end
context "without a principle technique or redesign process addressed" do
scenario "add new summary" do
visit "/profiles/1/redesign-summaries/new"
click_button "Save redesign summary"
expect(page).to_not have_text("Redesign summary created successfully.")
expect(page).to have_text("You must select at least one UDL Principle")
end
end
end
end | |
Use read-only audit status on the show page | module Sufia
class FileSetPresenter < ::CurationConcerns::FileSetPresenter
delegate :depositor, :tag, :date_created, to: :solr_document
def tweeter
user = ::User.find_by_user_key(depositor)
if user.try(:twitter_handle).present?
"@#{user.twitter_handle}"
else
I18n.translate('sufia.product_twitter_handle')
end
end
# Add a schema.org itemtype
def itemtype
# Look up the first non-empty resource type value in a hash from the config
Sufia.config.resource_types_to_schema[resource_type.to_a.reject(&:empty?).first] || 'http://schema.org/CreativeWork'
rescue
'http://schema.org/CreativeWork'
end
def events
@events ||= solr_document.to_model.events(100)
end
def audit_status
audit_service.human_readable_audit_status
end
def audit_service
# model = solr_document.to_model # See https://github.com/projecthydra-labs/hydra-pcdm/issues/197
model = FileSet.find(id)
@audit_service ||= CurationConcerns::FileSetAuditService.new(model)
end
end
end
| module Sufia
class FileSetPresenter < ::CurationConcerns::FileSetPresenter
delegate :depositor, :tag, :date_created, to: :solr_document
def tweeter
user = ::User.find_by_user_key(depositor)
if user.try(:twitter_handle).present?
"@#{user.twitter_handle}"
else
I18n.translate('sufia.product_twitter_handle')
end
end
# Add a schema.org itemtype
def itemtype
# Look up the first non-empty resource type value in a hash from the config
Sufia.config.resource_types_to_schema[resource_type.to_a.reject(&:empty?).first] || 'http://schema.org/CreativeWork'
rescue
'http://schema.org/CreativeWork'
end
def events
@events ||= solr_document.to_model.events(100)
end
def audit_status
audit_service.logged_audit_status
end
def audit_service
# model = solr_document.to_model # See https://github.com/projecthydra-labs/hydra-pcdm/issues/197
model = FileSet.find(id)
@audit_service ||= CurationConcerns::FileSetAuditService.new(model)
end
end
end
|
Add code accessor to NeographyError. | module Neography
class NeographyError < StandardError
attr_reader :message, :stacktrace
def initialize(message = nil, code = nil, stacktrace = nil)
@message = message
@stacktrace = stacktrace
end
end
# HTTP Authentication error
class UnauthorizedError < NeographyError; end
# the Neo4j server Exceptions returned by the REST API:
# A node could not be found
class NodeNotFoundException < NeographyError; end
# A node cannot be deleted because it has relationships
class OperationFailureException < NeographyError; end
# Properties can not be null
class PropertyValueException < NeographyError; end
# Trying to a delete a property that does not exist
class NoSuchPropertyException < NeographyError; end
# A relationship could not be found
class RelationshipNotFoundException < NeographyError; end
# Error during valid Cypher query
class BadInputException < NeographyError; end
# Invalid Cypher query syntax
class SyntaxException < NeographyError; end
# A path could not be found by node traversal
class NotFoundException < NeographyError; end
end
| module Neography
class NeographyError < StandardError
attr_reader :message, :code, :stacktrace
def initialize(message = nil, code = nil, stacktrace = nil)
@message = message
@code = code
@stacktrace = stacktrace
end
end
# HTTP Authentication error
class UnauthorizedError < NeographyError; end
# the Neo4j server Exceptions returned by the REST API:
# A node could not be found
class NodeNotFoundException < NeographyError; end
# A node cannot be deleted because it has relationships
class OperationFailureException < NeographyError; end
# Properties can not be null
class PropertyValueException < NeographyError; end
# Trying to a delete a property that does not exist
class NoSuchPropertyException < NeographyError; end
# A relationship could not be found
class RelationshipNotFoundException < NeographyError; end
# Error during valid Cypher query
class BadInputException < NeographyError; end
# Invalid Cypher query syntax
class SyntaxException < NeographyError; end
# A path could not be found by node traversal
class NotFoundException < NeographyError; end
end
|
Remove Webmock from Rake task | require 'webmock/rspec'
namespace :db do
desc 'Drop, create, migrate then seed the database'
task recreate: :environment do
WebMock.allow_net_connect!
Rake::Task['log:clear'].invoke
Rake::Task['tmp:clear'].invoke
Rake::Task['db:drop'].invoke
Rake::Task['db:create'].invoke
Rake::Task['db:migrate'].invoke
Rake::Task['db:seed'].invoke
Sidekiq::Queue.new.clear
Sidekiq::RetrySet.new.clear
end
end | namespace :db do
desc 'Drop, create, migrate then seed the database'
task recreate: :environment do
Rake::Task['log:clear'].invoke
Rake::Task['tmp:clear'].invoke
Rake::Task['db:drop'].invoke
Rake::Task['db:create'].invoke
Rake::Task['db:migrate'].invoke
Rake::Task['db:seed'].invoke
Sidekiq::Queue.new.clear
Sidekiq::RetrySet.new.clear
end
end |
Add File that allows explicit path setting | require 'time'
require 'rack/utils'
require 'rack/mime'
module DAV4Rack
# DAV4Rack::File simply allows us to use Rack::File but with the
# specific location we deem appropriate
class File < Rack::File
attr_accessor :path
alias :to_path :path
def initialize(path)
@path = path
end
def _call(env)
begin
if F.file?(@path) && F.readable?(@path)
serving
else
raise Errno::EPERM
end
rescue SystemCallError
not_found
end
end
def not_found
body = "File not found: #{Utils.unescape(env["PATH_INFO"])}\n"
[404, {"Content-Type" => "text/plain",
"Content-Length" => body.size.to_s,
"X-Cascade" => "pass"},
[body]]
end
end
end
| |
Remove smart trick that caused a segfault on mri 2.3.1 | require 'rom/types'
module ROM
module SQL
module Types
include ROM::Types
singleton_class.send(:define_method, :Constructor, &ROM::Types.method(:Constructor))
Serial = Int.constrained(gt: 0).meta(primary_key: true)
Blob = Constructor(Sequel::SQL::Blob, &Sequel::SQL::Blob.method(:new))
end
end
end
| require 'rom/types'
module ROM
module SQL
module Types
include ROM::Types
def self.Constructor(*args, &block)
ROM::Types.Constructor(*args, &block)
end
Serial = Int.constrained(gt: 0).meta(primary_key: true)
Blob = Constructor(Sequel::SQL::Blob, &Sequel::SQL::Blob.method(:new))
end
end
end
|
Add documentation (a **small** amount...) | class GoodbyeTranslated
def self.say_goodbye
return "Goodbye, World!"
end
def self.say_goodbye_to(people)
if people.nil?
return self.say_goodbye
elsif people.respond_to?("join")
# Join the list elements with commas
return "Goodbye, #{people.join(", ")}!"
else
return "Goodbye, #{people}!"
end
end
def self.say_goodbye_in(language)
translator = Translator.new(language)
return translator.say_goodbye
end
def self.say_goodbye_to_in(people, language)
translator = Translator.new(language)
return translator.say_goodbye_to(people)
end
def self.say_goodbye_in_to(language, people)
return self.say_goodbye_to_in(people, language)
end
end
require 'goodbye_translated/translator'
| # The main goodbye_translated driver
class GoodbyeTranslated
# Say goodbye to the world!
def self.say_goodbye
return "Goodbye, World!"
end
# Say goodbye to the world, a person or a list of people.
def self.say_goodbye_to(people)
if people.nil?
return self.say_goodbye
elsif people.respond_to?("join")
# Join the list elements with commas
return "Goodbye, #{people.join(", ")}!"
else
return "Goodbye, #{people}!"
end
end
# Say goodbye to the world in a language.
def self.say_goodbye_in(language)
translator = Translator.new(language)
return translator.say_goodbye
end
# Say goodbye to some people in a language.
def self.say_goodbye_to_in(people, language)
translator = Translator.new(language)
return translator.say_goodbye_to(people)
end
# Say goodbye in a language to some people.
def self.say_goodbye_in_to(language, people)
return self.say_goodbye_to_in(people, language)
end
end
require 'goodbye_translated/translator'
|
Remove needless validation in Contribution | class Contribution < ApplicationRecord
belongs_to :contributor
belongs_to :commit
validates :contributor_id, :commit_id, :presence => true
end
| class Contribution < ApplicationRecord
belongs_to :contributor
belongs_to :commit
end
|
Fix seed_fu failure with inserting milestones into test DB | Gitlab::Seeder.quiet do
Project.all.each do |project|
5.times do |i|
milestone_params = {
title: "v#{i}.0",
description: FFaker::Lorem.sentence,
state: ['opened', 'closed'].sample,
}
milestone = Milestones::CreateService.new(
project, project.team.users.sample, milestone_params).execute
print '.'
end
end
end
| Gitlab::Seeder.quiet do
Project.all.each do |project|
5.times do |i|
milestone_params = {
title: "v#{i}.0",
description: FFaker::Lorem.sentence,
state: [:active, :closed].sample,
}
milestone = Milestones::CreateService.new(
project, project.team.users.sample, milestone_params).execute
print '.'
end
end
end
|
Prepend leading slash to a manual section's `manual` attribute | require "formatters/abstract_indexable_formatter"
class ManualSectionIndexableFormatter < AbstractIndexableFormatter
def initialize(section, manual)
@entity = section
@manual = manual
end
def type
"manual_section"
end
private
attr_reader :manual
def extra_attributes
{
manual: manual.slug,
}
end
def title
"#{manual.title}: #{entity.title}"
end
def description
entity.summary
end
def link
with_leading_slash(entity.slug)
end
def indexable_content
entity.body
end
def public_timestamp
nil
end
def organisation_slugs
[manual.organisation_slug]
end
end
| require "formatters/abstract_indexable_formatter"
class ManualSectionIndexableFormatter < AbstractIndexableFormatter
def initialize(section, manual)
@entity = section
@manual = manual
end
def type
"manual_section"
end
private
attr_reader :manual
def extra_attributes
{
manual: manual_slug,
}
end
def manual_slug
with_leading_slash(manual.slug)
end
def title
"#{manual.title}: #{entity.title}"
end
def description
entity.summary
end
def link
with_leading_slash(entity.slug)
end
def indexable_content
entity.body
end
def public_timestamp
nil
end
def organisation_slugs
[manual.organisation_slug]
end
end
|
Simplify setting locale in controller | require 'gds_api/helpers'
require 'ics_renderer'
class CalendarController < ApplicationController
include GdsApi::Helpers
before_filter :load_calendar
rescue_from Calendar::CalendarNotFound, with: :simple_404
def calendar
set_expiry
respond_to do |format|
format.html do
@artefact = content_api.artefact(params[:scope])
set_locale(@artefact)
set_slimmer_artefact(@artefact)
set_slimmer_headers :format => "calendar"
render params[:scope].gsub('-', '_')
end
format.json do
render :json => @calendar
end
end
end
def division
target = @calendar.division(params[:division])
if params[:year]
target = target.year(params[:year])
end
set_expiry 1.day
respond_to do |format|
format.json { render :json => target }
format.ics { render :text => ICSRenderer.new(target.events, request.path).render }
format.all { simple_404 }
end
end
private
def load_calendar
simple_404 unless params[:scope] =~ /\A[a-z-]+\z/
@calendar = Calendar.find(params[:scope])
end
def simple_404
head 404
end
def set_locale(artefact)
if artefact and artefact["details"]
I18n.locale = artefact["details"]["language"]
end
end
end
| require 'gds_api/helpers'
require 'ics_renderer'
class CalendarController < ApplicationController
include GdsApi::Helpers
before_filter :load_calendar
rescue_from Calendar::CalendarNotFound, with: :simple_404
def calendar
set_expiry
respond_to do |format|
format.html do
@artefact = content_api.artefact(params[:scope])
I18n.locale = @artefact.details.language if @artefact
set_slimmer_artefact(@artefact)
set_slimmer_headers :format => "calendar"
render params[:scope].gsub('-', '_')
end
format.json do
render :json => @calendar
end
end
end
def division
target = @calendar.division(params[:division])
if params[:year]
target = target.year(params[:year])
end
set_expiry 1.day
respond_to do |format|
format.json { render :json => target }
format.ics { render :text => ICSRenderer.new(target.events, request.path).render }
format.all { simple_404 }
end
end
private
def load_calendar
simple_404 unless params[:scope] =~ /\A[a-z-]+\z/
@calendar = Calendar.find(params[:scope])
end
def simple_404
head 404
end
end
|
Allow globing of binaries with timestamps in the name | #!/usr/bin/env ruby
binary_name = ENV['BINARY_NAME']
file_path = Dir.glob("build-binary/binary-builder/#{binary_name}-*-linux-x64.{tar.gz,tgz}").first
unless file_path
puts "No binaries detected for upload."
exit
end
`apt-get -y install awscli`
file_name = File.basename(file_path)
if `aws s3 ls s3://pivotal-buildpacks/concourse-binaries/#{binary_name}/`.include? file_name
puts "Binary #{file_name} has already been detected on s3. Skipping upload for this file."
else
system("aws s3 cp #{file_path} s3://pivotal-buildpacks/concourse-binaries/#{binary_name}/#{file_name}")
end
| #!/usr/bin/env ruby
binary_name = ENV['BINARY_NAME']
file_path = Dir.glob("build-binary/binary-builder/#{binary_name}-*.{tar.gz,tgz}").first
unless file_path
puts "No binaries detected for upload."
exit
end
`apt-get -y install awscli`
file_name = File.basename(file_path)
if `aws s3 ls s3://pivotal-buildpacks/concourse-binaries/#{binary_name}/`.include? file_name
puts "Binary #{file_name} has already been detected on s3. Skipping upload for this file."
else
system("aws s3 cp #{file_path} s3://pivotal-buildpacks/concourse-binaries/#{binary_name}/#{file_name}")
end
|
Add unit test cases for tripleo::profile::base::swift | #
# Copyright (C) 2020 Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
require 'spec_helper'
describe 'tripleo::profile::base::swift' do
shared_examples_for 'tripleo::profile::base::swift' do
before :each do
facts.merge!({ :step => params[:step] })
end
let :pre_condition do
"class { 'swift':
swift_hash_path_prefix => 'foo',
}
include memcached
"
end
context 'with ipv4 memcache servers' do
let(:params) { {
:step => 4,
:memcache_servers => ['192.168.0.1', '192.168.0.2'],
} }
it 'configure cache with ipv4 ips' do
is_expected.to contain_class('swift::objectexpirer').with({
:pipeline => ['catch_errors', 'cache', 'proxy-server'],
:memcache_servers => ['192.168.0.1:11211', '192.168.0.2:11211']
})
end
end
context 'with ipv6 memcache servers' do
let(:params) { {
:step => 4,
:memcache_servers => ['::1', '::2'],
} }
it 'configure cache with ipv6 ips' do
is_expected.to contain_class('swift::objectexpirer').with({
:pipeline => ['catch_errors', 'cache', 'proxy-server'],
:memcache_servers => ['[::1]:11211', '[::2]:11211']
})
end
end
context 'with ipv4, ipv6 and fqdn memcache servers' do
let(:params) { {
:step => 4,
:memcache_servers => ['192.168.0.1', '::2', 'myserver.com'],
} }
it 'configure cache with ips and fqdn' do
is_expected.to contain_class('swift::objectexpirer').with({
:pipeline => ['catch_errors', 'cache', 'proxy-server'],
:memcache_servers => ['192.168.0.1:11211', '[::2]:11211', 'myserver.com:11211']
})
end
end
end
on_supported_os.each do |os, facts|
context "on #{os}" do
let(:facts) do
facts.merge({})
end
it_behaves_like 'tripleo::profile::base::swift'
end
end
end
| |
Fix bug in Provider Filter | require_relative 'operator'
module ConceptQL
module Operators
# Filters incoming events to only those that have been associated with
# providers matching the given criteria.
class ProviderFilter < Operator
register __FILE__
desc "Filters incoming events to only those that match the associated providers."
option :specialties, type: :codelist, vocab: "Specialty"
category "Filter Single Stream"
basic_type :temporal
allows_one_upstream
validate_one_upstream
validate_required_options :specialties
require_column :provider_id
default_query_columns
def query(db)
db.from(stream.evaluate(db))
.where(provider_id: matching_provider_ids(db))
end
private
def matching_provider_ids(db)
specialty_concept_ids = options[:specialties].split(/\s*,\s*/).map(&:to_i)
db.from(:provider)
.where(specialty_concept_id: specialty_concept_ids)
.select(:provider_id)
end
end
end
end
| require_relative 'operator'
module ConceptQL
module Operators
# Filters incoming events to only those that have been associated with
# providers matching the given criteria.
class ProviderFilter < Operator
register __FILE__
desc "Filters incoming events to only those that match the associated providers."
option :specialties, type: :string
category "Filter Single Stream"
basic_type :temporal
allows_one_upstream
validate_one_upstream
validate_required_options :specialties
require_column :provider_id
default_query_columns
def query(db)
db.from(stream.evaluate(db))
.where(provider_id: matching_provider_ids(db))
end
private
def matching_provider_ids(db)
specialty_concept_ids = options[:specialties].split(/\s*,\s*/).map(&:to_i)
db.from(:provider)
.where(specialty_concept_id: specialty_concept_ids)
.select(:provider_id)
end
end
end
end
|
Add --with-revprop to commit command | #!/usr/bin/ruby -w
# -*- ruby -*-
module Svnx
NAME = 'svnx'
VERSION = '2.7.1'
end
| #!/usr/bin/ruby -w
# -*- ruby -*-
module Svnx
NAME = 'svnx'
VERSION = '2.7.2'
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.