Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Update AppCode EAP to version 142.4675.7 | cask :v1 => 'appcode-eap' do
version '141.2455.5'
sha256 'd3b03735359c7342c005bd97a3bbc816ab1b86b7e12398f4177b797bc695b436'
url "https://download.jetbrains.com/objc/AppCode-#{version}.dmg"
name 'AppCode'
homepage 'https://confluence.jetbrains.com/display/OBJC/AppCode+EAP'
license :commercial
app 'AppCode.app'
zap :delete => [
'~/Library/Preferences/com.jetbrains.AppCode-EAP.plist',
'~/Library/Preferences/AppCode32',
'~/Library/Application Support/AppCode32',
'~/Library/Caches/AppCode32',
'~/Library/Logs/AppCode32',
]
conflicts_with :cask => 'appcode-eap-bundled-jdk'
caveats <<-EOS.undent
#{token} requires Java 6 like any other IntelliJ-based IDE.
You can install it with
brew cask install caskroom/homebrew-versions/java6
The vendor (JetBrains) doesn't support newer versions of Java (yet)
due to several critical issues, see details at
https://intellij-support.jetbrains.com/entries/27854363
EOS
end
| cask :v1 => 'appcode-eap' do
version '142.4675.7'
sha256 '88e430d88eaef3dd0870d4821cffcaf34f4d8552b1f112dc5100bda9afe424d3'
url "https://download.jetbrains.com/objc/AppCode-#{version}-custom-jdk-bundled.dmg"
name 'AppCode'
homepage 'https://confluence.jetbrains.com/display/OBJC/AppCode+EAP'
license :commercial
app 'AppCode EAP.app'
zap :delete => [
'~/Library/Preferences/com.jetbrains.AppCode-EAP.plist',
'~/Library/Preferences/AppCode33',
'~/Library/Application Support/AppCode33',
'~/Library/Caches/AppCode33',
'~/Library/Logs/AppCode33',
]
conflicts_with :cask => 'appcode-eap-bundled-jdk'
end
|
Add http schema to default hub | SocialStream::Ostatus.setup do |config|
# Default to the PubSubHubbub reference Hub server
# config.hub = 'pubsubhubbub.appspot.com'
config.node_base_url = 'http://localhost:3000'
end
| SocialStream::Ostatus.setup do |config|
# Default to the PubSubHubbub reference Hub server
# config.hub = 'http://pubsubhubbub.appspot.com'
config.node_base_url = 'http://localhost:3000'
end
|
Use bundler instead of manipulating load paths. | # encoding: UTF-8
# To make testing/debugging easier, test within this source tree versus an installed gem
dir = File.dirname(__FILE__)
root = File.expand_path(File.join(dir, '..'))
lib = File.expand_path(File.join(root, 'lib'))
ext = File.expand_path(File.join(root, 'ext', 'libxml'))
$LOAD_PATH << lib
$LOAD_PATH << ext
require 'xml'
require 'minitest/autorun'
| # encoding: UTF-8
# To make testing/debugging easier, test within this source tree versus an installed gem
require 'bundler/setup'
require 'minitest/autorun'
require 'libxml-ruby'
|
Rename and refactor method check_user_logged_in | class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
helper_method :current_user
def current_user
return nil if session[:user_id].nil?
User.find(session[:user_id])
end
def check_user_logged_in
if session[:user_id].nil?
redirect_to ideas_path
end
end
end
| class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
helper_method :current_user
def current_user
return nil if session[:user_id].nil?
User.find(session[:user_id])
end
def ensure_that_signed_in
redirect_to ideas_path, notice:'you should be signed in' if current_user.nil?
end
end
|
Add pending test for stylesheets in html comments | klass = ImageDownloaderAdapter::Base
describe klass do
xit 'should download img tags with src in scheme http' do
end
xit 'should download img tags with src in scheme http' do
end
xit 'should download img tags with srcset in scheme http' do
end
xit 'should download img tags with src in scheme https' do
end
xit 'should download img tags with srcset in scheme https' do
end
xit 'should download img tags with embedded images' do
end
xit 'should download elements with background property in style attr' do
end
xit 'should download elements with background-image property in style attr' do
end
xit 'should download elements with background property in stylesheet' do
end
xit 'should download elements with background-image property in stylesheet' do
end
xit 'should download lazily loaded elements' do
end
end
| klass = ImageDownloaderAdapter::Base
describe klass do
xit 'should download img tags with src in scheme http' do
end
xit 'should download img tags with src in scheme http' do
end
xit 'should download img tags with srcset in scheme http' do
end
xit 'should download img tags with src in scheme https' do
end
xit 'should download img tags with srcset in scheme https' do
end
xit 'should download img tags with embedded images' do
end
xit 'should download elements with background property in style attr' do
end
xit 'should download elements with background-image property in style attr' do
end
xit 'should download elements with background property in stylesheet' do
end
xit 'should download elements with background-image property in stylesheet' do
end
xit 'should download lazily loaded elements' do
end
xit 'should download images from html commented links to stylesheets' do
end
end
|
Add min required ruby version | name = "active_record_inherit_assoc"
Gem::Specification.new name, "2.6.0" do |s|
s.summary = "Attribute inheritance for AR associations"
s.authors = ["Ben Osheroff"]
s.email = ["ben@gimbo.net"]
s.files = `git ls-files lib`.split("\n")
s.license = "Apache License Version 2.0"
s.homepage = "https://github.com/zendesk/#{name}"
s.add_runtime_dependency "activerecord", ">= 4.2.0", "< 5.3"
s.add_development_dependency 'minitest'
s.add_development_dependency 'minitest-rg'
s.add_development_dependency 'rake'
s.add_development_dependency 'rails'
s.add_development_dependency 'bump'
s.add_development_dependency 'wwtd'
s.add_development_dependency 'sqlite3'
s.add_development_dependency 'byebug'
end
| name = "active_record_inherit_assoc"
Gem::Specification.new name, "2.6.0" do |s|
s.summary = "Attribute inheritance for AR associations"
s.authors = ["Ben Osheroff"]
s.email = ["ben@gimbo.net"]
s.files = `git ls-files lib`.split("\n")
s.license = "Apache License Version 2.0"
s.homepage = "https://github.com/zendesk/#{name}"
s.add_runtime_dependency 'activerecord', '>= 4.2.0', '< 5.3'
s.required_ruby_version = '>= 2.4'
s.add_development_dependency 'minitest'
s.add_development_dependency 'minitest-rg'
s.add_development_dependency 'rake'
s.add_development_dependency 'rails'
s.add_development_dependency 'bump'
s.add_development_dependency 'wwtd'
s.add_development_dependency 'sqlite3'
s.add_development_dependency 'byebug'
end
|
Add more relationships to members on the api | module Api
module V1
class MemberResource < BaseResource
immutable
has_many :gardens
attribute :login_name
end
end
end
| module Api
module V1
class MemberResource < BaseResource
immutable
has_many :gardens
has_many :plantings
has_many :harvests
has_many :seeds
has_many :photos
attribute :login_name
end
end
end
|
Make Shipment.cost default to 0 | class AddDefaultToShipmentCost < ActiveRecord::Migration
def up
change_column :spree_shipments, :cost, :decimal, precision: 10, scale: 2, default: 0.0
Spree::Shipment.where(cost: nil).update_all(cost: 0)
end
def down
change_column :spree_shipments, :cost, :decimal, precision: 10, scale: 2
end
end
| |
Order versions by build date | class StatsController < ApplicationController
before_filter :find_gem, :only => :show
before_filter :ensure_hosted, :only => :show
def index
@number_of_gems = Rubygem.total_count
@number_of_users = User.count
@number_of_downloads = Download.count
@most_downloaded = Rubygem.downloaded(10)
end
def show
if params[:version_id]
@subtitle = I18n.t('stats.show.for', :for => params[:version_id])
@version = Version.find_from_slug!(@rubygem.id, params[:version_id])
@versions = [@version]
@downloads_today = Download.today(@version)
@rank = Download.rank(@version)
else
@subtitle = I18n.t('stats.show.overview')
@version = @rubygem.versions.most_recent
@versions = @rubygem.versions.with_indexed.by_position.limit(5)
@downloads_today = Download.today(@rubygem.versions)
@rank = Download.highest_rank(@rubygem.versions)
end
@downloads_total = @version.rubygem.downloads
@cardinality = Download.cardinality
end
private
def ensure_hosted
render :file => 'public/404.html', :status => :not_found if !@rubygem.hosted?
end
end
| class StatsController < ApplicationController
before_filter :find_gem, :only => :show
before_filter :ensure_hosted, :only => :show
def index
@number_of_gems = Rubygem.total_count
@number_of_users = User.count
@number_of_downloads = Download.count
@most_downloaded = Rubygem.downloaded(10)
end
def show
if params[:version_id]
@subtitle = I18n.t('stats.show.for', :for => params[:version_id])
@version = Version.find_from_slug!(@rubygem.id, params[:version_id])
@versions = [@version]
@downloads_today = Download.today(@version)
@rank = Download.rank(@version)
else
@subtitle = I18n.t('stats.show.overview')
@version = @rubygem.versions.most_recent
@versions = @rubygem.versions.with_indexed.by_built_at.limit(5)
@downloads_today = Download.today(@rubygem.versions)
@rank = Download.highest_rank(@rubygem.versions)
end
@downloads_total = @version.rubygem.downloads
@cardinality = Download.cardinality
end
private
def ensure_hosted
render :file => 'public/404.html', :status => :not_found if !@rubygem.hosted?
end
end
|
Add missing set_pack def/filter in OAuth::AuthorizedApplicationsController. | # frozen_string_literal: true
class Oauth::AuthorizedApplicationsController < Doorkeeper::AuthorizedApplicationsController
skip_before_action :authenticate_resource_owner!
before_action :store_current_location
before_action :authenticate_resource_owner!
include Localized
private
def store_current_location
store_location_for(:user, request.url)
end
end
| # frozen_string_literal: true
class Oauth::AuthorizedApplicationsController < Doorkeeper::AuthorizedApplicationsController
skip_before_action :authenticate_resource_owner!
before_action :store_current_location
before_action :authenticate_resource_owner!
before_action :set_pack
include Localized
private
def store_current_location
store_location_for(:user, request.url)
end
def set_pack
use_pack 'settings'
end
end
|
Solve Pairing on nested data; write reflection | # RELEASE 2: NESTED STRUCTURE GOLF
# Hole 1
# Target element: "FORE"
array = [[1,2], ["inner", ["eagle", "par", ["FORE", "hook"]]]]
# attempts: 1
# ============================================================
p array[1][1][2][0]
# ============================================================
# Hole 2
# Target element: "congrats!"
hash = {outer: {inner: {"almost" => {3 => "congrats!"}}}}
# attempts: 1
# ============================================================
p hash[:outer][:inner]["almost"][3]
# ============================================================
# Hole 3
# Target element: "finished"
nested_data = {array: ["array", {hash: "finished"}]}
# attempts: 1
# ============================================================
p nested_data[:array][1][:hash]
# ============================================================
# RELEASE 3: ITERATE OVER NESTED STRUCTURES
number_array = [5, [10, 15], [20,25,30], 35]
number_array.map! do |outer|
if outer.kind_of?(Array)
outer.map! {|inner| inner + 5}
else outer + 5
end
end
p number_array
# We did not come up with a way to refactor, though i'd love to learn a way.
# Bonus:
startup_names = ["bit", ["find", "fast", ["optimize", "scope"]]]
startup_names.each do |outer|
if outer.kind_of?(Array)
outer.each do |inner|
if inner.kind_of?(Array)
inner.each {|innerinner| innerinner.insert(-1, "ly")}
else inner.insert(-1, "ly")
end
end
else outer.insert(-1, "ly")
end
end
p startup_names
# What are some general rules you can apply to nested arrays?
# It helps to name each level of nesting. You can reference an array within an array with mutiple [], so by counting how many levels, you know how many [] to use.
# What are some ways you can iterate over nested arrays?
# use map or each. I find it helps to start with the most nested array and work my way out of it. It is the "most" conditional, so all other conditions enclose it.
# Did you find any good new methods to implement or did you re-use one you were already familiar with? What was it and why did you decide that was a good option?
# We used .insert, which I was familiar with but had to look up again. It worked well because we could alter each string in one line. It was the first time I used kind_of? which
# my pair was aware of and it seemed necessary for determining what to do when an iteration reached an array.
| |
Add uniqueness index to users migration | class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :username, null: false
t.string :email, null: false
t.string :hashed_password, null: false
t.timestamps null: false
end
end
end
| class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :username, null: false
t.string :email, null: false
t.string :hashed_password, null: false
t.timestamps null: false
end
add_index :username, :email, :unique true
end
end
|
Expand compatibility to Rails > | $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "job_state/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "job_state"
s.version = JobState::VERSION
s.authors = ["Wyatt Greene", "Ian McLean"]
s.summary = "This engine provides a way to poll resque jobs for their status and display to the user."
s.homepage = "https://github.com/dmcouncil/job_state"
s.licenses = ['MIT']
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
s.test_files = Dir["test/**/*"]
s.add_dependency "rails", ">= 3.2.19", "< 4.1.0"
s.add_dependency "resque-status", '~>0.4.1'
end
| $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "job_state/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "job_state"
s.version = JobState::VERSION
s.authors = ["Wyatt Greene", "Ian McLean"]
s.summary = "This engine provides a way to poll resque jobs for their status and display to the user."
s.homepage = "https://github.com/dmcouncil/job_state"
s.licenses = ['MIT']
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
s.test_files = Dir["test/**/*"]
s.add_dependency "rails", ">= 3.2.19", "< 5.0"
s.add_dependency "resque-status", '~>0.4.1'
end
|
Fix spec around payload for tracker | require 'spec_helper'
describe PostsController do
let(:controller) {PostsController.new}
let(:session) {{}}
describe '#tracker' do
before(:each) do
SecureRandom.stubs(:uuid).returns('54321')
controller.stubs(:session).returns(session)
end
it 'builds a new tracker' do
tracker = controller.tracker
expect(tracker.respond_to?(:increment)).to eq(true)
expect(tracker.respond_to?(:decrement)).to eq(true)
end
it 'appends tracker to the notification payload' do
payload = {}
controller.append_info_to_payload(payload)
expect(payload["tremolo.tracker"]).to eq(controller.tracker)
end
end
describe "tracking exceptions" do
let(:tracker) {stub(:increment)}
before(:each) do
controller.stubs(:tracker).returns(tracker)
end
it 'still raises the error' do
expect { controller.destroy }.to raise_exception(NotImplementedError)
end
it 'tracks the error' do
controller.track_exception_with_tremolo(NotImplementedError.new)
expect(tracker).to have_received(:increment).with('exception', name: 'NotImplementedError')
end
it 'tracks the error and raises' do
expect {
controller.track_exception_with_tremolo_and_raise(NotImplementedError.new)
}.to raise_exception(NotImplementedError)
expect(tracker).to have_received(:increment).with('exception', name: 'NotImplementedError')
end
end
end
| require 'spec_helper'
describe PostsController do
let(:controller) {PostsController.new}
let(:session) {{}}
describe '#tracker' do
before(:each) do
SecureRandom.stubs(:uuid).returns('54321')
controller.stubs(:session).returns(session)
end
it 'builds a new tracker' do
tracker = controller.tracker
expect(tracker.respond_to?(:increment)).to eq(true)
expect(tracker.respond_to?(:decrement)).to eq(true)
end
it 'appends tracker to the notification payload' do
payload = {}
# calling fetch without config results in a new NoopTracker each time
Tremolo.stubs(:fetch).returns('tracker')
controller.append_info_to_payload(payload)
expect(payload["tremolo.tracker"]).to eq(controller.tracker)
end
end
describe "tracking exceptions" do
let(:tracker) {stub(:increment)}
before(:each) do
controller.stubs(:tracker).returns(tracker)
end
it 'still raises the error' do
expect { controller.destroy }.to raise_exception(NotImplementedError)
end
it 'tracks the error' do
controller.track_exception_with_tremolo(NotImplementedError.new)
expect(tracker).to have_received(:increment).with('exception', name: 'NotImplementedError')
end
it 'tracks the error and raises' do
expect {
controller.track_exception_with_tremolo_and_raise(NotImplementedError.new)
}.to raise_exception(NotImplementedError)
expect(tracker).to have_received(:increment).with('exception', name: 'NotImplementedError')
end
end
end
|
Add the project homepage to the readme | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'findrepos/version'
Gem::Specification.new do |spec|
spec.name = 'findrepos'
spec.version = Findrepos::VERSION
spec.authors = ['Nicolas McCurdy']
spec.email = ['thenickperson@gmail.com']
spec.summary = 'A tool for finding git repositories locally.'
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_dependency 'thor'
spec.add_development_dependency 'bundler', '~> 1.6'
spec.add_development_dependency 'rake'
spec.add_development_dependency 'rspec'
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'findrepos/version'
Gem::Specification.new do |spec|
spec.name = 'findrepos'
spec.version = Findrepos::VERSION
spec.authors = ['Nicolas McCurdy']
spec.email = ['thenickperson@gmail.com']
spec.summary = 'A tool for finding git repositories locally.'
spec.homepage = 'https://github.com/nicolasmccurdy/findrepos'
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 'thor'
spec.add_development_dependency 'bundler', '~> 1.6'
spec.add_development_dependency 'rake'
spec.add_development_dependency 'rspec'
end
|
Fix homepage. Bump to 0.0.3 | # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "petrovich"
s.version = "0.0.2"
s.authors = ["Andrew Kozloff"]
s.email = ["demerest@gmail.com"]
s.homepage = "https://github.com/tanraya/papillon"
s.summary = "Склонение падежей русских имён, фамилий и отчеств"
s.description = "Вы задаёте начальное имя в именительном падеже, а получаете в нужном вам"
s.files = Dir["{lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md"]
s.add_dependency "unicode_utils", "1.4.0"
s.add_development_dependency "rspec"
s.add_development_dependency "gem-release", "~> 0.4.1"
end
| # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "petrovich"
s.version = "0.0.3"
s.authors = ["Andrew Kozloff"]
s.email = ["demerest@gmail.com"]
s.homepage = "https://github.com/rocsci/petrovich"
s.summary = "Склонение падежей русских имён, фамилий и отчеств"
s.description = "Вы задаёте начальное имя в именительном падеже, а получаете в нужном вам"
s.files = Dir["{lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md"]
s.add_dependency "unicode_utils", "1.4.0"
s.add_development_dependency "rspec"
s.add_development_dependency "gem-release", "~> 0.4.1"
end
|
Allow new version of strip in the gem | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/stripe_mock/version', __FILE__)
Gem::Specification.new do |gem|
gem.name = "stripe-ruby-mock"
gem.version = StripeMock::VERSION
gem.summary = %q{TDD with stripe}
gem.description = %q{A drop-in library to test stripe without hitting their servers}
gem.license = "MIT"
gem.authors = ["Gilbert"]
gem.email = "gilbertbgarza@gmail.com"
gem.homepage = "https://github.com/rebelidealist/stripe-ruby-mock"
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_dependency 'stripe', '1.28.1'
gem.add_dependency 'jimson-temp'
gem.add_dependency 'dante', '>= 0.2.0'
gem.add_development_dependency 'rspec', '~> 3.1.0'
gem.add_development_dependency 'rubygems-tasks', '~> 0.2'
gem.add_development_dependency 'thin'
end
| # -*- encoding: utf-8 -*-
require File.expand_path('../lib/stripe_mock/version', __FILE__)
Gem::Specification.new do |gem|
gem.name = "stripe-ruby-mock"
gem.version = StripeMock::VERSION
gem.summary = %q{TDD with stripe}
gem.description = %q{A drop-in library to test stripe without hitting their servers}
gem.license = "MIT"
gem.authors = ["Gilbert"]
gem.email = "gilbertbgarza@gmail.com"
gem.homepage = "https://github.com/rebelidealist/stripe-ruby-mock"
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_dependency 'stripe', '~> 1.31.0'
gem.add_dependency 'jimson-temp'
gem.add_dependency 'dante', '>= 0.2.0'
gem.add_development_dependency 'rspec', '~> 3.1.0'
gem.add_development_dependency 'rubygems-tasks', '~> 0.2'
gem.add_development_dependency 'thin'
end
|
Use the Figs environment variable for the secret token | # Be sure to restart your server when you modify this file.
# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
PrivilegesGuide::Application.config.secret_token = Settings.secret_token
| # Be sure to restart your server when you modify this file.
# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
PrivilegesGuide::Application.config.secret_token = ENV['SECRET_TOKEN']
|
Add strong params for categories | module Refinery
module Products
module Admin
class CategoriesController < ::Refinery::AdminController
crudify :'refinery/products/category',
:xhr_paging => true
end
end
end
end
| module Refinery
module Products
module Admin
class CategoriesController < ::Refinery::AdminController
crudify :'refinery/products/category',
:xhr_paging => true
private
def category_params
params.require(:category).permit(:title)
end
end
end
end
end
|
Implement actions for users controller | class UsersController < ApplicationController
def new
end
def create
end
def edit
end
def update
end
def show
end
def index
end
def destroy
end
end
| class UsersController < ApplicationController
def index
@users = User.all
end
def new
@user = User.new
end
def create
user = User.find_by(username: user_params[:username])
unless user
@user = User.create(user_params)
session[:user_id] = @user.id
redirect_to root_path
else
flash[:notice] = "A user with that name or email already exists"
redirect_to new_user_path
end
end
def edit
find_user
end
def update
find_user
@user.assign_attributes(user_params)
if @user.save
redirect_to @user
else
render :edit
end
end
def show
find_user
end
def destroy
find_user
@user.destroy if @user
redirect_to root_path
end
private
def user_params
params.require(:user).permit(:username, :email, :password, :country_id, :native_language_id,
:study_language_id, :avatar_url, :points, :level_id)
end
def find_user
@user = User.find_by(id: params[:id])
end
end
|
Update rubocop requirement to = 0.50.0 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
Gem::Specification.new do |spec|
spec.name = 'fluent-plugin-graylog'
spec.version = '1.0.2'
spec.authors = ['Funding Circle']
spec.email = ['engineering@fundingcircle.com']
spec.summary = 'Graylog output plugin for Fluentd'
spec.description = 'Send logging information in JSON format via TCP to an instance of Graylog'
spec.license = 'BSD-3-Clause'
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(spec|features)/}) }
spec.bindir = 'exe'
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ['lib']
spec.required_ruby_version = '>= 1.9.3'
spec.add_runtime_dependency 'fluentd', '~> 0.12.36'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'rspec', '~> 3.3'
spec.add_development_dependency 'test-unit', '~> 3.1'
spec.add_development_dependency 'pry', '~> 0.10'
spec.add_development_dependency 'rubocop', '0.38.0'
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
Gem::Specification.new do |spec|
spec.name = 'fluent-plugin-graylog'
spec.version = '1.0.2'
spec.authors = ['Funding Circle']
spec.email = ['engineering@fundingcircle.com']
spec.summary = 'Graylog output plugin for Fluentd'
spec.description = 'Send logging information in JSON format via TCP to an instance of Graylog'
spec.license = 'BSD-3-Clause'
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(spec|features)/}) }
spec.bindir = 'exe'
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ['lib']
spec.required_ruby_version = '>= 1.9.3'
spec.add_runtime_dependency 'fluentd', '~> 0.12.36'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'rspec', '~> 3.3'
spec.add_development_dependency 'test-unit', '~> 3.1'
spec.add_development_dependency 'pry', '~> 0.10'
spec.add_development_dependency 'rubocop', '= 0.50.0'
end
|
Remove duplicate of "Gem::Specification.new do |s|" | version = File.read(File.expand_path('../PROJECT_VERSION', __FILE__)).strip Gem::Specification.new do |s|
Gem::Specification.new do |s|
s.name = 'iscinc-hw'
s.version = "iscinc-hw:PROJECT_VERSION"
s.default_executable = 'iscinc-hw'
s.summary = 'A hello world gem for iSC Inc. projects.'
s.description = 'This Ruby gem tests the commands of a iSC Inc. Ruby project.'
s.author = 'Suriyaa Kudo'
s.email = 'SuriyaaKudoIsc@users.noreply.github.com'
s.homepage = 'https://github.com/SuriyaaKudoIsc/iscinc-hw-gem'
s.license = 'Apache-v2'
s.date = '2015-12-05'
s.files = ['README.md', 'Rakefile', 'lib/iscinc-hw.rb', 'lib/iscinc-hw/translator.rb', 'bin/iscinc-hw']
s.test_files = ['test/test_iscinc-hw.rb']
s.require_paths = ['lib']
# s.add_dependency '', version
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
else
end
else
end
end
| version = File.read(File.expand_path('../RAILS_VERSION', __FILE__)).strip
Gem::Specification.new do |s|
s.name = 'iscinc-hw'
s.version = "iscinc-hw:PROJECT_VERSION"
s.default_executable = 'iscinc-hw'
s.summary = 'A hello world gem for iSC Inc. projects.'
s.description = 'This Ruby gem tests the commands of a iSC Inc. Ruby project.'
s.author = 'Suriyaa Kudo'
s.email = 'SuriyaaKudoIsc@users.noreply.github.com'
s.homepage = 'https://github.com/SuriyaaKudoIsc/iscinc-hw-gem'
s.license = 'Apache-v2'
s.date = '2015-12-05'
s.files = ['README.md', 'Rakefile', 'lib/iscinc-hw.rb', 'lib/iscinc-hw/translator.rb', 'bin/iscinc-hw']
s.test_files = ['test/test_iscinc-hw.rb']
s.require_paths = ['lib']
# s.add_dependency '', version
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
else
end
else
end
end
|
Fix XML salary range generate | # frozen_string_literal: true
xml.instruct!
xml.jobs do
@offers.each do |offer|
xml.job do
xml.title { xml.cdata! offer.title }
xml.id offer.id
xml.description { xml.cdata! markdown(offer.description) }
xml.link { xml.cdata! offer_url(offer) }
xml.location { xml.cdata! [offer.locations.first.country.name_en, offer.locations.first.xml_region].reject(&:blank?).join(', ') }
xml.company { xml.cdata! offer.company.name }
salary_frequency = if offer.salary
'hour'
elsif offer.hourly_wage
'month'
end
if salary_frequency
salary_column = salary_frequency == 'hour' ? :hourly_wage : :salary
xml.salary { xml.cdata! xml_salary_for(offer, salary_column, " per #{salary_frequency}") }
xml.salary_min { xml.cdata! localized_currency_value(offer.salary.first) }
xml.salary_max { xml.cdata! localized_currency_value(offer.salary.first) }
xml.salary_frequency { xml.cdata! salary_frequency }
xml.salary_currency { xml.cdata! offer.currency }
end
xml.category { xml.cdata! offer.field.name_en } if offer.field
xml.date { xml.cdata! offer.published_at.strftime('%F') }
end
end
end
| # frozen_string_literal: true
xml.instruct!
xml.jobs do
@offers.each do |offer|
xml.job do
xml.title { xml.cdata! offer.title }
xml.id offer.id
xml.description { xml.cdata! markdown(offer.description) }
xml.link { xml.cdata! offer_url(offer) }
xml.location { xml.cdata! [offer.locations.first.country.name_en, offer.locations.first.xml_region].reject(&:blank?).join(', ') }
xml.company { xml.cdata! offer.company.name }
salary_frequency = if offer.salary
'hour'
elsif offer.hourly_wage
'month'
end
if salary_frequency
salary_column = salary_frequency == 'hour' ? :hourly_wage : :salary
xml.salary { xml.cdata! xml_salary_for(offer, salary_column, " per #{salary_frequency}") }
xml.salary_min { xml.cdata! localized_currency_value(offer.salary.first) } if offer.read_attribute(salary_column)&.first
xml.salary_max { xml.cdata! localized_currency_value(offer.salary.last) } if offer.read_attribute(salary_column)&.last
xml.salary_frequency { xml.cdata! salary_frequency }
xml.salary_currency { xml.cdata! offer.currency }
end
xml.category { xml.cdata! offer.field.name_en } if offer.field
xml.date { xml.cdata! offer.published_at.strftime('%F') }
end
end
end
|
Write solution for vegetable counter | def count_vegetables(s)
arr = make_arr(s)
hash = hash_counter(arr)
nested_arr = hash.sort_by { |key, value| [value, key] }
nested_arr.reverse.map! { |arr| arr.reverse }
end
def hash_counter(arr)
hash = Hash.new(0)
arr.each { |el| hash[el] += 1 }
hash
end
def make_arr(s)
vegetables = "cabbage carrot celery cucumber mushroom onion pepper potato tofu turnip"
arr = s.split(' ')
arr.delete_if { |el| vegetables.include?(el) == false }
arr
end
p count_vegetables("pants potato tofu cucumber cabbage turnip pepper onion carrot celery mushroom potato tofu cucumber cabbage")
| |
Prepare EU Exit Finder publisher takes an array of topics | require 'publishing_api_finder_publisher'
class PrepareEuExitFinderPublisher
TEMPLATE_CONTENT_ITEM_PATH = "config/prepare-eu-exit.yml.erb".freeze
def initialize(finder_config, timestamp = Time.now.iso8601)
@finder_config = validate(finder_config)
@timestamp = timestamp
end
def call
template_content_item = File.read(TEMPLATE_CONTENT_ITEM_PATH)
@finder_config.each do |item|
config = {
finder_content_id: item["finder_content_id"],
timestamp: @timestamp,
topic_content_id: item["topic_content_id"],
topic_name: item["title"],
topic_slug: item["slug"],
}
finder = YAML.safe_load(ERB.new(template_content_item).result(binding))
PublishingApiFinderPublisher.new(finder, @timestamp).call
end
end
private
# Ensure that the config is an array of the right sort of hashes
def validate(finder_config)
raise PrepareEuExitFinderValidationError unless finder_config.all? do |item|
%w(finder_content_id topic_content_id title slug).all? { |key| item.has_key? key }
end
finder_config
end
end
class PrepareEuExitFinderValidationError < StandardError; end
| require 'publishing_api_finder_publisher'
class PrepareEuExitFinderPublisher
TEMPLATE_CONTENT_ITEM_PATH = "config/prepare-eu-exit.yml.erb".freeze
def initialize(topics, timestamp = Time.now.iso8601)
@topics = validate(topics)
@timestamp = timestamp
end
def call
template_content_item = File.read(TEMPLATE_CONTENT_ITEM_PATH)
@topics.each do |topic|
config = {
finder_content_id: topic["finder_content_id"],
timestamp: @timestamp,
topic_content_id: topic["topic_content_id"],
topic_name: topic["title"],
topic_slug: topic["slug"],
}
finder = YAML.safe_load(ERB.new(template_content_item).result(binding))
PublishingApiFinderPublisher.new(finder, @timestamp).call
end
end
private
# Ensure that the config is an array of the right sort of hashes
def validate(finder_config)
raise PrepareEuExitFinderValidationError unless finder_config.all? do |item|
%w(finder_content_id topic_content_id title slug).all? { |key| item.has_key? key }
end
finder_config
end
end
class PrepareEuExitFinderValidationError < StandardError; end
|
Replace type with activity_type in the model | class UnitActivitySet < ActiveRecord::Base
belongs_to :unit
validates :type, presence: true
validates :unit_id, presence: true
end
| class UnitActivitySet < ActiveRecord::Base
belongs_to :unit
validates :activity_type, presence: true
validates :unit_id, presence: true
end
|
Fix n+1 issue on index page | require "slim"
module Errdo
class ErrorsController < Errdo::ApplicationController
include Errdo::Helpers::ViewsHelper
helper_method :user_show_string, :user_show_path
before_action :authorize_user
def index
@errors = Errdo::Error.order(last_occurred_at: :desc).page params[:page]
end
def show
@error = Errdo::Error.find(params[:id])
@occurrence = selected_occurrence(@error)
end
def update
@error = Errdo::Error.find(params[:id])
if @error.update(error_params)
flash[:notice] = "Success updating status!"
else
flash[:alert] = "Updating failed"
end
@occurrence = selected_occurrence(@error)
render :show
end
private
def authorize_user
@authorization_adapter ||= nil
@authorization_adapter.try(:authorize, params["action"], Errdo::Error)
end
def error_params
params.require(:error).permit(:status)
end
def selected_occurrence(error)
if params[:occurrence_id]
Errdo::ErrorOccurrence.find(params[:occurrence_id])
else
error.error_occurrences.last
end
end
end
end
| require "slim"
module Errdo
class ErrorsController < Errdo::ApplicationController
include Errdo::Helpers::ViewsHelper
helper_method :user_show_string, :user_show_path
before_action :authorize_user
def index
@errors = Errdo::Error.order(last_occurred_at: :desc).includes(:last_experiencer).page params[:page]
end
def show
@error = Errdo::Error.find(params[:id])
@occurrence = selected_occurrence(@error)
end
def update
@error = Errdo::Error.find(params[:id])
if @error.update(error_params)
flash[:notice] = "Success updating status!"
else
flash[:alert] = "Updating failed"
end
@occurrence = selected_occurrence(@error)
render :show
end
private
def authorize_user
@authorization_adapter ||= nil
@authorization_adapter.try(:authorize, params["action"], Errdo::Error)
end
def error_params
params.require(:error).permit(:status)
end
def selected_occurrence(error)
if params[:occurrence_id]
Errdo::ErrorOccurrence.find(params[:occurrence_id])
else
error.error_occurrences.last
end
end
end
end
|
Replace all requires with require_all | module TZFormater
FILENAME = File.expand_path('tzformater/data/formats.pstore', File.dirname(__FILE__))
end
require 'tzformater/pstore_adapter'
require 'tzformater/posixtz' | module TZFormater
FILENAME = File.expand_path('tzformater/data/formats.pstore', File.dirname(__FILE__))
end
require 'require_all'
require_rel 'tzformater'
|
Add url as a rake task parameter | namespace :proposals do
desc "Updates all proposals by recalculating their hot_score"
task touch: :environment do
Proposal.find_in_batches do |proposals|
proposals.each(&:save)
end
end
desc "Import proposals from a xls file given an url"
task import: :environment do
file_url = "#{Rails.root}/tmp/proposals.xlsx"
ProposalXLSImporter.new(file_url).import
end
end
| namespace :proposals do
desc "Updates all proposals by recalculating their hot_score"
task touch: :environment do
Proposal.find_in_batches do |proposals|
proposals.each(&:save)
end
end
desc "Import proposals from a xls file given an url"
task :import, [:url] => :environment do |task, args|
if args.url.blank?
puts "Usage: rake proposals:import[url]"
else
ProposalXLSImporter.new(args.url).import
end
end
end
|
Update customer information on balanced and update profile on neighborly | module Neighborly::Balanced::Creditcard
class PaymentsController < ActionController::Base
def new
if current_user.balanced_contributor
@customer = Balanced::Customer.find(current_user.balanced_contributor.uri)
else
@customer = Balanced::Customer.new(meta: { user_id: current_user.id },
name: current_user.display_name,
email: current_user.email,
address: {
line1: current_user.address_street,
city: current_user.address_city,
state: current_user.address_state,
postal_code: current_user.address_zip_code
})
@customer.save
current_user.create_balanced_contributor(uri: @customer.uri)
end
@cards = @customer.cards
end
end
end
| module Neighborly::Balanced::Creditcard
class PaymentsController < ActionController::Base
def new
if current_user.balanced_contributor
@customer = resource
else
@customer = Balanced::Customer.new(meta: { user_id: current_user.id },
name: current_user.display_name,
email: current_user.email,
address: {
line1: current_user.address_street,
city: current_user.address_city,
state: current_user.address_state,
postal_code: current_user.address_zip_code
})
@customer.save
current_user.create_balanced_contributor(uri: @customer.uri)
end
@cards = @customer.cards
end
def create
end
private
def update_customer
customer = resource
customer.name = params[:payment][:user][:name]
customer.address = { line1: params[:payment][:user][:address_street],
city: params[:payment][:user][:address_city],
state: params[:payment][:user][:address_state],
postal_code: params[:payment][:user][:address_zip_code]
}
customer.save
current_user.update!(user_address_params[:payment][:user]) if params[:payment][:user][:update_address]
end
def user_address_params
params.permit(payment: { user: [:address_street, :address_city, :address_state, :address_zip_code] })
end
def resource
@customer ||= Balanced::Customer.find(current_user.balanced_contributor.uri)
end
end
end
|
Update migration for compatibility with older Rails versions | class CreateCustomVersions < ActiveRecord::Migration[6.1]
def change
create_table :custom_versions do |t|
t.string :item_type, null: false
t.integer :item_id, null: false
t.string :event, null: false
t.string :whodunnit
t.text :object
t.datetime :created_at
end
add_index :custom_versions, [:item_type, :item_id]
end
end
| class CreateCustomVersions < ActiveRecord::Migration[5.0]
def change
create_table :custom_versions do |t|
t.string :item_type, null: false
t.integer :item_id, null: false
t.string :event, null: false
t.string :whodunnit
t.text :object
t.datetime :created_at
end
add_index :custom_versions, [:item_type, :item_id]
end
end
|
Use a more accurate parameter name | module JSONApi
module Request
class Builder
attr_reader :fragments
def initialize(connection)
@connection = connection
@fragments = []
end
def capture(route, *args, **kwargs)
fragments << JSONApi::Request::Fragment.new(route, args, kwargs)
end
def new(**args)
JSONApi::Request::Object.new(current_route.new_class.new(args), self)
end
def get
@connection.get(to_url).body
end
def post(payload)
@connection.post(to_url, payload).body
end
def delete
@connection.delete(to_url).body
end
def put(payload)
@connection.put(to_url, payload).body
end
def method_missing(method, *args, **kwargs, &block)
if current_route && current_route.key?(method)
capture(current_route.fetch(method), *args, kwargs, &block)
self
else
super
end
end
def to_url
fragments.map(&:call).compact.join('/')
end
private
def current_route
fragments.last.route if fragments.last
end
end
end
end
| module JSONApi
module Request
class Builder
attr_reader :fragments
def initialize(connection)
@connection = connection
@fragments = []
end
def capture(route, *args, **kwargs)
fragments << JSONApi::Request::Fragment.new(route, args, kwargs)
end
def new(**kwargs)
JSONApi::Request::Object.new(current_route.new_class.new(kwargs), self)
end
def get
@connection.get(to_url).body
end
def post(payload)
@connection.post(to_url, payload).body
end
def delete
@connection.delete(to_url).body
end
def put(payload)
@connection.put(to_url, payload).body
end
def method_missing(method, *args, **kwargs, &block)
if current_route && current_route.key?(method)
capture(current_route.fetch(method), *args, kwargs, &block)
self
else
super
end
end
def to_url
fragments.map(&:call).compact.join('/')
end
private
def current_route
fragments.last.route if fragments.last
end
end
end
end
|
Fix typo in build stages reference migration | class MigrateBuildStageReference < ActiveRecord::Migration
include Gitlab::Database::MigrationHelpers
DOWNTIME = false
def up
disable_statement_timeout
stage_id = Arel.sql(<<-SQL.strip_heredoc
(SELECT id FROM ci_stages
WHERE ci_stages.pipeline_id = ci_builds.commit_id
AND ci_stages.name = ci_builds.stage)
SQL
update_column_in_batches(:ci_builds, :stage_id, stage_id) do |table, query|
query.where(table[:stage_id].eq(nil))
end
end
def down
disable_statement_timeout
update_column_in_batches(:ci_builds, :stage_id, nil)
end
end
| class MigrateBuildStageReference < ActiveRecord::Migration
include Gitlab::Database::MigrationHelpers
DOWNTIME = false
def up
disable_statement_timeout
stage_id = Arel.sql <<-SQL.strip_heredoc
(SELECT id FROM ci_stages
WHERE ci_stages.pipeline_id = ci_builds.commit_id
AND ci_stages.name = ci_builds.stage)
SQL
update_column_in_batches(:ci_builds, :stage_id, stage_id) do |table, query|
query.where(table[:stage_id].eq(nil))
end
end
def down
disable_statement_timeout
update_column_in_batches(:ci_builds, :stage_id, nil)
end
end
|
Remove obsolete load paths for specs | $LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "..", "lib"))
require "rubygems"
require "rspec"
require "rr"
require "vidibus-gem_template"
require "support/stubs"
require "support/models"
Mongoid.configure do |config|
name = "vidibus-gem_template_test"
host = "localhost"
config.master = Mongo::Connection.new.db(name)
config.logger = nil
end
RSpec.configure do |config|
config.mock_with :rr
config.before(:each) do
Mongoid.master.collections.select {|c| c.name !~ /system/}.each(&:drop)
end
end
|
require "rubygems"
require "rspec"
require "rr"
require "vidibus-gem_template"
require "support/stubs"
require "support/models"
Mongoid.configure do |config|
name = "vidibus-gem_template_test"
host = "localhost"
config.master = Mongo::Connection.new.db(name)
config.logger = nil
end
RSpec.configure do |config|
config.mock_with :rr
config.before(:each) do
Mongoid.master.collections.select {|c| c.name !~ /system/}.each(&:drop)
end
end
|
Add RSpec setup to allow focus. | require 'sparql/grammar'
require 'rdf/spec'
require 'rdf/ntriples'
RSpec.configure do |config|
config.include(RDF::Spec::Matchers)
end
DAWG = RDF::Vocabulary.new('http://www.w3.org/2001/sw/DataAccess/tests/test-dawg#')
MF = RDF::Vocabulary.new('http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#')
QT = RDF::Vocabulary.new('http://www.w3.org/2001/sw/DataAccess/tests/test-query#')
RS = RDF::Vocabulary.new('http://www.w3.org/2001/sw/DataAccess/tests/result-set#')
| require 'sparql/grammar'
require 'rdf/spec'
require 'rdf/ntriples'
RSpec.configure do |config|
config.include(RDF::Spec::Matchers)
config.filter_run :focus => true
config.run_all_when_everything_filtered = true
config.exclusion_filter = {:ruby => lambda { |version|
RUBY_VERSION.to_s !~ /^#{version}/
}}
end
DAWG = RDF::Vocabulary.new('http://www.w3.org/2001/sw/DataAccess/tests/test-dawg#')
MF = RDF::Vocabulary.new('http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#')
QT = RDF::Vocabulary.new('http://www.w3.org/2001/sw/DataAccess/tests/test-query#')
RS = RDF::Vocabulary.new('http://www.w3.org/2001/sw/DataAccess/tests/result-set#')
class RDF::Query
##
# @param [Object] other
# @return [Boolean]
def ==(other)
other.is_a?(RDF::Query) && patterns == other.patterns
end
end |
Add rspec options for favorable output | require "bundler/setup"
require 'capybara/mechanize'
require 'capybara/rspec'
require 'factory_girl'
require 'rspec'
RSpec.configure do |config|
config.include Capybara::DSL
config.include FactoryGirl::Syntax::Methods
config.before(:suite) do
FactoryGirl.definition_file_paths = %w(./factories/)
FactoryGirl.find_definitions
end
end
# Capybara config
Capybara.app = 'ts_mruby'
Capybara.default_driver = :mechanize
Capybara.app_host = 'http://127.0.0.1:8080'
Capybara.run_server = false
| require "bundler/setup"
require 'capybara/mechanize'
require 'capybara/rspec'
require 'factory_girl'
require 'rspec'
RSpec.configure do |config|
config.color = true
config.formatter = :documentation
config.include Capybara::DSL
config.include FactoryGirl::Syntax::Methods
config.before(:suite) do
FactoryGirl.definition_file_paths = %w(./factories/)
FactoryGirl.find_definitions
end
end
# Capybara config
Capybara.app = 'ts_mruby'
Capybara.default_driver = :mechanize
Capybara.app_host = 'http://127.0.0.1:8080'
Capybara.run_server = false
|
Fix tests broken due to zero-length window | # Encapsulates methods used on the Dashboard that need some business logic
module DateRangeHelper
def date_range_params
params.dig(:filters, :date_range).presence || this_year
end
def date_range_label
case (params.dig(:filters, :date_range_label).presence || "this year").downcase
when "yesterday"
"yesterday"
when "last 7 days"
"over the last week"
when "last 30 days"
"over the 30 days"
when "this month"
"this month, so far"
when "last month"
"during the last month"
else
selected_range_described
end
end
def this_year
"01/01/#{Time.zone.today.year} - 12/31/#{Time.zone.today.year}"
end
def selected_interval
date_range_params.split(" - ").map { |d| Date.strptime(d, "%m/%d/%Y") }
end
def selected_range
start_date, end_date = selected_interval
start_date..end_date
end
def selected_range_described
start_date, end_date = selected_interval
if start_date == Time.zone.today
return ""
elsif end_date == Time.zone.today
return "since #{start_date}"
else
return "during the period #{start_date.to_s(:short)} to #{end_date.to_s(:short)}"
end
end
end
| # Encapsulates methods used on the Dashboard that need some business logic
module DateRangeHelper
def date_range_params
params.dig(:filters, :date_range).presence || this_year
end
def date_range_label
case (params.dig(:filters, :date_range_label).presence || "this year").downcase
when "yesterday"
"yesterday"
when "last 7 days"
"over the last week"
when "last 30 days"
"over the 30 days"
when "this month"
"this month, so far"
when "last month"
"during the last month"
else
selected_range_described
end
end
def this_year
"01/01/#{Time.zone.today.year} - 12/31/#{Time.zone.today.year}"
end
def selected_interval
date_range_params.split(" - ").map { |d| Date.strptime(d, "%m/%d/%Y") }
end
def selected_range
start_date, end_date = selected_interval
(start_date.beginning_of_day)..(end_date.end_of_day)
end
def selected_range_described
start_date, end_date = selected_interval
if start_date == Time.zone.today
return ""
elsif end_date == Time.zone.today
return "since #{start_date}"
else
return "during the period #{start_date.to_s(:short)} to #{end_date.to_s(:short)}"
end
end
end
|
Write out a chef-marketplace-running.json during the reconfigure | include_recipe 'chef-marketplace::enable'
| include_recipe 'chef-marketplace::enable'
file '/etc/chef-marketplace/chef-marketplace-running.json' do
content Chef::JSONCompat.to_json_pretty('chef-marketplace' => node['chef-marketplace'])
owner 'root'
group 'root'
mode '0600'
end
|
Make the :boolean field a uint8. | require 'ffi/msgpack/types'
require 'ffi/msgpack/msg_array'
require 'ffi/msgpack/msg_map'
require 'ffi/msgpack/msg_raw'
module FFI
module MsgPack
class MsgObjectUnion < FFI::Union
layout :boolean, :bool,
:u64, :uint64,
:i64, :int64,
:dec, :double,
:array, MsgArray,
:map, MsgMap,
:raw, MsgRaw
end
end
end
| require 'ffi/msgpack/types'
require 'ffi/msgpack/msg_array'
require 'ffi/msgpack/msg_map'
require 'ffi/msgpack/msg_raw'
module FFI
module MsgPack
class MsgObjectUnion < FFI::Union
layout :boolean, :uint8,
:u64, :uint64,
:i64, :int64,
:dec, :double,
:array, MsgArray,
:map, MsgMap,
:raw, MsgRaw
end
end
end
|
Add test for adding column | require File.join(File.dirname(__FILE__), 'test_helper')
class AlterTableTest < Test::Unit::TestCase
def setup
ActiveRecord::Migration.verbose = false
ActiveRecord::Base.connection.create_table('users') do |t|
end
end
def teardown
ActiveRecord::Base.connection.drop_table('users')
end
def alter_model_table
ActiveRecord::Base.connection.alter_table(model.table_name) do |t|
yield(t)
end
end
end
def model
returning Class.new(ActiveRecord::Base) do |c|
c.table_name = 'users'
end
end
| require File.join(File.dirname(__FILE__), 'test_helper')
class AlterTableTest < Test::Unit::TestCase
def setup
ActiveRecord::Migration.verbose = false
ActiveRecord::Base.connection.create_table('users') do |t|
end
end
def teardown
ActiveRecord::Base.connection.drop_table('users')
end
def test_add_column
alter_model_table do |t|
t.add_column 'name', :string
end
assert model.column_names.include?('name')
end
def alter_model_table
ActiveRecord::Base.connection.alter_table(model.table_name) do |t|
yield(t)
end
end
end
def model
returning Class.new(ActiveRecord::Base) do |c|
c.table_name = 'users'
end
end
|
Add test on local macos. | require 'minitest/autorun'
class WithDockerTest < Minitest::Test
# Run code before a group of test (see: https://github.com/seattlerb/minitest#how-to-run-code-before-a-group-of-tests)
SETUP = begin
`docker-compose build`
end
def test_centos_6
test with: 'centos_6'
end
def test_centos_7
test with: 'centos_7'
end
def test_debian_8
test with: 'debian_8'
end
def test_debian_9
test with: 'debian_9'
end
def test_with_ubuntu_14
test with: 'ubuntu_14.04'
end
def test_with_ubuntu_16
test with: 'ubuntu_16.04'
end
def test_with_ubuntu_18
test with: 'ubuntu_18.04'
end
private
def test(with:)
assert_equal `docker-compose run --rm #{with}`.strip, 'wkhtmltopdf 0.12.5 (with patched qt)'
end
end
| require 'minitest/autorun'
class WithDockerTest < Minitest::Test
# Run code before a group of test (see: https://github.com/seattlerb/minitest#how-to-run-code-before-a-group-of-tests)
SETUP = begin
`docker-compose build`
end
def test_centos_6
test with: 'centos_6'
end
def test_centos_7
test with: 'centos_7'
end
def test_debian_8
test with: 'debian_8'
end
def test_debian_9
test with: 'debian_9'
end
def test_with_ubuntu_14
test with: 'ubuntu_14.04'
end
def test_with_ubuntu_16
test with: 'ubuntu_16.04'
end
def test_with_ubuntu_18
test with: 'ubuntu_18.04'
end
def test_with_macos
assert_equal `bin/wkhtmltopdf --version`.strip, 'wkhtmltopdf 0.12.5 (with patched qt)'
end
private
def test(with:)
assert_equal `docker-compose run --rm #{with}`.strip, 'wkhtmltopdf 0.12.5 (with patched qt)'
end
end
|
Allow us to set variables through ENV as well as yaml | # Load in the relevant yaml file, to set them in the Rails configuration object
def foursquare_api_config
foursquare_config = YAML.load_file("#{Rails.root}/config/foursquare.yml")
foursquare_config[Rails.env]
end
# Add the details to the config object
Rails.configuration.foursquare_client_id = foursquare_api_config['client_id']
Rails.configuration.foursquare_client_secret = foursquare_api_config['client_secret']
| # Load in the relevant yaml file, to set them in the Rails configuration object
def foursquare_api_config
foursquare_config = YAML.load_file("#{Rails.root}/config/foursquare.yml")
foursquare_config[Rails.env]
end
# Add the details to the config object
Rails.configuration.foursquare_client_id = ENV['FOURSQUARE_CLIENT_ID'] || foursquare_api_config['client_id']
Rails.configuration.foursquare_client_secret = ENV['FOURSQUARE_CLIENT_ID'] || foursquare_api_config['client_secret']
|
Add OBRA TT. Use standard results template. | class CompetitionsController < ApplicationController
caches_page :show
def show
# Very explicit because we don't want to call something like 'eval' on a request parameter!
if params[:type] == "rider_rankings"
competition_class = RiderRankings
elsif params[:type] == "cat4_womens_race_series"
competition_class = Cat4WomensRaceSeries
elsif params[:type] == "wsba_barr"
competition_class = WsbaBarr
elsif params[:type] == "wsba_masters_barr"
competition_class = WsbaMastersBarr
elsif params[:type] == "mbra_bar"
competition_class = MbraBar
else
raise ActiveRecord::RecordNotFound.new("No competition of type: #{params[:type]}")
end
@event = competition_class.year(@year).first || competition_class.new(:date => Time.zone.local(@year))
end
end
| class CompetitionsController < ApplicationController
caches_page :show
def show
# Very explicit because we don't want to call something like 'eval' on a request parameter!
if params[:type] == "rider_rankings"
competition_class = RiderRankings
elsif params[:type] == "cat4_womens_race_series"
competition_class = Cat4WomensRaceSeries
elsif params[:type] == "wsba_barr"
competition_class = WsbaBarr
elsif params[:type] == "wsba_masters_barr"
competition_class = WsbaMastersBarr
elsif params[:type] == "mbra_bar"
competition_class = MbraBar
elsif params[:type] == "obra_tt_cup"
competition_class = OBRATTCup
else
raise ActiveRecord::RecordNotFound.new("No competition of type: #{params[:type]}")
end
@event = competition_class.year(@year).first || competition_class.new(:date => Time.zone.local(@year))
render "results/event"
end
end
|
Return all errors for subscriptions, instead of only subscription-specific ones | class Api::BraintreeController < ApplicationController
def token
render json: { token: ::Braintree::ClientToken.generate }
end
def transaction
result = braintree::Transaction.make_transaction(transaction_options)
if result.success?
render json: { success: true, transaction_id: result.transaction.id }
else
render json: { success: false, errors: result.errors }
end
end
def subscription
result = braintree::Subscription.make_subscription(subscription_options)
if result.success?
render json: { success: true, subscription_id: result.subscription.id }
else
render json: { success: false, errors: result.errors.for(:subscription) }
end
end
private
def transaction_options
{
nonce: params[:payment_method_nonce],
user: params[:user],
amount: params[:amount].to_f,
store: Payment
}
end
def subscription_options
{
amount: params[:amount].to_f,
plan_id: '35wm',
payment_method_token: default_payment_method_token
}
end
def braintree
PaymentProcessor::Clients::Braintree
end
def default_payment_method_token
@token ||= ::Payment.customer(params[:email]).try(:card_vault_token)
end
end
| class Api::BraintreeController < ApplicationController
def token
render json: { token: ::Braintree::ClientToken.generate }
end
def transaction
result = braintree::Transaction.make_transaction(transaction_options)
if result.success?
render json: { success: true, transaction_id: result.transaction.id }
else
render json: { success: false, errors: result.errors }
end
end
def subscription
result = braintree::Subscription.make_subscription(subscription_options)
if result.success?
render json: { success: true, subscription_id: result.subscription.id }
else
# Subscription-specific errors can be accessed with results.errors.for(:subscription),
# but that would not include errors due to invalid parameters.
# Subscription-specific errors are raised e.g. if there's an attempt to update a deleted subscription.
render json: { success: false, errors: result.errors }
end
end
private
def transaction_options
{
nonce: params[:payment_method_nonce],
user: params[:user],
amount: params[:amount].to_f,
store: Payment
}
end
def subscription_options
{
amount: params[:amount].to_f,
plan_id: '35wm',
payment_method_token: default_payment_method_token
}
end
def braintree
PaymentProcessor::Clients::Braintree
end
def default_payment_method_token
@token ||= ::Payment.customer(params[:email]).try(:card_vault_token)
end
end
|
Clarify which caching is disabled | # Frozen-string-literal: true
# Copyright: 2012 - 2016 - MIT License
# Encoding: utf-8
Jekyll::Assets::Hook.register :env, :init do
cache = asset_config.fetch("cache", ".asset-cache")
type = asset_config.fetch("cache_type",
"filesystem"
)
if cache != false && type != "memory"
self.cache = begin
Sprockets::Cache::FileStore.new(
jekyll.in_source_dir(
cache
)
)
end
elsif cache && type == "memory"
self.cache = begin
Sprockets::Cache::MemoryStore.new
end
else
Jekyll.logger.info "", "Caching is disabled by configuration. " \
"However, if you're using proxies, a cache might still be created."
end
end
| # Frozen-string-literal: true
# Copyright: 2012 - 2016 - MIT License
# Encoding: utf-8
Jekyll::Assets::Hook.register :env, :init do
cache = asset_config.fetch("cache", ".asset-cache")
type = asset_config.fetch("cache_type",
"filesystem"
)
if cache != false && type != "memory"
self.cache = begin
Sprockets::Cache::FileStore.new(
jekyll.in_source_dir(
cache
)
)
end
elsif cache && type == "memory"
self.cache = begin
Sprockets::Cache::MemoryStore.new
end
else
Jekyll.logger.info "", "Asset caching is disabled by configuration. " \
"However, if you're using proxies, a cache might still be created."
end
end
|
Remove Rack::Lock not only if coap.only | require 'david/resource_discovery_proxy'
require 'david/show_exceptions'
module David
module Railties
class Middleware < Rails::Railtie
UNWANTED = [
ActionDispatch::Cookies,
ActionDispatch::DebugExceptions,
ActionDispatch::Flash,
ActionDispatch::RemoteIp,
ActionDispatch::RequestId,
ActionDispatch::Session::CookieStore,
Rack::ConditionalGet,
Rack::Head,
Rack::Lock,
Rack::MethodOverride,
Rack::Runtime,
]
initializer 'david.clear_out_middleware' do |app|
if config.coap.only
UNWANTED.each { |klass| app.middleware.delete(klass) }
end
app.middleware.swap(ActionDispatch::ShowExceptions, David::ShowExceptions)
app.middleware.insert_after(David::ShowExceptions, David::ResourceDiscoveryProxy)
end
end
end
end
| require 'david/resource_discovery_proxy'
require 'david/show_exceptions'
module David
module Railties
class Middleware < Rails::Railtie
UNWANTED = [
ActionDispatch::Cookies,
ActionDispatch::DebugExceptions,
ActionDispatch::Flash,
ActionDispatch::RemoteIp,
ActionDispatch::RequestId,
ActionDispatch::Session::CookieStore,
Rack::ConditionalGet,
Rack::Head,
Rack::MethodOverride,
Rack::Runtime,
]
initializer 'david.clear_out_middleware' do |app|
if config.coap.only
UNWANTED.each { |klass| app.middleware.delete(klass) }
end
app.middleware.delete(Rack::Lock)
app.middleware.swap(ActionDispatch::ShowExceptions, David::ShowExceptions)
app.middleware.insert_after(David::ShowExceptions, David::ResourceDiscoveryProxy)
end
end
end
end
|
Fix deprecation warning when using Rails 6 in zeitwerk mode | module SimpleGoogleAuth
class Engine < ::Rails::Engine
initializer "simple_google_auth.load_helpers" do
ActionController::Base.send :include, SimpleGoogleAuth::Controller
ActionController::Base.send :helper_method, :google_auth_data
end
end
end
| module SimpleGoogleAuth
class Engine < ::Rails::Engine
initializer "simple_google_auth.load_helpers" do
ActiveSupport.on_load(:action_controller) do
include SimpleGoogleAuth::Controller
helper_method :google_auth_data
end
end
end
end
|
Add missing migration from BigbluebuttonRails 2.0.0 | class BigbluebuttonRails200RecordingSize < ActiveRecord::Migration
def change
change_column :bigbluebutton_recordings, :size, :integer, limit: 8, default: 0
end
end
| |
Allow checking of unknown formulae | require 'formula'
require 'caveats'
module Homebrew extend self
def caveats
raise FormulaUnspecifiedError if ARGV.named.empty?
ARGV.formulae.each do |f|
puts_caveats f
end
end
def puts_caveats f
c = Caveats.new(f)
unless c.empty?
ohai "#{f.name}: Caveats", c.caveats
puts
end
end
end
Homebrew.caveats | require 'formula'
require 'caveats'
module Homebrew extend self
def caveats
raise FormulaUnspecifiedError if ARGV.named.empty?
ARGV.named.each do |f|
puts_caveats Formulary.factory(f) rescue nil
end
end
def puts_caveats f
c = Caveats.new(f)
unless c.empty?
ohai "#{f.name}: Caveats", c.caveats
puts
end
end
end
Homebrew.caveats
|
Fix helper spec for Rspec2. | require File.dirname(__FILE__) + '/../spec_helper'
describe EmailSpec::Helpers do
include EmailSpec::Helpers
describe "#parse_email_for_link" do
it "properly finds links with text" do
email = stub(:has_body_text? => true,
:body => %(<a href="/path/to/page">Click Here</a>))
parse_email_for_link(email, "Click Here").should == "/path/to/page"
end
it "recognizes img alt properties as text" do
email = stub(:has_body_text? => true,
:body => %(<a href="/path/to/page"><img src="http://host.com/images/image.gif" alt="an image" /></a>))
parse_email_for_link(email, "an image").should == "/path/to/page"
end
it "causes a spec to fail if the body doesn't contain the text specified to click" do
email = stub(:has_body_text? => false)
lambda { parse_email_for_link(email, "non-existent text") }.should raise_error(Rspec::Expectations::ExpectationNotMetError)
end
end
end
| require File.dirname(__FILE__) + '/../spec_helper'
describe EmailSpec::Helpers do
include EmailSpec::Helpers
describe "#parse_email_for_link" do
it "properly finds links with text" do
email = stub(:has_body_text? => true,
:body => %(<a href="/path/to/page">Click Here</a>))
parse_email_for_link(email, "Click Here").should == "/path/to/page"
end
it "recognizes img alt properties as text" do
email = stub(:has_body_text? => true,
:body => %(<a href="/path/to/page"><img src="http://host.com/images/image.gif" alt="an image" /></a>))
parse_email_for_link(email, "an image").should == "/path/to/page"
end
it "causes a spec to fail if the body doesn't contain the text specified to click" do
email = stub(:has_body_text? => false)
lambda { parse_email_for_link(email, "non-existent text") }.should raise_error(Rspec::Mocks::MockExpectationError)
end
end
end
|
Clean up FindByName a bit | module Economic
module Proxies
module Actions
module CreditorContactProxy
class FindByName
attr_reader :name
def initialize(caller, name)
@caller = caller
@name = name
end
def call
# Get a list of CreditorContactHandles from e-conomic
response = request('FindByName', {
'name' => name
})
# Make sure we always have an array of handles even if the result only contains one
handles = [response[:creditor_contact_handle]].flatten.reject(&:blank?)
# Create partial CreditorContact entities
contacts = handles.collect do |handle|
creditor_contact = build
creditor_contact.partial = true
creditor_contact.persisted = true
creditor_contact.handle = handle
creditor_contact.id = handle[:id]
creditor_contact.number = handle[:number]
creditor_contact
end
if owner.is_a?(Creditor)
# Scope to the owner
contacts.select do |creditor_contact|
creditor_contact.get_data
creditor_contact.creditor.handle == owner.handle
end
else
contacts
end
end
private
def build(*options)
@caller.build(options)
end
def owner
@caller.owner
end
def request(action, data)
@caller.request(action, data)
end
end
end
end
end
end
| module Economic
module Proxies
module Actions
module CreditorContactProxy
class FindByName
attr_reader :name
def initialize(caller, name)
@caller = caller
@name = name
end
def call
# Get a list of CreditorContactHandles from e-conomic
handles = [response[:creditor_contact_handle]].flatten.reject(&:blank?)
contacts = build_partial_contact_entities(handles)
scope_to_owner(contacts)
end
private
def build(*options)
@caller.build(options)
end
def build_partial_contact_entities(handles)
handles.collect do |handle|
creditor_contact = build
creditor_contact.partial = true
creditor_contact.persisted = true
creditor_contact.handle = handle
creditor_contact.id = handle[:id]
creditor_contact.number = handle[:number]
creditor_contact
end
end
def owner
@caller.owner
end
def request(action, data)
@caller.request(action, data)
end
def response
request('FindByName', {'name' => name})
end
def scope_to_owner(contacts)
if owner.is_a?(Creditor)
# Scope to the owner
contacts.select do |creditor_contact|
creditor_contact.get_data
creditor_contact.creditor.handle == owner.handle
end
else
contacts
end
end
end
end
end
end
end
|
Set header in after filter. | require "sinatra"
games_json = File.read("public/api/v1/games.json")
get "/" do
json_exists = File.exists?("public/api/v1/games.json")
json_modified_time = json_exists ? File.mtime("public/api/v1/games.json") : nil
scrape_started_long_ago = !File.exists?("scrape-started.txt") || (Time.now - File.mtime("scrape-started.txt") > 60 * 60)
scrape_finished_long_ago = !json_exists || (Time.now - json_modified_time > 60 * 60 * 8)
if scrape_started_long_ago && scrape_finished_long_ago
Thread.new do
FileUtils.touch("scrape-started.txt")
puts `ruby bgg-inventory-scraper.rb`
games_json = File.read("public/api/v1/games.json")
end
end
json_exists ? json_modified_time.to_s : ""
end
get "/api/v1/games.json" do
response.headers['Access-Control-Allow-Origin'] = "http://bgg-inventory.com"
games_json
end | require "sinatra"
get "/" do
json_exists = File.exists?("public/api/v1/games.json")
json_modified_time = json_exists ? File.mtime("public/api/v1/games.json") : nil
scrape_started_long_ago = !File.exists?("scrape-started.txt") || (Time.now - File.mtime("scrape-started.txt") > 60 * 60)
scrape_finished_long_ago = !json_exists || (Time.now - json_modified_time > 60 * 60 * 8)
if scrape_started_long_ago && scrape_finished_long_ago
Thread.new do
FileUtils.touch("scrape-started.txt")
puts `ruby bgg-inventory-scraper.rb`
end
end
json_exists ? json_modified_time.to_s : ""
end
after do
puts "after"
response.headers['Access-Control-Allow-Origin'] = "http://bgg-inventory.com"
end |
Load the rake task instead of requiring them | module SitemapGenerator
class Railtie < Rails::Railtie
rake_tasks do
require File.expand_path('../tasks', __FILE__)
end
end
end
| module SitemapGenerator
class Railtie < Rails::Railtie
rake_tasks do
load "tasks/sitemap_generator_tasks.rake"
end
end
end
|
Fix test app to work with 1.9 | require 'spec_helper'
require 'rack/test'
require 'hijacker/middleware'
module Hijacker
describe Middleware do
include Rack::Test::Methods
def app
Rack::Builder.new do
use Hijacker::Middleware
run lambda { |env| [200, { 'blah' => 'blah' }, "success"] }
end
end
describe "#call" do
context "When the 'X-Hijacker-DB' header is set" do
it "connects to the database from the header" do
Hijacker.should_receive(:connect).with("sample-db")
get '/',{}, 'HTTP_X_HIJACKER_DB' => 'sample-db'
end
end
context "When the 'X-Hijacker-DB' header is not set" do
it "doesn't connect to any database" do
Hijacker.should_not_receive(:connect)
get '/',{}, "x-not-db-header" => "something"
end
end
end
end
end
| require 'spec_helper'
require 'rack/test'
require 'hijacker/middleware'
module Hijacker
describe Middleware do
include Rack::Test::Methods
def app
Rack::Builder.new do
use Hijacker::Middleware
run lambda { |env| [200, { 'blah' => 'blah' }, ["success"]] }
end
end
describe "#call" do
context "When the 'X-Hijacker-DB' header is set" do
it "connects to the database from the header" do
Hijacker.should_receive(:connect).with("sample-db")
get '/',{}, 'HTTP_X_HIJACKER_DB' => 'sample-db'
end
end
context "When the 'X-Hijacker-DB' header is not set" do
it "doesn't connect to any database" do
Hijacker.should_not_receive(:connect)
get '/',{}, "x-not-db-header" => "something"
end
end
end
end
end
|
Use strings for index names instead of symbols. | class CreateMessageRecipients < ActiveRecord::Migration
def self.up
create_table :message_recipients do |t|
t.column :messageable_id, :integer, :unsigned => true, :references => nil
t.column :message_id, :integer, :null => false, :unsigned => true
t.column :kind, :string, :null => false, :default => 'to'
t.column :position, :integer, :null => false
t.column :type, :string, :null => false
end
add_index :message_recipients, [:message_id, :messageable_id, :type], :unique => true, :name => :unique_message_recipients
add_index :message_recipients, [:message_id, :position], :unique => true
end
def self.down
drop_table_if_exists :message_recipients
end
end | class CreateMessageRecipients < ActiveRecord::Migration
def self.up
create_table :message_recipients do |t|
t.column :messageable_id, :integer, :unsigned => true, :references => nil
t.column :message_id, :integer, :null => false, :unsigned => true
t.column :kind, :string, :null => false, :default => 'to'
t.column :position, :integer, :null => false
t.column :type, :string, :null => false
end
add_index :message_recipients, [:message_id, :messageable_id, :type], :unique => true, :name => 'unique_message_recipients'
add_index :message_recipients, [:message_id, :position], :unique => true
end
def self.down
drop_table_if_exists :message_recipients
end
end |
Choose the right database on the server | set :application, "optemo_site"
set :repository, "git@jaguar:site.git"
set :domain, "jaguar"
# If you aren't deploying to /u/apps/#{application} on the target
# servers (which is the default), you can specify the actual location
# via the :deploy_to variable:
# set :deploy_to, "/var/www/#{application}"
set :scm, :git
set :deploy_via, :remote_cache
set :user, 'jan'
#ssh_options[:paranoid] = false
default_run_options[:pty] = true
set :use_sudo, false
role :app, domain
role :web, domain
role :db, domain, :primary => true
############################################################
# Passenger
#############################################################
namespace :passenger do
desc "Restart Application"
task :restart do
run "touch #{current_path}/tmp/restart.txt"
end
end
desc "Compile C-Code"
task :compilec do
run "make #{current_path}/lib/c_code/clusteringCode/codes/connect"
end
after :deploy, "compilec"
after :compilec, "passenger:restart" | set :application, "optemo_site"
set :repository, "git@jaguar:site.git"
set :domain, "jaguar"
# If you aren't deploying to /u/apps/#{application} on the target
# servers (which is the default), you can specify the actual location
# via the :deploy_to variable:
# set :deploy_to, "/var/www/#{application}"
set :scm, :git
set :deploy_via, :remote_cache
set :user, 'jan'
#ssh_options[:paranoid] = false
default_run_options[:pty] = true
set :use_sudo, false
role :app, domain
role :web, domain
role :db, domain, :primary => true
############################################################
# Passenger
#############################################################
namespace :passenger do
desc "Restart Application"
task :restart do
run "touch #{current_path}/tmp/restart.txt"
end
end
desc "Compile C-Code"
task :compilec do
run "make #{current_path}/lib/c_code/clusteringCode/codes/connect"
end
after :deploy, "compilec"
after :compilec, "passenger:restart"
namespace :deploy do
task :after, :roles => :app do
# config on server
run "cd #{release_path}/config && cp -f database.yml.deploy database.yml"
end
end |
Call the setup! method from within Server.start, not Server.run! | # lib/frecon/server.rb
#
# Copyright (C) 2014 Christopher Cooper, Sam Craig, Tiger Huang, Vincent Mai, Sam Mercier, and Kristofer Rye
#
# This file is part of FReCon, an API for scouting at FRC Competitions, which is
# licensed under the MIT license. You should have received a copy of the MIT
# license with this program. If not, please see
# <http://opensource.org/licenses/MIT>.
require "sinatra/base"
require "frecon/database"
require "frecon/routes"
require "frecon/controllers"
module FReCon
class Server < Sinatra::Base
include Routes
before do
content_type "application/json"
end
def self.start
run!
end
protected
def self.setup!(server: %w[thin HTTP webrick], host: "localhost", port: 4567, environment: FReCon.environment)
set :server, server
set :bind, host
set :port, port
set :environment, environment
Database.setup(settings.environment)
end
def self.run!
self.setup!
super
end
end
end
| # lib/frecon/server.rb
#
# Copyright (C) 2014 Christopher Cooper, Sam Craig, Tiger Huang, Vincent Mai, Sam Mercier, and Kristofer Rye
#
# This file is part of FReCon, an API for scouting at FRC Competitions, which is
# licensed under the MIT license. You should have received a copy of the MIT
# license with this program. If not, please see
# <http://opensource.org/licenses/MIT>.
require "sinatra/base"
require "frecon/database"
require "frecon/routes"
require "frecon/controllers"
module FReCon
class Server < Sinatra::Base
include Routes
before do
content_type "application/json"
end
def self.start
setup!
run!
end
protected
def self.setup!(server: %w[thin HTTP webrick], host: "localhost", port: 4567, environment: FReCon.environment)
set :server, server
set :bind, host
set :port, port
set :environment, environment
Database.setup(settings.environment)
end
def self.run!
super
end
end
end
|
Update file detector Ruby example. | module Selenium
module WebDriver
#
# @api private
#
module DriverExtensions
module UploadsFiles
#
# Set the file detector to pass local files to a remote WebDriver.
#
# The detector is an object that responds to #call, and when called
# will determine if the given string represents a file. If it does,
# the path to the file on the local file system should be returned,
# otherwise nil or false.
#
# Example:
#
# driver = Selenium::WebDriver.for :remote
# driver.file_detector = lambda { |str| str if File.exist?(str) }
#
# driver.find_element(:id => "upload").send_keys "/path/to/file"
#
# By default, no file detection is performed.
#
def file_detector=(detector)
unless detector.nil? or detector.respond_to? :call
raise ArgumentError, "detector must respond to #call"
end
bridge.file_detector = detector
end
end # UploadsFiles
end # DriverExtensions
end # WebDriver
end # Selenium
| module Selenium
module WebDriver
#
# @api private
#
module DriverExtensions
module UploadsFiles
#
# Set the file detector to pass local files to a remote WebDriver.
#
# The detector is an object that responds to #call, and when called
# will determine if the given string represents a file. If it does,
# the path to the file on the local file system should be returned,
# otherwise nil or false.
#
# Example:
#
# driver = Selenium::WebDriver.for :remote
# driver.file_detector = lambda do |args|
# # args => ["/path/to/file"]
# str if File.exist?(args.first.to_s)
# end
#
# driver.find_element(:id => "upload").send_keys "/path/to/file"
#
# By default, no file detection is performed.
#
def file_detector=(detector)
unless detector.nil? or detector.respond_to? :call
raise ArgumentError, "detector must respond to #call"
end
bridge.file_detector = detector
end
end # UploadsFiles
end # DriverExtensions
end # WebDriver
end # Selenium
|
Remove unused methods in PollItem | module ZMQ
class PollItem < FFI::Struct
layout :socket, :pointer,
:fd, :int,
:events, :short,
:revents, :short
def socket
self[:socket]
end
def socket=(socket)
self[:socket] = socket
end
def fd
self[:fd]
end
def fd=(fd)
self[:fd] = fd
end
def events
self[:events]
end
def events=(events)
self[:events] = events
end
def readable?
(self[:revents] & LibZMQ::EVENT_FLAGS[:pollin]) > 0
end
def writable?
(self[:revents] & LibZMQ::EVENT_FLAGS[:pollout]) > 0
end
def self.create_array(poll_items)
pointer = FFI::MemoryPointer.new(size, poll_items.size, true)
poll_items.each_with_index do |poll_item, i|
pointer.put_bytes(i*poll_item.size, poll_item.pointer.read_bytes(poll_item.size), 0, poll_item.size)
end
pointer
end
end
end
| module ZMQ
class PollItem < FFI::Struct
layout :socket, :pointer,
:fd, :int,
:events, :short,
:revents, :short
def socket=(socket)
self[:socket] = socket
end
def fd=(fd)
self[:fd] = fd
end
def events=(events)
self[:events] = events
end
def readable?
(self[:revents] & LibZMQ::EVENT_FLAGS[:pollin]) > 0
end
def writable?
(self[:revents] & LibZMQ::EVENT_FLAGS[:pollout]) > 0
end
def self.create_array(poll_items)
pointer = FFI::MemoryPointer.new(size, poll_items.size, true)
poll_items.each_with_index do |poll_item, i|
pointer.put_bytes(i*poll_item.size, poll_item.pointer.read_bytes(poll_item.size), 0, poll_item.size)
end
pointer
end
end
end
|
Add associations to migration for progress notes | class MigrateProgressNotesToEventNotes < ActiveRecord::Migration
class DeprecatedProgressNotesClass < ActiveRecord::Base
self.table_name = :progress_notes
end
def change
sst_meeting = EventNoteType.find_by_name('SST Meeting')
raise "Please run DatabaseConstants.new.seed!" if sst_meeting.nil?
DeprecatedProgressNotesClass.find_each do |progress_note|
student = progress_note.intervention.student
educator = progress_note.educator
EventNote.create!(
student: student,
educator: educator,
event_note_type: sst_meeting,
text: progress_note.content,
recorded_at: progress_note.created_at
)
end
drop_table :progress_notes
end
end
| class MigrateProgressNotesToEventNotes < ActiveRecord::Migration
class DeprecatedProgressNotesClass < ActiveRecord::Base
self.table_name = :progress_notes
belongs_to :intervention
belongs_to :educator
end
def change
sst_meeting = EventNoteType.find_by_name('SST Meeting')
raise "Please run DatabaseConstants.new.seed!" if sst_meeting.nil?
DeprecatedProgressNotesClass.find_each do |progress_note|
student = progress_note.intervention.student
educator = progress_note.educator
EventNote.create!(
student: student,
educator: educator,
event_note_type: sst_meeting,
text: progress_note.content,
recorded_at: progress_note.created_at
)
end
drop_table :progress_notes
end
end
|
Move value3 to another column in the same CF. | create 'test', 'cf'
put 'test', 'row1', 'cf:col1', 'value1'
put 'test', 'row2', 'cf:col1', 'value2'
put 'test', 'row3', 'cf:col1', 'value3'
| create 'test', 'cf'
put 'test', 'row1', 'cf:col1', 'value1'
put 'test', 'row2', 'cf:col1', 'value2'
put 'test', 'row3', 'cf:col2', 'value3'
|
Add a test file for BMFF::Box::SyncSample. | # coding: utf-8
# vim: set expandtab tabstop=2 shiftwidth=2 softtabstop=2 autoindent:
require_relative '../../minitest_helper'
require 'bmff/box'
require 'stringio'
class TestBMFFBoxSyncSample < MiniTest::Unit::TestCase
def test_parse
io = StringIO.new("", "r+:ascii-8bit")
io.extend(BMFF::BinaryAccessor)
io.write_uint32(0)
io.write_ascii("stss")
io.write_uint8(0) # version
io.write_uint24(0) # flags
io.write_uint32(3) # entry_count
3.times do |i|
io.write_uint32(i) # sample_number
end
size = io.pos
io.pos = 0
io.write_uint32(size)
io.pos = 0
box = BMFF::Box.get_box(io, nil)
assert_instance_of(BMFF::Box::SyncSample, box)
assert_equal(size, box.actual_size)
assert_equal("stss", box.type)
assert_equal(0, box.version)
assert_equal(0, box.flags)
assert_equal(3, box.entry_count)
assert_equal([0, 1, 2], box.sample_number)
end
end
| |
Move capybara helpers in a separate template file | module CapybaraHelper
def page!
save_and_open_page
end
def screenshot!
save_and_open_screenshot
end
end
RSpec.configure do |config|
config.include CapybaraHelper, type: :feature
end
| |
Add next link to pagination. | module Liquid
module PaginationFilters
def paginate(pagination_info)
pagination_html = ""
if pagination_info.is_a? Hash
if pagination_info["current_page"] && (pagination_info["current_page"].to_i > 1)
pagination_html += "<a href=\"?page=#{pagination_info["current_page"].to_i - 1}\" class=\"prev_page\" rel=\"prev\">« Previous</a> "
end
end
pagination_html
end
end
end | module Liquid
module PaginationFilters
def paginate(pagination_info)
pagination_html = ""
if pagination_info.is_a?(Hash) && (pagination_info["current_page"] && pagination_info["per_page"] && pagination_info["total_entries"])
# Previous link, if appropriate
pagination_html += "<a href=\"?page=#{pagination_info["current_page"].to_i - 1}\" class=\"prev_page\" rel=\"prev\">« Previous</a>" if pagination_info["current_page"].to_i > 1
# Next link, if appropriate
if (pagination_info["current_page"].to_i * pagination_info["per_page"].to_i) < pagination_info["total_entries"].to_i
pagination_html += "<a href=\"?page=#{pagination_info["current_page"].to_i + 1}\" class=\"next_page\" rel=\"next\">Next »</a>"
end
end
pagination_html
end
end
end |
Resolve frozen string warning on Chef 13 | require File.join(File.dirname(__FILE__), 'ec2')
module Opscode
module Aws
module S3
include Opscode::Aws::Ec2
def s3
require 'aws-sdk'
Chef::Log.debug('Initializing the S3 Client')
@s3 ||= create_aws_interface(::Aws::S3::Client)
end
def s3_obj
require 'aws-sdk'
remote_path = new_resource.remote_path
remote_path.sub!(%r{^/*}, '')
Chef::Log.debug("Initializing the S3 Object for bucket: #{new_resource.bucket} path: #{remote_path}")
@s3_obj ||= ::Aws::S3::Object.new(bucket_name: new_resource.bucket, key: remote_path, client: s3)
end
def compare_md5s(remote_object, local_file_path)
return false unless ::File.exist?(local_file_path)
local_md5 = ::Digest::MD5.new
remote_hash = remote_object.etag.delete('"') # etags are always quoted
::File.open(local_file_path, 'rb') do |f|
f.each_line do |line|
local_md5.update line
end
end
local_hash = local_md5.hexdigest
Chef::Log.debug "Remote file md5 hash: #{remote_hash}"
Chef::Log.debug "Local file md5 hash: #{local_hash}"
local_hash == remote_hash
end
end
end
end
| require File.join(File.dirname(__FILE__), 'ec2')
module Opscode
module Aws
module S3
include Opscode::Aws::Ec2
def s3
require 'aws-sdk'
Chef::Log.debug('Initializing the S3 Client')
@s3 ||= create_aws_interface(::Aws::S3::Client)
end
def s3_obj
require 'aws-sdk'
remote_path = new_resource.remote_path.dup
remote_path.sub!(%r{^/*}, '')
Chef::Log.debug("Initializing the S3 Object for bucket: #{new_resource.bucket} path: #{remote_path}")
@s3_obj ||= ::Aws::S3::Object.new(bucket_name: new_resource.bucket, key: remote_path, client: s3)
end
def compare_md5s(remote_object, local_file_path)
return false unless ::File.exist?(local_file_path)
local_md5 = ::Digest::MD5.new
remote_hash = remote_object.etag.delete('"') # etags are always quoted
::File.open(local_file_path, 'rb') do |f|
f.each_line do |line|
local_md5.update line
end
end
local_hash = local_md5.hexdigest
Chef::Log.debug "Remote file md5 hash: #{remote_hash}"
Chef::Log.debug "Local file md5 hash: #{local_hash}"
local_hash == remote_hash
end
end
end
end
|
Build status - fix to display for specific build | module ApplicationHelper
def icon_for_status(status)
if @build
case @build.build_status
when 'success'
'<i class="fa fa-check fa-fw" style="color:green"></i>'
when 'warn'
'<i class="fa fa-warning fa-fw" style="color:orange"></i>'
when 'error'
'<i class="fa fa-warning fa-fw" style="color:red"></i>'
when 'failed'
'<i class="fa fa-warning fa-fw" style="color:red"></i>'
else
''
end
else
""
end
end
end
| module ApplicationHelper
def icon_for_status(status)
case status
when 'success'
'<i class="fa fa-check fa-fw" style="color:green"></i>'
when 'warn'
'<i class="fa fa-warning fa-fw" style="color:orange"></i>'
when 'error'
'<i class="fa fa-warning fa-fw" style="color:red"></i>'
when 'failed'
'<i class="fa fa-warning fa-fw" style="color:red"></i>'
else
''
end
end
end
|
Replace views generator with btgen gem | module Riews
module ViewsHelper
def generate_view_content_for(view)
content_tag :table do
generate_header_for(view) + generate_body_for(view)
end
end
def generate_header_for(view)
content_tag :thead do
content_tag :tr do
view.columns.map {|column| content_tag :th, column.method}.inject(:+)
end
end
end
def generate_body_for(view)
content_tag :tbody do
view.results.map do |object|
content_tag :tr do
view.columns.map do |column|
content_tag :td, object[column.method]
end.inject(:+)
end
end.inject(:+)
end
end
end
end
| module Riews
module ViewsHelper
def generate_view_content_for(view)
bootstrap_table do |table|
table.headers = view.columns.map(&:method)
view.results.each do |object|
table.rows << view.columns.map{ |column| object[column.method] }
end
end
end
end
end
|
Bump version for podspec fix | Pod::Spec.new do |s|
s.name = "MD5Digest"
s.version = "1.0.0"
s.summary = "An Objective-C NSString category for MD5 hex digests."
s.homepage = "https://github.com/Keithbsmiley/MD5Digest"
s.license = 'MIT'
s.author = { "Keith Smiley" => "keithbsmiley@gmail.com" }
s.source = { :git => "https://github.com/Keithbsmiley/MD5Digest.git", :tag => s.version.to_s }
s.source_files = 'NSString+MD5.{h,m}'
s.requires_arc = true
s.ios.deployment_target = "7.0"
s.osx.deployment_target = "10.8"
end
| Pod::Spec.new do |s|
s.name = "MD5Digest"
s.version = "1.0.1"
s.summary = "An Objective-C NSString category for MD5 hex digests."
s.homepage = "https://github.com/Keithbsmiley/MD5Digest"
s.license = 'MIT'
s.author = { "Keith Smiley" => "keithbsmiley@gmail.com" }
s.source = { :git => "https://github.com/Keithbsmiley/MD5Digest.git", :tag => s.version.to_s }
s.source_files = 'NSString+MD5.{h,m}'
s.requires_arc = true
s.ios.deployment_target = "7.0"
s.osx.deployment_target = "10.8"
end
|
Fix api shipment controller spec to set a shipment to 'ready' state before it can be shipped | require 'spec_helper'
describe Spree::Api::V1::ShipmentsController do
let!(:shipment) { Factory(:shipment) }
let!(:attributes) { [:id, :tracking, :number, :cost, :shipped_at] }
before do
shipment.order.payment_state == 'paid'
stub_authentication!
end
context "working with a shipment" do
let!(:resource_scoping) { { :order_id => shipment.order.to_param, :id => shipment.to_param } }
it "can make a shipment ready" do
api_put :ready
json_response.should have_attributes(attributes)
json_response["shipment"]["state"].should == "ready"
end
context "can transition a shipment from ready to ship" do
before do
shipment.order.update_attribute(:payment_state, 'paid')
shipment.update!(shipment.order)
end
it "can transition a shipment from ready to ship" do
shipment.reload
api_put :ship, :order_id => shipment.order.to_param, :id => shipment.to_param, :shipment => { :tracking => "123123" }
json_response.should have_attributes(attributes)
json_response["shipment"]["state"].should == "shipped"
end
end
end
end
| |
Add the mysql gem for the database cookbook | #
# Cookbook Name:: mariadb
# Recipe:: ruby
#
# Author:: Jesse Howarth (<him@jessehowarth.com>)
# Author:: Jamie Winsor (<jamie@vialstudios.com>)
#
# Copyright 2008-2013, Opscode, 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.
#
node.set['build_essential']['compiletime'] = true
include_recipe 'build-essential::default'
include_recipe 'mariadb::client'
node['mariadb']['client']['packages'].each do |name|
resources("package[#{name}]").run_action(:install)
end
chef_gem 'mysql2'
| #
# Cookbook Name:: mariadb
# Recipe:: ruby
#
# Author:: Jesse Howarth (<him@jessehowarth.com>)
# Author:: Jamie Winsor (<jamie@vialstudios.com>)
#
# Copyright 2008-2013, Opscode, 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.
#
node.set['build_essential']['compiletime'] = true
include_recipe 'build-essential::default'
include_recipe 'mariadb::client'
node['mariadb']['client']['packages'].each do |name|
resources("package[#{name}]").run_action(:install)
end
chef_gem 'mysql2'
# The database cookbook needs the mysql gem
chef_gem 'mysql'
|
Update the link to "Is my device compatible?" | # coding: utf-8
# This file is part of Mconf-Web, a web application that provides access
# to the Mconf webconferencing system. Copyright (C) 2010-2015 Mconf.
#
# This file is licensed under the Affero General Public License version
# 3 or later. See the LICENSE file.
module RnpHelper
def requirements_url
"https://wiki.rnp.br/pages/viewpage.action?pageId=89112372#ManualdoUsuáriodoserviçodeconferênciaweb-Requisitosdeuso"
end
def service_page_url
"https://www.rnp.br/servicos/servicos-avancados/conferencia-web"
end
def mconf_tec_url
"http://mconf.com"
end
def compatibility_url
"http://?????" # TODO
end
def sidenav_for_user?
params[:controller] == "my"
end
def sidenav_for_spaces?
@space.present?
end
def sidenav_room
if sidenav_for_user?
current_user.try(:bigbluebutton_room)
else
@space.try(:bigbluebutton_room)
end
end
end
| # coding: utf-8
# This file is part of Mconf-Web, a web application that provides access
# to the Mconf webconferencing system. Copyright (C) 2010-2015 Mconf.
#
# This file is licensed under the Affero General Public License version
# 3 or later. See the LICENSE file.
module RnpHelper
def requirements_url
"https://wiki.rnp.br/pages/viewpage.action?pageId=89112372#ManualdoUsuáriodoserviçodeconferênciaweb-Requisitosdeuso"
end
def service_page_url
"https://www.rnp.br/servicos/servicos-avancados/conferencia-web"
end
def mconf_tec_url
"http://mconf.com"
end
def compatibility_url
"https://wiki.rnp.br/pages/viewpage.action?pageId=90402465"
end
def sidenav_for_user?
params[:controller] == "my"
end
def sidenav_for_spaces?
@space.present?
end
def sidenav_room
if sidenav_for_user?
current_user.try(:bigbluebutton_room)
else
@space.try(:bigbluebutton_room)
end
end
end
|
Modify new and create actions | class DocsController < ApplicationController
def index
end
def show
end
def new
end
def create
end
def edit
end
def update
end
def destroy
end
private
def find_doc
end
def doc_params
end
end
| class DocsController < ApplicationController
def index
end
def show
end
def new
@doc = Doc.new
end
def create
@doc = Doc.new(doc_params)
if @doc.save
redirect_to @doc
else
render 'new'
end
end
def edit
end
def update
end
def destroy
end
private
def find_doc
end
def doc_params
params.require(:doc).permit(:title, :content)
end
end
|
Fix typo in url default | # default env vars that may not be set
ENV['ID_ROOT'] ||= 'https://id.prx.org/'
ENV['CMS_ROOT'] ||= 'https://cms.prx.org/api/vi/'
ENV['PRX_ROOT'] ||= 'https://beta.prx.org/stories/'
ENV['CRIER_ROOT'] ||= 'https://crier.prx.org/api/v1'
ENV['FEEDER_WEB_MASTER'] ||= 'prxhelp@prx.org (PRX)'
ENV['FEEDER_GENERATOR'] ||= "PRX Feeder v#{Feeder::VERSION}"
env_prefix = Rails.env.production? ? '' : (Rails.env + '-')
ENV['FEEDER_CDN_HOST'] ||= "#{env_prefix}f.prxu.org"
ENV['FEEDER_STORAGE_BUCKET'] ||= "#{env_prefix}prx-feed"
env_suffix = Rails.env.development? ? 'dev' : 'org'
ENV['FEEDER_APP_HOST'] ||= "feeder.prx.#{env_suffix}"
| # default env vars that may not be set
ENV['ID_ROOT'] ||= 'https://id.prx.org/'
ENV['CMS_ROOT'] ||= 'https://cms.prx.org/api/v1/'
ENV['PRX_ROOT'] ||= 'https://beta.prx.org/stories/'
ENV['CRIER_ROOT'] ||= 'https://crier.prx.org/api/v1'
ENV['FEEDER_WEB_MASTER'] ||= 'prxhelp@prx.org (PRX)'
ENV['FEEDER_GENERATOR'] ||= "PRX Feeder v#{Feeder::VERSION}"
env_prefix = Rails.env.production? ? '' : (Rails.env + '-')
ENV['FEEDER_CDN_HOST'] ||= "#{env_prefix}f.prxu.org"
ENV['FEEDER_STORAGE_BUCKET'] ||= "#{env_prefix}prx-feed"
env_suffix = Rails.env.development? ? 'dev' : 'org'
ENV['FEEDER_APP_HOST'] ||= "feeder.prx.#{env_suffix}"
|
Update target commit in podspec | Pod::Spec.new do |s|
s.ios.deployment_target = "6.0"
s.requires_arc = true
s.name = "LLReactiveMatchers"
s.version = "0.0.1"
s.summary = "Expecta matchers for ReactiveCocoa."
s.description = "Expecta matchers for ReactiveCocoa. Yay."
s.homepage = "https://github.com/lawrencelomax/LLReactiveMatchers"
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { "Lawrence Lomax" => "lomax.lawrence@gmail.com" }
s.source = { :git => "https://github.com/lawrencelomax/LLReactiveMatchers.git", :commit => "06f55c80013345af64d7bd92d0d017742412f237" }
s.source_files = 'LLReactiveMatchers/**/*.{h,m}'
s.prefix_header_file = 'LLReactiveMatchers/LLReactiveMatchers-Prefix.pch'
s.frameworks = 'Foundation', 'XCTest'
s.dependency 'ReactiveCocoa', '>=2.1.7'
s.dependency 'Expecta'
s.dependency 'Specta'
end
| Pod::Spec.new do |s|
s.ios.deployment_target = "6.0"
s.requires_arc = true
s.name = "LLReactiveMatchers"
s.version = "0.0.1"
s.summary = "Expecta matchers for ReactiveCocoa."
s.description = "Expecta matchers for ReactiveCocoa. Yay."
s.homepage = "https://github.com/lawrencelomax/LLReactiveMatchers"
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { "Lawrence Lomax" => "lomax.lawrence@gmail.com" }
s.source = { :git => "https://github.com/lawrencelomax/LLReactiveMatchers.git", :commit => "5fb16a96c774026eae957c1d4c712694fd2cff71" }
s.source_files = 'LLReactiveMatchers/**/*.{h,m}'
s.prefix_header_file = 'LLReactiveMatchers/LLReactiveMatchers-Prefix.pch'
s.frameworks = 'Foundation', 'XCTest'
s.dependency 'ReactiveCocoa', '>=2.1.7'
s.dependency 'Expecta'
s.dependency 'Specta'
end
|
Install mime-types gem along with fog | #
# Cookbook Name:: rackspacecloud
# Recipe:: default
#
# Copyright:: 2013, Rackspace Hosting <ryan.walker@rackspace.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
include_recipe 'xml::ruby' unless platform_family?("windows")
chef_gem "fog" do
version node[:rackspacecloud][:fog_version]
action :install
end
require 'fog'
| #
# Cookbook Name:: rackspacecloud
# Recipe:: default
#
# Copyright:: 2013, Rackspace Hosting <ryan.walker@rackspace.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
include_recipe 'xml::ruby' unless platform_family?("windows")
chef_gem "fog" do
version node[:rackspacecloud][:fog_version]
compile_time true if Chef::Resource::ChefGem.method_defined?(:compile_time)
action :install
end
chef_gem 'mime-types' do
compile_time true if Chef::Resource::ChefGem.method_defined?(:compile_time)
end
require 'fog'
|
Reset negative count on hand in existing non backorderable stock items | # frozen_string_literal: true
class ResetNegativeNonbackorderableCountOnHandInStockItems < ActiveRecord::Migration
module Spree
class StockItem < ActiveRecord::Base
self.table_name = "spree_stock_items"
end
end
def up
Spree::StockItem.where(backorderable: false)
.where("count_on_hand < 0")
.update_all(count_on_hand: 0)
end
def down
raise ActiveRecord::IrreversibleMigration
end
end
| |
Fix payload in publishing-api presenters | class TaxonPresenter
def initialize(base_path:, title:)
@base_path = base_path
@title = title
end
def payload
{
base_path: base_path,
document_type: 'taxon',
schema_name: 'taxon',
title: title,
publishing_app: 'collections-publisher',
rendering_app: 'collections',
public_updated_at: Time.now.iso8601,
locale: 'en',
routes: [
{ path: base_path, type: "exact" },
]
}
end
private
attr_reader :base_path, :title
end
| class TaxonPresenter
def initialize(base_path:, title:)
@base_path = base_path
@title = title
end
def payload
{
base_path: base_path,
document_type: 'taxon',
schema_name: 'taxon',
title: title,
publishing_app: 'collections-publisher',
rendering_app: 'collections',
public_updated_at: Time.now.iso8601,
locale: 'en',
details: {},
routes: [
{ path: base_path, type: "exact" },
]
}
end
private
attr_reader :base_path, :title
end
|
Check we're writing messages in the right format and buffering correctly | require 'spec_helper'
module ActivityBroker
describe MessageStream do
class FakeEventLoop
def register_read(listener, event, stop_event)
@listener = listener
@event = event
end
def notify_read_event
@listener.send(@event)
end
end
let(:event_loop) { FakeEventLoop.new }
it 'buffers messages from event source and streams them to the message listener' do
io = double(read_nonblock: '1|U|sender|recipient' + MessageStream::CRLF + '2|U|sender')
message_stream = MessageStream.new(io, event_loop, double.as_null_object)
message_listener = double(:process_message)
message_stream.read(message_listener)
expect(message_listener).to receive(:process_message).with('1|U|sender|recipient', message_stream)
event_loop.notify_read_event
end
end
end
| require 'spec_helper'
module ActivityBroker
describe MessageStream do
class FakeEventLoop
def register_read(listener, event, stop_event)
@listener = IOListener.new(listener, event, stop_event)
end
def notify_read_event
@listener.notify
end
def notify_write_event
@listener.notify
end
def register_write(listener, event, stop_event)
@listener = IOListener.new(listener, event, stop_event)
end
def deregister_write(listener, event)
end
end
let!(:event_loop) { FakeEventLoop.new }
let!(:fake_io) { double }
let!(:message_stream){ MessageStream.new(fake_io, event_loop, double.as_null_object) }
it 'buffers messages from event source and streams them to the message listener' do
fake_io.stub(read_nonblock: '1|U|sender|recipient' + MessageStream::CRLF + '2|U|sender')
message_listener = double(:process_message)
message_stream.read(message_listener)
expect(message_listener).to receive(:process_message).with('1|U|sender|recipient', message_stream)
event_loop.notify_read_event
end
it 'buffers outgoing messages and writes them in the right format' do
one_message = '1|U|sender|recipient'
# Try to write 3 messages
message_stream.write(one_message)
message_stream.write(one_message)
message_stream.write(one_message)
expected_message = (one_message + MessageStream::CRLF) * 3
expect(fake_io).to receive(:write_nonblock)
.with(expected_message)
.and_return(expected_message.bytesize / 3 * 2) # Acknowledge writing only two
event_loop.notify_write_event
expected_message = one_message + MessageStream::CRLF
expect(fake_io).to receive(:write_nonblock)
.with(expected_message)
.and_return(expected_message.bytesize) # Check if we get the last message
event_loop.notify_write_event
end
end
end
|
Use up and down on contacts migration | class RenameCompanyContactToContact < ActiveRecord::Migration
def change
if ActiveRecord::Base.connection.table_exists? 'contacts'
drop_table :contacts
end
rename_column :notifications, :company_contact_id, :contact_id
rename_table :company_contacts, :contacts
end
end
| class RenameCompanyContactToContact < ActiveRecord::Migration
def up
if ActiveRecord::Base.connection.table_exists? 'contacts'
drop_table :contacts
end
rename_column :notifications, :company_contact_id, :contact_id
rename_table :company_contacts, :contacts
end
def down
rename_column :notifications, :contact_id, :company_contact_id
rename_table :contacts, :company_contacts
end
end
|
Fix indenting on authenticate! method | module API
module V1
module Defaults
extend ActiveSupport::Concern
included do
prefix "api"
version "v1", using: :path
default_format :json
format :json
helpers do
def permitted_params
@permitted_params ||= declared(params,
include_missing: false)
end
def logger
Rails.logger
end
def authenticate!
if doorkeeper_token
doorkeeper_authorize!
else
error!('Unauthorized. Invalid or expired token.', 401) unless current_user #||
end
end
def current_user
# find token. Check if valid.
if doorkeeper_token
User.find(doorkeeper_token.resource_owner_id)
else
passed_token = request.headers["X-Token"] || params["token"]
token = ApiKey.where(access_token: passed_token).first
if token && !token.expired?
@current_user = User.find(token.user_id)
else
false
end
end
end
def restrict_to_role(role)
error!('Unauthorized. Insufficient access priviledges.', 401) unless role.include?(current_user.role)
end
end
rescue_from ActiveRecord::RecordNotFound do |e|
error_response(message: e.message, status: 404)
end
rescue_from ActiveRecord::RecordInvalid do |e|
error_response(message: e.message, status: 422)
end
end
end
end
end
| module API
module V1
module Defaults
extend ActiveSupport::Concern
included do
prefix "api"
version "v1", using: :path
default_format :json
format :json
helpers do
def permitted_params
@permitted_params ||= declared(params,
include_missing: false)
end
def logger
Rails.logger
end
def authenticate!
if doorkeeper_token
doorkeeper_authorize!
else
error!('Unauthorized. Invalid or expired token.', 401) unless current_user #||
end
end
def current_user
# find token. Check if valid.
if doorkeeper_token
User.find(doorkeeper_token.resource_owner_id)
else
passed_token = request.headers["X-Token"] || params["token"]
token = ApiKey.where(access_token: passed_token).first
if token && !token.expired?
@current_user = User.find(token.user_id)
else
false
end
end
end
def restrict_to_role(role)
error!('Unauthorized. Insufficient access priviledges.', 401) unless role.include?(current_user.role)
end
end
rescue_from ActiveRecord::RecordNotFound do |e|
error_response(message: e.message, status: 404)
end
rescue_from ActiveRecord::RecordInvalid do |e|
error_response(message: e.message, status: 422)
end
end
end
end
end
|
Revert :name back in _dashboard view | json.extract! dashboard, :id, :full_name, :currency
json.metadata dashboard.settings
json.data_sources dashboard.organizations.compact.map do |org|
json.id org.id
json.uid org.uid
json.label org.name
end
json.kpis dashboard.kpis, partial: 'mno_enterprise/jpi/v1/impac/kpis/kpi', as: :kpi
json.widgets dashboard.widgets, partial: 'mno_enterprise/jpi/v1/impac/widgets/widget', as: :widget
json.widgets_templates dashboard.filtered_widgets_templates
| json.extract! dashboard, :id, :name, :full_name, :currency
json.metadata dashboard.settings
json.data_sources dashboard.organizations.compact.map do |org|
json.id org.id
json.uid org.uid
json.label org.name
end
json.kpis dashboard.kpis, partial: 'mno_enterprise/jpi/v1/impac/kpis/kpi', as: :kpi
json.widgets dashboard.widgets, partial: 'mno_enterprise/jpi/v1/impac/widgets/widget', as: :widget
json.widgets_templates dashboard.filtered_widgets_templates
|
Revert "Fix error in ci?" | # frozen_string_literal: true
class Day < Sequel::Model
dataset_module do
def latest(date = Date.today)
where(date: select(:date).where(Sequel.lit('date <= ?', date))
.order(Sequel.desc(:date))
.limit(1))
end
def between(interval)
where(date: interval)
end
def currencies
select(:date,
Sequel.lit('rates.key').as(:iso_code),
Sequel.lit('rates.value::text::float').as(:rate))
.join(Sequel.function(:jsonb_each, :rates).lateral.as(:rates), true)
.order(Sequel.asc(:date), Sequel.asc(:iso_code))
end
end
end
| # frozen_string_literal: true
class Day < Sequel::Model
dataset_module do
def latest(date = Date.today)
where(date: select(:date).where(Sequel.lit('date <= ?', date))
.order(Sequel.desc(:date))
.limit(1))
end
def between(interval)
where(date: interval)
end
def currencies
select(:date,
Sequel.lit('rates.key').as(:iso_code),
Sequel.lit('rates.value::text::float').as(:rate))
.join(Sequel.function(:jsonb_each, :rates).lateral.as(:rates), true)
end
end
end
|
Fix flakey scheduled publishing test | require "govuk_sidekiq/testing"
require "sidekiq/api"
module SidekiqTestHelpers
def with_real_sidekiq
Sidekiq::Testing.disable! do
Sidekiq.configure_client do |config|
config.redis = { namespace: "whitehall-test" }
end
Sidekiq::ScheduledSet.new.clear
yield
end
end
end
| require "govuk_sidekiq/testing"
require "sidekiq/api"
module SidekiqTestHelpers
def with_real_sidekiq
Sidekiq::Testing.disable! do
Sidekiq.configure_client do |config|
# The Rails built-in test parallelization doesn't make it easy to find the worker number.
# So here we're using the number suffixed to the Postgres database name, because that is unique for each worker.
parallel_test_runner_number = ActiveRecord::Base.connection.current_database.split("-").last.to_i
config.redis = { db: parallel_test_runner_number }
end
Sidekiq::ScheduledSet.new.clear
yield
end
end
end
|
Set instance before calling Runtime initializer | require 'pathname'
module Rohbau
class Runtime
class << self
attr_reader :instance
def start
@instance = new
end
def running?
!!@instance
end
def terminate
@instance.terminate
@instance = nil
end
end
def self.register(name, plugin_class)
attr_reader name
plugins[name] = plugin_class
end
def self.delete(name)
plugins.delete(name)
end
def self.plugins
@plugins ||= {}
end
def initialize
on_boot
initialize_plugins
end
def terminate
# noop
end
def root
Pathname.new(Dir.pwd)
end
protected
def on_boot
# noop
end
def initialize_plugins
self.class.plugins.each do |name, plugin_class|
instance_variable_set :"@#{name}", plugin_class.new(self)
end
end
end
end
| require 'pathname'
module Rohbau
class Runtime
class << self
attr_reader :instance
def start
set_instance = proc do |instance|
@instance = instance
end
self.send :define_method, :initialize do |*args|
set_instance.call(self)
super(*args)
end
new
end
def running?
!!@instance
end
def terminate
@instance.terminate
@instance = nil
end
end
def self.register(name, plugin_class)
attr_reader name
plugins[name] = plugin_class
end
def self.delete(name)
plugins.delete(name)
end
def self.plugins
@plugins ||= {}
end
def initialize
on_boot
initialize_plugins
end
def terminate
# noop
end
def root
Pathname.new(Dir.pwd)
end
protected
def on_boot
# noop
end
def initialize_plugins
self.class.plugins.each do |name, plugin_class|
instance_variable_set :"@#{name}", plugin_class.new
end
end
end
end
|
Update PT sans to sha256 checksums | class FontPtSans < Cask
url 'http://www.fontstock.com/public/PTSans.zip'
homepage 'http://www.paratype.com/public/'
version '2.004'
sha1 '3e14c921c2c9eb524ad5680eff931d1d5cbca00a'
font 'PTC55F.ttf'
font 'PTC75F.ttf'
font 'PTN57F.ttf'
font 'PTN77F.ttf'
font 'PTS55F.ttf'
font 'PTS56F.ttf'
font 'PTS75F.ttf'
font 'PTS76F.ttf'
end
| class FontPtSans < Cask
url 'http://www.fontstock.com/public/PTSans.zip'
homepage 'http://www.paratype.com/public/'
version '2.004'
sha256 'c70b683ab35d28cc65367f6b9ef5f04d6d83b1217f2e727648bbaeb12dc140e7'
font 'PTC55F.ttf'
font 'PTC75F.ttf'
font 'PTN57F.ttf'
font 'PTN77F.ttf'
font 'PTS55F.ttf'
font 'PTS56F.ttf'
font 'PTS75F.ttf'
font 'PTS76F.ttf'
end
|
Make rubocop happy with my work | module SitePrism
module ElementChecker
def all_there?
Capybara.using_wait_time(0) do
expected_elements.all? { |element| send "has_#{element}?" }
end
end
private
def expected_elements
elements = self.class.mapped_items
if self.respond_to?(:excluded_elements)
elements = elements.select {|el| !self.excluded_elements.include? el}
end
elements
end
end
end
| module SitePrism
module ElementChecker
def all_there?
Capybara.using_wait_time(0) do
expected_elements.all? { |element| send "has_#{element}?" }
end
end
private
def expected_elements
elements = self.class.mapped_items
if self.respond_to?(:excluded_elements)
elements = elements.select { |el| !excluded_elements.include? el }
end
elements
end
end
end
|
Refactor method for setting metadata | class Genomer::OutputType::Genbank < Genomer::OutputType
SUFFIX = 'gb'
def generate
build = Bio::Sequence.new(sequence)
build.entry_id = @rules.identifier if @rules.identifier
build.definition = @rules.description if @rules.description
build.output(:genbank)
end
end
| class Genomer::OutputType::Genbank < Genomer::OutputType
SUFFIX = 'gb'
METADATA_MAP = {
:entry_id => :identifier,
:definition => :description
}
def generate
build = Bio::Sequence.new(sequence)
METADATA_MAP.each do |a,b|
value = @rules.send(b)
build.send(a.to_s + '=',value) unless value.nil?
end
build.output(:genbank)
end
end
|
Simplify and make private CommentEnumerator methods | module Unparser
class CommentEnumerator
def initialize(comments)
@comments = comments.dup
end
attr_writer :last_source_range_written
def take_eol_comments
return [] if @last_source_range_written.nil?
comments = take_up_to_line @last_source_range_written.end.line
doc_comments, eol_comments = comments.partition(&:document?)
doc_comments.reverse.each {|comment| @comments.unshift comment }
eol_comments
end
def take_while
array = []
until @comments.empty?
bool = yield @comments.first
break unless bool
array << @comments.shift
end
array
end
def take_all
take_while { true }
end
def take_before(position)
take_while { |comment| comment.location.expression.end_pos <= position }
end
def take_up_to_line(line)
take_while { |comment| comment.location.expression.line <= line }
end
end
end | module Unparser
class CommentEnumerator
def initialize(comments)
@comments = comments.dup
end
attr_writer :last_source_range_written
def take_eol_comments
return [] if @last_source_range_written.nil?
comments = take_up_to_line @last_source_range_written.end.line
doc_comments, eol_comments = comments.partition(&:document?)
doc_comments.reverse.each {|comment| @comments.unshift comment }
eol_comments
end
def take_all
take_while { true }
end
def take_before(position)
take_while { |comment| comment.location.expression.end_pos <= position }
end
private
def take_while
number_to_take = @comments.index {|comment| !yield(comment) } || @comments.size
@comments.shift(number_to_take)
end
def take_up_to_line(line)
take_while { |comment| comment.location.expression.line <= line }
end
end
end |
Fix for Transaction model (conversion to BigDecimal) | module Coinmate::Model
class Transaction < Base
DEBIT_TRANSACTION_TYPES = %w(SELL QUICK_SELL WITHDRAWAL CREATE_VOUCHER DEBIT)
attr_accessor :transaction_id, :timestamp, :transaction_type,
:amount, :amount_currency,
:price, :price_currency,
:fee, :fee_currency,
:description, :status, :order_id, :currency_pair
def initialize(attributes = {})
super
self.timestamp = Time.at(timestamp / 1000.0)
self.price = BigDecimal.new(price, 8)
self.amount = BigDecimal.new(amount, 12)
self.fee = BigDecimal.new(fee, 12) if fee
if DEBIT_TRANSACTION_TYPES.include?(transaction_type)
self.amount *= -1
end
end
def fiat_amount
if price
(price * amount).round(2)
else
raise Coinmate::Error.new("Cannot get fiat_amount for #{transaction_type}")
end
end
def to_hash
@raw
end
end
end | module Coinmate::Model
class Transaction < Base
DEBIT_TRANSACTION_TYPES = %w(SELL QUICK_SELL WITHDRAWAL CREATE_VOUCHER DEBIT)
attr_accessor :transaction_id, :timestamp, :transaction_type,
:amount, :amount_currency,
:price, :price_currency,
:fee, :fee_currency,
:description, :status, :order_id, :currency_pair
def initialize(attributes = {})
super
self.timestamp = Time.at(timestamp / 1000.0)
self.price = BigDecimal.new(price, 8) if price
self.amount = BigDecimal.new(amount, 12) if amount
self.fee = BigDecimal.new(fee, 12) if fee
if DEBIT_TRANSACTION_TYPES.include?(transaction_type)
self.amount *= -1
end
end
def fiat_amount
if price
(price * amount).round(2)
else
raise Coinmate::Error.new("Cannot get fiat_amount for #{transaction_type}")
end
end
def to_hash
@raw
end
end
end |
Fix public/views folder location problem | require "sinatra"
class Hash
def require(keys)
Hash[keys.uniq.map { |k| [k, self[k] ] }]
end
end
require_relative "texting"
require_relative "websockets"
require_relative "settings"
require_relative "auth"
set :static, true # serve assets from public/
get "/" do
erb :index
end
| require "sinatra"
class Hash
def require(keys)
Hash[keys.uniq.map { |k| [k, self[k] ] }]
end
end
require_relative "texting"
require_relative "websockets"
require_relative "settings"
require_relative "auth"
set :public_folder, File.join(File.dirname(__FILE__), "..", "public")
set :views, File.join(File.dirname(__FILE__), "..", "views")
get "/" do
erb :index
end
|
Add rake task to clean multiple answer parts | namespace :clean do
task :answer_parts, [:questionnaire_id, :question_id] => :environment do |t, args|
questionnaire = Questionnaire.find(args.questionnaire_id)
where_question = args.question_id ? "AND answers.question_id = #{args.question_id}" : ''
sql = <<-SQL
SELECT answers.id
FROM answers
INNER JOIN answer_parts ap ON ap.answer_id = answers.id
RIGHT OUTER JOIN questions q ON answers.question_id = q.id
WHERE ap.field_type_type = 'MultiAnswerOption' #{where_question}
GROUP BY answers.id
HAVING COUNT(answers.id) > 1
SQL
answers = Answer.find_by_sql(sql)
cleaned_answer_ids = []
puts "Nothing to clean!" unless answers.present?
answers.each do |answer|
aps = answer.answer_parts
most_recent = aps.order("updated_at DESC").first.id
puts "Most recent answer_part:\n"
puts "AnswerPart ID: #{most_recent}\n"
puts "Answer ID: #{answer.id}\n\n"
old_answer_parts = aps.where("id <> ?", most_recent)
cleaned_answer_ids << old_answer_parts.map(&:answer_id)
old_answer_parts.destroy_all
puts "Other answer_parts destroyed!"
puts "====================\n"
end
if cleaned_answer_ids.present?
puts "List of cleaned answers:\n"
puts cleaned_answer_ids.join("\n")
end
end
end
| |
Change to sync time reading for regular time | # frozen_string_literal: true
module Benchmark
module Perf
# Clock that represents monotonic time
module Clock
# Microseconds per second
MICROSECONDS_PER_SECOND = 1_000_000
# Microseconds per 100ms
MICROSECONDS_PER_100MS = 100_000
class_definition = Class.new do
def initialize
super()
@last_time = Time.now.to_f
end
if defined?(Process::CLOCK_MONOTONIC)
# @api private
def now
Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
else
# @api private
def now
current = Time.now.to_f
if @last_time < current
@last_time = current
else # clock moved back in time
@last_time += 0.000_001
end
end
end
end
MONOTONIC_CLOCK = class_definition.new
private_constant :MONOTONIC_CLOCK
# Current monotonic time
#
# @return [Float]
#
# @api public
def now
MONOTONIC_CLOCK.now
end
module_function :now
# Measure time elapsed with a monotonic clock
#
# @return [Float]
#
# @public
def measure
before = now
yield
after = now
after - before
end
module_function :measure
end # Clock
end # Perf
end # Benchmark
| # frozen_string_literal: true
module Benchmark
module Perf
# Clock that represents monotonic time
module Clock
# Microseconds per second
MICROSECONDS_PER_SECOND = 1_000_000
# Microseconds per 100ms
MICROSECONDS_PER_100MS = 100_000
class_definition = Class.new do
def initialize
super()
@last_time = Time.now.to_f
@lock = Mutex.new
end
if defined?(Process::CLOCK_MONOTONIC)
# @api private
def now
Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
else
# @api private
def now
@lock.synchronize do
current = Time.now.to_f
if @last_time < current
@last_time = current
else # clock moved back in time
@last_time += 0.000_001
end
end
end
end
end
MONOTONIC_CLOCK = class_definition.new
private_constant :MONOTONIC_CLOCK
# Current monotonic time
#
# @return [Float]
#
# @api public
def now
MONOTONIC_CLOCK.now
end
module_function :now
# Measure time elapsed with a monotonic clock
#
# @return [Float]
#
# @public
def measure
before = now
yield
after = now
after - before
end
module_function :measure
end # Clock
end # Perf
end # Benchmark
|
Add some meta test plan examples | $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'ruby-jmeter'
class Test
def initialize options = {}
@users = options[:users]
@ramp = options[:ramp]
@duration = options[:duration]
@region = options[:region] || 'ap-southeast-2'
@name = options[:name]
end
def flood domain
@domain = domain
test_plan.grid ENV['FLOOD_IO_KEY'], region: @region, name: @name
end
def jmeter domain
@domain = domain
test_plan.run path: '/usr/share/jmeter/bin/', gui:true
end
def test_plan
test do
grab_dsl self
defaults domain: @domain,
protocol: 'http',
image_parser: true,
concurrentDwn: true,
concurrentPool: 4
cookies
plan
end
end
def plan
threads @users, {ramp_time: @ramp, duration: @duration, scheduler: true, continue_forever: true} do
random_timer 5000, 10000
transaction '01_GET_home_page' do
visit '/'
end
end
end
def grab_dsl dsl
@dsl = dsl
end
def method_missing method, *args, &block
@dsl.__send__ method, *args, &block
end
end
test = Test.new users:10, ramp: 30, duration: 30, name: 'Test Number 1'
# test locally with JMeter
test.jmeter 'google.com'
# test distributed with flood
# test.flood 'google.com' | |
Change Railties and ActionPack dependency versions | require File.expand_path('../lib/twitter_bootstrap_form_for/version', __FILE__)
Gem::Specification.new do |s|
s.name = 'twitter_bootstrap_form_for'
s.version = TwitterBootstrapFormFor::VERSION
s.platform = Gem::Platform::RUBY
s.authors = [ 'Stephen Touset' ]
s.email = [ 'stephen@touset.org' ]
s.homepage = 'http://github.com/stouset/twitter_bootstrap_form_for'
s.summary = 'Rails form builder optimized for Twitter Bootstrap'
s.description = 'A custom Rails FormBuilder that assumes the use of Twitter Bootstrap'
s.files = `git ls-files`.split("\n")
s.executables = `git ls-files`.split("\n").map {|f| f =~ /^bin\/(.*)/ ? $1 : nil }.compact
s.require_path = 'lib'
s.add_dependency 'railties', '~> 3'
s.add_dependency 'actionpack', '~> 3'
end
| require File.expand_path('../lib/twitter_bootstrap_form_for/version', __FILE__)
Gem::Specification.new do |s|
s.name = 'twitter_bootstrap_form_for'
s.version = TwitterBootstrapFormFor::VERSION
s.platform = Gem::Platform::RUBY
s.authors = [ 'Stephen Touset' ]
s.email = [ 'stephen@touset.org' ]
s.homepage = 'http://github.com/stouset/twitter_bootstrap_form_for'
s.summary = 'Rails form builder optimized for Twitter Bootstrap'
s.description = 'A custom Rails FormBuilder that assumes the use of Twitter Bootstrap'
s.files = `git ls-files`.split("\n")
s.executables = `git ls-files`.split("\n").map {|f| f =~ /^bin\/(.*)/ ? $1 : nil }.compact
s.require_path = 'lib'
s.add_dependency 'railties', '~> 4'
s.add_dependency 'actionpack', '~> 4'
end
|
Add license to CVE model | class CVE < ActiveRecord::Base
has_many :references, :class_name => "CVEReference"
has_many :comments, :class_name => "CVEComment"
end
| # ===GLSAMaker v2
# Copyright (C) 2010 Alex Legler <a3li@gentoo.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# For more information, see the LICENSE file.
class CVE < ActiveRecord::Base
has_many :references, :class_name => "CVEReference"
has_many :comments, :class_name => "CVEComment"
has_and_belongs_to_many :cpes, :class_name => "CPE"
end
|
Add min/max per page to the example | class PostSearch
include SearchObject.module(:model, :sorting, :will_paginate)
scope { Post.all }
sort_by :created_at, :views_count, :likes_count, :comments_count
per_page 15
option :user_id
option :category_name
option :title do |scope, value|
scope.where 'title LIKE ?', escape_search_term(value)
end
option :published do |scope, value|
scope.where published: true if value.present?
end
option :term do |scope, value|
scope.where 'title LIKE :term OR body LIKE :term', term: escape_search_term(value)
end
option :created_after do |scope, value|
date = parse_date value
scope.where('DATE(created_at) >= ?', date) if date.present?
end
option :created_before do |scope, value|
date = parse_date value
scope.where('DATE(created_at) <= ?', date) if date.present?
end
private
def parse_date(date)
Date.strptime(date, '%Y-%m-%d') rescue nil
end
def escape_search_term(term)
"%#{term.gsub(/\s+/, '%')}%"
end
end
| class PostSearch
include SearchObject.module(:model, :sorting, :will_paginate)
scope { Post.all }
sort_by :created_at, :views_count, :likes_count, :comments_count
per_page 15
min_per_page 10
max_per_page 100
option :user_id
option :category_name
option :title do |scope, value|
scope.where 'title LIKE ?', escape_search_term(value)
end
option :published do |scope, value|
scope.where published: true if value.present?
end
option :term do |scope, value|
scope.where 'title LIKE :term OR body LIKE :term', term: escape_search_term(value)
end
option :created_after do |scope, value|
date = parse_date value
scope.where('DATE(created_at) >= ?', date) if date.present?
end
option :created_before do |scope, value|
date = parse_date value
scope.where('DATE(created_at) <= ?', date) if date.present?
end
private
def parse_date(date)
Date.strptime(date, '%Y-%m-%d') rescue nil
end
def escape_search_term(term)
"%#{term.gsub(/\s+/, '%')}%"
end
end
|
Fix FormalityLevelSerializer using wrong url. | class FormalityLevelSerializer < ApplicationSerializer
class Reference < ApplicationSerializer
attributes :iri
attributes :name
def iri
urls.license_model_url(object, host: Settings.hostname)
end
end
attributes :iri
attributes :name, :description
def iri
Reference.new(object).iri
end
end
| class FormalityLevelSerializer < ApplicationSerializer
class Reference < ApplicationSerializer
attributes :iri
attributes :name
def iri
urls.formality_level_url(object, host: Settings.hostname)
end
end
attributes :iri
attributes :name, :description
def iri
Reference.new(object).iri
end
end
|
Fix Tags name searching syntax | class Tag < ActiveRecord::Base
has_and_belongs_to_many :ideas,
-> { order('rating') },
join_table: "idea_tags"
validates :name, presence: true, uniqueness: {case_sensitive: false}
include PgSearch
pg_search_scope :search_name, against: [:name]
def self.from_string(tag_names)
tags = []
tag_names.first.strip.downcase.gsub(/ +/, '').split(/,/).each do |tag_name|
tags.push(find_or_create_by(name: tag_name)) if !tag_name.blank?
end
tags
end
end
| class Tag < ActiveRecord::Base
has_and_belongs_to_many :ideas,
-> { order('rating') },
join_table: "idea_tags"
validates :name, presence: true, uniqueness: {case_sensitive: false}
include PgSearch
pg_search_scope :search_name, :against => :name
def self.from_string(tag_names)
tags = []
tag_names.first.strip.downcase.gsub(/ +/, '').split(/,/).each do |tag_name|
tags.push(find_or_create_by(name: tag_name)) if !tag_name.blank?
end
tags
end
end
|
Order uses body instead of query | module CrowdFlower
class Order
include Defaults
attr_reader :job
def initialize(job)
@job = job
Order.base_uri CrowdFlower.with_domain("/jobs/#{@job.id}/orders")
Order.default_params CrowdFlower.key
end
def debit(percentage = 100, channels = ["amt"])
Order.post("", {:query => {:percentage => percentage, :channels => channels}})
end
end
end | module CrowdFlower
class Order
include Defaults
attr_reader :job
def initialize(job)
@job = job
Order.base_uri CrowdFlower.with_domain("/jobs/#{@job.id}/orders")
Order.default_params CrowdFlower.key
end
def debit(percentage = 100, channels = ["amt"])
Order.post("", {:body => {:percentage => percentage, :channels => channels}})
end
end
end |
Fix the DSL name for rds_event_subscription | require_relative '../resource'
module Convection
module Model
class Template
class Resource
##
# AWS::RDS::EventSubscription
##
class RDSEventSubscription < Resource
type 'AWS::RDS::EventSubscription', :rds_instance
property :enabled, 'Enabled'
property :event_category, 'EventCategories', :type => :list
property :sns_topic_arn, 'SnsTopicArn'
property :source_id, 'SourceIds', :type => :list
property :source_type, 'SourceType'
end
end
end
end
end
| require_relative '../resource'
module Convection
module Model
class Template
class Resource
# @example
# rds_event_subscription 'myEventSubscription' do
# event_category 'configuration change'
# event_category 'failure'
# event_category 'deletion'
# sns_topic_arn 'arn:aws:sns:us-west-2:123456789012:example-topic'
# source_id 'db-instance-1'
# source_id fn_ref('myDBInstance')
# source_type 'db-instance'
# enabled false
# end
class RDSEventSubscription < Resource
type 'AWS::RDS::EventSubscription'
property :enabled, 'Enabled'
property :event_category, 'EventCategories', :type => :list
property :sns_topic_arn, 'SnsTopicArn'
property :source_id, 'SourceIds', :type => :list
property :source_type, 'SourceType'
end
end
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.