Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Write correct require line in vendor/assets/javascript files
module SpreeReviews module Generators class InstallGenerator < Rails::Generators::Base class_option :auto_run_migrations, :type => :boolean, :default => false def add_devise_config # Silences Devise warnings create_file "config/initializers/devise.rb", %Q{ Devise.secret_key = "fake" * 10 } end def add_javascripts append_file "vendor/assets/javascripts/spree/frontend/all.js", "//= require spree/frontend\n" append_file "vendor/assets/javascripts/spree/backend/all.js", "//= require spree/backend\n" end def add_stylesheets inject_into_file "vendor/assets/stylesheets/spree/frontend/all.css", " *= require spree/frontend/spree_reviews\n", :before => /\*\//, :verbose => true end def add_migrations run 'bundle exec rake railties:install:migrations FROM=spree_reviews' end def run_migrations run_migrations = options[:auto_run_migrations] || ['', 'y', 'Y'].include?(ask 'Would you like to run the migrations now? [Y/n]') if run_migrations run 'bundle exec rake db:migrate' else puts 'Skipping rake db:migrate, don\'t forget to run it!' end end end end end
module SpreeReviews module Generators class InstallGenerator < Rails::Generators::Base class_option :auto_run_migrations, :type => :boolean, :default => false def add_devise_config # Silences Devise warnings create_file "config/initializers/devise.rb", %Q{ Devise.secret_key = "fake" * 10 } end def add_javascripts append_file "vendor/assets/javascripts/spree/frontend/all.js", "//= require spree/frontend/spree_reviews\n" append_file "vendor/assets/javascripts/spree/backend/all.js", "//= require spree/backend/spree_reviews\n" end def add_stylesheets inject_into_file "vendor/assets/stylesheets/spree/frontend/all.css", " *= require spree/frontend/spree_reviews\n", :before => /\*\//, :verbose => true end def add_migrations run 'bundle exec rake railties:install:migrations FROM=spree_reviews' end def run_migrations run_migrations = options[:auto_run_migrations] || ['', 'y', 'Y'].include?(ask 'Would you like to run the migrations now? [Y/n]') if run_migrations run 'bundle exec rake db:migrate' else puts 'Skipping rake db:migrate, don\'t forget to run it!' end end end end end
Add unit test for local search client
require_relative "../../test_helper" require "health_check/logging_config" require "health_check/local_search_client" Logging.logger.root.appenders = nil module HealthCheck class LocalSearchClientTest < ShouldaUnitTestCase def setup @search_index = stub("search index") @index_name = "my index" @search_server = stub("search server") @search_server.stubs(:index).with(@index_name).returns(@search_index) SearchConfig.any_instance.stubs(:search_server).returns(@search_server) end should "get the index from the SearchConfig by name" do @search_server.expects(:index).with(@index_name) LocalSearchClient.new(index: @index_name) end should "perform a search using the index and extract results" do term = "food" result = stub("result", link: "/food") result_set = stub("result set", results: [result]) @search_index.expects(:search).with(term).returns(result_set) client = LocalSearchClient.new(index: @index_name) assert_equal [result.link], client.search(term) end end end
Add a limit to the context column
class ActsAsTaggableOnPosts < ActiveRecord::Migration def self.up return if table_exists? :tags create_table :tags do |t| t.string :name end create_table :taggings do |t| t.references :tag # You should make sure that the column created is # long enough to store the required class names. t.references :taggable, :polymorphic => true t.references :tagger, :polymorphic => true t.string :context t.datetime :created_at end add_index :taggings, :tag_id add_index :taggings, [:taggable_id, :taggable_type, :context] end def self.down return unless table_exists? :tags drop_table :tags drop_table :taggings end end
class ActsAsTaggableOnPosts < ActiveRecord::Migration def self.up return if table_exists? :tags create_table :tags do |t| t.string :name end create_table :taggings do |t| t.references :tag # You should make sure that the column created is # long enough to store the required class names. t.references :taggable, :polymorphic => true t.references :tagger, :polymorphic => true # Limit is created to prevent MySQL error on index # length for MyISAM table type: http://bit.ly/vgW2Ql t.string :context, :limit => 128 t.datetime :created_at end add_index :taggings, :tag_id add_index :taggings, [:taggable_id, :taggable_type, :context] end def self.down return unless table_exists? :tags drop_table :tags drop_table :taggings end end
Return nil for both exceptions and when the response code isn't 200
require "kmdata/version" require "net/http" require "json" require "ostruct" module KMData ENDPOINT = "kmdata.osu.edu" class << self def get(path, params = {}) path = path_with_params("/api/#{path}.json", params) response = http.request(Net::HTTP::Get.new(path)) process(JSON.parse(response.body)) rescue Exception => exception false end private def http @http ||= begin http = Net::HTTP.new(ENDPOINT, 443) http.use_ssl = true http end end def process(json) if json.is_a? Array json.map { |element| process(element) } elsif json.is_a? Hash OpenStruct.new(Hash[json.map { |key, value| [key, process(value)] }]) else json end end def path_with_params(path, params) [path, URI.encode_www_form(params)].join("?") end end end
require "kmdata/version" require "net/http" require "json" require "ostruct" module KMData ENDPOINT = "kmdata.osu.edu" class << self def get(path, params = {}) path = path_with_params("/api/#{path}.json", params) response = http.request(Net::HTTP::Get.new(path)) process(JSON.parse(response.body)) if response.code == "200" rescue Exception => exception end private def http @http ||= begin http = Net::HTTP.new(ENDPOINT, 443) http.use_ssl = true http end end def process(json) if json.is_a? Array json.map { |element| process(element) } elsif json.is_a? Hash OpenStruct.new(Hash[json.map { |key, value| [key, process(value)] }]) else json end end def path_with_params(path, params) [path, URI.encode_www_form(params)].join("?") end end end
Update registration controller to permit avatar params
class Users::RegistrationsController < Devise::RegistrationsController def update # required for settings form to submit when password is left blank if params[:user][:password].blank? params[:user].delete("password") params[:user].delete("password_confirmation") end @user = User.find(current_user.id) if @user.update_attributes(params[:user]) set_flash_message :notice, :updated # Sign in the user bypassing validation in case his password changed sign_in @user, bypass: true redirect_to after_update_path_for(@user) else render "devise/registrations/edit" end end end
class Users::RegistrationsController < Devise::RegistrationsController def update @user = User.find(current_user.id) if user_params["password"].blank? if @user.update_without_password( user_params ) set_flash_message :notice, :updated redirect_to after_update_path_for(@user) else render "devise/registrations/edit" end else if @user.update_attributes(user_params) set_flash_message :notice, :updated # Sign in the user bypassing validation in case his password changed sign_in @user, bypass: true redirect_to after_update_path_for(@user) else render "devise/registrations/edit" end end end private def user_params params.require(:user).permit(:name, :email, :password, :password_confirmation, :avatar, :avatar_cache) end end
Add spec for complex object
require File.dirname(__FILE__) + "/../lib/odb" class Post include ODB::Persistent attr_accessor :title, :author, :comment end class Comment def initialize @name = 1 @value = 2.5 end end describe ODB::Persistent do it "should save a post" do db = ODB.new post = Post.new.tap {|p| p.title = "x"; p.author = "Joe"; p.comment = Comment.new } db.transaction do db.store[:post] = post db.store[:comment] = post.comment end db.store[:post].should == post db.store[:post].comment.object_id.should == db.store[:comment].object_id end end
require File.dirname(__FILE__) + "/../lib/odb" require 'yard' class Post include ODB::Persistent attr_accessor :title, :author, :comment end class Comment def initialize @name = 1 @value = 2.5 end end describe ODB::Persistent do it "should save a post" do db = ODB.new(ODB::JSONStore.new("Hello")) post = Post.new.tap {|p| p.title = "x"; p.author = "Joe"; p.comment = Comment.new } db.transaction do db.store[:post] = post db.store[:comment] = post.comment end db = ODB.new(ODB::JSONStore.new("Hello")) db.store[:post].should == post db.store[:post].comment.object_id.should == db.store[:comment].object_id end it "should save a complex object" do YARD.parse(File.dirname(__FILE__) + '/../lib/**/*.rb') db = ODB.new(ODB::JSONStore.new("yard")) db.transaction do db.store[:registry] = YARD::Registry.instance end end end
Include address in label for autocomplete
require_dependency "renalware/directory" module Renalware module Directory class PersonAutoCompletePresenter < DumbDelegator def to_hash { id: id, label: to_s } end end end end
require_dependency "renalware/directory" module Renalware module Directory class PersonAutoCompletePresenter < DumbDelegator def name_and_address [family_name, given_name, address].compact.join(", ") end def to_hash { id: id, label: name_and_address } end end end end
Update ELB sample to show usage
$: << File.expand_path("../../lib", __FILE__) require 'aws/elb' ## # Expects your Amazon keys to be in the environment, something like # # export AWS_KEY="KEY" # export AWS_SECRET="SECRET" ## $elb = AWS::ELB.new ENV["AWS_KEY"], ENV["AWS_SECRET"] puts "", "Your Load Balancers", "" p $elb.describe_load_balancesr
$: << File.expand_path("../../lib", __FILE__) require 'aws/elb' ## # Expects your Amazon keys to be in the environment, something like # # export AWS_KEY="KEY" # export AWS_SECRET="SECRET" ## $elb = AWS::ELB.new ENV["AWS_KEY"], ENV["AWS_SECRET"] puts "", "Your Load Balancers", "" $elb.describe_load_balancers.describe_load_balancers_result.load_balancer_descriptions.each do |elb| puts "Name: #{elb.load_balancer_name}" puts "HealthCheck: #{elb.health_check.inspect}" elb.listener_descriptions.each do |desc| l = desc.listener puts "Listener: #{l.protocol}:#{l.load_balancer_port} => #{l.instance_protocol}:#{l.instance_port}" end puts "" end
Copy data from overrides to the episode columns
class AddEpisodeAttributes < ActiveRecord::Migration def change add_column :episodes, :url, :string add_column :episodes, :author_name, :string add_column :episodes, :author_email, :string add_column :episodes, :title, :text add_column :episodes, :subtitle, :text add_column :episodes, :content, :text add_column :episodes, :summary, :text add_column :episodes, :published, :datetime add_column :episodes, :updated, :datetime add_column :episodes, :image_url, :string add_column :episodes, :explicit, :string add_column :episodes, :keywords, :text add_column :episodes, :description, :text add_column :episodes, :categories, :text add_column :episodes, :block, :boolean add_column :episodes, :is_closed_captioned, :boolean add_column :episodes, :position, :integer add_column :episodes, :feedburner_orig_link, :string add_column :episodes, :feedburner_orig_enclosure_link, :string add_column :episodes, :is_perma_link, :boolean end end
class AddEpisodeAttributes < ActiveRecord::Migration def change add_column :episodes, :url, :string add_column :episodes, :author_name, :string add_column :episodes, :author_email, :string add_column :episodes, :title, :text add_column :episodes, :subtitle, :text add_column :episodes, :content, :text add_column :episodes, :summary, :text add_column :episodes, :published, :datetime add_column :episodes, :updated, :datetime add_column :episodes, :image_url, :string add_column :episodes, :explicit, :string add_column :episodes, :keywords, :text add_column :episodes, :description, :text add_column :episodes, :categories, :text add_column :episodes, :block, :boolean add_column :episodes, :is_closed_captioned, :boolean add_column :episodes, :position, :integer add_column :episodes, :feedburner_orig_link, :string add_column :episodes, :feedburner_orig_enclosure_link, :string add_column :episodes, :is_perma_link, :boolean Episode.where(prx_uri: nil, title: nil).each { |e| EpisodeEntryHandler.new(e).update_from_overrides } end end
Move to autoloading the modules
libdir = File.dirname(__FILE__) $LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir) require 'ruby_rexster/vertex' require 'ruby_rexster/edge' module RubyRexster end
libdir = File.dirname(__FILE__) $LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir) module RubyRexster autoload :Vertex, 'ruby_rexster/vertex' autoload :Edge, 'ruby_rexster/edge' end
Remove debugging statement and unecessary method
require 'rails' require 'tilt' require 'nailgun' module ClojurescriptRails class ClojurescriptTemplate < ::Tilt::Template def self.engine_initialized? not @compiler.nil? end def initialize_engine debugger @compiler = ClojurescriptCompiler.new end def prepare end def evaluate(scope, locals = {}, &block) # cmd = "#{CLJS_COMPILER} #{@file} '{:optimizations :advanced}'" # @output = `#{cmd}` @output ||= @compiler.compile @file end end class ClojurescriptCompiler CLOJURESCRIPT_HOME = File.dirname(__FILE__) + "/../../clojurescript/" COMPILER = "#{CLOJURESCRIPT_HOME}bin/cljsc.clj" def self.prepare_ng @@ng = Nailgun::NgCommand @@ng_path = Nailgun::NgCommand::NGPATH @@ng.start_server %w{src/clj src/cljs lib/clojure.jar lib/compiler.jar lib/goog.jar lib/js.jar}.each do |f| @@ng.ng_cp "#{CLOJURESCRIPT_HOME}#{f}" end end def compile(file) `#{@@ng_path} clojure.main #{COMPILER} #{file} "{:optimizations :advanced}"` end end end
require 'rails' require 'tilt' require 'nailgun' module ClojurescriptRails class ClojurescriptTemplate < ::Tilt::Template def initialize_engine @compiler ||= ClojurescriptCompiler.new end def prepare end def evaluate(scope, locals = {}, &block) # cmd = "#{CLJS_COMPILER} #{@file} '{:optimizations :advanced}'" # @output = `#{cmd}` @output ||= @compiler.compile @file end end class ClojurescriptCompiler CLOJURESCRIPT_HOME = File.dirname(__FILE__) + "/../../clojurescript/" COMPILER = "#{CLOJURESCRIPT_HOME}bin/cljsc.clj" def self.prepare_ng @@ng = Nailgun::NgCommand @@ng_path = Nailgun::NgCommand::NGPATH @@ng.start_server %w{src/clj src/cljs lib/clojure.jar lib/compiler.jar lib/goog.jar lib/js.jar}.each do |f| @@ng.ng_cp "#{CLOJURESCRIPT_HOME}#{f}" end end def compile(file) `#{@@ng_path} clojure.main #{COMPILER} #{file} "{:optimizations :advanced}"` end end end
Fix spec for last change.
require File.expand_path("../../../spec_helper", __FILE__) module Selenium module WebDriver module Remote module Http describe Common do it "sends Content-Length=0 header for POST requests without a command in the body" do common = Common.new common.server_url = URI.parse("http://server") common.should_receive(:request). with(:post, URI.parse("http://server/clear"), hash_including("Content-Length" => "0"), nil) common.call(:post, "clear", nil) end end # Common end # Http end # Remote end # WebDriver end # Selenium
require File.expand_path("../../../spec_helper", __FILE__) module Selenium module WebDriver module Remote module Http describe Common do it "sends non-empty body header for POST requests without command data" do common = Common.new common.server_url = URI.parse("http://server") common.should_receive(:request). with(:post, URI.parse("http://server/clear"), hash_including("Content-Length" => "2"), "{}") common.call(:post, "clear", nil) end end # Common end # Http end # Remote end # WebDriver end # Selenium
Correct use of node type predicates
module Mutant class Mutator class Node class Send # Mutator for sends that correspond to a binary operator class Binary < self children :left, :operator, :right private # Emit mutations # # @return [undefined] # # @api private # def dispatch emit(left) emit_left_mutations emit_selector_replacement emit(right) unless splat?(right) emit_right_mutations end end # Binary end # Send end # Node end # Mutator end # Mutant
module Mutant class Mutator class Node class Send # Mutator for sends that correspond to a binary operator class Binary < self children :left, :operator, :right private # Emit mutations # # @return [undefined] # # @api private # def dispatch emit(left) emit_left_mutations emit_selector_replacement emit(right) unless n_splat?(right) emit_right_mutations end end # Binary end # Send end # Node end # Mutator end # Mutant
Fix `no implicit conversion of Pathname into String (TypeError)`
module ActiveSupportDecorators def self.paths @paths ||= [] end def self.pattern @pattern ||= '_decorator' end def self.pattern=(pattern) @pattern = pattern end def self.expanded_paths paths.map { |p| Dir[p] }.flatten end def self.debug @debug ||= false end def self.debug=(debugging_enabled) @debug = debugging_enabled end def self.log(message) puts message if debug end def self.is_decorator?(file_name) sanitize(file_name).ends_with?(pattern) end def self.all(file_name, const_path = nil) file = sanitize(file_name) if const_path file = const_path.underscore else first_autoload_match = ActiveSupport::Dependencies.autoload_paths.find { |p| file.include?(p) } file.sub!(first_autoload_match, '') if first_autoload_match end relative_target = "#{file}#{pattern}.rb" expanded_paths.map { |path| File.join(path, relative_target) }.select { |candidate| File.file?(candidate) } end def self.original_const_name(file_name) first_match = expanded_paths.find { |path| file_name.include?(path) } if first_match sanitize(file_name).sub("#{first_match}/", '').sub(pattern, '').camelize else nil end end private def self.sanitize(file_name) file_name.sub(/\.rb$/, '') end end
module ActiveSupportDecorators def self.paths @paths ||= [] end def self.pattern @pattern ||= '_decorator' end def self.pattern=(pattern) @pattern = pattern end def self.expanded_paths paths.map { |p| Dir[p] }.flatten end def self.debug @debug ||= false end def self.debug=(debugging_enabled) @debug = debugging_enabled end def self.log(message) puts message if debug end def self.is_decorator?(file_name) sanitize(file_name).ends_with?(pattern) end def self.all(file_name, const_path = nil) file = sanitize(file_name) if const_path file = const_path.underscore else first_autoload_match = ActiveSupport::Dependencies.autoload_paths.find { |p| file.include?(p.to_s) } file.sub!(first_autoload_match, '') if first_autoload_match end relative_target = "#{file}#{pattern}.rb" expanded_paths.map { |path| File.join(path, relative_target) }.select { |candidate| File.file?(candidate) } end def self.original_const_name(file_name) first_match = expanded_paths.find { |path| file_name.include?(path) } if first_match sanitize(file_name).sub("#{first_match}/", '').sub(pattern, '').camelize else nil end end private def self.sanitize(file_name) file_name.sub(/\.rb$/, '') end end
Add lc_email to initial entry (John Glenn)
require 'spec_helper' describe "User pages" do subject { page } describe "signup page" do before { visit signup_path } it { should have_title(user_title('Sign up')) } it { should have_content('Sign up') } end describe "profile page" do let(:user) { FactoryGirl.create(:user) } before { visit user_path(user) } it { should have_title(user_title(user.name)) } it { should have_content(user.name) } end end
require 'spec_helper' describe "User pages" do subject { page } describe "signup page" do before { visit signup_path } it { should have_title(user_title('Sign up')) } it { should have_content('Sign up') } end describe "profile page" do let(:user) { FactoryGirl.create(:user) } before { visit user_path(user) } it { should have_title(user_title(user.name)) } it { should have_content(user.name) } it { should have_content(user.email) } end end
Work around pathologically slow buffer scanning in Neovim
# Copyright 2010-present Greg Hurrell. All rights reserved. # Licensed under the terms of the BSD 2-clause license. module CommandT class Scanner # Returns a list of all open buffers. class BufferScanner < Scanner include PathUtilities def paths (0..(::VIM::Buffer.count - 1)).map do |n| buffer = ::VIM::Buffer[n] # Beware, name may be nil, and on Neovim unlisted buffers (like # Command-T's match listing itself) will be returned and must be # skipped. if buffer.name && ::VIM::evaluate("buflisted(#{buffer.number})") != 0 relative_path_under_working_directory buffer.name end end.compact end end end end
# Copyright 2010-present Greg Hurrell. All rights reserved. # Licensed under the terms of the BSD 2-clause license. module CommandT class Scanner # Returns a list of all open buffers. class BufferScanner < Scanner include PathUtilities def paths VIM.capture('silent ls').scan(/\n\s*(\d+)[^\n]+/).map do |n| number = n[0].to_i name = ::VIM.evaluate("bufname(#{number})") relative_path_under_working_directory(name) unless name == '' end.compact end end end end
Update unity sdk source to use cdn
# # Be sure to run `pod spec lint YumiUnitySDK.podspec' to ensure this is a # valid spec and to remove all comments including this before submitting the spec. # # To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html # To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/ # Pod::Spec.new do |s| s.name = "YumiUnitySDK" s.version = "2.0.0" s.summary = "YumiUnitySDK." s.description = "YumiUnitySDK is the Unity SDK cocoapods created by Yumimobi" s.homepage = "http://www.yumimobi.com/" s.license = "MIT" s.author = { "Yumimobi sdk team" => "ad-client@zplay.cn" } s.ios.deployment_target = "7.0" s.source = { :http => "http://ad-sdk.oss-cn-beijing.aliyuncs.com/iOS/Unity_SDK_v#{s.version}.zip" } src_root = "Unity_SDK_v#{s.version}/lib" s.vendored_frameworks = "#{src_root}/UnityAds.framework" s.resource = "#{src_root}/UnityAds.bundle" end
# # Be sure to run `pod spec lint YumiUnitySDK.podspec' to ensure this is a # valid spec and to remove all comments including this before submitting the spec. # # To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html # To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/ # Pod::Spec.new do |s| s.name = "YumiUnitySDK" s.version = "2.0.0" s.summary = "YumiUnitySDK." s.description = "YumiUnitySDK is the Unity SDK cocoapods created by Yumimobi" s.homepage = "http://www.yumimobi.com/" s.license = "MIT" s.author = { "Yumimobi sdk team" => "ad-client@zplay.cn" } s.ios.deployment_target = "7.0" s.source = { :http => "http://adsdk.yumimobi.com/iOS/Unity_SDK_v#{s.version}.zip" } src_root = "Unity_SDK_v#{s.version}/lib" s.vendored_frameworks = "#{src_root}/UnityAds.framework" s.resource = "#{src_root}/UnityAds.bundle" end
Add failing spec for redirect to index after remove done
require 'rails_helper' RSpec.describe ItemsController, type: :controller do describe "GET index" do let(:items) { [double(:item)] } before do allow(Item).to receive(:all) { items } end it "assign all the items for the view" do get :index expect(assigns[:items]).to eq items end end describe "POST create" do before do allow(Item).to receive :create end def do_create post :create, item: {name: "do it!"} end it "creates a new item" do do_create expect(Item).to have_received(:create).with name: "do it!" end it "redirect to the index" do do_create expect(response).to redirect_to action: :index end end describe "POST mark_done" do before do allow(Item).to receive :mark_done end def do_mark_done post :mark_done, id: "1" end it "marks item as done" do do_mark_done expect(Item).to have_received(:mark_done).with "1" end it "redirect to the index" do do_mark_done expect(response).to redirect_to action: :index end end end
require 'rails_helper' RSpec.describe ItemsController, type: :controller do describe "GET index" do let(:items) { [double(:item)] } before do allow(Item).to receive(:all) { items } end it "assign all the items for the view" do get :index expect(assigns[:items]).to eq items end end describe "POST create" do before do allow(Item).to receive :create end def do_create post :create, item: {name: "do it!"} end it "creates a new item" do do_create expect(Item).to have_received(:create).with name: "do it!" end it "redirect to the index" do do_create expect(response).to redirect_to action: :index end end describe "POST mark_done" do before do allow(Item).to receive :mark_done end def do_mark_done post :mark_done, id: "1" end it "marks item as done" do do_mark_done expect(Item).to have_received(:mark_done).with "1" end it "redirect to the index" do do_mark_done expect(response).to redirect_to action: :index end end describe "POST remove_done" do def do_remove_done end it "redirect to the index" do do_remove_done expect(response).to redirect_to action: :index end end end
Add create receptacle action trait
require 'modularity' require 'lims-laboratory-app/laboratory/receptacle' require 'lims-laboratory-app/laboratory/sample/create_sample_shared' require 'lims-laboratory-app/laboratory/create_labellable_resource_action' module Lims::LaboratoryApp module Laboratory::Receptacle module CreateReceptacleActionTrait as_trait do |args| include Laboratory::CreateLabellableResourceAction include Laboratory::Sample::CreateSampleShared attribute :aliquots, Array, :default => [] receptacle_name = args[:receptacle_name].to_sym receptacle_class = args[:receptacle_class] extra_parameters = args[:extra_parameters] || [] define_method(:receptacle_parameters) do {}.tap do |p| extra_parameters.map(&:to_sym).each do |extra| p[extra] = self.send(extra) end end end define_method(:create) do |session| new_receptacle = receptacle_class.new(receptacle_parameters) session << new_receptacle count = 0 if aliquots aliquots.each do |aliquot| # The sample uuid comes from lims-management-app, # as a result, the sample is not present in the # lims-laboratory-app sample table. The following # creates a new sample with the expected uuid. aliquot_ready = aliquot.mash do |k,v| case k.to_s when "sample_uuid" then count += 1 ["sample", create_sample(session, "Sample #{count}", v)] else [k,v] end end new_receptacle << Laboratory::Aliquot.new(aliquot_ready) end end {receptacle_name => new_receptacle, :uuid => session.uuid_for!(new_receptacle)} end end end end end
Remove name property from the resource
property :name, String, name_property: true property :data, Array, default: [] action :create do converge_by("Create Smokeping target file for #{new_resource.name}") do name = new_resource.name etc_dir = node['smokeping']['etc_dir'] file = "#{etc_dir}/config.d/#{name}.targets" template file do cookbook 'smokeping' source 'group_targets.erb' mode '0644' variables( data: new_resource.data ) end Chef::Log.info "#{file} created" # we look for all the "targets" files and add them to main Targets Dir.chdir("#{etc_dir}/config.d") targets = Dir.glob('*.targets') file = "#{node['smokeping']['etc_dir']}/config.d/Targets" template file do cookbook 'smokeping' source 'Targets.erb' owner 'root' group 'root' mode '0644' variables( targets: targets ) notifies :restart, 'service[smokeping]', :delayed end Chef::Log.info "#{file} re-generated" end end action :delete do converge_by("Remove Smokeping target file for #{new_resource.name}") do name = new_resource.name file = "#{node['smokeping']['etc_dir']}/#{name}.targets" ::File.delete(file) if ::File.exist?(file) Chef::Log.info "#{file} deleted" end end
property :data, Array, default: [] action :create do converge_by("Create Smokeping target file for #{new_resource.name}") do name = new_resource.name etc_dir = node['smokeping']['etc_dir'] file = "#{etc_dir}/config.d/#{name}.targets" template file do cookbook 'smokeping' source 'group_targets.erb' mode '0644' variables( data: new_resource.data ) end Chef::Log.info "#{file} created" # we look for all the "targets" files and add them to main Targets Dir.chdir("#{etc_dir}/config.d") targets = Dir.glob('*.targets') file = "#{node['smokeping']['etc_dir']}/config.d/Targets" template file do cookbook 'smokeping' source 'Targets.erb' owner 'root' group 'root' mode '0644' variables( targets: targets ) notifies :restart, 'service[smokeping]', :delayed end Chef::Log.info "#{file} re-generated" end end action :delete do converge_by("Remove Smokeping target file for #{new_resource.name}") do name = new_resource.name file = "#{node['smokeping']['etc_dir']}/#{name}.targets" ::File.delete(file) if ::File.exist?(file) Chef::Log.info "#{file} deleted" end end
Rename spec support method for faster tab completion on save_and_open_page
module OpenFoodNetwork module HtmlHelper def save_and_open(html) require "launchy" file = Tempfile.new('html') file.write html Launchy.open(file.path) end end end
module OpenFoodNetwork module HtmlHelper def html_save_and_open(html) require "launchy" file = Tempfile.new('html') file.write html Launchy.open(file.path) end end end
Add myself as gem author
lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "climate_control/version" Gem::Specification.new do |gem| gem.name = "climate_control" gem.version = ClimateControl::VERSION gem.authors = ["Joshua Clayton"] gem.email = ["joshua.clayton@gmail.com"] gem.description = "Modify your ENV" gem.summary = "Modify your ENV easily with ClimateControl" gem.homepage = "https://github.com/thoughtbot/climate_control" gem.license = "MIT" gem.files = `git ls-files`.split($/) gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.require_paths = ["lib"] gem.required_ruby_version = ">= 2.5.0" gem.add_development_dependency "rspec" gem.add_development_dependency "rake" gem.add_development_dependency "simplecov" gem.add_development_dependency "standard" end
lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "climate_control/version" Gem::Specification.new do |gem| gem.name = "climate_control" gem.version = ClimateControl::VERSION gem.authors = ["Joshua Clayton", "Dorian Marié"] gem.email = ["joshua.clayton@gmail.com", "dorian@dorianmarie.fr"] gem.description = "Modify your ENV" gem.summary = "Modify your ENV easily with ClimateControl" gem.homepage = "https://github.com/thoughtbot/climate_control" gem.license = "MIT" gem.files = `git ls-files`.split($/) gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.require_paths = ["lib"] gem.required_ruby_version = ">= 2.5.0" gem.add_development_dependency "rspec" gem.add_development_dependency "rake" gem.add_development_dependency "simplecov" gem.add_development_dependency "standard" end
Create index against column type varchar for PostgreSQL
class ChangeColumnTypeToText < ActiveRecord::Migration def change return unless Redmine::Database.postgresql? opclass = "pgroonga.varchar_full_text_search_ops" reversible do |d| d.up do remove_index(:projects, [:id, :name, :identifier, :description]) remove_index(:news, [:id, :title, :summary, :description]) remove_index(:issues, [:id, :subject, :description]) remove_index(:documents, [:id, :title, :description]) remove_index(:messages, [:id, :subject, :content]) remove_index(:wiki_pages, [:id, :title]) remove_index(:attachments, [:id, :filename, :description]) [ [:projects, "id, name #{opclass}, identifier #{opclass}, description"], [:news, "id, title #{opclass}, summary #{opclass}, description"], [:issues, "id, subject #{opclass}, description"], [:documents, "id, title #{opclass}, description"], [:messages, "id, subject #{opclass}, content"], [:wiki_pages, "id, title #{opclass}"], [:attachments, "id, filename #{opclass}, description"], ].each do |table, columns| sql = "CREATE INDEX index_#{table}_pgroonga ON #{table} USING pgroonga (#{columns})" execute(sql) end end d.down do remove_index(:projects, name: "index_projects_pgroonga") remove_index(:news, name: "index_news_pgroonga") remove_index(:issues, name: "index_issues_pgroonga") remove_index(:documents, name: "index_documents_pgroonga") remove_index(:messages, name: "index_messages_pgroonga") remove_index(:wiki_pages, name: "index_wiki_pages_pgroonga") remove_index(:attachments, name: "index_attachments_pgroonga") add_index(:projects, [:id, :name, :identifier, :description], using: "pgroonga") add_index(:news, [:id, :title, :summary, :description], using: "pgroonga") add_index(:issues, [:id, :subject, :description], using: "pgroonga") add_index(:documents, [:id, :title, :description], using: "pgroonga") add_index(:messages, [:id, :subject, :content], using: "pgroonga") add_index(:wiki_pages, [:id, :title], using: "pgroonga") add_index(:attachments, [:id, :filename, :description], using: "pgroonga") end end end end
Rename and migrate art_museum.png to museum_art.png in node_types table
class ChangeArtMuseumToMuseumArt < ActiveRecord::Migration class LocalNodeType < ActiveRecord::Base self.table_name = 'node_types' validates :icon, presence: true end # Rename art_museum.png to museum_art.png but keep same identifier & osm_value def up node_type = LocalNodeType.find_by(id: 153) if node_type.nil? return else node_type.icon = 'museum_art.png' node_type.save end end def down node_type = LocalNodeType.find_by(id: 153) if node_type.nil? return else node_type.icon = 'art_museum.png' node_type.save end end end
Check if column even exists
namespace :data do desc "Data points, collections, etc. for aggregation." namespace :points do desc "Load data points and related records." task load: :environment do SpreadsheetConverter.new('db/fixtures/data_points.csv').perform! end end desc "Check that tables are there." namespace :tables do desc "Check that all the expected tables are in." task check: :environment do tables = DataPoint.find_each.map(&:tables).uniq! header tables.map do |table| status = table_status(table) puts "#{status}#{table}" end footer end def table_status(table) if GeographicDatabase.connection.table_exists? table "EXISTS #{good_keys?(table)}\t" else "MISSING\t\t\t" end end def good_keys?(table) conn = GeographicDatabase.connection keys = conn.execute "SELECT COUNT(*) FROM #{table} WHERE substring(geoid from '^.{7}') = '14000US';" count = conn.execute "SELECT COUNT(*) FROM #{table};" keys == conn ? "WITH GOOD IDS" : "BUT BAD IDS" end def header puts "\n" puts "STATUS / GEOIDS\t\tTABLE" puts "---------------------------------------------------------" end def footer # puts "=========================================================" puts "\n" end end end
namespace :data do desc "Data points, collections, etc. for aggregation." namespace :points do desc "Load data points and related records." task load: :environment do SpreadsheetConverter.new('db/fixtures/data_points.csv').perform! puts "Loaded #{DataPoint.count} data points!" end end desc "Check that tables are there." namespace :tables do desc "Check that all the expected tables are in." task check: :environment do tables = DataPoint.find_each.map(&:tables).uniq! header tables.map do |table| status = table_status(table) puts "#{status}#{table}" end footer end def table_status(table) if GeographicDatabase.connection.table_exists? table "EXISTS #{good_keys?(table)}\t" else "MISSING\t\t\t" end end def good_keys?(table) conn = GeographicDatabase.connection geoid = conn.column_exists?(table, 'geoid') return "NO COLUMN 'GEOID'" unless geoid keys = conn.execute "SELECT COUNT(*) FROM #{table} WHERE substring(geoid from '^.{7}') = '14000US';" count = conn.execute "SELECT COUNT(*) FROM #{table};" keys == conn ? "WITH GOOD IDS" : "BUT BAD IDS" end def header puts "\n" puts "STATUS / GEOIDS\t\tTABLE" puts "---------------------------------------------------------" end def footer # puts "=========================================================" puts "\n" end end end
Add support of <b> tag
When /^I get the bold text for the "([^\"]*)" element$/ do |el| @b = @page.send "#{el}" end Then /^I should see "([^\"]*)" in bold$/ do |text| @b.should == text end When /^I search bold text for the (\w+) by "([^"]*)"$/ do |text_decorator, type| @b = @page.send "#{text_decorator}_#{type}" end
When /^I get the bold text for the "([^\"]*)" element$/ do |el| @b = @page.send "#{el}_id" end Then /^I should see "([^\"]*)" in bold$/ do |text| @b.should == text end When /^I search bold text for the (\w+) by "([^"]*)"$/ do |text_decorator, type| @b = @page.send "#{text_decorator}_#{type}" end
Add test for related items on start page.
require 'spec_helper' describe "Start page" do specify "Inspecting the start page" do visit "/#{APP_SLUG}" within 'section#content' do within 'header' do page.should have_content("Business finance and support finder") page.should have_content("Quick answer") end within 'article[role=article]' do within 'section.intro' do page.should have_link("Get started", :href => "/#{APP_SLUG}/sectors") end end page.should have_selector(".article-container #test-report_a_problem") end end end
require 'spec_helper' describe "Start page" do specify "Inspecting the start page" do visit "/#{APP_SLUG}" within 'section#content' do within 'header' do page.should have_content("Business finance and support finder") page.should have_content("Quick answer") end within 'article[role=article]' do within 'section.intro' do page.should have_link("Get started", :href => "/#{APP_SLUG}/sectors") end end page.should have_selector(".article-container #test-report_a_problem") page.should have_selector("#test-related") end end end
Add simple instructions to get the tests running
require 'capybara' require 'capybara/mechanize' require 'sinatra' require 'spec' require 'capybara/spec/extended_test_app' # TODO move this stuff into capybara require 'capybara/spec/driver' require 'capybara/spec/session' alias :running :lambda Capybara.default_wait_time = 0 # less timeout so tests run faster Spec::Runner.configure do |config| config.after do Capybara.default_selector = :xpath end end REMOTE_TEST_HOST = "capybara-testapp.heroku.com" REMOTE_TEST_URL = "http://#{REMOTE_TEST_HOST}:8070"
require 'capybara' require 'capybara/mechanize' require 'sinatra' require 'spec' require 'capybara/spec/extended_test_app' # TODO move this stuff into capybara require 'capybara/spec/driver' require 'capybara/spec/session' alias :running :lambda Capybara.default_wait_time = 0 # less timeout so tests run faster Spec::Runner.configure do |config| config.after do Capybara.default_selector = :xpath end end # Until this library is merge with capybara there needs to be local app and you need to add # 127.0.0.1 capybara-testapp.heroku.com to your host file # Run the app with the following line: # ruby -rrubygems lib/capybara/spec/extended_test_app.rb REMOTE_TEST_HOST = "capybara-testapp.heroku.com" REMOTE_TEST_URL = "http://#{REMOTE_TEST_HOST}:8070"
Replace deprecated CodeClimate::TestReporter by SimpleCov
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require "codeclimate-test-reporter" CodeClimate::TestReporter.start require "panda_doc" RSpec.configure do |config| # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest # assertions if you prefer. config.expect_with :rspec do |expectations| # This option will default to `true` in RSpec 4. It makes the `description` # and `failure_message` of custom matchers include text for helper methods # defined using `chain`, e.g.: # be_bigger_than(2).and_smaller_than(4).description # # => "be bigger than 2 and smaller than 4" # ...rather than: # # => "be bigger than 2" expectations.include_chain_clauses_in_custom_matcher_descriptions = true end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on # a real object. This is generally recommended, and will default to # `true` in RSpec 4. mocks.verify_partial_doubles = true end end
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'simplecov' SimpleCov.start require 'panda_doc' RSpec.configure do |config| # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest # assertions if you prefer. config.expect_with :rspec do |expectations| # This option will default to `true` in RSpec 4. It makes the `description` # and `failure_message` of custom matchers include text for helper methods # defined using `chain`, e.g.: # be_bigger_than(2).and_smaller_than(4).description # # => "be bigger than 2 and smaller than 4" # ...rather than: # # => "be bigger than 2" expectations.include_chain_clauses_in_custom_matcher_descriptions = true end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on # a real object. This is generally recommended, and will default to # `true` in RSpec 4. mocks.verify_partial_doubles = true end end
Reset Timecop after each spec
ENV['RACK_ENV'] = "test" require File.expand_path(File.dirname(__FILE__) + "/../config/boot") require 'webmock/rspec' Webrat.configure do |conf| conf.mode = :rack end RSpec.configure do |conf| conf.include Rack::Test::Methods conf.include Webrat::Methods conf.include Webrat::Matchers conf.before(:each) { WebMock.reset! } end WebMock.disable_net_connect!
ENV['RACK_ENV'] = "test" require File.expand_path(File.dirname(__FILE__) + "/../config/boot") require 'webmock/rspec' Webrat.configure do |conf| conf.mode = :rack end RSpec.configure do |conf| conf.include Rack::Test::Methods conf.include Webrat::Methods conf.include Webrat::Matchers conf.before(:each) { WebMock.reset! } conf.after(:each) { Timecop.return } end WebMock.disable_net_connect!
Use environment variables for API keys
$LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require 'rubygems' require 'bundler' require 'bundler/setup' Bundler.setup(:development) require 'mailgun' require_relative 'unit/connection/test_client' # INSERT YOUR API KEYS HERE APIKEY = "key" PUB_APIKEY = "pubkey" APIHOST = "api.mailgun.net" APIVERSION = "v2" SSL= true
$LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require 'rubygems' require 'bundler' require 'bundler/setup' Bundler.setup(:development) require 'mailgun' require_relative 'unit/connection/test_client' # INSERT YOUR API KEYS HERE APIKEY = ENV['MAILGUN_API_KEY'] PUB_APIKEY = ENV['MAILGUN_PUBLIC_KEY'] APIHOST = "api.mailgun.net" APIVERSION = "v2" SSL = true
Add "/admin" prefix to path for article_manager
require_dependency "uramon_article_viewer/application_controller" require "faraday" module UramonArticleViewer class ArticlesController < ::ApplicationController BASE_URI = "http://localhost:3000/" before_filter :setup_connection def index response = @connection.get("/articles.json") @articles = JSON.parse(response.body) end def show response = @connection.get("/articles/1.json") @article = JSON.parse(response.body) end private def setup_connection @connection = Faraday::Connection.new(:url => BASE_URI) do |builder| builder.use Faraday::Request::UrlEncoded builder.use Faraday::Response::Logger builder.use Faraday::Adapter::NetHttp end end end end
require_dependency "uramon_article_viewer/application_controller" require "faraday" module UramonArticleViewer class ArticlesController < ::ApplicationController BASE_URI = "http://localhost:3000/" before_filter :setup_connection def index response = @connection.get("/admin/articles.json") p response.body @articles = JSON.parse(response.body) end def show response = @connection.get("/admin/articles/1.json") @article = JSON.parse(response.body) end private def setup_connection @connection = Faraday::Connection.new(:url => BASE_URI) do |builder| builder.use Faraday::Request::UrlEncoded builder.use Faraday::Response::Logger builder.use Faraday::Adapter::NetHttp end end end end
Fix issues with missing translation handling
if defined?(ActionView) module ActionView module Helpers module TranslationHelper def translate_with_rescue_format(key, options = {}) translate_without_rescue_format(key, options.merge(rescue_format: true)) end def t(key, options = {}) translate_without_rescue_format(key, options.merge(rescue_format: true)) end alias_method_chain :translate, :rescue_format end end end unless ActionView::Helpers::TranslationHelper.respond_to?(:translate_with_rescue_format) end
if defined?(ActionView) module ActionView module Helpers module TranslationHelper def translate_with_rescue_format(key, options = {}) translate_without_rescue_format(key, options.merge(raise: false)) end def t(key, options = {}) translate_without_rescue_format(key, options.merge(raise: false)) end alias_method_chain :translate, :rescue_format end end end unless ActionView::Helpers::TranslationHelper.respond_to?(:translate_with_rescue_format) end
Revert "Typo in hook declaration"
class CoreChargesHooks < Spree::ThemeSupport::HookListener insert_bottom :admin_product_form_right do '<%= f.label :core_amount, t("core_amount") %> <br /> <%= f.select :core_amount, [nil, 25.0, 50.0, 75.0, 100.0, 150.0, 200.0], :class => "text " %> <%= f.error_message_on :core_amount %>' end # insert_after :cart_items do # '<%- if @order.core_charges.any? -%><div class="right charge"><h3><%= t("core_charge_total") -%>: <span class="price"><%= number_to_currency(@order.core_charges.map(&:amount).sum) -%></span></h3></div><%- end -%>' # end end
class CoreChargesHooks < Spree::ThemeSupport::HookListener insert_after :admin_product_form_right do '<%= f.label :core_amount, t("core_amount") %> <br /> <%= f.select :core_amount, [nil, 25.0, 50.0, 75.0, 100.0, 150.0, 200.0], :class => "text " %> <%= f.error_message_on :core_amount %>' end # insert_after :cart_items do # '<%- if @order.core_charges.any? -%><div class="right charge"><h3><%= t("core_charge_total") -%>: <span class="price"><%= number_to_currency(@order.core_charges.map(&:amount).sum) -%></span></h3></div><%- end -%>' # end end
Update TG Pro.app to v2.8.5
cask :v1 => 'tg-pro' do version '2.8.4' sha256 'e574e92e411b694f19c9a1ac0583361187f428524987d6a220ea82d39d64ac46' url "http://www.tunabellysoftware.com/resources/TGPro_#{version.gsub('.','_')}.zip" name 'TG Pro' appcast 'http://tunabellysoftware.com/resources/sparkle/tgpro/profileInfo.php', :sha256 => '6377de7a9e67766d24c12c4580337b509d9572552e3def8a8f33af09272942e2' homepage 'http://www.tunabellysoftware.com/tgpro/' license :commercial app 'TG Pro.app' end
cask :v1 => 'tg-pro' do version '2.8.5' sha256 'ddffad55f0c8998323d270649f22f3e7a63ed45f867ba141a4b6df2b76bca6fc' url "http://www.tunabellysoftware.com/resources/TGPro_#{version.gsub('.','_')}.zip" name 'TG Pro' appcast 'http://tunabellysoftware.com/resources/sparkle/tgpro/profileInfo.php', :sha256 => '6377de7a9e67766d24c12c4580337b509d9572552e3def8a8f33af09272942e2' homepage 'http://www.tunabellysoftware.com/tgpro/' license :commercial app 'TG Pro.app' end
Bump podspec version to 2.0.0-alpha.2
Pod::Spec.new do |s| s.name = "Hydrant" s.version = "2.0.0-alpha" s.summary = "A simple data mapper / object serializer for objective-c" s.description = <<-DESC A simple object data mapper for Objective-C. Automated mapping of NSDictionaries/NSArrays to Value Objects with the goal of being exception-free and support graceful error handling. Read up the documentation at http://hydrant.readthedocs.org/. DESC s.homepage = "https://github.com/jeffh/Hydrant" s.license = { :type => 'BSD', :file => 'LICENSE' } s.author = { "Jeff Hui" => "jeff@jeffhui.net" } s.social_media_url = "http://twitter.com/jeffhui" s.ios.deployment_target = '6.0' s.osx.deployment_target = '10.8' s.source = { :git => "https://github.com/jeffh/Hydrant.git", :tag => "v#{s.version}" } s.source_files = 'Hydrant/**/*.{h,m}' s.public_header_files = 'Hydrant/Public/**/*.h' s.requires_arc = true end
Pod::Spec.new do |s| s.name = "Hydrant" s.version = "2.0.0-alpha.2" s.summary = "A simple data mapper / object serializer for objective-c" s.description = <<-DESC A simple object data mapper for Objective-C. Automated mapping of NSDictionaries/NSArrays to Value Objects with the goal of being exception-free and support graceful error handling. Read up the documentation at http://hydrant.readthedocs.org/. DESC s.homepage = "https://github.com/jeffh/Hydrant" s.license = { :type => 'BSD', :file => 'LICENSE' } s.author = { "Jeff Hui" => "jeff@jeffhui.net" } s.social_media_url = "http://twitter.com/jeffhui" s.ios.deployment_target = '6.0' s.osx.deployment_target = '10.8' s.source = { :git => "https://github.com/jeffh/Hydrant.git", :tag => "v#{s.version}" } s.source_files = 'Hydrant/**/*.{h,m}' s.public_header_files = 'Hydrant/Public/**/*.h' s.requires_arc = true end
Revert "A temp commit to test random failures"
require_relative '../../spec_helper' describe 'using director with nats server', type: :integration do # context 'when NATS ca cert provided does not verify the NATS server certificates' do # with_reset_sandbox_before_each(with_incorrect_nats_server_ca: true) # # it 'throws certificate validator error' do # manifest_hash = Bosh::Spec::Deployments.simple_manifest # # _, exit_code = deploy_from_scratch(manifest_hash: manifest_hash, failure_expected: true, return_exit_code: true) # expect(exit_code).to_not eq(0) # # task_id = bosh_runner.get_most_recent_task_id # debug_output = bosh_runner.run("task #{task_id} --debug", failure_expected: true) # expect(debug_output).to include('NATS client error: TLS Verification failed checking issuer based on CA') # end # end end
require_relative '../../spec_helper' describe 'using director with nats server', type: :integration do context 'when NATS ca cert provided does not verify the NATS server certificates' do with_reset_sandbox_before_each(with_incorrect_nats_server_ca: true) it 'throws certificate validator error' do manifest_hash = Bosh::Spec::Deployments.simple_manifest _, exit_code = deploy_from_scratch(manifest_hash: manifest_hash, failure_expected: true, return_exit_code: true) expect(exit_code).to_not eq(0) task_id = bosh_runner.get_most_recent_task_id debug_output = bosh_runner.run("task #{task_id} --debug", failure_expected: true) expect(debug_output).to include('NATS client error: TLS Verification failed checking issuer based on CA') end end end
Make snapshot name more unique
module VagrantPlugins module ProviderVirtualBox module Driver class Base def snapshot_take execute("snapshot", @uuid, "take", "vagrant-snap", "--pause") end def snapshot_rollback(bootmode) halt sleep 2 # race condition on locked VMs otherwise? execute("snapshot", @uuid, "restorecurrent") start(bootmode) end end end end end
module VagrantPlugins module ProviderVirtualBox module Driver class Base def snapshot_take execute("snapshot", @uuid, "take", "vagrant-snap-#{Time.now.to_i}", "--pause") end def snapshot_rollback(bootmode) halt sleep 2 # race condition on locked VMs otherwise? execute("snapshot", @uuid, "restorecurrent") start(bootmode) end end end end end
Set up configuration file from opsworks env variables
# Set up app's stack environment variables in the environment. node[:deploy].each do |application, deploy| custom_env_template do application application deploy deploy env node[:deploy][application][:environment_variables] if node[:opsworks][:instance][:layers].include?('rails-app') notifies :run, resources(:execute => "restart Rails app #{application} for custom env") end end end
Allow usage with Rails 4.x and 5.x
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "import_o_matic/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "import_o_matic" s.version = ImportOMatic::VERSION s.authors = ["Ruben Sierra Gonzelez"] s.email = ["ruben@simplelogica.net"] s.summary = "Data importation" s.description = "Data importation" s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", "~> 4" s.add_development_dependency "sqlite3" s.add_development_dependency "globalize", "~> 5.0.0" end
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "import_o_matic/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "import_o_matic" s.version = ImportOMatic::VERSION s.authors = ["Ruben Sierra Gonzelez"] s.email = ["ruben@simplelogica.net"] s.summary = "Data importation" s.description = "Data importation" s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", ">= 4" s.add_development_dependency "sqlite3" s.add_development_dependency "globalize", "~> 5.0.0" end
Add test for resource bindings
require_relative '../../integration/support/int_helper' #require 'core/app' describe Pakyow::App, '#resource' do include ReqResHelpers before do Pakyow::App.stage(:test) Pakyow.app.context = Pakyow::AppContext.new(mock_request, mock_response) end context 'called with a resource name, path, and block' do before do Pakyow.app.resource :test, "tests" do list do end end Pakyow.app.presenter.load end it 'creates a binding set for the resource name' do scope = Pakyow::Presenter::Binder.instance.sets[:main].scopes[:test] expect(scope).not_to be_nil end describe 'the binding set block' do let(:binding_set_block) { Pakyow.app.bindings[:main] } it 'exists' do expect(binding_set_block).to be_kind_of Proc end context 'when evaluated' do let(:set) { Pakyow::Presenter::BinderSet.new(&binding_set_block) } it 'creates restful bindings with with scope for resource name' do expect(set.has_prop?(:test, :_root, {})).to be true end end end end context 'called without a block' do before do Pakyow::App.routes :test do restful :test, "tests" do list do end end end end it 'presenter does not override core method' do expect(Pakyow.app.resource(:test)).to eq Pakyow::App.routes[:test] end end context 'called without a path' do it 'presenter does not override core method' do no_path_passed = Proc.new { Pakyow.app.resource(:test) {} } nil_path_passed = Proc.new { Pakyow.app.resource(:test, nil) {} } expect(no_path_passed).to raise_error ArgumentError expect(nil_path_passed).to raise_error ArgumentError end end context 'called without a resource name' do it 'presenter does not override core method' do no_name_passed = Proc.new { Pakyow.app.resource() {} } nil_name_passed = Proc.new { Pakyow.app.resource(nil, "tests") {} } expect(no_name_passed).to raise_error ArgumentError expect(nil_name_passed).to raise_error ArgumentError end end end
Modify list clean up job
class ListCleanupJob < ActiveJob::Base queue_as :default # rescue_from(Gibbon::MailChimpError) do |exception| # end def perform(lists) gibbon_service = GibbonService.new contacts_data = gibbon_service.delete_lists(lists.pluck(:uid)) lists.destroy_all end end
class ListCleanupJob < ActiveJob::Base queue_as :default # rescue_from(Gibbon::MailChimpError) do |exception| # end def perform(list_uids = []) gibbon_service = GibbonService.new contacts_data = gibbon_service.delete_lists(list_uids) Spree::Marketing::List.where(uid: list_uids).destroy_all end end
Fix SmartyPants in markdown renderer
class Forest::MarkdownRenderer < Redcarpet::Render::HTML include Redcarpet::Render::SmartyPants def self.options { hard_wrap: true, autolink: true, tables: true, safe_links_only: true, no_intra_emphasis: true, space_after_headers: true } end def postprocess(full_document) begin without_leading_trailing_paragraphs = Regexp.new(/\A<p>(.*)<\/p>\Z/mi).match(full_document)[1] unless without_leading_trailing_paragraphs.include?('<p>') full_document = without_leading_trailing_paragraphs end rescue Exception => e end full_document end end
class Forest::MarkdownRenderer < Redcarpet::Render::HTML def self.options { hard_wrap: true, autolink: true, tables: true, safe_links_only: true, no_intra_emphasis: true, space_after_headers: true } end def postprocess(full_document) begin without_leading_trailing_paragraphs = Regexp.new(/\A<p>(.*)<\/p>\Z/mi).match(full_document)[1] unless without_leading_trailing_paragraphs.include?('<p>') full_document = without_leading_trailing_paragraphs end full_document = Redcarpet::Render::SmartyPants.render(full_document) rescue Exception => e logger.error { "Error in Forest::MarkdownRenderer postprocess #{e.inspect}" } end full_document end end
Add a migration to update old-style redirect unpublishings
class UpdateOldRedirectUnpublishings < ActiveRecord::Migration[5.0] def up Unpublishing .where(type: :redirect) .where(redirects: nil) .find_each do |unpublishing| # this magical line works because the 'redirects' getter is overriden # to generate a JSON blob automatically if it is nil within the # database unpublishing.update_attribute(:redirects, unpublishing.redirects) end end end
Update gollum dependency to the lastest version.
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'gitnesse/version' Gem::Specification.new do |gem| gem.name = "gitnesse" gem.version = Gitnesse::VERSION gem.authors = ["www.hybridgroup.com"] gem.email = ["info@hybridgroup.com"] gem.description = %q{Use github wiki to store feature stories, then execute then using Cucumber} gem.summary = %q{Features on git-based Wiki!} gem.homepage = "https://github.com/hybridgroup/gitnesse" gem.files = `git ls-files`.split($/) gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.require_paths = ["lib"] gem.add_dependency("bundler","~> 1.2.1") gem.add_dependency("gollum","~> 2.3.4") gem.add_development_dependency("minitest-matchers") gem.add_development_dependency("mocha") gem.add_development_dependency("cucumber") gem.executables << 'gitnesse' end
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'gitnesse/version' Gem::Specification.new do |gem| gem.name = "gitnesse" gem.version = Gitnesse::VERSION gem.authors = ["www.hybridgroup.com"] gem.email = ["info@hybridgroup.com"] gem.description = %q{Use github wiki to store feature stories, then execute then using Cucumber} gem.summary = %q{Features on git-based Wiki!} gem.homepage = "https://github.com/hybridgroup/gitnesse" gem.files = `git ls-files`.split($/) gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.require_paths = ["lib"] gem.add_dependency("bundler","~> 1.2.1") gem.add_dependency("gollum","~> 2.3.12") gem.add_development_dependency("minitest-matchers") gem.add_development_dependency("mocha") gem.add_development_dependency("cucumber") gem.executables << 'gitnesse' end
Add missing dependencies to gemspec
$LOAD_PATH.unshift File.expand_path('../lib', __FILE__) require 'attribute_predicates/version' Gem::Specification.new do |s| s.name = "attribute_predicates" s.version = AttributePredicates::VERSION s.authors = ["Aaron Pfeifer"] s.email = "aaron@pluginaweek.org" s.homepage = "http://www.pluginaweek.org" s.description = "Adds automatic generation of predicate methods for attributes" s.summary = "Predicate methods for attributes" s.require_paths = ["lib"] s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- test/*`.split("\n") s.rdoc_options = %w(--line-numbers --inline-source --title attribute_predicates --main README.rdoc) s.extra_rdoc_files = %w(README.rdoc CHANGELOG.rdoc LICENSE) end
$LOAD_PATH.unshift File.expand_path('../lib', __FILE__) require 'attribute_predicates/version' Gem::Specification.new do |s| s.name = "attribute_predicates" s.version = AttributePredicates::VERSION s.authors = ["Aaron Pfeifer"] s.email = "aaron@pluginaweek.org" s.homepage = "http://www.pluginaweek.org" s.description = "Adds automatic generation of predicate methods for attributes" s.summary = "Predicate methods for attributes" s.require_paths = ["lib"] s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- test/*`.split("\n") s.rdoc_options = %w(--line-numbers --inline-source --title attribute_predicates --main README.rdoc) s.extra_rdoc_files = %w(README.rdoc CHANGELOG.rdoc LICENSE) s.add_development_dependency("rake") s.add_development_dependency("plugin_test_helper", ">= 0.3.2") end
Revise the example on OpenBSD
require_relative '../../spec_helper' describe "File.birthtime" do before :each do @file = __FILE__ end after :each do @file = nil end platform_is :windows, :darwin, :freebsd, :netbsd do it "returns the birth time for the named file as a Time object" do File.birthtime(@file) File.birthtime(@file).should be_kind_of(Time) end it "accepts an object that has a #to_path method" do File.birthtime(mock_to_path(@file)) end it "raises an Errno::ENOENT exception if the file is not found" do lambda { File.birthtime('bogus') }.should raise_error(Errno::ENOENT) end end # TODO: fix it. #platform_is :linux, :openbsd do # it "raises an NotImplementedError" do # lambda { File.birthtime(@file) }.should raise_error(NotImplementedError) # end #end end describe "File#birthtime" do before :each do @file = File.open(__FILE__) end after :each do @file.close @file = nil end platform_is :windows, :darwin, :freebsd, :netbsd do it "returns the birth time for self" do @file.birthtime @file.birthtime.should be_kind_of(Time) end end platform_is :linux, :openbsd do it "raises an NotImplementedError" do lambda { @file.birthtime }.should raise_error(NotImplementedError) end end end
require_relative '../../spec_helper' describe "File.birthtime" do before :each do @file = __FILE__ end after :each do @file = nil end platform_is :windows, :darwin, :freebsd, :netbsd do it "returns the birth time for the named file as a Time object" do File.birthtime(@file) File.birthtime(@file).should be_kind_of(Time) end it "accepts an object that has a #to_path method" do File.birthtime(mock_to_path(@file)) end it "raises an Errno::ENOENT exception if the file is not found" do lambda { File.birthtime('bogus') }.should raise_error(Errno::ENOENT) end end platform_is :openbsd do it "raises an NotImplementedError" do lambda { File.birthtime(@file) }.should raise_error(NotImplementedError) end end # TODO: depends on Linux kernel version end describe "File#birthtime" do before :each do @file = File.open(__FILE__) end after :each do @file.close @file = nil end platform_is :windows, :darwin, :freebsd, :netbsd do it "returns the birth time for self" do @file.birthtime @file.birthtime.should be_kind_of(Time) end end platform_is :linux, :openbsd do it "raises an NotImplementedError" do lambda { @file.birthtime }.should raise_error(NotImplementedError) end end end
Allow for some console hacking
require 'griddler/errors' require 'griddler/engine' require 'griddler/email' require 'griddler/email_parser' require 'griddler/configuration' module Griddler end
require 'rails/engine' require 'action_view' require 'griddler/errors' require 'griddler/engine' require 'griddler/email' require 'griddler/email_parser' require 'griddler/configuration' module Griddler end
Fix stty warning when reading terminal size
module Inch # The CLI module is tasked with the deconstruction of CLI calls # into API calls. # # @see Inch::API module CLI class << self # Returns the columns of the terminal window # (defaults to 80) # @param default [Fixnum] default value for columns # @return [Fixnum] def get_term_columns(default = 80) str = `stty size` rows_cols = str.split(' ').map(&:to_i) rows_cols[1] || default rescue default end end COLUMNS = get_term_columns end end require 'inch/cli/arguments' require 'inch/cli/sparkline_helper' require 'inch/cli/trace_helper' require 'inch/cli/yardopts_helper' require 'inch/cli/command'
module Inch # The CLI module is tasked with the deconstruction of CLI calls # into API calls. # # @see Inch::API module CLI class << self # Returns the columns of the terminal window # (defaults to 80) # @param default [Fixnum] default value for columns # @return [Fixnum] def get_term_columns(default = 80) str = `stty size 2>&1` if str =~ /Invalid argument/ default else rows_cols = str.split(' ').map(&:to_i) rows_cols[1] || default end rescue default end end COLUMNS = get_term_columns end end require 'inch/cli/arguments' require 'inch/cli/sparkline_helper' require 'inch/cli/trace_helper' require 'inch/cli/yardopts_helper' require 'inch/cli/command'
Add description for module tasks
# A ModuleTask represents two file tasks: a dynamic library and an # associated .swiftmodule file. require 'rake' require 'rake/tasklib' require_relative 'group_task' require_relative 'dylib_task' module Swift class ModuleTask < Rake::TaskLib attr_accessor :module_name, :dylib_name, :swiftmodule_name, :source_files def initialize(module_name, source_files) @module_name = module_name @dylib_name = dylib_for_module(module_name) @swiftmodule_name = module_name.ext('.swiftmodule') @source_files = source_files end def define define_dylib_task define_swiftmodule_task define_wrapper_task end def define_dylib_task deps = DylibTask.synthesize_object_file_dependencies(source_files, module_name) DylibTask.define_task(dylib_name => deps) end def define_swiftmodule_task SwiftmoduleTask.define_task(swiftmodule_name => source_files) end def define_wrapper_task ModuleWrapperTask.define_task(module_name => [dylib_name, swiftmodule_name]) end private def dylib_for_module(module_name) module_name.sub(/^(?!lib)/, 'lib').ext('.dylib') end end class ModuleWrapperTask < Rake::Task include GroupTask end end
# A ModuleTask represents two file tasks: a dynamic library and an # associated .swiftmodule file. require 'rake' require 'rake/tasklib' require_relative 'group_task' require_relative 'dylib_task' module Swift class ModuleTask < Rake::TaskLib attr_accessor :module_name, :dylib_name, :swiftmodule_name, :source_files def initialize(module_name, source_files) @module_name = module_name @dylib_name = dylib_for_module(module_name) @swiftmodule_name = module_name.ext('.swiftmodule') @source_files = source_files end def define define_dylib_task define_swiftmodule_task define_wrapper_task end def define_dylib_task deps = DylibTask.synthesize_object_file_dependencies(source_files, module_name) DylibTask.define_task(dylib_name => deps) end def define_swiftmodule_task SwiftmoduleTask.define_task(swiftmodule_name => source_files) end def define_wrapper_task desc "Build module '#{module_name}'" ModuleWrapperTask.define_task(module_name => [dylib_name, swiftmodule_name]) end private def dylib_for_module(module_name) module_name.sub(/^(?!lib)/, 'lib').ext('.dylib') end end class ModuleWrapperTask < Rake::Task include GroupTask end end
Add the spec for the hash fetcher
require 'spec_helper' require 'observed/hash/fetcher' describe Observed::Hash::Fetcher do subject { described_class.new(hash) } context 'when the source hash is nil' do let(:hash) { nil } it 'fails' do expect { subject }.to raise_error end end context 'when the source hash is nested' do let(:hash) { {foo:{bar:1},baz:2} } it 'decodes the key path to recursively find the value' do expect(subject['foo.bar']).to eq(1) expect(subject['baz']).to eq(2) end end end
Allow save options to be passed in to archive! method
require 'active_support/concern' module Archivable module Model extend ActiveSupport::Concern module ClassMethods def archived scoped(conditions: { archived: true }) end def unarchived scoped(conditions: { archived: false }) end end def archived? archived end def archive! self.archived = true save end def unarchive! self.archived = false save end def is_archivable? respond_to?(:archived) end end end
require 'active_support/concern' module Archivable module Model extend ActiveSupport::Concern module ClassMethods def archived scoped(conditions: { archived: true }) end def unarchived scoped(conditions: { archived: false }) end end def archived? archived end def archive!(save_args = {}) self.archived = true save(save_args) end def unarchive! self.archived = false save end def is_archivable? respond_to?(:archived) end end end
Fix 500 error when requesting the favicon when not logged in.
module AuthenticationBehavior extend ActiveSupport::Concern included do before_action :require_netbadge end private def require_netbadge # # if the user is already signed in, then we are good... # if user_signed_in? return end # # check the request environment and see if we have a user defined by netbadge # if request.env['HTTP_REMOTE_USER'].present? puts "=====> HTTP_REMOTE_USER: #{request.env['HTTP_REMOTE_USER']}" begin return if sign_in_user_id( request.env['HTTP_REMOTE_USER'] ) rescue return false end end puts "=====> HTTP_REMOTE_USER NOT defined" # # a hack to allow us to login without netbadge # if ENV['ALLOW_FAKE_NETBADGE'] == 'true' @users = User.order( :email ) @users = @users.map {|user| user.email.split("@")[0] } else raise ActionController::RoutingError.new( 'Forbidden' ) end end end
module AuthenticationBehavior extend ActiveSupport::Concern included do before_action :require_netbadge end private def require_netbadge # # if the user is already signed in, then we are good... # if user_signed_in? return end # # check the request environment and see if we have a user defined by netbadge # if request.env['HTTP_REMOTE_USER'].present? puts "=====> HTTP_REMOTE_USER: #{request.env['HTTP_REMOTE_USER']}" begin # TODO-PER: This fails when called when requesting the favicon. I'm not sure why, but the errors are obscuring real system errors. return if sign_in_user_id( request.env['HTTP_REMOTE_USER'] ) rescue return false end end puts "=====> HTTP_REMOTE_USER NOT defined" # # a hack to allow us to login without netbadge # if ENV['ALLOW_FAKE_NETBADGE'] == 'true' @users = User.order( :email ) @users = @users.map {|user| user.email.split("@")[0] } else raise ActionController::RoutingError.new( 'Forbidden' ) end end end
Remove outdated activesupport dependency Update webmock dependency version
# coding: utf-8 $:.push File.expand_path('../lib', __FILE__) require 'sms_ru/version' Gem::Specification.new do |spec| spec.name = 'smsru' spec.version = SmsRu::VERSION spec.authors = ['Alex Antonov'] spec.email = ['alex@fasteria.ru'] spec.summary = %q{http://sms.ru api integration for ruby} spec.homepage = 'https://github.com/asiniy/sms_ru' spec.license = 'MIT' spec.files = `git ls-files`.split("\n") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = `git ls-files -- spec/*`.split("\n").map{ |f| File.basename(f) } spec.require_paths = ['lib'] spec.required_ruby_version = '>= 2.0.0' spec.add_dependency 'activesupport', '~> 4.2.0' spec.add_dependency 'launchy', '~> 2.4' spec.add_dependency 'webmock', '~> 1.20' spec.add_development_dependency 'bundler', '~> 1.7' spec.add_development_dependency 'rake', '~> 10.0' spec.add_development_dependency 'rspec', '~> 3' end
# coding: utf-8 $:.push File.expand_path('../lib', __FILE__) require 'sms_ru/version' Gem::Specification.new do |spec| spec.name = 'smsru' spec.version = SmsRu::VERSION spec.authors = ['Alex Antonov'] spec.email = ['alex@fasteria.ru'] spec.summary = %q{http://sms.ru api integration for ruby} spec.homepage = 'https://github.com/asiniy/sms_ru' spec.license = 'MIT' spec.files = `git ls-files`.split("\n") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = `git ls-files -- spec/*`.split("\n").map{ |f| File.basename(f) } spec.require_paths = ['lib'] spec.required_ruby_version = '>= 2.0.0' spec.add_dependency 'launchy', '~> 2.4' spec.add_dependency 'webmock', '~> 2.3' spec.add_development_dependency 'bundler', '~> 1.7' spec.add_development_dependency 'rake', '~> 10.0' spec.add_development_dependency 'rspec', '~> 3' end
Test with another user for unicorn deployment
# Set your full path to application. app_path = "/home/rails/current" # Set unicorn options worker_processes 3 preload_app true timeout 180 listen "127.0.0.1:8080" # Spawn unicorn master worker for user apps (group: apps) user 'root', 'rails' # Fill path to your app working_directory app_path # Should be 'production' by default, otherwise use other env rails_env = ENV['RAILS_ENV'] || 'production' # Log everything to one file stderr_path "log/unicorn.log" stdout_path "log/unicorn.log" # Set master PID location pid "#{app_path}/tmp/pids/unicorn.pid" before_fork do |server, worker| ActiveRecord::Base.connection.disconnect! old_pid = "#{server.config[:pid]}.oldbin" if File.exists?(old_pid) && server.pid != old_pid begin Process.kill("QUIT", File.read(old_pid).to_i) rescue Errno::ENOENT, Errno::ESRCH # someone else did our job for us end end end after_fork do |server, worker| ActiveRecord::Base.establish_connection end
# Set your full path to application. app_path = "/home/rails/current" # Set unicorn options worker_processes 3 preload_app true timeout 180 listen "127.0.0.1:8080" # Spawn unicorn master worker for user apps (group: apps) user 'root', 'root' # Fill path to your app working_directory app_path # Should be 'production' by default, otherwise use other env rails_env = ENV['RAILS_ENV'] || 'production' # Log everything to one file stderr_path "log/unicorn.log" stdout_path "log/unicorn.log" # Set master PID location pid "#{app_path}/tmp/pids/unicorn.pid" before_fork do |server, worker| ActiveRecord::Base.connection.disconnect! old_pid = "#{server.config[:pid]}.oldbin" if File.exists?(old_pid) && server.pid != old_pid begin Process.kill("QUIT", File.read(old_pid).to_i) rescue Errno::ENOENT, Errno::ESRCH # someone else did our job for us end end end after_fork do |server, worker| ActiveRecord::Base.establish_connection end
Add radial example of circles
require './lib/lodo' ROW_COUNT = 9 COL_COUNT = 9 COLOR_COUNT = 18 board = Lodo::Board.new offset = 0.0 spread = 1.3 border_brightness = 0.0 border_brightness_increasing = true border_brightness_speed = 0.2 distance_table = [] COL_COUNT.times do |col| distance_table[col] = [] ROW_COUNT.times do |row| distance_table[col][row] = Math.sqrt(((row - 4) ** 2)+((col - 4)) ** 2) end end loop do COL_COUNT.times do |col| ROW_COUNT.times do |row| distance = distance_table[col][row] brightness = Math.sin((distance + offset) * spread) * 100 # puts "(#{row - 4}, #{col-4}, #{distance})" # brightness = (distance - 2) * -255 + 255 # if distance <= 2 # board.draw_pixel(col, row, {red: 255, blue: 255, green: 255}) if brightness <= 0 board.draw_pixel(col, row, {red: 0, blue: 0, green: 0}) else board.draw_pixel(col, row, {red: brightness.abs.to_i, blue: brightness.abs.to_i, green: brightness.abs.to_i}) end end end [0,8].each do |col| ROW_COUNT.times do |row| board.draw_pixel(col, row, {red: border_brightness, blue: 0, green: 0}) end end COL_COUNT.times do |col| [0,8].each do |row| board.draw_pixel(col, row, {red: border_brightness.to_i, blue: 0, green: 0}) end end if border_brightness_increasing border_brightness += border_brightness_speed else border_brightness -= border_brightness_speed end if border_brightness >= 100 border_brightness_increasing = false border_brightness = 100 elsif border_brightness <= 0 border_brightness_increasing = true border_brightness = 0 end board.save offset -= 0.005 end
Set swift version no to 5.0
Pod::Spec.new do |s| s.name = 'Bulldog' s.version = '1.0.3' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'Bulldog is a super-fast json parser that will keep attacking until it gets the value you desire, or you give up. Just like a bulldog.' s.social_media_url = 'http://twitter.com/iosCook' s.homepage = 'https://github.com/freesuraj/Bulldog' s.authors = { 'Suraj Pathak' => 'freesuraj@gmail.com' } s.source = { :git => 'https://github.com/freesuraj/Bulldog.git', :tag => s.version } s.ios.deployment_target = '9.0' s.swift_version = '5.0' s.source_files = 'Source/*swift' end
Pod::Spec.new do |s| s.name = 'Bulldog' s.version = '1.0.3' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'Bulldog is a super-fast json parser that will keep attacking until it gets the value you desire, or you give up. Just like a bulldog.' s.social_media_url = 'http://twitter.com/iosCook' s.homepage = 'https://github.com/freesuraj/Bulldog' s.authors = { 'Suraj Pathak' => 'freesuraj@gmail.com' } s.source = { :git => 'https://github.com/freesuraj/Bulldog.git', :tag => s.version } s.ios.deployment_target = '9.0' s.swift_version = "4.2" s.swift_versions = ['4.0', '4.2', '5.0'] s.source_files = 'Source/*swift' end
Add steps for personal phone and address
Given /^my first name is "(.*?)"$/ do |name| @first_name = name end Given /^my last name is "(.*?)"$/ do |name| @last_name = name end Given /^I do not work for anyone$/ do @company = nil end Given /^I work for "(.*?)"$/ do |company| @company = company end Given /^my email address is "(.*)"$/ do |email| @email = email end Given /^that company has a invoice contact email of "(.*?)"$/ do |email| @invoice_email = email end Given /^that company has a invoice phone number of "(.*?)"$/ do |phone| @invoice_phone = phone end Given /^that company has a invoice address of "(.*?)"$/ do |invoice_address| @invoice_address = invoice_address end Given /^I entered a purchase order number "(.*?)"$/ do |po_number| @purchase_order_number = po_number end Given /^I entered a VAT registration number "(.*?)"$/ do |vat_reg_number| @vat_reg_number = vat_reg_number end Given /^I entered a membership number "(.*?)"$/ do |membership_number| @membership_number = membership_number end Given /^I paid with Paypal$/ do @payment_method = :paypal end Given /^I requested an invoice$/ do @payment_method = :invoice end
Given /^my first name is "(.*?)"$/ do |name| @first_name = name end Given /^my last name is "(.*?)"$/ do |name| @last_name = name end Given /^I do not work for anyone$/ do @company = nil end Given /^I work for "(.*?)"$/ do |company| @company = company end Given /^my email address is "(.*)"$/ do |email| @email = email end Given /^my phone number is "(.*?)"$/ do |phone| @phone = phone end Given /^my address is "(.*?)"$/ do |address| @address = address end Given /^that company has a invoice contact email of "(.*?)"$/ do |email| @invoice_email = email end Given /^that company has a invoice phone number of "(.*?)"$/ do |phone| @invoice_phone = phone end Given /^that company has a invoice address of "(.*?)"$/ do |invoice_address| @invoice_address = invoice_address end Given /^I entered a purchase order number "(.*?)"$/ do |po_number| @purchase_order_number = po_number end Given /^I entered a VAT registration number "(.*?)"$/ do |vat_reg_number| @vat_reg_number = vat_reg_number end Given /^I entered a membership number "(.*?)"$/ do |membership_number| @membership_number = membership_number end Given /^I paid with Paypal$/ do @payment_method = :paypal end Given /^I requested an invoice$/ do @payment_method = :invoice end
Return a lambda in the translation instead of a standard value. Also adds template name as prefix key for translation
require 'mustache' require 'alephant/views' require 'hashie' require 'i18n' module Alephant::Views class Base < Mustache attr_accessor :data, :locale def initialize(data = {}) @data = Hashie::Mash.new data @locale = 'en' end def locale=(l) @locale = l end def t(*args) I18n.locale = @locale I18n.t(*args) end def self.inherited(subclass) ::Alephant::Views.register(subclass) end end end
require 'mustache' require 'alephant/views' require 'hashie' require 'json' require 'i18n' module Alephant::Views class Base < Mustache attr_accessor :data, :locale def initialize(data = {}, locale = 'en') @data = Hashie::Mash.new data @locale = locale end def locale=(l) @locale = l end def t(*args) I18n.locale = @locale lambda do |comma_delimited_args| args = comma_delimited_args.strip.split ',' key = args.shift params = args.empty? ? {} : JSON.parse(args.first).with_indifferent_access prefix = /\/([^\/]+)\./.match(template_file)[1] I18n.translate("#{prefix}.#{key}", params) end end def self.inherited(subclass) ::Alephant::Views.register(subclass) end end end
Disable persistence for search window in GridPanel
module Netzke module Basepack class SearchWindow < Netzke::Basepack::Window action :search do { :text => I18n.t('netzke.basepack.search_window.action.search') } end action :cancel do { :text => I18n.t('netzke.basepack.search_window.action.search') } end js_properties :width => "50%", :auto_height => true, :close_action => "hide", :buttons => [:search.action, :cancel.action], :modal => true def configuration super.tap do |s| s[:items] = [:search_panel.component(:prevent_header => true)] s[:title] = I18n.t('netzke.basepack.search_window.title') end end component :search_panel do { :class_name => "Netzke::Basepack::QueryBuilder", :model => config[:model] } end js_method :init_component, <<-JS function(){ this.callParent(); this.on('show', function(){ this.closeRes = 'cancel'; }); } JS js_method :get_query, <<-JS function(){ return this.items.first().getQuery(); } JS js_method :on_search, <<-JS function(){ this.closeRes = 'search'; this.hide(); } JS js_method :on_cancel, <<-JS function(){ this.hide(); } JS end end end
module Netzke module Basepack class SearchWindow < Netzke::Basepack::Window action :search do { :text => I18n.t('netzke.basepack.search_window.action.search') } end action :cancel do { :text => I18n.t('netzke.basepack.search_window.action.search') } end js_properties :width => "50%", :auto_height => true, :close_action => "hide", :buttons => [:search.action, :cancel.action], :modal => true def configuration super.tap do |s| s[:items] = [:search_panel.component(:prevent_header => true)] s[:title] = I18n.t('netzke.basepack.search_window.title') s[:persistence] = false end end component :search_panel do { :class_name => "Netzke::Basepack::QueryBuilder", :model => config[:model] } end js_method :init_component, <<-JS function(){ this.callParent(); this.on('show', function(){ this.closeRes = 'cancel'; }); } JS js_method :get_query, <<-JS function(){ return this.items.first().getQuery(); } JS js_method :on_search, <<-JS function(){ this.closeRes = 'search'; this.hide(); } JS js_method :on_cancel, <<-JS function(){ this.hide(); } JS end end end
Create spec examples for DbNew button class
describe ApplicationHelper::Button::DbNew do let(:view_context) { setup_view_context_with_sandbox({}) } let(:dashboard_count) { 9 } let(:widgetsets) { Array.new(dashboard_count) { |_i| FactoryGirl.create(:miq_widget_set) } } let(:button) { described_class.new(view_context, {}, {'widgetsets' => widgetsets}, {}) } describe '#calculate_properties' do before { button.calculate_properties } context 'when dashboard group is full' do let(:dashboard_count) { 10 } it_behaves_like 'a disabled button', 'Only 10 Dashboards are allowed for a group' end context 'when dashboard group has still room for a new dashboard' do it_behaves_like 'an enabled button' end end end
Add a default if a planning app has no location
class PlanningApplication::IssuesController < IssuesController before_filter :load_planning_application before_filter :check_for_issue def new @issue = @planning_application.populate_issue @start_location = @planning_application.location render 'issues/new' end protected def load_planning_application @planning_application = PlanningApplication.find params[:planning_application_id] end def check_for_issue if @planning_application.issue set_flash_message :already redirect_to planning_application_path @planning_application end end end
class PlanningApplication::IssuesController < IssuesController before_filter :load_planning_application before_filter :check_for_issue def new @issue = @planning_application.populate_issue @start_location = @planning_application.location || index_start_location render 'issues/new' end protected def load_planning_application @planning_application = PlanningApplication.find params[:planning_application_id] end def check_for_issue if @planning_application.issue set_flash_message :already redirect_to planning_application_path @planning_application end end end
Read results from the queue
require "testjour/commands/command" require "testjour/http_queue" require "systemu" require "net/http" module Testjour module Commands class Run < Command def execute testjour_path = File.expand_path(File.dirname(__FILE__) + "/../../../bin/testjour") cmd = "#{testjour_path} local:run #{@args.join(' ')}" HttpQueue.with_queue do require 'cucumber/cli/main' configuration.load_language HttpQueue.with_net_http do |http| configuration.feature_files.each do |feature_file| post = Net::HTTP::Post.new("/feature_files") post.form_data = {"data" => feature_file} http.request(post) end end status, stdout, stderr = systemu(cmd) @out_stream.write stdout @err_stream.write stderr status.exitstatus end end def configuration return @configuration if @configuration @configuration = Cucumber::Cli::Configuration.new(StringIO.new, StringIO.new) @configuration.parse!(@args) @configuration end end end end
require "testjour/commands/command" require "testjour/http_queue" require "systemu" require "net/http" module Testjour module Commands class Run < Command def execute HttpQueue.with_queue do require 'cucumber/cli/main' configuration.load_language HttpQueue.with_net_http do |http| configuration.feature_files.each do |feature_file| post = Net::HTTP::Post.new("/feature_files") post.form_data = {"data" => feature_file} http.request(post) end end testjour_path = File.expand_path(File.dirname(__FILE__) + "/../../../bin/testjour") cmd = "#{testjour_path} local:run #{@args.join(' ')}" systemu(cmd) results = [] HttpQueue.with_net_http do |http| configuration.feature_files.each do |feature_file| get = Net::HTTP::Get.new("/results") results << http.request(get).body end end if results.include?("F") @out_stream.write "Failed" 1 else @out_stream.write "Passed" 0 end end end def configuration return @configuration if @configuration @configuration = Cucumber::Cli::Configuration.new(StringIO.new, StringIO.new) @configuration.parse!(@args) @configuration end end end end
Add the timing-fields to the generated migration
module Announcements class InstallGenerator < Rails::Generators::Base desc "Installs the Announcement gem" source_root File.expand_path('../templates', __FILE__) def create_model say "--- Creating model in app/models..." template "announcement.rb", "app/models/announcement.rb" say "--- Creating the migration ..." generate("model", "announcement body:text heading:text type:string --skip") say "--- Running the migration..." rake("db:migrate") end def create_js_files say "--- Copying js to vendor/assets/javascripts..." template "announcements.js", "vendor/assets/javascripts/announcements.js" say "--- Adding require in app/assets/javascripts/application.js..." insert_into_file "app/assets/javascripts/application.js", "//= require announcements\n", :after => "jquery_ujs\n" say "--- IMPORTANT: New asset was added in the vendor folder; you have to precompile assets for production!" end end end
module Announcements class InstallGenerator < Rails::Generators::Base desc "Installs the Announcement gem" source_root File.expand_path('../templates', __FILE__) def create_model say "--- Creating model in app/models..." template "announcement.rb", "app/models/announcement.rb" say "--- Creating the migration ..." generate("model", "announcement body:text heading:text type:string visible_at:datetime invisible_at:datetime --skip") say "--- Running the migration..." rake("db:migrate") end def create_js_files say "--- Copying js to vendor/assets/javascripts..." template "announcements.js", "vendor/assets/javascripts/announcements.js" say "--- Adding require in app/assets/javascripts/application.js..." insert_into_file "app/assets/javascripts/application.js", "//= require announcements\n", :after => "jquery_ujs\n" say "--- IMPORTANT: New asset was added in the vendor folder; you have to precompile assets for production!" end end end
Add tests for rsync finalizer
require "test_helper" require "roger/testing/mock_release" module Roger # Test for Roger Rsync finalizer class RsyncTest < ::Test::Unit::TestCase include TestConstruct::Helpers def setup @release = Testing::MockRelease.new # Create a file to release in the build dir @release.project.construct.file "build/index.html" # Set fixed version @release.scm.version = "1.0.0" # A target dir @target_path = setup_construct(chdir: false) end # called after every single test def teardown teardown_construct(@target_path) @release.destroy @release = nil end def test_basic_functionality finalizer = Roger::Release::Finalizers::Rsync.new( remote_path: @target_path.to_s, ask: false ) finalizer.call(@release) assert File.exist?(@target_path + "index.html"), @release.target_path.inspect end def test_rsync_command_works finalizer = Roger::Release::Finalizers::Rsync.new( rsync: "rsync-0123456789", # Let's hope nobody actually has this command remote_path: @target_path.to_s, ask: false ) assert_raise(RuntimeError) do finalizer.call(@release) end end end end
Fix fonts install skipping issue
# frozen_string_literal: true # https://github.com/adobe-fonts/source-han-code-jp/archive/2.011R.tar.gz # node['source_han_code_jp_conts']['version'] version = node['source_han_code_jp_conts']['version'] archive_name = "#{version}.tar.gz" download_path = File.join(Chef::Config['file_cache_path'], archive_name) install_dir = node['source_han_code_jp_conts']['install_dir'] remote_file download_path do source "https://github.com/adobe-fonts/source-han-code-jp/archive/#{version}.tar.gz" mode 0o0644 not_if "test -f #{download_path}" end execute 'install source han code jp fonts' do cwd Chef::Config['file_cache_path'] command <<-COMMAND tar xzf #{archive_name} cp source-han-code-jp-#{version}/OTF/*.otf #{install_dir}/ fc-cache -fv COMMAND not_if 'ls #{install_dir} | grep SourceHanCodeJP' end
# frozen_string_literal: true # https://github.com/adobe-fonts/source-han-code-jp/archive/2.011R.tar.gz # node['source_han_code_jp_conts']['version'] version = node['source_han_code_jp_conts']['version'] archive_name = "#{version}.tar.gz" download_path = File.join(Chef::Config['file_cache_path'], archive_name) install_dir = node['source_han_code_jp_conts']['install_dir'] remote_file download_path do source "https://github.com/adobe-fonts/source-han-code-jp/archive/#{version}.tar.gz" mode 0o0644 not_if "test -f #{download_path}" end execute 'install source han code jp fonts' do cwd Chef::Config['file_cache_path'] command <<-COMMAND tar xzf #{archive_name} cp source-han-code-jp-#{version}/OTF/*.otf #{install_dir}/ fc-cache -fv COMMAND not_if "ls #{install_dir} | grep SourceHanCodeJP" end
Set working directory to pwd
require 'god' unless ENV.has_key?('HIPCHAT_API_TOKEN') abort 'Set HIPCHAT_API_TOKEN environment variable with your HipChat API Token: https://hipchat.com/account/api' end God.watch do |w| w.name = 'irc2hipchat' w.start = 'bundle exec ruby irc2hipchat.rb' end
require 'god' unless ENV.has_key?('HIPCHAT_API_TOKEN') abort 'Set HIPCHAT_API_TOKEN environment variable with your HipChat API Token: https://hipchat.com/account/api' end God.watch do |w| w.name = 'irc2hipchat' w.start = "bundle exec ruby irc2hipchat.rb" w.dir = `pwd`.chomp w.keepalive end
Fix for case-sensitive systems in Kindle Cask
cask :v1 => 'kindle' do version '41015' sha256 '1c15ce4df69044dc9d2d3562b7f5a8589b65efa5b8e64bc2bcdd7ed41c05df38' url "http://kindleformac.amazon.com/#{version}/KindleForMac-#{version}.dmg" name 'Kindle for Mac' homepage 'https://www.amazon.com/gp/digital/fiona/kcp-landing-page' license :gratis app 'Kindle.App' zap :delete => [ '~/Library/Preferences/com.amazon.Kindle.plist', '~/Library/Application Support/Kindle/', '~/Library/Saved Application State/com.amazon.Kindle.savedState/', '~/Library/Caches/com.amazon.Kindle-Crash-Reporter/' ] end
cask :v1 => 'kindle' do version '41015' sha256 '1c15ce4df69044dc9d2d3562b7f5a8589b65efa5b8e64bc2bcdd7ed41c05df38' url "http://kindleformac.amazon.com/#{version}/KindleForMac-#{version}.dmg" name 'Kindle for Mac' homepage 'https://www.amazon.com/gp/digital/fiona/kcp-landing-page' license :gratis app 'Kindle.app' zap :delete => [ '~/Library/Preferences/com.amazon.Kindle.plist', '~/Library/Application Support/Kindle/', '~/Library/Saved Application State/com.amazon.Kindle.savedState/', '~/Library/Caches/com.amazon.Kindle-Crash-Reporter/' ] end
Add array accessors and method to set (delete all and add new) tags.
module SharedMethods def to_hash result = {} self.each do |key, value| if result[key] if result[key].is_a? Array result[key] << value else result[key] = [result[key], value] end else result[key] = value end end result end def inspect items = [] self.to_hash.sort.each do |k,v| items << %Q["#{k}"=>#{v.inspect}] end "#<#{self.class.name}: {#{items.join(', ')}}>" end end
module SharedMethods def to_hash result = {} self.each do |key, value| if result[key] if result[key].is_a? Array result[key] << value else result[key] = [result[key], value] end else result[key] = value end end result end def inspect items = [] self.to_hash.sort.each do |k,v| items << %Q["#{k}"=>#{v.inspect}] end "#<#{self.class.name}: {#{items.join(', ')}}>" end def [](key) self.to_hash[key] end def []=(key, value) delete_all(key) if value.is_a?(Array) value.each do |v| self.add(key, v) end else self.add(key, value) end end def delete_all(key) del = true while(del) do del = self.delete(key) end end end
Remove serverspec tests that are unable to be tested w/o TS key
# Encoding: utf-8 require 'serverspec' set :backend, :exec describe package('threatstack-agent') do it { should be_installed } end describe service('cloudsight') do it { should be_enabled } end describe service('cloudsight') do it { should be_running } end describe service('tsfim') do it { should be_running } end describe service('tsauditd') do it { should be_running } end describe file('/opt/threatstack/cloudsight/config/.secret') do it { should be_file } end
# Encoding: utf-8 require 'serverspec' set :backend, :exec describe package('threatstack-agent') do it { should be_installed } end describe service('cloudsight') do it { should be_enabled } end
Make target_dir parameter of migrate_assets rake task
namespace :asset_manager do desc "Migrates Assets to Asset Manager." task migrate_assets: :environment do MigrateAssetsToAssetManager.new.perform end end
namespace :asset_manager do desc "Migrates Assets to Asset Manager." task :migrate_assets, [:target_dir] => :environment do |_, args| abort(usage_string) unless args[:target_dir] MigrateAssetsToAssetManager.new(args[:target_dir]).perform end private def usage_string %{Usage: asset_manager:migrate_assets[<path>] Where <path> is a subdirectory under Whitehall.clean_uploads_root e.g. `system/uploads/organisation/logo` } end end
Remove old dead env vars
# # Copyright 2022 Thoughtworks, 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. # ENV['ADMIN_OAUTH_URL_PREFIX'] = "admin" ENV['LOAD_OAUTH_SILENTLY'] = "yes" # Load the Rails application. require_relative 'application' # Initialize the Rails application. Rails.application.initialize!
# # Copyright 2022 Thoughtworks, 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. # # Load the Rails application. require_relative 'application' # Initialize the Rails application. Rails.application.initialize!
Update attributes for device data updater
# # Author:: Tim Smith(<tim.smith@webtrends.com>) # Cookbook Name:: wt_devicedataupdater # Attribute:: default # # Copyright 2012, Webtrends Inc. # default['wt_devicedataupdater']['zip_file'] = "RoadRunner.zip" default['wt_devicedataupdater']['build_url'] = "" default['wt_devicedataupdater']['install_dir'] = "\\DeviceDataUpdater" default['wt_devicedataupdater']['log_dir'] = "\\logs"
# # Author:: Tim Smith(<tim.smith@webtrends.com>) # Cookbook Name:: wt_devicedataupdater # Attribute:: default # # Copyright 2012, Webtrends Inc. # default['wt_devicedataupdater']['artifact'] = "DeviceDataUpdater.zip" default['wt_devicedataupdater']['download_url'] = "" default['wt_devicedataupdater']['install_dir'] = "\\DeviceDataUpdater" default['wt_devicedataupdater']['log_dir'] = "\\logs"
Remove dependency on ruby debug
# Standard Ruby. require 'singleton' require 'set' # Gems. require 'rubygems' require 'active_support' require 'eventmachine' require 'json' require 'ruby-debug' # Application. require 'officer/log' require 'officer/commands' require 'officer/connection' require 'officer/lock_store' require 'officer/server'
# Standard Ruby. require 'singleton' require 'set' # Gems. require 'rubygems' require 'active_support' require 'eventmachine' require 'json' # Application. require 'officer/log' require 'officer/commands' require 'officer/connection' require 'officer/lock_store' require 'officer/server'
Fix test folder in gemspec
Gem::Specification.new do |s| s.name = "airplay" s.version = "0.2.6" s.summary = "Airplay client" s.description = "Send image/video to an airplay enabled device" s.authors = ["elcuervo"] s.email = ["yo@brunoaguirre.com"] s.homepage = "http://github.com/elcuervo/airplay" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files spec`.split("\n") s.add_dependency("dnssd") s.add_dependency("net-http-persistent") s.add_dependency("net-http-digest_auth") s.add_development_dependency("cutest") s.add_development_dependency("capybara") s.add_development_dependency("fakeweb") s.add_development_dependency("vcr") end
Gem::Specification.new do |s| s.name = "airplay" s.version = "0.2.6" s.summary = "Airplay client" s.description = "Send image/video to an airplay enabled device" s.authors = ["elcuervo"] s.email = ["yo@brunoaguirre.com"] s.homepage = "http://github.com/elcuervo/airplay" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files test`.split("\n") s.add_dependency("dnssd") s.add_dependency("net-http-persistent") s.add_dependency("net-http-digest_auth") s.add_development_dependency("cutest") s.add_development_dependency("capybara") s.add_development_dependency("fakeweb") s.add_development_dependency("vcr") end
Delete conditional and replace with recursive method call
module JsonTestData class JsonSchema attr_accessor :schema def initialize(schema) @schema = JSON.parse(schema, symbolize_names: true) end def generate_example @schema.fetch(:type) == "object" ? generate_object(schema).to_json : generate_array(schema).to_json end private def object_of_type(type) case type when "number" 1 when "integer" 1 when "boolean" true when "string" "string" end end def generate(obj) if is_object?(obj) generate_object(obj) elsif is_array?(obj) generate_array(obj) else object_of_type(obj.fetch(:type)) end end def is_object?(property) property.fetch(:type) == "object" end def is_array?(property) property.fetch(:type) == "array" end def generate_object(object) obj = {} object.fetch(:properties).each do |k, v| obj[k] = nil unless v.has_key?(:type) obj[k] = generate(v) end obj end def generate_array(object) return [] unless object.fetch(:items).has_key?(:type) [generate(object.fetch(:items))].compact end end end
module JsonTestData class JsonSchema attr_accessor :schema def initialize(schema) @schema = JSON.parse(schema, symbolize_names: true) end def generate_example generate(schema).to_json end private def object_of_type(type) case type when "number" 1 when "integer" 1 when "boolean" true when "string" "string" end end def generate(obj) if is_object?(obj) generate_object(obj) elsif is_array?(obj) generate_array(obj) else object_of_type(obj.fetch(:type)) end end def is_object?(property) property.fetch(:type) == "object" end def is_array?(property) property.fetch(:type) == "array" end def generate_object(object) obj = {} object.fetch(:properties).each do |k, v| obj[k] = nil unless v.has_key?(:type) obj[k] = generate(v) end obj end def generate_array(object) return [] unless object.fetch(:items).has_key?(:type) [generate(object.fetch(:items))].compact end end end
Add doc dir in gem
require 'rubygems' spec = Gem::Specification.new do |s| s.name = "rmodbus" s.version = "0.2.1" s.author = 'A.Timin, J. Sanders' s.platform = Gem::Platform::RUBY s.summary = "RModBus - free implementation of protocol ModBus" s.files = Dir['lib/**/*.rb','examples/*.rb','spec/*.rb'] s.autorequire = "rmodbus" s.has_rdoc = true s.rdoc_options = ["--title", "RModBus", "--inline-source", "--main", "README"] s.extra_rdoc_files = ["README", "AUTHORS", "LICENSE", "CHANGES"] end
require 'rubygems' spec = Gem::Specification.new do |s| s.name = "rmodbus" s.version = "0.2.1" s.author = 'A.Timin, J. Sanders' s.platform = Gem::Platform::RUBY s.summary = "RModBus - free implementation of protocol ModBus" s.files = Dir['lib/**/*.rb','examples/*.rb','spec/*.rb','doc/*/*'] s.autorequire = "rmodbus" s.has_rdoc = true s.rdoc_options = ["--title", "RModBus", "--inline-source", "--main", "README"] s.extra_rdoc_files = ["README", "AUTHORS", "LICENSE", "CHANGES"] end
Add some docs to Chrome::Profile
module Selenium module WebDriver module Chrome # # @private # class Profile include ProfileHelper def initialize(model = nil) @model = verify_model(model) end def layout_on_disk dir = @model ? create_tmp_copy(@model) : Dir.mktmpdir("webdriver-chrome-profile") FileReaper << dir write_prefs_to dir dir end def []=(key, value) parts = key.split(".") parts[0..-2].inject(prefs) { |pr, k| pr[k] ||= {} }[parts.last] = value end def [](key) parts = key.split(".") parts.inject(prefs) { |pr, k| pr.fetch(k) } end def write_prefs_to(dir) prefs_file = prefs_file_for(dir) FileUtils.mkdir_p File.dirname(prefs_file) File.open(prefs_file, "w") { |file| file << prefs.to_json } end def prefs @prefs ||= read_model_prefs end private def read_model_prefs return {} unless @model JSON.parse File.read(prefs_file_for(@model)) end def prefs_file_for(dir) File.join dir, 'Default', 'Preferences' end end # Profile end # Chrome end # WebDriver end # Selenium
module Selenium module WebDriver module Chrome # # @private # class Profile include ProfileHelper def initialize(model = nil) @model = verify_model(model) end # # Set a preference in the profile. # # See http://codesearch.google.com/codesearch#OAMlx_jo-ck/src/chrome/common/pref_names.cc&exact_package=chromium # def []=(key, value) parts = key.split(".") parts[0..-2].inject(prefs) { |pr, k| pr[k] ||= {} }[parts.last] = value end def [](key) parts = key.split(".") parts.inject(prefs) { |pr, k| pr.fetch(k) } end def layout_on_disk dir = @model ? create_tmp_copy(@model) : Dir.mktmpdir("webdriver-chrome-profile") FileReaper << dir write_prefs_to dir dir end private def write_prefs_to(dir) prefs_file = prefs_file_for(dir) FileUtils.mkdir_p File.dirname(prefs_file) File.open(prefs_file, "w") { |file| file << prefs.to_json } end def prefs @prefs ||= read_model_prefs end def read_model_prefs return {} unless @model JSON.parse File.read(prefs_file_for(@model)) end def prefs_file_for(dir) File.join dir, 'Default', 'Preferences' end end # Profile end # Chrome end # WebDriver end # Selenium
Use double-quotes on all lines
require 'formula' class P0f < Formula homepage 'http://lcamtuf.coredump.cx/p0f3/' url 'http://lcamtuf.coredump.cx/p0f3/releases/p0f-3.07b.tgz' sha1 'ae2c4fbcddf2a5ced33abd81992405b93207e7c8' def install inreplace "config.h", "p0f.fp", "#{etc}/p0f/p0f.fp" system './build.sh' sbin.install 'p0f' (etc + 'p0f').install 'p0f.fp' end test do require 'base64' pcap = '1MOyoQIABAAAAAAAAAAAAP//AAAAAAAA92EsVI67DgBEAAAA' \ 'RAAAAAIAAABFAABAbvpAAEAGAAB/AAABfwAAAcv8Iyjt2/Pg' \ 'AAAAALAC///+NAAAAgQ/2AEDAwQBAQgKCyrc9wAAAAAEAgAA' (testpath / 'test.pcap').write(Base64.decode64(pcap)) system "#{sbin}/p0f", "-r", "test.pcap" end end
require "formula" class P0f < Formula homepage "http://lcamtuf.coredump.cx/p0f3/" url "http://lcamtuf.coredump.cx/p0f3/releases/p0f-3.07b.tgz" sha1 "ae2c4fbcddf2a5ced33abd81992405b93207e7c8" def install inreplace "config.h", "p0f.fp", "#{etc}/p0f/p0f.fp" system "./build.sh" sbin.install "p0f" (etc + "p0f").install "p0f.fp" end test do require "base64" pcap = "1MOyoQIABAAAAAAAAAAAAP//AAAAAAAA92EsVI67DgBEAAAA" \ "RAAAAAIAAABFAABAbvpAAEAGAAB/AAABfwAAAcv8Iyjt2/Pg" \ "AAAAALAC///+NAAAAgQ/2AEDAwQBAQgKCyrc9wAAAAAEAgAA" (testpath / "test.pcap").write(Base64.decode64(pcap)) system "#{sbin}/p0f", "-r", "test.pcap" end end
Use spy instead of mock
describe BirthdayBot do let(:bot) { BirthdayBot.new } describe "#perform" do context "When birthday of someone" do before do Timecop.freeze("2016-06-12") end it "posts tweet" do expect(bot).to receive(:post_tweet).with("今日はキュアミラクル(Cv. 高橋李依)の誕生日です! https://github.com/sue445/cure-bots") bot.perform end end context "When birthday of nobody" do before do Timecop.freeze("2016-01-01") end it "does not post tweet" do expect(bot).not_to receive(:post_tweet) bot.perform end end end end
describe BirthdayBot do let(:bot) { BirthdayBot.new } describe "#perform" do context "When birthday of someone" do before do Timecop.freeze("2016-06-12") end it "posts tweet" do allow(bot).to receive(:post_tweet) bot.perform expect(bot).to have_received(:post_tweet).with("今日はキュアミラクル(Cv. 高橋李依)の誕生日です! https://github.com/sue445/cure-bots") end end context "When birthday of nobody" do before do Timecop.freeze("2016-01-01") end it "does not post tweet" do allow(bot).to receive(:post_tweet) bot.perform expect(bot).not_to have_received(:post_tweet) end end end end
Remove whitespaces adjacent to newline. Actually pass all tests
module AttributeNormalizer module Normalizers module WhitespaceNormalizer def self.normalize(value, options = {}) value.is_a?(String) ? value.gsub(/[^\S\n]+/, ' ').gsub(/\s+\n$/, "\n").strip : value end end end end
module AttributeNormalizer module Normalizers module WhitespaceNormalizer def self.normalize(value, options = {}) value.is_a?(String) ? value.gsub(/[^\S\n]+/, ' ').gsub(/\s?\n\s?/, "\n").strip : value end end end end
Remove versions of dependent gems in development
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'ydf/version' Gem::Specification.new do |spec| spec.name = "ydf" spec.version = YDF::VERSION spec.authors = ["Naoki Iwasawa"] spec.email = ["niwasawa@maigo.info"] spec.summary = %q{This library is a converter of geo data format for YDF (YOLP Data Format) on Ruby. This library is experimental and unstable.} spec.description = %q{This library is a converter of geo data format for YDF (YOLP Data Format) on Ruby. This library is experimental and unstable.} spec.homepage = "https://github.com/niwasawa/ydf-ruby" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.12" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "rspec", "~> 3.0" end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'ydf/version' Gem::Specification.new do |spec| spec.name = "ydf" spec.version = YDF::VERSION spec.authors = ["Naoki Iwasawa"] spec.email = ["niwasawa@maigo.info"] spec.summary = %q{This library is a converter of geo data format for YDF (YOLP Data Format) on Ruby. This library is experimental and unstable.} spec.description = %q{This library is a converter of geo data format for YDF (YOLP Data Format) on Ruby. This library is experimental and unstable.} spec.homepage = "https://github.com/niwasawa/ydf-ruby" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_development_dependency "bundler" spec.add_development_dependency "rake" spec.add_development_dependency "rspec" end
Fix yet another hardcoded spec
require "spec_helper" describe Henson::Source::GitHub do subject(:it) { described_class.new("foo", ">= 0", "bar/puppet-foo") } it "can be instantiated" do expect(it).to_not be_nil end it "inherits Henson::Source::Tarball" do expect(it).to be_a(Henson::Source::Tarball) end describe "#repo" do it "should return the repository name for the module" do expect(it.repo).to eq("bar/puppet-foo") end end describe "#installed?" do it "should always return false" do expect(it.installed?).to be_false end end describe "#download!" do let(:ui) { mock } before do Henson.ui = ui end it "should make an API request to download the module" do it.expects(:version).returns("1.1.2").at_least(3) ui.expects(:debug). with("Downloading bar/puppet-foo@1.1.2 to /Users/wfarr/src/henson/.henson/cache/github/foo-1.1.2.tar.gz...") it.send(:api).expects(:download_tag_for_repo).with( 'bar/puppet-foo', it.send(:version), it.send(:cache_path).to_path ) it.send(:download!) end end end
require "spec_helper" describe Henson::Source::GitHub do subject(:it) { described_class.new("foo", ">= 0", "bar/puppet-foo") } it "can be instantiated" do expect(it).to_not be_nil end it "inherits Henson::Source::Tarball" do expect(it).to be_a(Henson::Source::Tarball) end describe "#repo" do it "should return the repository name for the module" do expect(it.repo).to eq("bar/puppet-foo") end end describe "#installed?" do it "should always return false" do expect(it.installed?).to be_false end end describe "#download!" do let(:ui) { mock } before do Henson.ui = ui end it "should make an API request to download the module" do it.expects(:version).returns("1.1.2").at_least(3) ui.expects(:debug). with("Downloading #{it.send(:repo)}@#{it.send(:version)} to #{it.send(:cache_path).to_path}...") it.send(:api).expects(:download_tag_for_repo).with( 'bar/puppet-foo', it.send(:version), it.send(:cache_path).to_path ) it.send(:download!) end end end
Add spec to ensure error messages are showing
require "rails_helper" describe "medicaid/contact_social_security/edit.html.erb" do before do controller.singleton_class.class_eval do def current_path "/steps/medicaid/contact_social_security" end helper_method :current_path end end context "one member has an invalid SSN" do it "shows an error for that one member" do controller.singleton_class.class_eval do def single_member_household? true end helper_method :single_member_household? end app = create(:medicaid_application, anyone_new_mom: true) member = build(:member, ssn: "wrong", benefit_application: app) member.save(validate: false) member.valid? step = Medicaid::ContactSocialSecurity.new(members: [member]) assign(:step, step) render expect(rendered).to include("Make sure to provide 9 digits") end end context "two members have invalid SSN's" do it "shows errors for each member" do controller.singleton_class.class_eval do def single_member_household? false end helper_method :single_member_household? end app = create(:medicaid_application, anyone_new_mom: true) member1 = build(:member, ssn: "wrong", benefit_application: app) member1.save(validate: false) member1.valid? member2 = build(:member, ssn: "nope", benefit_application: app) member2.save(validate: false) member2.valid? step = Medicaid::ContactSocialSecurity.new(members: [member1, member2]) assign(:step, step) render expect(rendered.scan("Make sure to provide 9 digits").size).to eq 2 end end end
Use Windows CRLF line endings when rendering RTF letters
# frozen_string_literal: true require_dependency "renalware/letters" module Renalware module Letters # Use pandoc to convert the html letter to RTF class RTFRenderer pattr_initialize :letter REGEX_TO_STRIP_IMAGES = %r{(?m)<img\s*.*?"\s*\/>}.freeze def render using_temp_html_file do |temp_file| rtf_content_converted_from(temp_file) end end def filename "#{letter.pdf_filename}.rtf" end def disposition "attachment; filename=\"#{filename}\"" end private def using_temp_html_file temp_html_file = Tempfile.new("html_to_be_converted_to_rtf") temp_html_file << html_with_images_stripped temp_html_file.close yield(temp_html_file) if block_given? ensure temp_html_file.unlink # allows garbage collection and temp file removal end def rtf_content_converted_from(html_temp_file) rtf_template = File.join(Engine.root, "lib", "pandoc", "templates", "default.rtf") options = { template: rtf_template } PandocRuby.html([html_temp_file.path], options, :standalone).to_rtf end def html_with_images_stripped letter.to_html.gsub(REGEX_TO_STRIP_IMAGES, "") end end end end
# frozen_string_literal: true require_dependency "renalware/letters" module Renalware module Letters # Use pandoc to convert the html letter to RTF class RTFRenderer pattr_initialize :letter REGEX_TO_STRIP_IMAGES = %r{(?m)<img\s*.*?"\s*\/>}.freeze def render using_temp_html_file do |temp_file| rtf_content_converted_from(temp_file) end end def filename "#{letter.pdf_filename}.rtf" end def disposition "attachment; filename=\"#{filename}\"" end private def using_temp_html_file temp_html_file = Tempfile.new("html_to_be_converted_to_rtf") temp_html_file << html_with_images_stripped temp_html_file.close yield(temp_html_file) if block_given? ensure temp_html_file.unlink # allows garbage collection and temp file removal end # Use windows line endings (CRLF) rather than linux (LF). # This solves a problem at Barts exporting RTFs to send to GPs def rtf_content_converted_from(html_temp_file) rtf_template = File.join(Engine.root, "lib", "pandoc", "templates", "default.rtf") options = { template: rtf_template } PandocRuby.html([html_temp_file.path], options, :standalone).to_rtf("--eol=crlf") end def html_with_images_stripped letter.to_html.gsub(REGEX_TO_STRIP_IMAGES, "") end end end end
Use json-api adapter for error render
class ApplicationController < ActionController::API include DeviseTokenAuth::Concerns::SetUserByToken rescue_from ActiveRecord::RecordNotFound, with: :not_found protected def not_found render json: { errors: 'Not found' }, status: :not_found end end
class ApplicationController < ActionController::API include DeviseTokenAuth::Concerns::SetUserByToken rescue_from ActiveRecord::RecordNotFound, with: :not_found protected def not_found(exception) model = build_not_found_model(exception.model) render_error(model, :not_found) end def build_not_found_model(model_name) model = model_name.classify.constantize.new model.errors.add(:id, 'Not found') model end def render_error(model, status) render json: model, status: status, adapter: :json_api, serializer: ActiveModel::Serializer::ErrorSerializer end end
Remove unecessary label values in favour of idLabel
module Lita # Returns cards that are in the Confirmed column class NewCard def initialize(trello_client, list_id, id_labels) @trello_client = trello_client @list_id = list_id @id_labels = id_labels end def display_confirmed_msg(board_id) board = @trello_client.find(:boards, board_id) confirmed_cards = detect_confirmed(board).cards message = "Confirmed cards:\n" message += confirmed_cards.map do |card| "#{card.name}, #{card.url}" end.join("\n") end def create_new_card data = { 'name'=>'tc-i18n-hygiene check failed', 'idList'=>"#{@list_id}", 'due'=>nil, 'desc'=>'https://buildkite.com/conversation/tc-i18n-hygiene', 'labels'=>['name'=>'TC','color'=>'green'], 'idLabels'=>["#{@id_labels}"] } @trello_client.create(:card, data) end private def detect_confirmed(board) list = board.lists.detect{|list| list.name.starts_with?('Confirmed')} end end end
module Lita # Returns cards that are in the Confirmed column class NewCard def initialize(trello_client, list_id, id_labels) @trello_client = trello_client @list_id = list_id @id_labels = id_labels end def display_confirmed_msg(board_id) board = @trello_client.find(:boards, board_id) confirmed_cards = detect_confirmed(board).cards message = "Confirmed cards:\n" message += confirmed_cards.map do |card| "#{card.name}, #{card.url}" end.join("\n") end def create_new_card data = { 'name'=>'tc-i18n-hygiene check failed', 'idList'=>"#{@list_id}", 'due'=>nil, 'desc'=>'https://buildkite.com/conversation/tc-i18n-hygiene', 'idLabels'=>["#{@id_labels}"] } @trello_client.create(:card, data) end private def detect_confirmed(board) list = board.lists.detect{|list| list.name.starts_with?('Confirmed')} end end end
Add Webmock and VCR dependencies
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'lyricfy/version' Gem::Specification.new do |gem| gem.name = "lyricfy" gem.version = Lyricfy::VERSION gem.authors = ["Javier Hidalgo"] gem.email = ["hola@soyjavierhidalgo.com"] gem.description = %q{Song Lyrics for your Ruby apps} gem.summary = %q{Lyricfy lets you get song lyrics that you can use on your apps} gem.homepage = "https://github.com/javichito/lyricfy" 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.require_paths = ["lib"] gem.add_runtime_dependency "nokogiri", [">= 1.3.3"] gem.add_development_dependency "fakeweb", ["~> 1.3"] end
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'lyricfy/version' Gem::Specification.new do |gem| gem.name = "lyricfy" gem.version = Lyricfy::VERSION gem.authors = ["Javier Hidalgo"] gem.email = ["hola@soyjavierhidalgo.com"] gem.description = %q{Song Lyrics for your Ruby apps} gem.summary = %q{Lyricfy lets you get song lyrics that you can use on your apps} gem.homepage = "https://github.com/javichito/lyricfy" 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.require_paths = ["lib"] gem.add_runtime_dependency "rake" gem.add_runtime_dependency "nokogiri", [">= 1.3.3"] gem.add_development_dependency "webmock", ["1.8.0"] gem.add_development_dependency "vcr", ["~> 2.4.0"] end
Add small discriptions to gemspec
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'wak/version' Gem::Specification.new do |spec| spec.name = "wak" spec.version = Wak::VERSION spec.authors = ["Bob Van Landuyt"] spec.email = ["bob@vanlanduyt.co"] spec.summary = %q{TODO: Write a short summary. Required.} spec.description = %q{TODO: Write a longer description. Optional.} spec.homepage = "" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.7" spec.add_development_dependency "rake", "~> 10.0" end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'wak/version' Gem::Specification.new do |spec| spec.name = "wak" spec.version = Wak::VERSION spec.authors = ["Bob Van Landuyt"] spec.email = ["bob@vanlanduyt.co"] spec.summary = "Easy rack hosting in development" spec.description = "Host rack apps in development using ngnix" spec.homepage = "" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.7" spec.add_development_dependency "rake", "~> 10.0" end
Make sure to generate the site in the test about the non-HTML files.
require 'helper' class TestJekyllMentions < Minitest::Test include MentionsTestHelpers def setup @site = fixture_site @site.read @mentions = Jekyll::Mentions.new(@site) @mention = "test <a href='https://github.com/test' class='user-mention'>@test</a> test" end should "replace @mention with link" do page = page_with_name(@site, "index.md") @mentions.mentionify page assert_equal @mention, page.content end should "replace page content on generate" do @mentions.generate(@site) assert_equal @mention, @site.pages.first.content end should "not mangle liquid templating" do page = page_with_name(@site, "leave-liquid-alone.md") @mentions.mentionify page assert_equal "#{@mention}<a href=\"{{ test }}\">test</a>", page.content end should "not mangle markdown" do page = page_with_name(@site, "mentioned-markdown.md") @mentions.mentionify page assert_equal "#{@mention}\n> test", page.content end should "not mangle non-mentioned content" do page = page_with_name(@site, "non-mentioned.md") @mentions.mentionify page assert_equal "test test test\n> test", page.content end should "not touch non-HTML pages" do assert_equal "test @test test", page_with_name(@site, "test.json").content end end
require 'helper' class TestJekyllMentions < Minitest::Test include MentionsTestHelpers def setup @site = fixture_site @site.read @mentions = Jekyll::Mentions.new(@site) @mention = "test <a href='https://github.com/test' class='user-mention'>@test</a> test" end should "replace @mention with link" do page = page_with_name(@site, "index.md") @mentions.mentionify page assert_equal @mention, page.content end should "replace page content on generate" do @mentions.generate(@site) assert_equal @mention, @site.pages.first.content end should "not mangle liquid templating" do page = page_with_name(@site, "leave-liquid-alone.md") @mentions.mentionify page assert_equal "#{@mention}<a href=\"{{ test }}\">test</a>", page.content end should "not mangle markdown" do page = page_with_name(@site, "mentioned-markdown.md") @mentions.mentionify page assert_equal "#{@mention}\n> test", page.content end should "not mangle non-mentioned content" do page = page_with_name(@site, "non-mentioned.md") @mentions.mentionify page assert_equal "test test test\n> test", page.content end should "not touch non-HTML pages" do @mentions.generate(@site) assert_equal "test @test test", page_with_name(@site, "test.json").content end end
Add `output_capacity` to molecule nodes
# frozen_string_literal: true require_relative 'node' module Atlas # Describes a Node in the molecules graph. class MoleculeNode include Node directory_name 'graphs/molecules/nodes' def self.graph_config GraphConfig.molecules end attribute :from_energy, NodeAttributes::EnergyToMolecules # Public: The queries to be executed and saved on the Refinery graph. # # Defaults demand to zero, as the molecule graph should have no flows. # # Returns a Hash. def queries { demand: '0.0' }.merge(super) end end end
# frozen_string_literal: true require_relative 'node' module Atlas # Describes a Node in the molecules graph. class MoleculeNode include Node directory_name 'graphs/molecules/nodes' def self.graph_config GraphConfig.molecules end attribute :from_energy, NodeAttributes::EnergyToMolecules # Molecule nodes define output capacity; the capacity of all non-loss output carriers. attribute :output_capacity, Float # Public: The queries to be executed and saved on the Refinery graph. # # Defaults demand to zero, as the molecule graph should have no flows. # # Returns a Hash. def queries { demand: '0.0' }.merge(super) end end end
Change rails dependency to all rails 5.o to be used
# coding: utf-8 $:.push File.expand_path("../lib", __FILE__) # The gem's version number require 'seed_tray/version' Gem::Specification.new do |spec| spec.name = "seed_tray" spec.version = SeedTray::VERSION spec.authors = ["Jeffrey Guenther"] spec.email = ["guenther.jeffrey@gmail.com"] spec.summary = %q{Custom coffeescript for your views} spec.description = %q{A small, convention-based library for implementing view specific javascript.} spec.homepage = "https://github.com/LoamStudios/seed_tray" spec.license = "MIT" spec.test_files = Dir["test/**/*"] spec.files = Dir["{lib,app}/**/*"] spec.add_dependency "rails", "~> 4.2.5" spec.add_dependency 'jquery-rails' spec.add_development_dependency 'sass-rails', '~> 5.0' spec.add_development_dependency 'coffee-rails', '~> 4.1.0' spec.add_development_dependency 'jquery-rails' spec.add_development_dependency 'turbolinks' spec.add_development_dependency "sqlite3" spec.add_development_dependency "minitest-rails", "~> 2.2.0" end
# coding: utf-8 $:.push File.expand_path("../lib", __FILE__) # The gem's version number require 'seed_tray/version' Gem::Specification.new do |spec| spec.name = "seed_tray" spec.version = SeedTray::VERSION spec.authors = ["Jeffrey Guenther"] spec.email = ["guenther.jeffrey@gmail.com"] spec.summary = %q{Custom coffeescript for your views} spec.description = %q{A small, convention-based library for implementing view specific javascript.} spec.homepage = "https://github.com/LoamStudios/seed_tray" spec.license = "MIT" spec.test_files = Dir["test/**/*"] spec.files = Dir["{lib,app}/**/*"] spec.add_dependency "rails", ">= 4.0" spec.add_dependency 'jquery-rails' spec.add_development_dependency 'sass-rails', '~> 5.0' spec.add_development_dependency 'coffee-rails', '~> 4.1.0' spec.add_development_dependency 'jquery-rails' spec.add_development_dependency 'turbolinks' spec.add_development_dependency "sqlite3" spec.add_development_dependency "minitest-rails", "~> 2.2.0" end
Change Default Push Events and Channels
require 'net/http' module Pushable require 'pushable/railtie' if defined?(Rails) extend ActiveSupport::Concern included do after_create :push_create after_update :push_update after_destroy :push_destroy end [:create, :update, :destroy].each do |event| define_method "push_#{event.to_s}" do Array.wrap(self.class.pushes[event]).each do |channel| ActionPusher.new.push event, evaluate(channel), self end end end def collection_channel self.class.name.underscore.pluralize end def instance_channel "#{self.class.name.underscore}_#{id}" end def evaluate(channel) case channel when :collections collection_channel when :instances instance_channel when Symbol #references association associate = send(channel) "#{associate.class.name.underscore}_#{associate.id}_#{self.class.name.underscore.pluralize}" when String eval '"' + channel + '"' when Proc evaluate channel.call(self) end end module ClassMethods def push(options={}) @pushes = options end def pushes @pushes ||= { create: :collections, update: [ :collections, :instances ], destroy: :collections } #default events and channels end end module Rails module Faye mattr_accessor :address self.address = 'https://localhost:9292' end end end
require 'net/http' module Pushable require 'pushable/railtie' if defined?(Rails) extend ActiveSupport::Concern included do after_create :push_create after_update :push_update after_destroy :push_destroy end [:create, :update, :destroy].each do |event| define_method "push_#{event.to_s}" do Array.wrap(self.class.pushes[event]).each do |channel| ActionPusher.new.push event, evaluate(channel), self end end end def collection_channel self.class.name.underscore.pluralize end def instance_channel "#{self.class.name.underscore}_#{id}" end def evaluate(channel) case channel when :collections collection_channel when :instances instance_channel when Symbol #references association associate = send(channel) "#{associate.class.name.underscore}_#{associate.id}_#{self.class.name.underscore.pluralize}" when String eval '"' + channel + '"' when Proc evaluate channel.call(self) end end module ClassMethods attr_accessor :pushes def pushable @pushes = { create: :collections, update: [ :collections, :instances ], destroy: [ :collections, :instances ] } #default events and channels end def push(options={}) @pushes = options end end module Rails module Faye mattr_accessor :address self.address = 'http://localhost:9292' end end end
Add nokogiri to gem dependencies.
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'panties/version' Gem::Specification.new do |spec| spec.name = "panties" spec.version = Panties::VERSION spec.authors = ["Hendrik Mans"] spec.email = ["hendrik@mans.de"] spec.summary = %q{Command line client for #pants.} spec.description = %q{#pants is a force for good. This is its command line client.} spec.homepage = "https://github.com/hmans/panties" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_dependency 'httparty', '~> 0.13.0' spec.add_development_dependency "bundler", "~> 1.6" spec.add_development_dependency "rake" end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'panties/version' Gem::Specification.new do |spec| spec.name = "panties" spec.version = Panties::VERSION spec.authors = ["Hendrik Mans"] spec.email = ["hendrik@mans.de"] spec.summary = %q{Command line client for #pants.} spec.description = %q{#pants is a force for good. This is its command line client.} spec.homepage = "https://github.com/hmans/panties" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_dependency 'httparty', '~> 0.13.0' spec.add_dependency 'nokogiri', '~> 1.4' spec.add_development_dependency "bundler", "~> 1.6" spec.add_development_dependency "rake" end
Update podspec to pass linter
Pod::Spec.new do |s| s.name = 'UITextView+UIControl' s.version = '0.1' s.source_files = "Classes" end
Pod::Spec.new do |s| s.name = 'UITextView+UIControl' s.summary = 'A UIControl-like API addition to UITextView.' s.homepage = 'https://github.com/andrewsardone/UITextView-UIControl' s.source = { :git => 'https://github.com/andrewsardone/UITextView-UIControl.git', :tag => '0.1' } s.version = '0.1' s.authors = { 'Andrew Sardone' => 'andrew@andrewsardone.com' } s.license = 'MIT' s.source_files = "Classes" s.platform = :ios end
Remove exception test generator for rna transcription exercise
require 'generator/exercise_case' class RnaTranscriptionCase < Generator::ExerciseCase def workload if expects_error? assert_raises(ArgumentError) { test_case } else assert_equal { test_case } end end private def test_case "assert_equal '#{expected}', Complement.of_dna('#{dna}')" end def expects_error? expected.is_a? Hash end end
require 'generator/exercise_case' class RnaTranscriptionCase < Generator::ExerciseCase def workload "assert_equal '#{expected}', Complement.of_dna('#{dna}')" end end
Revert "Set new GoogleApiClient podname"
Pod::Spec.new do |s| s.name = "HSGoogleDrivePicker" s.version = "0.1.5" s.summary = "A sane and simple file picker for Google Drive." s.homepage = "https://github.com/ConfusedVorlon/HSGoogleDrivePicker" s.screenshots = "https://raw.githubusercontent.com/ConfusedVorlon/HSGoogleDrivePicker/master/images/iPadPicker.png" s.license = "MIT" s.author = { "Rob" => "Rob@HobbyistSoftware.com" } s.platform = :ios, "7.0" s.source = { :git => "https://github.com/ConfusedVorlon/HSGoogleDrivePicker.git", :tag => "0.1.5" } s.source_files = "HSGoogleDrivePicker/HSGoogleDrivePicker" s.requires_arc = true s.dependency 'AsyncImageView' s.dependency 'GoogleAPIClient/Drive' s.dependency 'SVPullToRefresh' end
Pod::Spec.new do |s| s.name = "HSGoogleDrivePicker" s.version = "0.1.5" s.summary = "A sane and simple file picker for Google Drive." s.homepage = "https://github.com/ConfusedVorlon/HSGoogleDrivePicker" s.screenshots = "https://raw.githubusercontent.com/ConfusedVorlon/HSGoogleDrivePicker/master/images/iPadPicker.png" s.license = "MIT" s.author = { "Rob" => "Rob@HobbyistSoftware.com" } s.platform = :ios, "7.0" s.source = { :git => "https://github.com/ConfusedVorlon/HSGoogleDrivePicker.git", :tag => "0.1.5" } s.source_files = "HSGoogleDrivePicker/HSGoogleDrivePicker" s.requires_arc = true s.dependency 'AsyncImageView' s.dependency 'Google-API-Client/Drive' s.dependency 'SVPullToRefresh' end
Set the From in the event mailer to the user sending the mail
class EventMailer < ApplicationMailer def event_info(to, email) @email = email mail(to: to, subject: @email[:subject]) end end
class EventMailer < ApplicationMailer def event_info(to, email) @email = email mail(from: @email.user.email, to: to, subject: @email[:subject]) end end
Reduce migration version to accommodate rails 5.0+
class CreateActiveEncodeEncodeRecords < ActiveRecord::Migration[5.2] def change create_table :active_encode_encode_records do |t| t.string :global_id t.string :state t.string :adapter t.string :title t.text :raw_object t.timestamps end end end
class CreateActiveEncodeEncodeRecords < ActiveRecord::Migration[5.0] def change create_table :active_encode_encode_records do |t| t.string :global_id t.string :state t.string :adapter t.string :title t.text :raw_object t.timestamps end end end
Fix in the right location
class ApplicationController < ActionController::Base protect_from_forgery force_ssl if: :ssl_configured? before_filter :authenticate_user before_filter :ensure_team def authenticate_user find_user redirect_to '/login' unless @current_user end def find_user @current_user = LoginUserFinder.new(session[:user_id]).find end def current_user @current_user end helper_method :current_user def require_staff if current_user redirect_to "/" unless current_user.staff? end end def ssl_configured? !(Rails.env.development? || Rails.env.test?) end def is_staff? current_user.staff? end def ensure_team return true if is_staff? if current_user and current_user.team_id.nil? redirect_to "/join" end end end
class ApplicationController < ActionController::Base protect_from_forgery force_ssl if: :ssl_configured? before_filter :authenticate_user before_filter :ensure_team def authenticate_user find_user redirect_to '/login' unless @current_user end def find_user @current_user = LoginUserFinder.new(session[:user_id]).find end def current_user @current_user end helper_method :current_user def require_staff redirect_to "/" unless current_user.staff? end def ssl_configured? !(Rails.env.development? || Rails.env.test?) end def is_staff? current_user && current_user.staff? end def ensure_team return true if is_staff? if current_user and current_user.team_id.nil? redirect_to "/join" end end end