text
stringlengths
10
2.61M
name 'logrotate' maintainer 'Steven Danna' maintainer_email 'steve@chef.io' license 'Apache 2.0' description 'Installs logrotate package and provides a definition for logrotate configs' long_description 'Installs the logrotate package, manages /etc/logrotate.conf, and provides a logrotate_app definition.' version '1.10...
class User < ApplicationRecord has_many :topics has_many :statements, through: :topics has_many :photos, through: :topics before_save { self.email = email.downcase } validates :name, presence: true, length: {maximum: 255} validates :email, presence: true, length: { maximum: 255 }, uniqueness: {case_sensitiv...
# Example usage of JavaClass::Dependencies::Graph: Iterate all folders of a root folder. # Load each component separately and construct the dependency graph. # Author:: Peter Kofler # Copyright:: Copyright (c) 2009, Peter Kofler. # License:: {BSD License}[link:/files/license_txt.html] # # =...
class Admin < ActiveRecord::Base has_secure_password validates_uniqueness_of :email validates_presence_of :name, :email end
require 'spec_helper' describe 'Patient' do let(:patient) { Patient.new({name: "Elrey", birthday: "1980-01-22", doctor_id: 1 }) } let(:patient2) { Patient.new({name: "Elrey", birthday: "1980-01-22", doctor_id: 1}) } let(:patient3) { Patient.new({name: "Oscar", birthday: "1987-10-06", doctor_id: 2 }) } describ...
module PartialHelper def partial(path, indent: 0, skip_first_indent: true, vars: Nanoc::Core::Context.new({})) content_path = File.expand_path('../../../content', __FILE__) path = File.join(content_path, "#{path}#{File.extname(item.raw_filename)}") raise "Partial #{path} was not found" unless File.exists?...
class CreateEconomicEventInstances < ActiveRecord::Migration[5.1] def change create_table :economic_event_instances do |t| t.references :economic_event, foreign_key: true t.datetime :released t.boolean :preliminary t.float :actual t.float :forecast t.float :previous t.ti...
class AddLatLongToConcert < ActiveRecord::Migration def change add_column :concerts, :venue_lat, :decimal add_column :concerts, :venue_long, :decimal end end
module Bcpc_Hadoop # TODO: CamelCase this name to make rubocop happy # Load Helper module for BCPC-Hadoop module Helper include Chef::Mixin::ShellOut # Apply translation rules for Hortonworks release # string to a debian package name string # # package name - String for base package name # ...
module CsvUploads class ColorSets < CsvUploader def self.identifier "ColorSet" end def self.label :color end end end
# This Rspec tests are meant to be some basic tests over the controller and the CRUD actions, only some scenarios cover to demonstrate hability for writting tests require 'rails_helper' RSpec.describe BooksController, type: :controller do describe "GET #index" do render_views before do Book.create(na...
class AddTokenToCustomer < ActiveRecord::Migration def change add_column :customers, :token, :string, unique: true end end
class User < ActiveRecord::Base attr_accessor :missing_info_page # -------------- SECTION FOR ASSOCAITIONS --------------------- # ------------------------------------------------------------- # Other options: :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :regi...
class OwnBadgesController < ApplicationController def index @own_badges = current_user.own_badges end end
ActiveAdmin.register Committee do menu priority: 14 menu parent: "Conferences" before_filter :skip_sidebar!, only: :index config.batch_actions = false permit_params :order_id, :committee_name, :chair, :vice_chair, :topic_guide_url, :image_url, :category_id, :is_active, topics_attributes: [:order, :topic_name...
class JobsTechnologies < ApplicationRecord belongs_to :job belongs_to :technology end
require 'minitest/autorun' require './calculator' class CalculatorSpec < MiniTest::Test def test_accumulator my_calculator = Calculator.new my_calculator.accumulator = 12 assert_equal(12, my_calculator.accumulator) end def test_floating_point my_calculator = Calculator.new my_calculator.ac...
class CreateMatches < ActiveRecord::Migration[5.0] def change create_table :matches do |t| t.references :project, null: false, index: true t.references :congressman, null: false, index: true t.string :status, null: false, default: 'calling' t.timestamps null: false end add_index :...
class CreateJoinTableCustomPagesImages < ActiveRecord::Migration[5.0] def change create_join_table :custom_pages, :pictures do |t| t.index [:custom_page_id, :picture_id] t.index [:picture_id, :custom_page_id] end end end
class CreateUserSignups < ActiveRecord::Migration def self.up create_table :user_signups, :force => true do |t| t.string :email,:limit=>35 t.string :password,:limit=>35 t.string :password_reset,:limit=>35 t.string :uuid,:limit=>50 t.string :kid_gender1,:limit=>2 t.string :kid_g...
# -*- coding: utf-8 -*- """ Faça um Programa que leia 2 números e em seguida pergunte ao usuário qual operação ele deseja realizar. O resultado da operação deve ser acompanhado de uma frase que diga se o número é: a. par ou ímpar; b. positivo ou negativo; c. inteiro ou decimal. """ puts "=============================...
class Dashboard::ExpensesController < DashboardController def index @expenses = current_user.expenses end def new @expense = Expense.new end def create if current_user.expenses.create(expense_params) redirect_to new_dashboard_expense_path else render :new end end def ed...
class FontMasinahikanDene < Formula head "https://www.languagegeek.com/font/MasinahikanDene.zip" desc "Masinahikan Dene" homepage "https://www.languagegeek.com/font/fontdownload.html" def install (share/"fonts").install "MasinahikanDene_h.ttf" (share/"fonts").install "MasinahikanDene_h_Bold.ttf" (sh...
require 'rails_helper' RSpec.describe Animal do describe 'attributes' do %w( birth_date birth_type embryo_transfer percentage registration_type breed type ).each do |required_attribute| it { is_expected.to validate_presence_of required_attribute } end ...
shared_examples_for 'an action requiring logged in user' do |action| let(:example_user) { FactoryBot.create(:user) } before :each do logout end context 'user is logged in' do before do login(example_user) call_action(action, parameters) end it 'does not display not logged in warning...
# inputs.rb # Gets inputs from user. module GetInputs attr_reader :input def self.get_input prompt = '> ' print prompt @input = gets.chomp end end
module Cloudpassage class ConfigurationPolicies < Base def type 'policies' end end end
require 'spec_helper' # module OpenFec RSpec.configure do |config| config.before(:each) do # Response Stub Data invalid_key_response = JSON.parse(File.read("spec/stubs/client/invalid_key_response.json")) candidates_all = JSON.parse(File.read("spec/stubs/client/candidates_all.json")) # R...
module TChat module Command class HandshakeCommandFactory def initialize(commands_manager) self.commands_manager = commands_manager end def create_command(command_line, users_manager, socket) if !command_line.nil? && !command_line.strip.rstrip.empty? ...
require "rubygems" require 'eventmachine' module Micro # The world populates # class World attr_accessor :agents, :step_proc, :begin_proc, :end_proc def initialize(cycle_delay_seconds, number_of_agents, percent_per_cycle = 1.0, step_proc = nil, begin_proc = nil, end_proc = nil, &block) @cycl...
# frozen_string_literal: true RSpec.shared_context 'with user membership' do let(:membership) { build(:membership) } before { user.memberships << membership } end
require('spec_helper') describe '#Train' do describe('.all') do it("returns an empty array when there are no trains") do expect(Train.all).to(eq([])) end end describe('#save') do it("saves a train") do train = Train.new({:color => "Blue", :id => nil}) train.save() train2 =...
class CreateTags < ActiveRecord::Migration def change create_table :tags do |t| t.belongs_to :photo, index:true t.belongs_to :user, index: true t.integer :left_px t.integer :top_px t.integer :width_px t.integer :height_px t.timestamps null: false end end end
# frozen_string_literal: true module Dotfiles module Installers class Vim < BaseInstaller def name 'vim configuration' end private # rubocop:disable Metrics/AbcSize def perform_installation symlink(dotfile('vim'), destination_for('.vim')) symlink(dotfile('v...
module Backend # Posts controller class MessagesController < BackendController before_filter :set_message, only: [:destroy, :show] before_filter :authorize_with_klass, only: [ :index, :show, :destroy ] add_breadcrumb I18n.t('breadcrumbs.dashboard'), :backend_path add_breadcrumb I18n.t('breadcrumbs....
class CreateCalendars < ActiveRecord::Migration def up create_table :calendars do |t| t.string "name" t.string "place" t.string "info" t.string "date1" t.string "date2" t.integer "position" t.timestamps end end def down drop_table :calendars end end
class Forecasts::PurchasesController < ApplicationController before_action :set_purchase, only: [:show, :edit, :update, :destroy] before_filter :new_purchase, only: [:new, :create] load_and_authorize_resource through: :current_forecast #before_action :set_heading_classes, only: [:new, :edit] # GET /purchases...
require 'mime/types' class Photo < ActiveRecord::Base belongs_to :gallery acts_as_list :scope => :gallery has_attached_file :image, :styles => { :gal => ["700x466>", :jpg], :thumb => ["48x48#", :jpg], :admin_thumb => ["70x47>", :jpg], :admin_prev => ["140x94>", :jpg] }, :convert_options => { ...
class AddMapSize < ActiveRecord::Migration def up add_column :maps, :size_x, :integer add_column :maps, :size_y, :integer end def down remove_column :maps, :size_x remove_column :maps, :size_x end end
class CreateDiningRooms < ActiveRecord::Migration[5.1] def change create_table :dining_rooms, id: :uuid do |t| t.integer :number_of_benches, default: 0, null: false t.integer :number_of_ovens, default: 0, null: false t.integer :number_of_cookers, default: 0, null: false t.integer :number_o...
class PigLatinizer def piglatinize(text) self.to_pig_latin(text) end def to_pig_latin(text) text_array = text.split text_array.collect do |word| index_first_vowel = word.index(/[AaEeIiOoUu]/) if index_first_vowel == 0 wo...
# # Service which will execute the tasks # # @author [nityamvakil] # class TaskExecutor def initialize(params = {}) @task_id = params[:id] @execution_path = params[:path] @arguments = params[:arguments] @command = 'sh ~/' + execution_path + ' ' + (arguments ? arguments : '') end attr_reader :tas...
module Pages module Cells class Show < Core::Cells::Template def find_template(options) template_options = template_options_for(options) template_options.delete(:suffix) file = page.file_name template_for( [File.dirname(file)], File.basename(file), template_optio...
class CreateEmpires < ActiveRecord::Migration def change create_table :empires do |t| t.integer :user_id t.string :name t.integer :capitol_id t.string :capitol t.timestamps null: false end rename_column :countries, :user_id, :empire_id end end
class Movie < ApplicationRecord validates :title, presence: true, uniqueness: { scope: :overview } validates :overview, presence: true validates :release_date, presence: true validates :inventory, presence: true has_many :rentals def available_inventory inventory - rentals.count end end
require 'json' require 'date' module IndexHelper # Given a metadata JSON file, return a Hash that can be used to generate an Elasticsearch index def generate_index_data(thumbnails_folder, file) metadata = JSON.parse(File.read(file), symbolize_names: true).freeze index_data = {} index_data[:id] = metadata[:id]...
VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.box = "ubuntu/trusty64" # We want vagrant to use its default key. config.ssh.insert_key = false # Set our ip. # This can be updated to any ip address # preferred. This will allow us to access # the site via t...
class Directory < ApplicationRecord has_many_attached :files has_many :subdirectories, class_name: "Directory", foreign_key: "ref_directory_id" #ref alias reference belongs_to :ref_directory, class_name: "Directory", optional: true #Scopes scope :borders, -> { where(ref_directory_id: nil) } ...
FactoryGirl.define do factory :lenticular_cms_category, class: 'LenticularCms::Category' do name "MyString" description "MyString" slug "MyString" end end
class Dashboard::ArticlesController < DashboardController before_filter :prime, except: :sort def index @title = "Articles" @articles = ArticleSearchQuery.new(Article.order_by_publication_date).filter(params).paginate(:page => params[:page]) @issues = Issue.all end def new @article = Article.n...
class Category < ApplicationRecord extend FriendlyId friendly_id :name, use: :slugged # has_many :products end
File.open(ARGV[0]).each_line do |line| first = line.split('|')[0].split(' ').collect { |i| i.to_i } second = line.split('|')[1].split(' ').collect { |i| i.to_i } first.each_with_index do |item, index| print "#{item * second[index]} " end puts end
require 'misc' module ScannerHierarchy class Base def inspect pretty end end class Match < Base # must be initialized with a node in the abstract # syntax tree (AST) def initialize(ast_node, succ) @node = ast_node @succ = succ end attr_reader :node, :succ def accept(visitor); visitor.visit...
require 'colorize' require_relative 'logger' require_relative 'ssh' require_relative 'actions' require_relative 'environment' require_relative 'host/environment' require_relative 'host/file_system' require_relative 'part' class Screenplay # An Host runs Screenplay::Actions on a remote host. # # host = Screen...
class CreateQuestions < ActiveRecord::Migration def self.up create_table :questions do |t| t.string :subject, :null => false t.text :body, :null => false t.boolean :answered, :default => false t.integer :replies_count, :default =>...
require 'rails_helper' RSpec.feature 'Infrastructure Component Management - ', type: :feature do let(:user_a) { create(:user) } before(:each) do @infrastructure = create(:infrastructure) @infrastructure_component = create(:infrastructure_component, infrastructure_id: @infrastructure.id) end describe '...
class CollectionsController < ApplicationController before_action :authenticate, only: [:new, :create] def index @collections = Collection.all end def new @collection = Collection.new end def create @collection = Collection.new(collection_params) if @collection.save redirect_to(co...
class MockActionControllerParameters def initialize(obj) @obj = obj end def permit! self end def to_h @obj end end
module FiscalYearMixin extend ActiveSupport::Concern FISCAL_YEAR_START_MONTH = 10 # 1-based included do scope :for_fiscal_year, lambda { |year| range = range_for_fiscal_year(year) where(created_at: range[:start_time]...range[:end_time]) } def self.range_for_fiscal_year(year) start...
require 'stock_picker' describe "#stock_picker" do it "should raise an error if not an array" do expect{stock_picker(1)}.to raise_error end it "should not raise an error if an array is passed" do array=Array.new expect{stock_picker(array)}.not_to raise_error end it "should return an array" do ...
class TwitterusersTable < ActiveRecord::Migration def change create_table :twitterusers do |t| t.string :user_name t.datetime :last_saved end end end
# frozen_string_literal: true module GraphQL module StaticValidation module FragmentNamesAreUnique def initialize(*) super @fragments_by_name = Hash.new { |h, k| h[k] = [] } end def on_fragment_definition(node, parent) @fragments_by_name[node.name] << node super...
# frozen_string_literal: true unless Rails.env.test? || Rails.env.development? Nucore::Application.configure do config.lograge.enabled = false config.lograge.formatter = Lograge::Formatters::Logstash.new # Add params to the log config.lograge.custom_options = lambda do |event| { params: event....
FactoryGirl.define do factory :user do firstname { Faker::Name.first_name } lastname { Faker::Name.last_name } email "me@andela.com" password "foobar" end end
class Accounts::RegistrationsController < Devise::RegistrationsController before_action :configure_sign_up_params, only: [:create] before_action :configure_account_update_params, only: [:update] protected def configure_sign_up_params devise_parameter_sanitizer.for(:sign_up).concat([:username, :name]) en...
json.community do json.partial! "api/v1/communities/full", community: @community end
#!/usr/bin/env ruby require 'bfire' require 'optparse' require 'logger' require 'pp' logger = Logger.new(STDERR) logger.level = Logger.const_get(ENV['DEBUG'] || "WARN") @options = { :logger => logger, :restfully_config => File.expand_path( "~/.restfully/api.bonfire-project.eu" ) } filename = ARGV[0] if f...
require 'rails/generators' require 'rails/generators/named_base' module Transponder module Generators class Base < Rails::Generators::NamedBase def javascripts_path "app/assets/javascripts" end def self.source_root @_transponder_source_root ||= File.expand_path(File.join(File....
require File.expand_path('../spec_helper', File.dirname(__FILE__)) describe Tr8n::LanguageContextRule do describe "finding fallback rules" do it "should return fallback rule" do rule = Tr8n::LanguageContextRule.create(:keyword => "one", :definition => {"conditions" => "(= 1 @n)"}, :examples => "1")...
class CreateEmployeeDetails < ActiveRecord::Migration[5.0] def change create_table :employee_details do |t| t.uuid :employee_id, null: false t.uuid :field_id, null: false t.text :value, null: false t.datetime :deleted_at t.timestamps end end end
class Phrase < ActiveRecord::Base paginates_per 5 belongs_to :language has_many :lexeme_phrases, :dependent => :destroy has_many :lexemes, :order => 'lexeme_phrases.position', :through => :lexeme_phrases has_many :phrase_stories, :dependent => :destroy has_many :stories, :order => 'phrase_stories.p...
# Exercise: Find the largest integer in an array # Write a method largest_integer which takes as its input an Array of integers and returns the largest integer in the Array. # For example: # largest_integer([-10, 0, 10]) # => 10 # largest_integer([-10, -20, -30]) # => -10 # If the input Array is empty largest_inte...
class CreateCoursesStudentsJoin < ActiveRecord::Migration def change create_table( :courses_students, id: false ) do |t| t.integer "course_id" t.integer "student_id" end add_index( :courses_students, ["course_id", "student_id"]) end end
#!/usr/bin/env ruby # frozen_string_literal: true require 'bundler/setup' require 'vedeu' class EditorApp Vedeu.bind(:_initialize_) { Vedeu.trigger(:_refresh_) } Vedeu.configure do debug! log Dir.tmpdir + '/vedeu.log' renderers(Vedeu::Renderers::Terminal.new, Vedeu::Renderers::Text.ne...
# frozen_string_literal: true resource_name :elasticsearch_index self.class.include ::Ayte::Chef::Cookbook::ElasticSearch::ResourceDefinitionMethods define_common_attributes(timeout: 8) attribute :index, [String, Symbol], name_attribute: true attribute :settings, [Hash, String, NilClass] attribute :mapping, [Hash, ...
class Tower attr_accessor :stacks def initialize @stacks = [ [3,2,1], [], [] ] end def moving_piece(stack) unless stack < 0 || stack > 2 || @stacks[stack].empty? @stacks[stack].pop else raise "Must select a valid, non-empty stack" end end def move(o_stack, to_stack) piece =...
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe Roodi::Checks::NpathComplexityMethodCheck do before(:each) do @roodi = Roodi::Core::Runner.new(Roodi::Checks::NpathComplexityMethodCheck.make({'complexity' => 0})) end def verify_content_complexity(content, complexity) @roo...
Rails.application.routes.draw do devise_for :users # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html #Root site function root 'pinboard#index' #Normal routes get 'about' => 'pages#about' end
$:.unshift(File.dirname(__FILE__)) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) require 'dget' module DGet class GoogleCodeDoc include DGet attr_reader :project_name, :pages, :root_doc def initialize project_name @project_name = pro...
Rails.application.routes.draw do devise_for :users # devise_for :users, controllers: { # sessions: 'users/sessions', # registrations: 'users/registrations' # } # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root to: "homes#top", as: 'root' resourc...
control "M-4.2" do title "4.2 Ensure that containers use trusted base images (Not Scored)" desc " Ensure that the container image is written either from scratch or is based on another established and trusted base image downloaded over a secure channel. Official repositories are Docker images curated an...
require 'cucumber/cli/options' module Cucumber module Cli class Options BUILTIN_FORMATS['calliope_import'] = ['Cucumber::CalliopeImporter::Json', 'Prints the feature as JSON and uploads them to Calliope.pro'] end end end
def read_file(file_path) File.read(file_path).split("\n") end def is_func?(line) if /(\w+)\*? +(\w+)\(.*\)/.match(line) == nil return false end true end def get_class_data(file_path) container = {} lines = read_file(file_path) class_name = "" lines.each { |line| if line.i...
class Category < ApplicationRecord belongs_to :space has_many :resources, dependent: :destroy attr_accessor :no_of_resources end
module Api module V1 class PostsController < ApplicationController def index posts = Post.order(created_at: :desc) new_posts = [] posts.each do |post| introduced_user_name = User.find(post.introduced_user_id).name post = { id: post.id, ...
#displays the blank board def display_board(board) puts " #{board[0]} | #{board[1]} | #{board[2]} " puts "-----------" puts " #{board[3]} | #{board[4]} | #{board[5]} " puts "-----------" puts " #{board[6]} | #{board[7]} | #{board[8]} " end #valid move method accepts two arguments, board and index d...
class RemovePriceImageFingerprintFromPrices < ActiveRecord::Migration def change remove_column :prices, :price_image_fingerprint end end
# -*- coding: utf-8 -*- class BabyBookPage < ActiveRecord::Base validates_presence_of :baby_book_id acts_as_list :scope=>:baby_book_id belongs_to :baby_book_layout, :foreign_key=>:layout_id belongs_to :baby_book,:counter_cache => true upload_column :logo,:process => '1024x1024',:versions => {:thumb600=>...
class Provider < ActiveRecord::Base has_many :credentials, :dependent => :destroy scope :with_auth, where(:has_auth => true) scope :with_photos, where(:has_photos => true) def to_param self.code end end
class RPNCalculator attr_reader :value def initialize @stack = [] @value = nil end def push(value) @stack.push(value) end def perform if @stack.length >= 2 and @value.nil? @value = yield @stack.pop, @stack.pop elsif @stack.length >= 1 and not @value.nil? @value = yield @va...
class FlabbleController < ApplicationController def index end def y @x = params[:x].to_i fail('Expected integer 1..100') unless (1..100).include?(@x) @options = ('a'..'z').map { |s| "#{@x}#{s}" } render layout: false end def z @y = params[:y] fail('Expected integer plus character') ...
class BooksController < HighlandController # GET /books def index @q = policy_scope(Book).ransack(params[:q]) @books = @q.result.page(params[:page]).per(@per_page) end # GET /books/1 def show end # GET /books/new def new @book.build_info end # GET /books/1/edit def edit end # ...
class RemoveDistilleryFromWhiskey < ActiveRecord::Migration def up remove_column :whiskeys, :distillery end def down add_column :whiskeys, :distillery, :string end end
class FixColumnName < ActiveRecord::Migration def change rename_column :reservations, :restaurant, :restaurant_id end end
#!/usr/bin/env ruby HOME = ENV['HOME'] TEXT = "/Volumes/Huluk/Documents" IMG = "/Volumes/Huluk/Pictures" IOTA = "i" # proper iota doesn't work :( def strip_prefix(str, prefix=/^\w+\-/) str.sub(prefix, '') end ARGV.each do |filepath| name = File.basename(filepath) destination = case name when /^\w{3}_P_...
# Ensures that an article is sent to a subscriber only once. Sending the article gets it committed to this table. # Regardless of what happens with the SentMail join-table(ie. subscribers being removed/added from an article), # SavedEmail will remember that at some point a given subscriber already received an email. Hm...
class Exercise < ActiveRecord::Base belongs_to :user validates :name, :user_id, :description, :presence => true validates :name, :description, :uniqueness => true end
require 'paysafe/result' module Paysafe class BirthDate < Result attributes :year, :month, :day def date @date ||= Date.new(year, month, day) end end end
require 'spec_helper' describe "cell_skeds/index.html.erb" do before(:each) do assign(:cell_skeds, [ stub_model(CellSked), stub_model(CellSked) ]) end it "renders a list of cell_skeds" do render end end
# frozen_string_literal: true require 'test_helper' class CommentInterfaceTest < ActionDispatch::IntegrationTest include ActiveJob::TestHelper setup do @user = users(:maymie) @friend = users(:ronny) @not_friend = users(:cole) @status_update = @user.status_updates.first @image = @user.images.f...