Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Allow any parameters to be specified via an env.variable for hr:sync rake task.
namespace :hr do desc 'Synchronizes all attributes locally cached by has_remote' task :sync => :environment do models = ENV['MODELS'].nil? ? HasRemote.models : extract_models options = {} options[:limit] = ENV['LIMIT'] if ENV['LIMIT'] options[:since] = ENV['SINCE'] if ENV['SINCE'] models.each{...
namespace :hr do desc 'Synchronizes all attributes locally cached by has_remote' task :sync => :environment do models = ENV['MODELS'].nil? ? HasRemote.models : extract_models options = ENV['PARAMS'] ? Rack::Utils.parse_query(ENV['PARAMS']) : {} models.each{|model| model.synchronize!(options)} end ...
Change expectations to match reality
require 'parslet' module Rip::Compiler class AST < Parslet::Transform attr_reader :origin def initialize(origin) @origin = origin end protected def location_for(slice) slice.line_and_column end end end
require 'parslet' module Rip::Compiler class AST < Parslet::Transform attr_reader :origin def initialize(origin = nil, &block) @origin = origin super(&block) end def apply(tree, context = nil) _context = context ? context : {} super(tree, _context.merge(:origin => origin)) ...
Add asset precompilation for all assets
require "backbone-rails" require "bootstrap-sass-rails" require "ejs" require "font-awesome-rails" require "geocens-js-api-rails" require "haml" require "jquery-rails" module Workbench class Engine < ::Rails::Engine isolate_namespace Workbench end end
require "backbone-rails" require "bootstrap-sass-rails" require "ejs" require "font-awesome-rails" require "geocens-js-api-rails" require "haml" require "jquery-rails" module Workbench class Engine < ::Rails::Engine isolate_namespace Workbench initializer :assets do |config| Rails.application.config.a...
Add a method for checking if an expression is empty
require 'irb/ruby-lex' require 'stringio' module Temple module Utils extend self LITERAL_TOKENS = [RubyToken::TkSTRING, RubyToken::TkDSTRING] def literal_string?(str) lexer = RubyLex.new lexer.set_input(StringIO.new(str.strip)) # The first token has to be a string. ...
require 'irb/ruby-lex' require 'stringio' module Temple module Utils extend self LITERAL_TOKENS = [RubyToken::TkSTRING, RubyToken::TkDSTRING] def literal_string?(str) lexer = RubyLex.new lexer.set_input(StringIO.new(str.strip)) # The first token has to be a string. ...
Add code wars (7) - which triangle is that?
# http://www.codewars.com/kata/564d398e2ecf66cec00000a9 # --- iteration 1 --- def type_of_triangle(a, b, c) return "Not a valid triangle" unless [a, b, c].all? { |x| x.is_a? Integer } return "Not a valid triangle" unless (a + b) > c && (a + c) > b && (b + c) > a return "Equilateral" if a == b && b == c return "...
Disable the Router API client during Cucumber
require 'gds_api/router' # We never have to go to the Router during Feature tests. Disable. GdsApi::Router.any_instance.stubs(:add_route).returns true GdsApi::Router.any_instance.stubs(:delete_route).returns true
Add WebCT wording to new Import Content page
# CANVAS-240 Add WebCT wording to new Import Content page # This overrides Canvas' own course_copy_importer in /lib/canvas/plugins/default_plugins.rb Rails.configuration.to_prepare do require_dependency 'canvas/migration/worker/course_copy_worker' Canvas::Plugin.register 'course_copy_importer', :export_system, { ...
Remove newlines from start of logs
require 'active_support/log_subscriber' module ActionMailer # Implements the ActiveSupport::LogSubscriber for logging notifications when # email is delivered or received. class LogSubscriber < ActiveSupport::LogSubscriber # An email was delivered. def deliver(event) info do recipients = Arr...
require 'active_support/log_subscriber' module ActionMailer # Implements the ActiveSupport::LogSubscriber for logging notifications when # email is delivered or received. class LogSubscriber < ActiveSupport::LogSubscriber # An email was delivered. def deliver(event) info do recipients = Arr...
Update homebrew cask for v2.1.0
cask 'awsaml' do version '2.0.0' sha256 'cea42994cb52a71b8f811c38b25281604360b8216889e0f3217d4583cd7ead1a' url "https://github.com/rapid7/awsaml/releases/download/v#{version}/awsaml-v#{version}-darwin-x64.zip" appcast 'https://github.com/rapid7/awsaml/releases.atom', checkpoint: '786054d12bd083162881...
cask 'awsaml' do version '2.1.0' sha256 '187f13a51cb28546fc04f127827e21b5d9c8515db577a3f5f463ac91648e512f' url "https://github.com/rapid7/awsaml/releases/download/v#{version}/awsaml-v#{version}-darwin-x64.zip" appcast 'https://github.com/rapid7/awsaml/releases.atom', checkpoint: '600ea5739ae752442c89...
Set Jenkins to the latest LTS version
default['jenkins']['master']['version'] = '1.619-1.1' default['jenkins']['master']['jvm_options'] = '-Xms256m -Xmx256m' default['jenkins']['master']['listen_address'] = '127.0.0.1'
default['jenkins']['master']['version'] = '1.642-1.1' # LTS default['jenkins']['master']['jvm_options'] = '-Xms256m -Xmx256m' default['jenkins']['master']['listen_address'] = '127.0.0.1'
Add file for exporting stats
module Carto module Export class MapStatistics FILE_MODE = :file STDOUT_MODE = :stdout VALID_MODES = [FILE_MODE, STDOUT_MODE].freeze def initialize(mode: :file, path: nil, types: ['derived']) assert_valid_mode(mode) @mode = mode @path = path || "/tmp/map_statistics...
Add datatype for strings with embedded language
class Chalmersit::StringWithLang attr_accessor :lang, :value def initialize(string) @lang, @value = string.split(';', 2) end def self.create(la, string) self.new("#{la};#{string}") end %w(sv en).each do |l| define_singleton_method "create_#{l}" do |str| self.create(l, str) end en...
Change the initial question example to include a tiny bit of markdown
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel...
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel...
Implement RTA API Integration service.
class RtaApiService def get_wo_trans(query) uri = URI("https://api.rtafleet.com/graphql") unless check_api_key return {success: false, response: "API key not found."} end token = JSON.parse(get_token.body)["access_token"] headers = { 'Content-Type': 'application/json', 'Au...
Use :belongs_to instead of :references in :order_cycles_shipping_methods
class CreateOrderCycleShippingMethods < ActiveRecord::Migration[6.1] def up create_table :order_cycles_shipping_methods, id: false do |t| t.references :order_cycle t.references :shipping_method, foreign_key: { to_table: :spree_shipping_methods } end add_index :order_cycles_shipping_methods, ...
class CreateOrderCyclesShippingMethods < ActiveRecord::Migration[6.1] def up create_table :order_cycles_shipping_methods, id: false do |t| t.belongs_to :order_cycle t.belongs_to :shipping_method, foreign_key: { to_table: :spree_shipping_methods } t.index [:order_cycle_id, :shipping_method_id], ...
Add hashie as development dependency
$LOAD_PATH.unshift 'lib' Gem::Specification.new do |s| s.name = 'git-review' s.version = '1.1.7' s.date = Time.now.strftime('%F') s.summary = 'facilitates GitHub code reviews' s.homepage = 'http://github.com/b4mboo/git-review' s.email = 'bamberger.dominik@gmail.com' s.authors = ['Dominik Ba...
$LOAD_PATH.unshift 'lib' Gem::Specification.new do |s| s.name = 'git-review' s.version = '1.1.7' s.date = Time.now.strftime('%F') s.summary = 'facilitates GitHub code reviews' s.homepage = 'http://github.com/b4mboo/git-review' s.email = 'bamberger.dominik@gmail.com' s.authors = ['Dominik Ba...
Set fixture paths for unit tests
require 'puppetlabs_spec_helper/module_spec_helper' require 'shared_examples' require 'puppet-openstack_spec_helper/facts' RSpec.configure do |c| c.alias_it_should_behave_like_to :it_configures, 'configures' c.alias_it_should_behave_like_to :it_raises, 'raises' end at_exit { RSpec::Puppet::Coverage.report! }
require 'puppetlabs_spec_helper/module_spec_helper' require 'shared_examples' require 'puppet-openstack_spec_helper/facts' fixture_path = File.expand_path(File.join(File.dirname(__FILE__), 'fixtures')) RSpec.configure do |c| c.alias_it_should_behave_like_to :it_configures, 'configures' c.alias_it_should_behave_li...
Remove obsolete RSpec config option
# coding: utf-8 RSpec.configure do |config| config.expect_with :rspec do |c| c.syntax = :expect end config.mock_with :rspec do |c| c.syntax = :expect end config.color = true config.treat_symbols_as_metadata_keys_with_true_values = true end require 'simplecov' if ENV['TRAVIS'] require 'coveral...
# coding: utf-8 RSpec.configure do |config| config.expect_with :rspec do |c| c.syntax = :expect end config.mock_with :rspec do |c| c.syntax = :expect end config.color = true end require 'simplecov' if ENV['TRAVIS'] require 'coveralls' SimpleCov.formatter = Coveralls::SimpleCov::Formatter elsi...
Add podspec file for iOS framework sourced from S3
Pod::Spec.new do |s| s.name = 'Tangram-es' s.version = '0.7.1' s.summary = 'Open source C++ library for rendering 2D and 3D maps from vector data using OpenGL ES.' s.description = 'Open source C++ library for rendering 2D and 3D maps from vector data using OpenGL ES, wrapped with native Coc...
Update gem's summary and description
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'dartsduino/games/x01/version' Gem::Specification.new do |spec| spec.name = "dartsduino-games-x01" spec.version = Dartsduino::Games::X01::VERSION spec.authors = ["Ikuo T...
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'dartsduino/games/x01/version' Gem::Specification.new do |spec| spec.name = "dartsduino-games-x01" spec.version = Dartsduino::Games::X01::VERSION spec.authors = ["Ikuo T...
Add integration test for middleware
require 'rails_helper' RSpec.describe 'Integration Test', :type => :request do let(:url) { '/posts/1234?categoryFilter[categoryName][]=food' } let(:headers) do { "CONTENT_TYPE" => "application/json", 'X-Key-Inflection' => 'camel' } end let(:params) do { 'post' => { 'authorName' => 'John Smith' } } en...
Add redis set for managing recursive project score calcualtion batches
class ProjectScoreCalculationBatch def initialize(platform, project_ids) @platform = platform @project_ids = project_ids @updated_projects = [] @dependent_project_ids = [] @maximums = ProjectScoreCalculator.maximums(@platform) end def process projects_scope.find_each do |project| sc...
class ProjectScoreCalculationBatch def self.run(platform, limit = 5000) # pull project ids from start of redis sorted set key = queue_key(platform) project_ids = REDIS.multi do REDIS.zrange key, 0, limit-1 REDIS.zremrangebyrank key, 0, limit-1 end.first # process batch = ProjectSc...
Use actual secure gravatar URL
module ApplicationHelper def gravatar_image_tag(email, size = 16) hash = Digest::MD5.hexdigest(email.strip.downcase) image_tag "https://www.gravatar.com/avatar/#{hash}?s=#{size}&d=identicon", :size => "#{size}x#{size}" end end
module ApplicationHelper def gravatar_image_tag(email, size = 16) hash = Digest::MD5.hexdigest(email.strip.downcase) image_tag "https://secure.gravatar.com/avatar/#{hash}?s=#{size}&d=identicon", :size => "#{size}x#{size}" end end
Make navigation highlighting method more dumb
module ApplicationHelper def requirejs_base_url folder_name(requirejs_main_path) end def requirejs_main_path if Rails.application.assets.find_asset("production.js").present? asset_path("production.js") else asset_path("main.js") end end def requirejs_module_path(asset) trim_...
module ApplicationHelper def requirejs_base_url folder_name(requirejs_main_path) end def requirejs_main_path if Rails.application.assets.find_asset("production.js").present? asset_path("production.js") else asset_path("main.js") end end def requirejs_module_path(asset) trim_...
Support for Ruby 1.8.7 failing due new Hash syntax
if defined?(Delayed) require 'delayed_job' module Delayed module Plugins class Raven < ::Delayed::Plugin callbacks do |lifecycle| lifecycle.around(:invoke_job) do |job, *args, &block| begin # Forward the call to the next callback in the callback chain ...
if defined?(Delayed) require 'delayed_job' module Delayed module Plugins class Raven < ::Delayed::Plugin callbacks do |lifecycle| lifecycle.around(:invoke_job) do |job, *args, &block| begin # Forward the call to the next callback in the callback chain ...
Update rubocop requirement from ~> 0.56.0 to ~> 0.57.2
# frozen_string_literal: true require File.expand_path("lib/active_record/safer_migrations/version", __dir__) Gem::Specification.new do |gem| gem.name = "activerecord-safer_migrations" gem.version = ActiveRecord::SaferMigrations::VERSION gem.summary = "ActiveRecord migration helpers to avoi...
# frozen_string_literal: true require File.expand_path("lib/active_record/safer_migrations/version", __dir__) Gem::Specification.new do |gem| gem.name = "activerecord-safer_migrations" gem.version = ActiveRecord::SaferMigrations::VERSION gem.summary = "ActiveRecord migration helpers to avoi...
Add Selling Agreement API points
module FundAmerica class SellingAgreement class << self # End point: https://apps.fundamerica.com/api/selling_agreements (POST) # Usage: FundAmerica::SellingAgreement.create(options) # Output: Creates a new rta_agreement def create(options) API::request(:post, 'selling_agreements'...
module FundAmerica class SellingAgreement class << self # End point: https://apps.fundamerica.com/api/selling_agreements (POST) # Usage: FundAmerica::SellingAgreement.create(options) # Output: Creates a new rta_agreement def create(options) API::request(:post, 'selling_agreements'...
Fix blank is included in filepath
#!ruby -Ks # encoding: utf-8 require 'win32ole' require 'fileutils' # This class converts visio file into pdf file. class Visio2Pdf VSDEXTS = '.vsd' PDFEXTS = '.pdf' @visio = nil @in_dir = nil @vsd_fullpath = nil @pdf_fullpath = nil def visio2pdf_controller if ARGV.length == 2 @in_dir, @_out_d...
#!ruby -Ks # encoding: utf-8 require 'win32ole' require 'fileutils' # This class converts visio file into pdf file. class Visio2Pdf VSDEXTS = '.vsd' PDFEXTS = '.pdf' @visio = nil @in_dir = nil @vsd_fullpath = nil @pdf_fullpath = nil def visio2pdf_controller if ARGV.length == 2 @in_dir, @_out_d...
Fix homepage to use SSL in OmniGraffle Cask
cask :v1 => 'omnigraffle' do if MacOS.release <= :snow_leopard version '5.4.4' sha256 '7bcc64093f46bd4808b1a4cb86cf90c0380a5c5ffffd55ce8f742712818558df' url "http://www.omnigroup.com/ftp1/pub/software/MacOSX/10.6/OmniGraffle-#{version}.dmg" elsif MacOS.release <= :mavericks version '6.0.5' sha25...
cask :v1 => 'omnigraffle' do if MacOS.release <= :snow_leopard version '5.4.4' sha256 '7bcc64093f46bd4808b1a4cb86cf90c0380a5c5ffffd55ce8f742712818558df' url "http://www.omnigroup.com/ftp1/pub/software/MacOSX/10.6/OmniGraffle-#{version}.dmg" elsif MacOS.release <= :mavericks version '6.0.5' sha25...
Add global error handler for unexpected exceptions
module API module V1 # Default options for all API endpoints and versions module Defaults extend ActiveSupport::Concern included do # Common Grape settings version 'v1', using: :accept_version_header format :json prefix :api # Global handler for simple not...
module API module V1 # Default options for all API endpoints and versions module Defaults extend ActiveSupport::Concern included do # Common Grape settings version 'v1', using: :accept_version_header format :json prefix :api # Global handler for simple not...
Support updating from multiple repositories.
#!/usr/bin/ruby require 'optparse' require 'sqlite3' require 'apt' options = { :config => 'testrepo.txt', :database => 'test.db' } OptionParser.new do |opts| opts.banner = "Usage: #{$0} [options]" opts.on('-c', '--config [PATH]', 'Config file') do |v| options[:config] = v end opts.on('-d', '--database [PATH]...
#!/usr/bin/ruby require 'optparse' require 'sqlite3' require 'apt' options = { :config => 'testrepo.txt', :database => 'test.db' } OptionParser.new do |opts| opts.banner = "Usage: #{$0} [options]" opts.on('-c', '--config [PATH]', 'Config file') do |v| options[:config] = v end opts.on('-d', '--database [PATH]...
Downgrade Ruby version requirement to >= 2.0.0
Gem::Specification.new do |s| s.name = 'thailang4r' s.version = '0.1.0' s.authors = ['Vee Satayamas'] s.email = ['5ssgdxltv@relay.firefox.com'] s.description = "Thai language tools for Ruby, i.e. a word tokenizer, a character level indentifier, and a romanization tool" s.homepage = "https://github.com/veer6...
Gem::Specification.new do |s| s.name = 'thailang4r' s.version = '0.1.0' s.authors = ['Vee Satayamas'] s.email = ['5ssgdxltv@relay.firefox.com'] s.description = "Thai language tools for Ruby, i.e. a word tokenizer, a character level indentifier, and a romanization tool" s.homepage = "https://github.com/veer6...
Exclude hidden field from check_box
require 'bootstrap_form' module BootstrapValidatorRails class FormBuilder < BootstrapForm::FormBuilder def initialize(object_name, object, template, options) @attributes = BootstrapValidatorRails::Validators::Attributes.new(object) super end FIELD_HELPERS.each do |method_name| define_m...
require 'bootstrap_form' module BootstrapValidatorRails class FormBuilder < BootstrapForm::FormBuilder def initialize(object_name, object, template, options) @attributes = BootstrapValidatorRails::Validators::Attributes.new(object) super end FIELD_HELPERS.each do |method_name| define_m...
Add url parameter to parse_feed method
require 'uri' require 'rss' require 'time' module EndiFeed # This module contains various useful functions. module Util def self.included(base) base.extend self end module_function # Fetches and parses RSS feed # @return [RSS] parsed XML feed or nil def parse_feed open('http:/...
# encoding: utf-8 require 'uri' require 'rss' require 'time' module EndiFeed # This module contains various useful functions. module Util def self.included(base) base.extend self end module_function # Fetches and parses RSS feed # @param [String] url to parse # @return [RSS] parsed ...
Write a test to make sure that the last child of an ExpansionBlock knows its an arg if the ExpansionBlock is expected to return.
require 'minitest/autorun' require_relative '../../lib/tritium/parser/macro_expander' class MacroTest < MiniTest::Unit::TestCase include Tritium::Parser def setup @expander = MacroExpander.new end def test_positionals macro = @expander.macros[[:insert_top, 1]] assert_equal %|insert_at("top", ...
require 'minitest/autorun' require_relative '../../lib/tritium/parser/macro_expander' class MacroTest < MiniTest::Unit::TestCase include Tritium::Parser def setup @expander = MacroExpander.new test_returning_macro = Macro.build_macro_from_string("log('a')\nconcat('wor', 'ked') { yield() }", "test", 0) ...
Remove vcr tag from stubbed test in downloads spec
require 'helper' describe Octokit::Client::Downloads do before do Octokit.reset! @client = oauth_client end describe ".downloads", :vcr do it "lists available downloads" do downloads = @client.downloads("github/hubot") expect(downloads.last.description).to eq("Version 1.0.0 of the Hubot...
require 'helper' describe Octokit::Client::Downloads do before do Octokit.reset! @client = oauth_client end describe ".downloads", :vcr do it "lists available downloads" do downloads = @client.downloads("github/hubot") expect(downloads.last.description).to eq("Version 1.0.0 of the Hubot...
Use the correct comment character
require 'rbcoremidi.bundle' module CoreMIDI def sources API.sources end def number_of_sources API.get_num_sources end def create_input_port(client_name, port_name, &proc) API.create_input_port(client_name, port_name, proc) end end
require 'rbcoremidi.bundle' module CoreMIDI def sources API.sources end def number_of_sources API.get_num_sources end def create_input_port(client_name, port_name, &proc) # AFAIK this is the only way to pass the proc to a C function API.create_input_port(client_name, port_name, proc) ...
Package version is incremented from 0.0.2.0 to 0.0.3.0
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'clock' s.summary = 'Clock interface with support for dependency configuration for real and null object implementations' s.version = '0.0.2.0' s.description = ' ' s.authors = ['Obsidian Software, Inc'] s.email = 'opensource@obsidianexchange.c...
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'clock' s.summary = 'Clock interface with support for dependency configuration for real and null object implementations' s.version = '0.0.3.0' s.description = ' ' s.authors = ['Obsidian Software, Inc'] s.email = 'opensource@obsidianexchange.c...
Update Balsamiq Mockups to 3.1.6.
cask :v1 => 'balsamiq-mockups' do version '3.1.5' sha256 '738c986bc3d43d6a9cd0bbef9e8bd50edf5b5e7b865ff72c8fa9fe9048c662d8' # amazonaws is the official download host per the vendor homepage url "https://s3.amazonaws.com/build_production/mockups-desktop/Balsamiq_Mockups_#{version}.dmg" name 'Balsamiq Mockups'...
cask :v1 => 'balsamiq-mockups' do version '3.1.6' sha256 '5f6fec35f0ab2fdaea766b5139cc9ea604782eeda6ac417b606e6d309c7b89b7' # amazonaws is the official download host per the vendor homepage url "https://s3.amazonaws.com/build_production/mockups-desktop/Balsamiq_Mockups_#{version}.dmg" name 'Balsamiq Mockups'...
Use meeting_url instead of path
class MeetingInvitationMailer < ActionMailer::Base include EmailHeaderHelper include ApplicationHelper helper ApplicationHelper def attending meeting, member, invitation @member = member @meeting = meeting @host_address = AddressDecorator.new(@meeting.venue.address) @cancellation_url = 'https:...
class MeetingInvitationMailer < ActionMailer::Base include EmailHeaderHelper include ApplicationHelper helper ApplicationHelper def attending meeting, member, invitation @member = member @meeting = meeting @host_address = AddressDecorator.new(@meeting.venue.address) @cancellation_url = meeting...
Stop error when param not supplied
class Users::RegistrationsController < Devise::RegistrationsController def create if params[:bicycle_wheels].strip == '12' && params[:real_name].blank? super else build_resource(sign_up_params) clean_up_passwords(resource) flash[:alert] = I18n.t(:failure, scope: "devise.registrations....
class Users::RegistrationsController < Devise::RegistrationsController def create if params[:bicycle_wheels].try(:strip) == '12' && params[:real_name].blank? super else build_resource(sign_up_params) clean_up_passwords(resource) flash[:alert] = I18n.t(:failure, scope: "devise.registra...
Use curly braces for cassette filter to please URI parser
require 'vcr' VCR.configure do |c| c.cassette_library_dir = 'spec/fixtures/vcr' c.hook_into :webmock c.default_cassette_options = { serialize_with: :json, record: :once } c.debug_logger = File.open(Rails.root.join('log', 'vcr.log'), 'a') c.filter_sensitive_data('<WUNDERGROUND_KEY>') { ENV['WUNDERGROUND_KEY']...
require 'vcr' VCR.configure do |c| c.cassette_library_dir = 'spec/fixtures/vcr' c.hook_into :webmock c.default_cassette_options = { serialize_with: :json, record: :once } c.debug_logger = File.open(Rails.root.join('log', 'vcr.log'), 'a') c.filter_sensitive_data('{WUNDERGROUND_KEY}') { ENV['WUNDERGROUND_KEY']...
Remove spec of returned result from job
require 'rails_helper' RSpec.describe StatsReportGenerationJob, type: :job do describe '#perform' do let(:report_type) { 'provisional_assessment' } let(:result) { double(:generator_result) } subject(:job) { described_class.new } it 'calls the stats report generator with the provided report type' do...
require 'rails_helper' RSpec.describe StatsReportGenerationJob, type: :job do subject(:job) { described_class.new } describe '#perform' do subject (:perform) { job.perform(report_type) } let(:report_type) { 'provisional_assessment' } it 'calls the stats report generator with the provided report type...
Fix rubocop warning in LoadBalancerHelper
module LoadBalancerHelper include_concern 'TextualSummary' # Display a protocol and port_range as a string suitable for rendering (e.g. # "TCP:1000-1010"). # # @param protocol [#to_s] the protocol to render # @param port_range [Range, nil] a range of ports (or nil, in which case "nil" # is rendered) ...
module LoadBalancerHelper include_concern 'TextualSummary' # Display a protocol and port_range as a string suitable for rendering (e.g. # "TCP:1000-1010"). # # @param protocol [#to_s] the protocol to render # @param port_range [Range, nil] a range of ports (or nil, in which case "nil" # is rendered) ...
Check if user is logged in before executing certain actions
class CommentsController < ApplicationController before_action :set_comment, only: [:show, :edit, :update, :destroy] # do we need this? # def index # @comments = Comment.all # end def show end def new @comment = Comment.new end def edit end def create @comment = Comment.new(commen...
class CommentsController < ApplicationController before_action :set_comment, only: [:show, :edit, :update, :destroy] # do we need this? # def index # @comments = Comment.all # end def show end def new if current_user @comment = Comment.new else redirect_to root_path, notice: 'Yo...
Add id attribute to material serializer
class MaterialSerializer < ActiveModel::Serializer attributes( :original_link, :caption_original, :caption_translated, :annotation_original, :annotation_translated, :original_language, :translation_language, :tags ) belongs_to :rightholder belongs_to :owner belongs_to :state ...
class MaterialSerializer < ActiveModel::Serializer attributes( :id, :original_link, :caption_original, :caption_translated, :annotation_original, :annotation_translated, :original_language, :translation_language, :tags ) belongs_to :rightholder belongs_to :owner belongs_to...
Move to newer RSpec matcher syntax
require 'rspec/expectations' module Arrthorizer module RSpec module Matchers module Roles class AppliesToUser def initialize(user) @user = user end def matches?(role) @role = role role.applies_to_user?(user, context) end ...
require 'rspec/expectations' module Arrthorizer module RSpec module Matchers module Roles class AppliesToUser def initialize(user) @user = user end def matches?(role) @role = role role.applies_to_user?(user, context) end ...
Fix error in updating existing user invites
class AddUsedColumnToUserInvitations < ActiveRecord::Migration def change transaction do add_column :user_invitations, :used, :boolean, default: false uis = UserInvitations.all uis.each do |ui| user = User.where(email: ui.email) user_already_at_org = false user_already_a...
class AddUsedColumnToUserInvitations < ActiveRecord::Migration def change add_column :user_invitations, :used, :boolean, default: false update_existing_user_invitations end def update_existing_user_invitations UserInvitation.all.each do |ui| user = User.where(email: ui.email) user_alread...
Fix bug; mistake same prefix project name
module Ruboty module Gitlab module Actions class Base NAMESPACE = "gitlab" attr_reader :message def initialize(message) @message = message end private def private_tokens message.robot.brain.data[NAMESPACE] ||= {} end de...
module Ruboty module Gitlab module Actions class Base NAMESPACE = "gitlab" attr_reader :message def initialize(message) @message = message end private def private_tokens message.robot.brain.data[NAMESPACE] ||= {} end de...
Update podspec for 1.1 release
# # Be sure to run `pod lib lint PINRemoteImage.podspec' to ensure this is a # valid spec and remove all comments before submitting the spec. # # Any lines starting with a # are optional, but encouraged # # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.nam...
# # Be sure to run `pod lib lint PINRemoteImage.podspec' to ensure this is a # valid spec and remove all comments before submitting the spec. # # Any lines starting with a # are optional, but encouraged # # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.nam...
Add unit tests or setting
require 'spec_helper' class SettingTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
require 'spec_helper' describe Setting do before :each do load "#{Rails.root}/db/seeds.rb" end it "should return the api server" do api_server = Setting.api_server api_server.should_not be_nil api_server.should_not be_false Setting.api_server.should_not be_nil end it "should return tru...
Use schema gem to find schemas
require 'json-schema' class SchemaValidator attr_reader :errors def initialize(type:, schema_name: nil, schema: nil) @errors = [] @type = type @schema = schema @schema_name = schema_name end def validate(payload) @payload = payload return true if schema_name_exception? @errors +...
require 'json-schema' class SchemaValidator attr_reader :errors def initialize(type:, schema_name: nil, schema: nil) @errors = [] @type = type @schema = schema @schema_name = schema_name end def validate(payload) @payload = payload return true if schema_name_exception? @errors +...
Fix issue where TravisBuildKiller blows up when manageiq repo is missing.
class TravisBuildKiller include Sidekiq::Worker include Sidetiq::Schedulable include MiqToolsServices::SidekiqWorkerMixin sidekiq_options :queue => :miq_bot, :retry => false recurrence { hourly.minute_of_hour(0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55) } def perform if !first_unique_worker? lo...
class TravisBuildKiller include Sidekiq::Worker include Sidetiq::Schedulable include MiqToolsServices::SidekiqWorkerMixin sidekiq_options :queue => :miq_bot, :retry => false recurrence { hourly.minute_of_hour(0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55) } def perform if !first_unique_worker? lo...
Fix request spec for header id attributes
require 'rails_helper' RSpec.describe "Pages", :type => :request do let(:valid_attributes) {{ body: "# header 1\n\nbody" }} let(:rory) {User.create!(name: 'Rory', uid: "1")} describe "POST /preview" do it "redirects when unauthenticated" do post preview_path, params: valid_attributes expect(resp...
require 'rails_helper' RSpec.describe "Pages", :type => :request do let(:valid_attributes) {{ body: "# header 1\n\nbody" }} let(:rory) {User.create!(name: 'Rory', uid: "1")} describe "POST /preview" do it "redirects when unauthenticated" do post preview_path, params: valid_attributes expect(resp...
Fix TypeError raised by ActiveSupport::SafeBuffer
module Grease class Adapter def initialize(engine) @engine = engine end def call(input) context = input[:environment].context_class.new(input) template = @engine.new { input[:data] } output = template.render(context, {}) context.metadata.merge(data: output) end end en...
module Grease class Adapter def initialize(engine) @engine = engine end def call(input) context = input[:environment].context_class.new(input) template = @engine.new { input[:data] } # TODO: Hack for converting ActiveSupport::SafeBuffer into String output = "#{template.rend...
Change the cache store to a memory store so that caching will be performed if it is turned on
GradeCraft::Application.configure do config.action_controller.perform_caching = false config.action_dispatch.best_standards_support = :builtin config.asset_host = "http://localhost:5000" config.action_mailer.default_url_options = { :host => 'localhost:5000' } config.action_mailer.delivery_method = :letter_ope...
GradeCraft::Application.configure do config.action_controller.perform_caching = false config.action_dispatch.best_standards_support = :builtin config.asset_host = "http://localhost:5000" config.action_mailer.default_url_options = { :host => 'localhost:5000' } config.action_mailer.delivery_method = :letter_ope...
Write a test for the functional_test_location
require 'minitest/autorun' require_relative '../lib/tritium/config' class ConfigTest < MiniTest::Unit::TestCase def test_functional_location assert File.exists?(Tritium.functional_test_location), "can't find functional tests" end end
Make sure coveralls is initialized before anything else
require 'ruby-bbcode' require "minitest/autorun" require 'coveralls' Coveralls.wear! # This hack allows us to make all the private methods of a class public. class Class def publicize_methods saved_private_instance_methods = self.private_instance_methods self.class_eval { public(*saved_private_instance_meth...
require 'coveralls' Coveralls.wear! require 'ruby-bbcode' require "minitest/autorun" # This hack allows us to make all the private methods of a class public. class Class def publicize_methods saved_private_instance_methods = self.private_instance_methods self.class_eval { public(*saved_private_instance_meth...
Boost the number of blocks in the profile test to get better results
#!/usr/bin/env ruby -rprofile require ARGV[0]||"./core" require "./rijndael" require "crypt/cbc" puts "Encrypting a fairly big block of text...\n"; huge_ptext = File.open("bwulf10.txt", "r").read big_ptext = huge_ptext[0, 10240] #big_ptext="Oh, the grand old Duke of York,\nHe had ten thousand men;\nHe marched them up...
#!/usr/bin/env ruby -rprofile require ARGV[0]||"./core" require "./rijndael" require "crypt/cbc" puts "Encrypting a fairly big block of text...\n"; huge_ptext = File.open("bwulf10.txt", "r").read big_ptext = huge_ptext[0, 102400] #big_ptext="Oh, the grand old Duke of York,\nHe had ten thousand men;\nHe marched them u...
Correct module name for RSpec, prevent deprecation warnings
require 'capybara' require 'capybara/dsl' Rspec.configure do |config| config.include Capybara config.after do Capybara.reset_sessions! Capybara.use_default_driver end config.before do Capybara.current_driver = Capybara.javascript_driver if example.metadata[:js] Capybara.current_driver = example...
require 'capybara' require 'capybara/dsl' RSpec.configure do |config| config.include Capybara config.after do Capybara.reset_sessions! Capybara.use_default_driver end config.before do Capybara.current_driver = Capybara.javascript_driver if example.metadata[:js] Capybara.current_driver = example...
Add suites of empty serverspec tests.
# Tests for a Racktable install require 'serverspec' include Serverspec::Helper::Exec include Serverspec::Helper::DetectOS # Setup something with root user paths? # Not sure what is going on here, but it's in the kitchen-ci docs RSpec.configure do |c| c.before :all do c.path = '/sbin:/usr/sbin' end en...
Add definition for pg gem
# # Copyright 2014 Chef Software, 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...
Remove interface used to expose migration code
# frozen_string_literal: true require 'yaml' require 'feature_flagger/version' require 'feature_flagger/storage/redis' require 'feature_flagger/control' require 'feature_flagger/model' require 'feature_flagger/model_settings' require 'feature_flagger/feature' require 'feature_flagger/key_resolver' require 'feature_fl...
# frozen_string_literal: true require 'yaml' require 'feature_flagger/version' require 'feature_flagger/storage/redis' require 'feature_flagger/control' require 'feature_flagger/model' require 'feature_flagger/model_settings' require 'feature_flagger/feature' require 'feature_flagger/key_resolver' require 'feature_fl...
Upgrade rake to version 12.3.1
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'easy_logging/version' Gem::Specification.new do |spec| spec.name = "easy_logging" spec.version = EasyLogging::VERSION spec.authors = ["thisismydesign"] spec.email ...
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'easy_logging/version' Gem::Specification.new do |spec| spec.name = "easy_logging" spec.version = EasyLogging::VERSION spec.authors = ["thisismydesign"] spec.email ...
Fix typo in sample_data zone creation (zonEable) and added clause to avoid re-adding the same country to the zone
module Addressing private def address(string) state = country.states.first parts = string.split(", ") Spree::Address.new( address1: parts[0], city: parts[1], zipcode: parts[2], state: state, country: country ) end def zone zone = Spree::Zone.find_or_create_by_...
module Addressing private def address(string) state = country.states.first parts = string.split(", ") Spree::Address.new( address1: parts[0], city: parts[1], zipcode: parts[2], state: state, country: country ) end def zone zone = Spree::Zone.find_or_create_by_...
Add keyword directly to the array
Bundler.require class SearchPostStream def initialize(keyword, language: nil) # Set environment variable TWINGLY_SEARCH_KEY client = Twingly::Search::Client.new do |client| client.user_agent = "MyCompany/1.0" # Set optional user agent end @query = client.query do |query| query_parts = [ ...
Bundler.require class SearchPostStream def initialize(keyword, language: nil) # Set environment variable TWINGLY_SEARCH_KEY client = Twingly::Search::Client.new do |client| client.user_agent = "MyCompany/1.0" # Set optional user agent end @query = client.query do |query| query_parts = [ ...
Add conde wars (7) - find the smallest power
# http://www.codewars.com/kata/56ba65c6a15703ac7e002075/ # --- iteration 1 --- def find_next_power(val, pow) lower = val ** (1.fdiv(pow)) ((lower.floor + 1) ** pow) end
Add remote tests for SecurePayTech
require File.dirname(__FILE__) + '/../test_helper' class RemoteSecurePayTechTest < Test::Unit::TestCase ACCEPTED_AMOUNT = 10000 DECLINED_AMOUNT = 10075 def setup @gateway = SecurePayTechGateway.new(fixtures(:secure_pay_tech)) @creditcard = credit_card('4987654321098769', :month => 5, :year => 2013) ...
Set persistent object on repo success
module LittleMapper module MapperInstanceMethods def to_persistent(entity) pe = self.class.persistent_entity.new self.class.mappings.each do |m| m.from(entity).to_persistent(pe) end pe end def to_entity(persistent) e = self.class.entity.new e.id = persistent.id...
module LittleMapper module MapperInstanceMethods def to_persistent(entity) pe = self.class.persistent_entity.new self.class.mappings.each do |m| m.from(entity).to_persistent(pe) end pe end def to_entity(persistent) e = self.class.entity.new e.id = persistent.id...
Add test for checking status.
require 'spec_helper' describe Ruzai2 do it 'has a version number' do expect(Ruzai2::VERSION).not_to be nil end describe Ruzai2::RuzaiList do describe ".ban" do subject { Ruzai2::RuzaiList.ban!(id_params) } let(:id_params) { { test_id1: 1, test_id2: 2, ...
require 'spec_helper' describe Ruzai2 do it 'has a version number' do expect(Ruzai2::VERSION).not_to be nil end describe Ruzai2::RuzaiList do describe ".ban" do subject { Ruzai2::RuzaiList.ban!(id_params) } let(:id_params) { { test_id1: 1, test_id2: 2, ...
Mark as deprecated in podspec
Pod::Spec.new do |s| s.name = "DTXcodeUtils" s.version = "0.1.1" s.summary = "Useful helper functions for writing Xcode plugins" s.homepage = "https://github.com/thurn/DTXcodeUtils" s.license = 'Creative Commons Zero' s.author = { "Derek Thurn" => "de...
Pod::Spec.new do |s| s.name = "DTXcodeUtils" s.deprecated = true s.version = "0.1.1" s.summary = "Useful helper functions for writing Xcode plugins" s.homepage = "https://github.com/thurn/DTXcodeUtils" s.license = 'Creative Commons Zero' s.author ...
Remove spurious line from ESI fund spec
require "fast_spec_helper" require "formatters/esi_fund_publication_alert_formatter" RSpec.describe EsiFundPublicationAlertFormatter do let(:url_maker) { double(:url_maker, published_specialist_document_path: "http://www.example.com" ) } let(:document) { double(:document, alert_type: "dru...
require "fast_spec_helper" require "formatters/esi_fund_publication_alert_formatter" RSpec.describe EsiFundPublicationAlertFormatter do let(:url_maker) { double(:url_maker, published_specialist_document_path: "http://www.example.com" ) } let(:document) { double(:document, title: "Some tit...
Clean up type-fixing migration script
class FixTypeColumnName < ActiveRecord::Migration def change rename_column :documents, :type, :file_type rename_column :submissions, :type, :file_type end end
# Encoding: utf-8 # Fix type column name class FixTypeColumnName < ActiveRecord::Migration def change rename_column :documents, :type, :file_type rename_column :submissions, :type, :file_type end end
Send input_capacity with the converter stats
module Api module V3 class ConverterStatsPresenter ATTRIBUTES = [ :demand, :electricity_output_capacity, :number_of_units ].freeze attr_reader :key def initialize(key, gql) @key = key @gql = gql @present = @gql.present_graph.converter(@key...
module Api module V3 class ConverterStatsPresenter ATTRIBUTES = [ :demand, :electricity_output_capacity, :input_capacity, :number_of_units ].freeze attr_reader :key def initialize(key, gql) @key = key @gql = gql @present = @gql.pre...
Add Rob to gem authors.
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "plan_executor" s.summary = "A Gem for handling FHIR test executions" s.description = "A Gem for handling FHIR test executions" s.email = "jwalonoski@mitre.org" s.homepage = "https://github.com/hl7-fhir/fhir-svn" s.authors = ["Andre Quina", "...
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "plan_executor" s.summary = "A Gem for handling FHIR test executions" s.description = "A Gem for handling FHIR test executions" s.email = "jwalonoski@mitre.org" s.homepage = "https://github.com/hl7-fhir/fhir-svn" s.authors = ["Andre Quina", "...
Add support for RPM based install
include_recipe 'omnibus_updater::set_remote_path' remote_file "chef omnibus_package[#{File.basename(node[:omnibus_updater][:full_uri])}]" do path File.join(node[:omnibus_updater][:cache_dir], File.basename(node[:omnibus_updater][:full_uri])) source node[:omnibus_updater][:full_uri] backup false not_if do F...
Fix sorting on search api
class Api::SearchController < Api::ApplicationController before_action :check_api_key def index @query = params[:q] @search = Project.search(params[:q], filters: { platform: current_platform, normalized_licenses: current_license, language: current_language, keywords_array: params[:k...
class Api::SearchController < Api::ApplicationController before_action :check_api_key def index @query = params[:q] @search = Project.search(params[:q], filters: { platform: current_platform, normalized_licenses: current_license, language: current_language, keywords_array: params[:k...
Complete initial solution passing all tests
# Shortest String # I worked on this challenge [by myself]. # shortest_string is a method that takes an array of strings as its input # and returns the shortest string # # +list_of_words+ is an array of strings # shortest_string(array) should return the shortest string in the +list_of_words+ # # If +list_of_words+ is...
Add a tool that generates data to use many segments
#!/usr/bin/env ruby # # Copyright(C) 2019 Kouhei Sutou <kou@clear-code.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License version 2.1 as published by the Free Software Foundation. # # This library is distributed in the hope that ...
Refactor ratings find route to emit json
Rails.application.routes.draw do root 'static_pages#index' mount Buttercms::Engine => '/blog' resources :genres resources :casts, defaults: {:format => 'json'} resources :dramas, only: [:index, :show], defaults: {:format => 'json'} do resources :ratings, except: [:new, :edit] resources :reviews, e...
Rails.application.routes.draw do root 'static_pages#index' mount Buttercms::Engine => '/blog' resources :genres resources :casts, defaults: {:format => 'json'} resources :dramas, only: [:index, :show], defaults: {:format => 'json'} do resources :ratings, except: [:new, :edit] resources :reviews, e...
Tweak permalink transformation again so existing tests don't break
class String # Returns a-string-with-dashes when passed 'a string with dashes'. # All special chars are stripped in the process def to_url return if self.nil? self.downcase.tr("\"'", '').strip.gsub(/\W/, '-').tr(' ', '-').squeeze('-') end # A quick and dirty fix to add 'nofollow' to any urls in a st...
class String # Returns a-string-with-dashes when passed 'a string with dashes'. # All special chars are stripped in the process def to_url return if self.nil? self.downcase.tr("\"'", '').gsub(/\W/, ' ').strip.tr_s(' ', '-').tr(' ', '-').sub(/^$/, "-") end # A quick and dirty fix to add 'nofollow' to...
Add support for a post update script
module V1 class WebhooksController < BaseController # No authorization necessary for webhook skip_before_action :doorkeeper_authorize! # POST /v1/webhooks/github def github # We are always answering with a 202 render json: {}, status: :accepted # Skip any further actions unless it ...
module V1 class WebhooksController < BaseController # No authorization necessary for webhook skip_before_action :doorkeeper_authorize! # POST /v1/webhooks/github def github # We are always answering with a 202 render json: {}, status: :accepted # Skip any further actions unless it ...
Fix issues with finding bus stops
class BusStopsController < ApplicationController version 1 caches :show, :index def index scope = BusStop.limit(5) scope = scope.stop_near(params[:near]) if params[:near] expose scope.all, :compact => true end def show bus_stop = BusStop.find_using_slug!(params[:id]) expose bus_stop ...
class BusStopsController < ApplicationController version 1 caches :show, :index def index scope = BusStop.limit(5) scope = scope.stop_near(params[:near]) if params[:near] expose scope.all, :compact => true end def show bus_stop = BusStop.where(:stop_number => params[:id]).first! expose...
Complete and upload 8.6 Ruby Review
# U2.W6: Testing Assert Statements # I worked on this challenge by myself. # 1. Review the simple assert statement def assert raise "Assertion failed!" unless yield end name = "bettysue" assert { name == "bettysue" } assert { name == "billybob" } # 2. Pseudocode what happens when the code above runs # define a...
Update Diskmaker X to v5.0.3
cask 'diskmaker-x' do version :latest sha256 :no_check url 'http://diskmakerx.com/downloads/DiskMaker_X.dmg' name 'DiskMaker X' homepage 'http://diskmakerx.com/' license :gratis app 'DiskMaker X 5.app' end
cask 'diskmaker-x' do version '5.0.3' sha256 '040a21bdef0c2682c518a9e9572f7547b5f1fb02b8930a8a084ae85b12e70518' url "http://diskmakerx.com/downloads/DiskMaker_X_#{version.no_dots}.dmg" appcast 'http://diskmakerx.com/feed/', checkpoint: '65c41b1c32cf72f4cccd0f467d903ed768dedc407936bf1a64ec90764deb7da1...
Add script for getting data about training due dates and completion
require 'csv' cohort = Cohort.find_by(slug: 'spring_2016') # CSV of all assigned training modules for courses in the cohort: # course slug, training module, due date courses = cohort.courses csv_data = [] courses.each do |course| course.training_modules.each do |training_module| due_date = TrainingModuleDueDat...
Set up spec tests for pd_regimes controller.
require 'rails_helper' RSpec.describe PdRegimesController, :type => :controller do end
require 'rails_helper' RSpec.describe PdRegimesController, :type => :controller do describe 'GET #new' do it 'renders the new template' do get :new expect(response).to render_template('new') end end describe 'POST #create' do context "with valid attributes" do it 'creates a new PD...
Disable connecting to a database on precompile
# Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. Rails.application.config.assets.version = '1.0' # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. # Rails...
# Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. Rails.application.config.assets.version = '1.0' Rails.application.config.assets.initialize_on_precompile = false # Precompile additional assets. # application.js, application.css, ...
Fix OR expressions where the left side is true
module JMESPath # @api private module Nodes class Or < Node def initialize(left, right) @left = left @right = right end def visit(value) result = @left.visit(value) if result == false || result.nil? || result.empty? @right.visit(value) else ...
module JMESPath # @api private module Nodes class Or < Node def initialize(left, right) @left = left @right = right end def visit(value) result = @left.visit(value) if result == false || result.nil? || (result.respond_to?(:empty?) && result.empty?) @r...
Include spec/ when calling rcov.
begin require 'metric_fu' MetricFu::Configuration.run do |config| config.rcov[:test_files] = 'spec/**/*_spec.rb' end rescue LoadError end
begin require 'metric_fu' MetricFu::Configuration.run do |config| config.rcov[:test_files] = 'spec/**/*_spec.rb' config.rcov[:rcov_opts] << '-Ispec' end rescue LoadError end
Fix copy and paste error
module Helpers module GraphiteHelpers require 'socket' def graphite_plot(logString) if Deployinator.graphite_host s = TCPSocket.new(Deployinator.graphite_host,Deployinator.graphite_po s.write "#{logString} #{Time.now.to_i}\n" s.close end end end end
module Helpers module GraphiteHelpers require 'socket' def graphite_plot(logString) if Deployinator.graphite_host s = TCPSocket.new(Deployinator.graphite_host,Deployinator.graphite_port || 2003) s.write "#{logString} #{Time.now.to_i}\n" s.close end end end end
Add my original hangman written during interview
# HangMan that I first wrote in my interview class HangMan require 'SecureRandom' def initialize @lives = 8 @wrong_letters = [] all_words = File.new('words.txt').readlines() @word = all_words[SecureRandom.random_number(all_words.length)].chomp puts "pssst, the word is #{@word}" @word_pro...
Enable xrange and yrange options
module Nyaplot class Plot include Jsonizable define_properties(Array, :diagrams) define_group_properties(:options, [:width, :height, :margin, :xrange, :yrange, :x_label, :y_label, :bg_color, :grid_color, :legend, :legend_width, :legend_options, :zoom]) def initialize set_property(:diagrams, []...
module Nyaplot class Plot include Jsonizable define_properties(Array, :diagrams) define_group_properties(:options, [:width, :height, :margin, :xrange, :yrange, :x_label, :y_label, :bg_color, :grid_color, :legend, :legend_width, :legend_options, :zoom]) def initialize set_property(:diagrams, []...
Add version constraints to gemspec.
# coding: utf-8 lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "ndb/version" Gem::Specification.new do |spec| spec.name = "ndb-ruby" spec.version = NDB::VERSION spec.authors = ["Alex Stophel"] spec.email = ["alexstophel@gmail.com"] spec.summary = "...
# coding: utf-8 lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "ndb/version" Gem::Specification.new do |spec| spec.name = "ndb-ruby" spec.version = NDB::VERSION spec.authors = ["Alex Stophel"] spec.email = ["alexstophel@gmail.com"] spec.summary = "...
Add test for OSTYPE macro on FreeBSD
require 'spec_helper' describe 'sendmail::mc::ostype' do context 'on Debian' do let(:title) { 'debian' } it { should contain_concat__fragment('sendmail_mc-ostype-debian') \ .with_content(/^OSTYPE\(`debian'\)dnl$/) \ .with_order('05') \ .that_notifies('Class[se...
require 'spec_helper' describe 'sendmail::mc::ostype' do context 'on Debian' do let(:title) { 'debian' } it { should contain_concat__fragment('sendmail_mc-ostype-debian') \ .with_content(/^OSTYPE\(`debian'\)dnl$/) \ .with_order('05') \ .that_notifies('Class[se...
Add association to music for Season
class Season < ActiveRecord::Base validates :name, presence: true validates :start, presence: true validates :expiry, presence: true validate :start_must_be_before_expiry def start_must_be_before_expiry if (start.present? && expiry.present?) && (start > expiry) errors.add(:expiry, "can't be after t...
class Season < ActiveRecord::Base has_many :musics validates :name, presence: true validates :start, presence: true validates :expiry, presence: true validate :start_must_be_before_expiry def start_must_be_before_expiry if (start.present? && expiry.present?) && (start > expiry) errors.add(:expir...
Change MountVmwareSharedFolder to use symlinks.
module VagrantPlugins module VMwareFreeBSD module Cap class MountVmwareSharedFolder def self.mount_vmware_shared_folder(machine, name, guestpath, options) machine.communicate.tap do |comm| comm.sudo("rm \"#{guestpath}\"") if comm.test("test -L \"#{guestpath}\"", :sudo => tr...
module VagrantPlugins module VMwareFreeBSD module Cap class MountVmwareSharedFolder def self.mount_vmware_shared_folder(machine, name, guestpath, options) machine.communicate.tap do |comm| comm.sudo("rm \"#{guestpath}\"") if comm.test("test -L \"#{guestpath}\"", :sudo => tr...
Improve data-load being sent to client
class DashboardController < ApplicationController before_action :authorize helper_method :days_till_water def index puts(current_user.id) @user = User.find(current_user.id) @plants = @user.plants.all @water_events = WaterEvent.where(plant_id: @plants.ids) end end
class DashboardController < ApplicationController before_action :authorize helper_method :days_till_water def index puts(current_user.id) @user = User.find(current_user.id) @plants = @user.plants.all @water_events = [] @plants.each do |p| event = WaterEvent.where(plant_id: p.id).order(w...
Add check for length restrictions of file name and folders
class Cleaner def self.clean_folder path dirty_folders = [] Dir.glob(path + "/**").sort.each do |file| if File.directory?(file) self.clean_folder file dirty_folders << file else puts 'cleaning file' + file self.rename_file file, path end end self.rena...
class Cleaner def self.clean_folder path dirty_folders = [] Dir.glob(path + "/**").sort.each do |file| if File.directory?(file) self.clean_folder file dirty_folders << file else new_file = self.rename_file file, path self.cut_file_name(new_file, path) if new_file.l...
Remove deprecation check for 'public/assets' as that's we're precompiled assets get created.
# check for incorect product assets path in public directory if File.exist?(Rails.root.join("public/assets/products")) || File.exist?(Rails.root.join("public/assets/taxons")) puts %q{[DEPRECATION] Your applications public directory contains an assets/products and/or assets/taxons subdirectory. Run `rake spree...
# check for incorect product assets path in public directory if File.exist?(Rails.root.join("public/assets/products")) || File.exist?(Rails.root.join("public/assets/taxons")) puts %q{[DEPRECATION] Your applications public directory contains an assets/products and/or assets/taxons subdirectory. Run `rake spree...