text
stringlengths
10
2.61M
module V1 module Services class Create < Base helpers V1::Params::Services desc I18n.t('api.v1.services.create.desc') do failure( [ { code: 400, message: I18n.t('api.code_400') }, { code: 422, message: I18n.t('api.code_422') } ] ) su...
module Jelastic class DockerNode < Node attr_accessor :cmd, :image, :links, :envs attr_reader :registry, :group DockerRegistry = Struct.new(:user, :password, :url) def initialize @type = 'docker' super end def as_application_server @group = 'cp' end def as_load_b...
polymer = File.read("../inputs/day5.in").strip.chars # polymer = "dabAcCaCBAcCcaDA".chars # codepoint difference between upper and lowercase letters is 32 CODEPOINT_DIFF = 32 def react polymer polymer = polymer.dup reduced = [] # Use stack a = polymer.shift reduced << a while !polymer.empty? # compare...
def test_place_ant_randomly(args, assert) ant = Ant.place_new(args) ant2 = Ant.place_new(args) assert.true! ant.position != ant2.position, 'position was same' assert.true! Ant.orientation(ant) != Ant.orientation(ant2), 'orientation was same' end def test_place_ant_with_values(args, assert) ant = Ant.place_n...
require 'spec_helper' describe BoardComment do describe "バリデーション" do it { should validate_presence_of :from } it { should validate_presence_of :body } it { should validate_presence_of(:board_id).with_message("の掲示板が見つかりません") } end describe "callback" do describe "before_save" do let(:board_...
class UsersController < ApplicationController def index @users = User.order(:email) end def new @user = User.new end def create User.create(params[:user]) redirect_to(users_path) end end
# contains methods for website elements class Element include RSpec::Matchers include Capybara::DSL # contructor to create a hash def initialize(type, value) @value = Hash[type: type, value: value] end # perfom functions with the hash value def find Capybara.find(@value[:type], @value[:value]) e...
if ENV['CI'] == 'true' require 'simplecov' SimpleCov.start require 'codecov' SimpleCov.formatter = SimpleCov::Formatter::Codecov end RSpec.configure do |config| config.expect_with :rspec do |expectations| expectations.include_chain_clauses_in_custom_matcher_descriptions = true end config.mock_with :...
require 'spec_helper' describe 'vmworld::default' do it 'installed the correct version of nginx' do if os[:release].to_i == 6 expect(package('nginx')).to be_installed.with_version('1.8.0-1.el6.ngx') elsif os[:release].to_i == 7 expect(package('nginx')).to be_installed.with_version('1.8.0-1.el7.ng...
# NoMethodError: undefined method `keys' for Array # This is because there is no method called keys for Arrays
class Book attr_writer :title def title words = @title.split(" ") unless @title.nil? if @title.nil? return "No title set yet. Please set a title first before calling this method" end words.map! do |word| if word == words[0] word.capitalize elsif word.match(/^a$|^a(n|nd)$...
class Reservation < ApplicationRecord belongs_to :user belongs_to :morty enum progress: { pending: 0, confirmation: 1, abordation: 2 } end
class Peep include DataMapper::Resource belongs_to :user has n, :responses property :id, Serial property :content, Text property :time, DateTime def display_time_format self.time.strftime("%H:%M, %d %b %y") end end
class FontPlayfairDisplay < Formula head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/playfairdisplay" desc "Playfair Display" homepage "https://fonts.google.com/specimen/Playfair+Display" def install (share/"fonts").install "PlayfairDisplay-Ita...
lane_johnson = PlayerCard.create do |card| card.first_name = 'Lane' card.last_name = 'Johnson' card.overall = 96 card.team_chemistry_id = Chemistry.by_team_city(:philadelphia).first.id card.program = POWER_UP_TIER_5 card.position ...
json.array!(@contacts) do |contact| json.extract! contact, :id, :name, :phone_no, :member_id json.url contact_url(contact, format: :json) end
class CreateDomains < ActiveRecord::Migration def change create_table :domains do |t| t.integer :user_id, :null => false, :default => 1 t.string :name, :null => false, :default => "" t.string :label, :null => false, :default => "" t.string :regex, :null => false, :default => "" t.integer...
desc 'Generate default Donut roles' task generate_roles: :environment do ['admin'].each do |role| puts "Generating role #{role}" Role.where(name: role).first_or_create end end
class Doctor < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable, # :registerable # commented out registerable to prevent users from creating accounts without # admin privileges devise :database_authenticatable,...
# frozen_string_literal: true module Api::V1::Admin::Coaches::Avatar class DestroyAction < ::Api::V1::BaseAction step :authorize try :find, catch: Sequel::NoMatchingRow map :destroy private def find(input) ::Coach.with_pk!(input.fetch(:coach_id)) end def destroy(coach) ::De...
class Project < ApplicationRecord validates :name, presence: true, uniqueness: true validates :client, presence: true end
class AddDatarecordToWind < ActiveRecord::Migration def change add_reference :winds, :datarecord, index: true add_foreign_key :winds, :datarecords end end
class Component < Asset include Assignable::Quantity multisearchable( against: [:name, :asset_tag, :serial], additional_attributes: ->(record) { { label: record.name } }, ) tracked resourcify scope :includes_associated, -> { includes([:manufacturer, :category, :vendor, :activities]) } end
module RTALogger # Logging severity. module SeverityLevel # all information that helps us to trace the processing of an incoming request through our application TRACE = 0 # Low-level information, mostly for developers. DEBUG = 1 # Generic (useful) information about system operation. ...
class Order < ActiveRecord::Base default_scope { order('created_at DESC') } scope :nowe, -> { where(status: 1)} #Zaakceptepowane przez wnioskującego scope :potw, -> { where(status: 2)} #Zaakceptowane przez Koordynator scope :abii, -> { where(status: 4)} #Zaakceptowane przez ABI scope :gou, -> { where(status: ...
class AddShortlinksToLinks < ActiveRecord::Migration def change add_column :links, :original_url, :string add_column :links, :shortlink, :string end end
#!/usr/bin/env ruby gem 'minitest', '>= 5.0.0' require 'minitest/autorun' require 'minitest/benchmark' require 'minitest/pride' require 'set' require_relative 'distinct_permutation' class DistinctPermutationTest < Minitest::Test def test_behaves_like_array_permutations_when_all_numbers_are_different # skip a...
class City < ActiveRecord::Base validates :name, :state_id, presence: true has_many :companies belongs_to :state end
require 'aws-sdk' require 'rest-client' class Chef::DataBagHelper def initialize @bucket = @node[:aws][:key_bucket] AWS.config(access_key_id: @node[:aws][:access_key], secret_access_key: @node[:aws][:secret_key]) end def s3 @s3 ||= AWS::S3.new end def generate_s3_url(path) ...
# frozen_string_literal: true module Tikkie module Api module Resources # Resource for a Payment Request Subscription. class PaymentRequestsSubscription < Base def subscription_id body[:subscriptionId] end private def create_resource(attributes) r...
class CreateContestInfos < ActiveRecord::Migration def self.up create_table :contest_infos do |t| t.string :name t.integer :grading t.datetime :sdate t.datetime :edate t.integer :tasks_count end end def self.down drop_table :contest_infos end end
class FilmCategory < ApplicationRecord self.table_name = "film_category" belongs_to :film belongs_to :category end
class SqlParser def self.sql_data_types # MySQL data types # http://www.w3schools.com/sql/sql_datatypes.asp types = 'char varchar tinytext text blob mediumtext mediumblob longtext longblob tinyint smallint mediumint int bigint float double decimal date datetime timestemp time year' @types = types.spl...
require 'spec_helper' describe 'java::oracle' do let(:chef_run) do runner = ChefSpec::ServerRunner.new runner.converge(described_recipe) end it 'should include the set_java_home recipe' do expect(chef_run).to include_recipe('java::set_java_home') end it 'should include the notify recipe' do ...
module NdrDevSupport module IntegrationTesting # ========================================================================== # # !! Caution - please read carefully !! # # This approach to connection sharing is known to be susceptible # to race conditions. Anecdotally, we've ...
class AddIndexToPutStamps < ActiveRecord::Migration def change add_index :put_stamps, :board_id add_index :put_stamps, :stamp_id end end
class AddColumnShortDescriptionToMealInfos < ActiveRecord::Migration def change add_column :meal_infos, :short_description, :string end end
require "spec_helper" describe Refunge::Cursor do attr_reader :cursor context "when moving left" do before(:each) do @cursor = described_class.new(10, 10) cursor.change_direction_to :left end context "when x is at 0" do it "should move to the end" do cursor.move! exp...
class Users::RegistrationsController < Devise::RegistrationsController def new build_resource({}) self.resource.account = Account.new respond_with self.resource end def create super end private def sign_up_params allow = [:email, :password, :password_confirmation, :account, ...
#!/usr/bin/env ruby require 'rubygems' require 'json' require "yaml" require 'open-uri' require 'cgi' require 'mp3info' POST_ORGANIZE = true CHECK_FILES = false AUTOTAG = true DESTINATION = "/Users/justin/Music/mp3_rape/" DEFAULT_ARTIST = "Unknown" DEFAULT_TRACK_NAME = "Untitled" DEFAULT_ALBUM ...
class PostSerializer < ActiveModel::Serializer attributes :id, :content, :user, :created_at def user object.user_id end end
# Try coding a method that allows you to multiply every array item by a specified value: def multiply(array, multiplier) out_array = [] index = 0 while index < array.size out_array << array[index] * multiplier index += 1 end out_array end my_numbers = [1, 4, 3, 7, 2, 6] p multiply(my_numbers, 3)
# == Schema Information # # Table name: messages # # id :integer not null, primary key # sender_id :integer # receiver_id :integer # body :text # created_at :datetime not null # updated_at :datetime not null # class Message < ApplicationRecord validates :sender_id, ...
class User < ApplicationRecord has_secure_password VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i validates :email, presence: true, uniqueness: true has_one :booking scope :admin, -> { where(admin: true )} before_save { self.email = email.downcase } validates :name, presence:...
Jekyll::Hooks.register :site, :post_write do |site| resources = site.config['site_resources'] resources.each { |r| Jekyll.logger.info "ResourcesCopy copy:", r['name'] src = Jekyll.sanitized_path(site.source, r['src_base']) Jekyll.logger.debug "ResourcesCopy source:", src f = Jekyll::StaticFile.new...
class FontSairaSemiCondensed < Formula head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/sairasemicondensed" desc "Saira Semi Condensed" homepage "https://fonts.google.com/specimen/Saira+Semi+Condensed" def install (share/"fonts").install "Saira...
class Transaction < ActiveRecord::Base include Filterable TYPE = %w( All Income Expense ) belongs_to :company belongs_to :transactionable, polymorphic: true scope :for_start_date, -> (start_date) { where('date >= ?', Date.parse(start_date)) } scope :for_end_date, -> (end_date) { where('date <= ?', Date....
class RemoveLifespanFromCategories < ActiveRecord::Migration def change remove_column :categories, :lifespan, :integer end end
class Club < ApplicationRecord has_many :players has_and_belongs_to_many :owners end
# # Cookbook Name:: git # Recipe:: source # # Copyright 2012, Brian Flad, Fletcher Nichol # # 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 # ...
require 'spec_helper' require 'belafonte/help/app_extensions' module Belafonte module Help describe AppExtensions do let(:simple) {Simple.new([]).extend(described_class)} let(:multi) {Multi.new([]).extend(described_class)} let(:unlimited) {Unlimited.new([]).extend(described_class)} let(:a...
class ProjectsController < ApplicationController include Filterable before_action :set_project, only: [:show, :edit, :update, :destroy] # GET /projects # GET /projects.json def index @projects_created = Project.where('user_id == ?', current_user.id) @projects_created = @projects_created.sta...
class ERB module Util def html_escape(s) s = s.to_s if s.html_safe? s else s.gsub(/[&"><]/) { |special| HTML_ESCAPE[special] }.html_safe end end alias h html_escape module_function :h module_function :html_escape end end
class Passenger < ActiveRecord::Base belongs_to :bookings validates :name, presence: true validates :email, presence: true end
class AddApprovedAtToApprovals < ActiveRecord::Migration def up add_column :approvals, :approved_at, :datetime execute <<-SQL UPDATE approvals SET approved_at = updated_at WHERE status = 'approved'; SQL end def down remove_column :approvals, :approved_at end end
class PortfolioItemsController < ApplicationController include ApplicationHelper before_action :authenticate_user!, except: [:zoomed_item] before_action :require_admin, except: [:zoomed_item] def new @portfolio_item = PortfolioItem.new end # TODO I don't think this even gets used (we use ActiveAdmin) ...
class AddIsHiddenToPhotos < ActiveRecord::Migration def change add_column :photos, :is_hidden, 'tinyint(1) unsigned', :null => false, :default => 0, :after => :is_visible end end
class NewslettersController < ApplicationController def index @newsletter = Newsletter.all end def create @newsletter = Newsletter.new(newsletter_params) if @newsletter.save flash[:success] = "Your e-mail was saved" else flash[:alert] = "Your e-mail was not saved" end end d...
# frozen_string_literal: true require 'spec_helper' require 'bolt/transport/local' require 'bolt/target' require 'bolt/inventory' require 'bolt/util' require 'bolt_spec/transport' require 'bolt_spec/conn' require 'shared_examples/transport' describe Bolt::Transport::Local do include BoltSpec::Transport let(:hos...
# frozen_string_literal: true require 'rails_helper' RSpec.describe User, type: :model do context 'valid Factory' do it 'has a valid factory' do expect(FactoryGirl.build(:user)).to be_valid end end context 'User from omniauth' do describe '.from_omniauth' do it 'is expected to be_valid' ...
require 'gon' class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :authenticate_user! before_action :configure_permitted_parameters, if: :devise_controller? before_action :add_abilities before_action :add_gon_variables helper_method :abilities, :can? ...
# frozen_string_literal: true RSpec.describe 'Checkin Premiere Request', type: :request do include_context 'with user token' include_context 'with user membership' include_context 'with json response' include_context 'with event' include_context 'with branch location' subject(:patch!) do post( "...
# frozen_string_literal: true require 'nokogiri' require 'uri' module MangaEdenRipper class Comic VALID_HOSTS = [ /mangaeden.com\z/ ].freeze MANGA_INFO_URL = 'https://www.mangaeden.com/api/manga/:id'.freeze def self.applies?(url) uri = URI.parse(url) VALID_HOSTS.any? { |pattern| p...
class Upload < ActiveRecord::Base validates_presence_of :user_id belongs_to :blog belongs_to :user has_attached_file :asset, :styles => { :thumb => ["64x64#", :jpg], :preview => ["200x", :jpg] }, :path => ":rails_root/public/images/u/assets/:class/:id/:style_:basename.:extens...
class StringWrapper MAX_LINE_LENGTH = 72 def initialize(indent_string, bullet) @indent_string= indent_string @bullet= bullet @first= true end def word_too_big(line, word) !line.empty? && line.length + word.length >= MAX_LINE_LENGTH end def wrap(s, nobreak= false) result= '' line= ...
class AddCodeToDdhOrders < ActiveRecord::Migration def self.up add_column :ddh_orders, :code, :string end def self.down end end
module Google class Shortner attr_accessor :short_url, :long_url def initialize(long_url) options = {"longUrl" => long_url}.inspect resp = Request.post('/urlshortener/v1/url', :body => options) if resp.code == 200 self.short_url = resp['id'] self.long_url ...
$:.push File.expand_path('../lib', __FILE__) # Maintain your gem's version: require 'has_searcher/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = 'has_searcher' s.version = HasSearcher::VERSION s.authors = ['Dmitry Lihachev'] s.email = ['l...
class CreateArticles < ActiveRecord::Migration[5.2] def change create_table :articles do |t| t.string :title t.string :subtitle t.text :main_article t.text :second_article t.string :writer t.string :photo_url t.string :photo t.string :second_photo t.timestamp...
class CreateProfileManagers < ActiveRecord::Migration[5.0] def change create_table :profile_managers do |t| t.references :user, foreign_key: true t.references :address, foreign_key: true t.references :contact, foreign_key: true t.references :rank, foreign_key: true t.references :skil...
class FamiliesController < ApplicationController def index @all_families = Family.all.by_last_name.limit(10) @active_families = Family.active.by_last_name.limit(10) @inactive_families = Family.inactive.by_last_name.limit(10) end def show @family = Family.find(params[:id]) end def new @fa...
feature "See hit points" do scenario "See player 2's hit points" do sign_in_and_play expect(page).to have_content "Two: 60HP" end end
class UsersController < ApplicationController before_action :set_user def show; end private def set_user @user ||= User.find_by(id: params[:id]) end def user_params params.require(:user).permit(:id) end end
class VentaController < ApplicationController before_action :set_ventum, only: [:show, :edit, :update, :destroy] # GET /venta # GET /venta.json def index @venta = Ventum.all end # GET /venta/1 # GET /venta/1.json def show @ventum.Costo=List.where( ventum_id: params[:id]).sum(:costo) @ventu...
# frozen_string_literal: true # Force the request headers to only accept JSON, and disable gzip. # This makes our VCR cassettes human readable. module RestClient class Request def default_headers FacebookAds::REQUEST_HEADERS end end end
require "spec_helper" describe "element node" do def build_single_element_node XPain::Builder.new do |xsd| xsd.schema do xsd.element "street", :type => "string" end end end it "should create a single element node" do schema = build_single_element_node schema.doc.xpath("//xsd...
module FluxHue module Discovery # Helpers for SSDP discovery of bridges. module SSDP def ssdp_scan! setup_ssdp_lib! Playful::SSDP .search("IpBridge") .select { |resp| ssdp_response?(resp) } .map { |resp| ssdp_extract(resp) } end # Loads the Play...
class FontGermaniaOne < Formula head "https://github.com/google/fonts/raw/main/ofl/germaniaone/GermaniaOne-Regular.ttf", verified: "github.com/google/fonts/" desc "Germania One" homepage "https://fonts.google.com/specimen/Germania+One" def install (share/"fonts").install "GermaniaOne-Regular.ttf" end te...
class ApplicationController < ActionController::Base protected def errors?(response) response.key?('errors') end end
module CamaleonCms class UniqValidator < ActiveModel::Validator def validate(record) return if record.skip_slug_validation? if CamaleonCms::TermTaxonomy.where(slug: record.slug).where.not(id: record.id).where("#{CamaleonCms::TermTaxonomy.table_name}.taxonomy" => record.taxonomy).where("#{CamaleonCms:...
class User::ParameterSanitizer < Devise::ParameterSanitizer private def account_update default_params.permit(:first_name, :last_name, :email, :password, :password_confirmation, :current_password) end end
# SteelyCms. # # Rails based Content Management System. # # Author:: Rafal Wicha (mailto:rafwic@gmail.com) # Copyright:: Rafal Wicha # The class handles Pages managment. class Admin::PagesController < Admin::BaseController # Kind of initializer. Sets and configure common values. def init @permitted_groups...
require_relative 'manufacturer' class Wagon include Manufacturer attr_reader :type def initialize(type) @type = type end end
class Homework < ActiveRecord::Base has_many :problems, dependent: :destroy accepts_nested_attributes_for :problems, :reject_if => :all_blank, :allow_destroy => true end
class Pokemon < ApplicationRecord belongs_to :trainer def generate_names self.nickname = Faker::Name.first_name self.species = Faker::Games::Pokemon.name end end
# == Schema Information # # Table name: events # # id :integer not null, primary key # agent_id :integer # title :string(255) # begin_time :datetime # end_time :datetime # short_description :text(65535) # description :text(65535) # created_at ...
class CreateOutflows < ActiveRecord::Migration def change create_table :outflows do |t| t.date :feha t.string :concepto t.integer :nit t.string :entidad t.integer :numero_factura t.decimal :valor t.timestamps null: false end end end
class CreateBookings < ActiveRecord::Migration def change create_table :bookings do |t| t.integer :check_in t.integer :check_out t.integer :num_of_people t.string :contract t.string :form_of_payment t.timestamps end end end
require_relative 'component_runner' class MysqlRunner < ComponentRunner def start_redis add_pid Process.spawn "redis-server #{asset "redis.conf"}", log_options(:redis) wait_for_tcp_ready("Redis", 5454) end def start(opts=nil) cleanup_mysql_dbs start_redis Dir.chdir("#{SPEC_ROOT}/../ng/mysql"...
FactoryGirl.define do factory :financial_ticket do emission_date "2017-09-30" due_date "2017-09-30" financial nil end end
class BiblioCommonsListContentMatch < ActiveRecord::Base include ContentMatch belongs_to :tweet belongs_to :biblio_commons_list_content_item attr_accessible :tweet, :biblio_commons_list_content_item validates :tweet, :biblio_commons_list_content_item, :presence => ...
class CreateArtistes < ActiveRecord::Migration[5.0] def change create_table :artistes do |t| t.string :pseudo t.integer :age t.integer :taille t.string :description t.timestamps end end end
class Buyer < ActiveRecord::Base has_secure_password validates :email, presence: true has_many :variants has_many :products, through: :variants end
class AddOriginNameToWines < ActiveRecord::Migration def change add_column :wines, :origin_name, :string end end
class AirsController < ApplicationController before_filter :get_form # GET /airs # GET /airs.xml def index @airs = [@form.air] respond_to do |format| format.html # index.html.erb format.xml { render :xml => @airs } end end # GET /airs/new # GET /airs/new.xml def new ...
require 'test_helper' class TopTracksControllerTest < ActionDispatch::IntegrationTest setup do @top_track = top_tracks(:one) end test "should get index" do get top_tracks_url assert_response :success end test "should get new" do get new_top_track_url assert_response :success end te...
class PagesController < ApplicationController def home @jobs = Job.all @my_jobs = @jobs.where(user_id:current_user) if params[:query].present? @jobs_address = Job.where("address ILIKE ?", "%#{params[:query]}%") @jobs_title = Job.where("title ILIKE ?", "%#{params[:query]}%") if @jobs_ad...
class User < ActiveRecord::Base has_secure_password validates :first_name, presence: true validates :last_name, presence: true validates :email, uniqueness: { case_sensitive: false }, presence: true validates :password, confirmation: true validates :password_confirmation, presence: true validates_length_...
class OmniauthController < ApplicationController skip_before_action :authenticate_user def callback user = User.find_or_create_from_auth(request.env['omniauth.auth']) log_in user redirect_to user, success: "Twitterでログインしました。" end end
require 'json' require 'date' class InvalidPeriodError < StandardError end class Car attr_reader :price_per_day, :price_per_km def initialize(cid, price_per_day, price_per_km) @cid = cid @price_per_day = price_per_day @price_per_km = price_per_km end end class Rental # Discount-priced intervals of days F...