text stringlengths 10 2.61M |
|---|
class VisitsController < ApplicationController
before_action :find_visit, only: [:update]
def update
if @visit.update_attributes(visit_params)
@visit.update_procedures @visit.research_billing_qty, 'research_billing_qty'
@visit.update_procedures @visit.insurance_billing_qty, 'insurance_billing_qty'
... |
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:omniauthable, omniauth_providers: [:facebook,... |
# Source: https://launchschool.com/exercises/e0500589
# Write a method that takes a string, and then returns a hash that contains 3 entries: one represents the percentage of characters in the string that are lowercase letters, one the percentage of characters that are uppercase letters, and one the percentage of chara... |
require 'file_upload_cache/engine.rb'
require 'active_support/core_ext/module/attribute_accessors.rb'
require 'file_upload_cache/cached_attributes.rb'
require 'uuid'
module FileUploadCache
mattr_accessor :cache
def self.file_cache
if cache
cache
elsif defined?(Rails)
Rails.cache
else
... |
class CreateHotelDatePrices < ActiveRecord::Migration
def change
create_table :hotel_date_prices do |t|
t.date :date
t.float :price
t.integer :f2r_hotel_inventory_item_id
t.timestamps
end
end
end
|
class RouteArgument < ApplicationRecord
belongs_to :message_route, inverse_of: :route_arguments, optional: true
# validates_presence_of :message_route
validates_presence_of :key, :allow_blank => false
end
|
require 'Gosu'
require_relative '../Lives.rb'
require_relative '../bullet_types.rb'
require_relative 'being.rb'
class Player < Being
def initialize()
super
@sprite = Gosu::Image.new('../sprites/spaceship2.png')
#@engine_sfx = Gosu::Song.new('sfx/player/red_bullet_sfx.mp3')
#@explosi... |
# frozen_string_literal: true
require 'bolt/task/run'
module Bolt
class Plugin
class Module
class InvalidPluginData < Bolt::Plugin::PluginError
def initialize(msg, plugin)
msg = "Invalid Plugin Data for #{plugin}: #{msg}"
super(msg, 'bolt/invalid-plugin-data')
end
... |
require_relative '../lib/cart.rb'
describe Cart do
before do
@cart = Cart.new
end
context "第一種情境:不打折" do
it "第一集買 1 本" do
@cart.add({ "1st": 1, "2nd": 0, "3rd": 0, "4th": 0, "5th": 0 })
expect(@cart.calculate).to eq(100)
end
it "第一集買 3... |
class Programme < ActiveRecord::Base
validate :date_in_the_past
def date_in_the_past
errors.add(:date, "You can't choose a date in the past.") if
!date.blank? and date < Date.today
end
end
|
#Example 1
RSpec.describe "An Example Group with positive and negative Examples" do
context 'when testing Ruby\'s build-in math library' do
it 'can do normal numeric operations' do
expect(1 + 1).to eq(2)
end
it 'generates an error when expected' do
expect{1/0}.to raise_error(Zer... |
module Boris
module Structure
include Lumberjack
CATEGORIES = %w{
file_systems
hardware
hosted_shares
installed_applications
installed_patches
installed_services
local_user_groups
network_id
network_interfaces
operating_system
running_proc... |
require 'test_helper'
class EncontrosControllerTest < ActionDispatch::IntegrationTest
setup do
@encontro = encontros(:one)
end
test "should get index" do
get encontros_url
assert_response :success
end
test "should get new" do
get new_encontro_url
assert_response :success
end
test "... |
module CDI
module V1
module ServiceConcerns
module UserParams
extend ActiveSupport::Concern
WHITELIST_ATTRIBUTES = [
:first_name,
:last_name,
:birthday,
:gender,
:email,
:about,
:profile_type,
:password,
... |
require 'rails_helper'
RSpec.feature 'user', type: :feature do
given(:user) { build(:user) }
given(:login_user) { create(:user) }
given(:prototype) { build(:prototype, :with_sub_images) }
it 'creates new user', js: true do
visit root_path
page.save_screenshot 'sample.png'
click_on 'Get Started'
... |
# encoding: utf-8
module TextUtils
module Filter
# allow plugins/helpers; process source (including header) using erb
def erb( content, options={} )
puts " Running embedded Ruby (erb) code/helpers..."
content = ERB.new( content ).result( binding() )
content
end
end # module Filter
e... |
class Holopic < ActiveRecord::Base
#Interpolation
Paperclip.interpolates :file_name do |attachment, style|
"image_#{attachment.instance.id.to_s}"
end
# This method associates the attribute ":avatar" with a file attachment
has_attached_file :avatar, path: ":style/:file_name"
validates_attachment_conten... |
require_dependency 'hooks/change_header_color_hook'
Redmine::Plugin.register :redmine_change_header_color do
name 'Redmine Change Header Color plugin'
author 'Joe Naha'
description 'This is a plugin for changing header color by projects'
version '0.0.1'
url 'https://github.com/j5a/redmine_change_header_color... |
# write a method that returns an array that contains
# every other element of an array
# that is passed in as an argument
# the values in the returned list should be those values
# that are in the 1st, 3rd, 5th, and so on elements of the argument array
# Examples:
#
# oddities([2, 3, 4, 5, 6]) == [2, 4, 6]
# odditie... |
# What will each of the 4 puts statements print?
require 'date'
puts Date.new
# -4712-01-01 defaults to the Julian year
puts Date.new(2016)
# 2016, month - day defaults to 01
puts Date.new(2016, 5)
# 2016-05. day default
puts Date.new(2016, 5, 13)
# no default values |
# 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 rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Ch... |
class AddHeaderFieldsToParticipants < ActiveRecord::Migration
def change
add_column :participants, :recruitment_source, :string
add_column :participants, :external_id, :string
add_column :participants, :middle_initial, :string, limit: 1
end
end
|
module Effect
class CraftingRecipe
attr_reader :name
attr_reader :costs
attr_reader :catalysts
attr_reader :reagents
attr_reader :outputs
attr_reader :message
def initialize(parent, costs = nil, catalysts = nil, reagents = nil, outputs = nil, message = nil, name = nil)
@parent = parent
@costs = H... |
class Game < ActiveRecord::Base
before_create :set_vars
#takes a shot at the grid square specified by coord. if no coordinates are
#given, the cpu shoots at the player. returns a message and the shot location.
def shoot(*coord)
location = 0 #shot location
ships = '' #ship hitpoints
board = '' #boa... |
class NoteController < ApplicationController
def index
@notes = Note.all
end
def show
@note = Note.find(params[:id])
end
def new
@note = Note.new
end
def create
@note = Note.new(note_params)
if @note.try(:save)
flash.notice = '"#{@note.name}" has been created.'
# Belo... |
class RenameLineItemsCountToQuantity < ActiveRecord::Migration
def up
rename_column :line_items, :count, :quantity
change_column :line_items, :quantity, :decimal
change_column_default :line_items, :quantity, 0
LineItem.where(quantity: nil).each do |line_item|
line_item.update_column(:quantity, ... |
require 'data_mapper' unless defined?DataMapper
module Yito
module Model
module Booking
class BookingCategoryHistoric
include DataMapper::Resource
storage_names[:default] = 'bookds_categories_historics'
belongs_to :category, 'Yito::Model::Booking::BookingCategory',
... |
# frozen_string_literal: true
module HealthQuest
module PatientGeneratedData
module Patient
##
# A service object for querying the PGD for Patient resources.
#
# @!attribute headers
# @return [Hash]
class MapQuery
include PatientGeneratedData::FHIRClient
att... |
json.array!(@seats) do |seat|
json.extract! seat, :id, :user_id, :row, :seat, :section
json.url seat_url(seat, format: :json)
end
|
# -*- ruby -*-
module LAAG
VERSION = $LOADED_FEATURES
.map { |f| f.match %r{/laag-(?<version>[[:digit:]]+\.[[:digit:]]+\.[[:digit:]]+(\.pre)?)} }
.compact
.map { |gem| gem['version'] }
.uniq
.first
end
|
require 'spec_helper'
require 'hutch/worker'
describe Hutch::Worker do
let(:consumer) { double('Consumer', routing_keys: %w( a b c ),
get_queue_name: 'consumer', get_arguments: {},
get_options: {}, get_serializer: nil) }
let(:consumers) { [consumer, double('Consu... |
require_relative 'merchant'
require_relative 'csv_loader'
require_relative 'search'
class MerchantRepository
include CsvLoader
include Search
attr_reader :merchants
def initialize(csv_file_path, engine)
@merchants = create_merchants(csv_file_path, engine)
@engine = engine
return self
end
def... |
class CreateContainerKinds < ActiveRecord::Migration
def self.up
create_table :container_kinds do |t|
t.string :name
t.string :aka
t.boolean :can_contain_boxes
t.timestamps
end
end
def self.down
drop_table :container_kinds
end
end
|
class Planets
attr_accessor :name, :rotation_period, :orbital_period, :diameter, :climate, :gravity, :population
@@all = []
def initialize(name:, rotation_period:, orbital_period:, diameter:, climate:, gravity:, population:)
self.name = name
self.rotation_period = rotation_period
self.orbital_period = o... |
# frozen_string_literal: true
class TasksController < ApplicationController
def index
# Returns all tasks in order by id
@tasks = Task.order(id: :asc)
end
def filtered
# this is the task that have been filterd by the users input
@tasks = Task.where(tag: params[:tagsearch])
# if noting was e... |
class AddPackageRefToPackageItems < ActiveRecord::Migration[5.0]
def change
add_reference :package_items, :package, foreign_key: true
end
end
|
class AddMissingIndex < ActiveRecord::Migration
def change
add_index :texts, ["app", "context", "locale"]
end
end
|
class KatoRoomsController < ApplicationController
before_action :set_kato_room, only: [:show, :edit, :update, :destroy]
# GET /kato_rooms
# GET /kato_rooms.json
def index
@url =KatoAdHocExpress.setInfo( response, "EMxxK0z32ULskJgTKlgrouB6C9fDIjkXq92UPb1ICwk",3600, "1", "foo", "1", "bar")
respond_t... |
require_relative 'game'
class HumanPlayers
attr_accessor :guess
attr_reader :name, :game
def initialize(name)
@name = name
end
def guess
gets.chomp
end
def alert_invalid_guess
"Invalid play, try again. "
end
end
|
class Book < ActiveRecord::Base
before_save :generate_timestamp
validates :name, presence: true, uniqueness: true
mount_uploader :cover_image, BookImageUploader
def generate_timestamp
self.create_at = DateTime.now
end
end
|
require 'spec_helper'
module Fakebook
describe Cache::Persist do
it 'saves the item' do
item = Cache::Persist.new('me_fields_name', { :name => 'Jordan Rogers-Smith', id: 123456789 })
item.save
expect(Dir[@directory].empty?).to be false
end
it 'give subdirectory saves there' ... |
module SubmissionsHelper
def potentially_truncated_errors(submission)
submission.sheet_errors.any? { |_sheet_key, errors| errors.size >= 10 }
end
def submission_completed_text(task)
[
task.description,
"management information for #{task.framework.short_name} #{task.framework.name} submitted t... |
# -*- coding: utf-8 -*-
require 'spec_helper'
describe Follower do
before :all do
DB = db_connect 'test'
@model = Object.const_get('Follower')
@model.truncate
end
context 'save followers' do
before do
@source = [0,8,4,2,6]
end
it 'should save and restore dummy value' do
@mo... |
class AuthenticationController < ApplicationController
skip_before_action :authenticate_request, only: %i[login finding_user]
# POST /auth/login
def login
if params[:email].present?
# @user = User.find_by_email(params[:email])
@user = User.find_by("email ILIKE ?", "%#{params[:email]}%")
if @user && ... |
class CreateEntries < ActiveRecord::Migration[6.0]
def change
create_table :entries do |t|
t.date :date
t.string :feather
t.string :stone
t.belongs_to :user
t.timestamps
end
end
end
|
# 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 rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Ch... |
class CreateCategories < ActiveRecord::Migration
def change
create_table :categories do |t|
t.string :category_name1
t.string :category_name2
t.string :icon1
t.string :icon2
t.string :category_intro
# 1 : 중앙동아리 2 : 과 동아리
t.integer :category_flag
t.timestamps nul... |
require_relative '../../test_helper'
class CmsFixtureBlockTest < ActiveSupport::TestCase
def test_params
text = '{% cms_fixture id:header locale:en %} Hello World{% endcms_fixture %}'
template = Liquid::Template.parse(text)
tag = template.root.nodelist.detect { |t| t.params['id'] == 'header' }
asser... |
require 'minitest_helper'
describe FuzzyScanner do
before do
@fs = FuzzyScanner.new
@fs.regex = /([0 ][1-9]|1[012])[-\/.~X](0[1-9]|[12][0-9]|3[01])[-\/.~X]([0-9][0-9]$)/
end
describe "Fuzzily find matching text!" do
describe "finds the matches" do
it "finds perfectly matched t... |
module MessageSchemas
@cog_message_schema = {
"type" => "object",
"required" => ["patient_id", "status", "study_id"],
"properties" => {
"patient_id" => {"type" => "string", "minLength" => 1},
"study_id" => {"type" => "string", "minLength" => 1},
"status" => {"type" => ... |
require "rails_helper"
RSpec.describe User do
describe "Validations" do
it { should validate_uniqueness_of(:email) }
it { should validate_presence_of(:password) }
end
describe "Associations" do
it { should have_many(:links) }
end
describe "Methods" do
describe "#links_by_updated_at" do
... |
require 'test_helper'
class EndorsementsControllerTest < ActionDispatch::IntegrationTest
setup do
@endorsement = endorsements(:one)
end
test "should get index" do
get endorsements_url
assert_response :success
end
test "should get new" do
get new_endorsement_url
assert_response :success
... |
class CreateOpportunities < ActiveRecord::Migration[5.2]
def change
create_table :opportunities do |t|
t.string :sfdc_id
t.string :account_id
t.string :name
t.string :stage
t.string :batch
t.string :status
t.timestamps
end
end
end
|
class Category < ActiveHash::Base
self.data = [
{id: 1, name: '---'}, {id: 2, name: '小説・文学'}, {id: 3, name: '言語'},
{id: 4, name: '自己啓発'},{id: 5, name: 'ビジネス・経済'}, {id: 6, name: '自然科学'},
{id: 7, name: 'テクノロジー'}, {id: 8, name: '歴史・地理'},{id: 9, name: '専門書'}
]
end
#class Category < ApplicationRecord
... |
module Queries
NodeIdentification = GraphQL::Relay::GlobalNodeIdentification.define do
# Given a UUID & the query context,
# return the corresponding application object
object_from_id ->(id, _config) do
type_name, id = NodeIdentification.from_global_id(id)
return Viewer if id == ::Viewer.id
... |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module MobileCenterApi
module Models
#
# Model object.
#
#
class DistributionGroupUserDeleteResponse
# @return [String] T... |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module MobileCenterApi
module Models
#
# a single frame of a stack trace
#
class StackFrame
# @return [String] address of the... |
class Match < ApplicationRecord
belongs_to :loser, class_name: "Player"
belongs_to :winner, class_name: "Player"
end
|
class AddQuestionCommentToReviewQuestionInstance < ActiveRecord::Migration
def self.up
add_column :review_question_instances, :question_comment, :boolean, :default => false
end
def self.down
remove_column :review_question_instances, :question_comment
end
end
|
module TestBench
module Controls
module Path
def self.example
TestFile.filename
end
def self.alternate
TestFile::Alternate.filename
end
Directory = Controls::Directory
module TestFile
def self.example(filename: nil, text: nil, directory: nil)
... |
module ApplicationHelper
def paperclip_url(attachment)
#FixMe: Esto debe buscar la url actual
if Rails.env == "production"
"http://congresos.uach.mx#{attachment.url}"
elsif Rails.env == "development"
"http://localhost:3000#{attachment.url}"
end
end
def imagen?(nombre_archivo)
nomb... |
require 'spec_helper'
require File.expand_path "../../lib/injectable_rails_env", __FILE__
describe "InjectableRailsEnv" do
class Foo
include InjectableRailsEnv
end
let(:foo) { Foo.new }
# maybe not the best idea to meta progam tests but I'm lazy here :)
InjectableRailsEnv::SUPPORTED_ENVS.each do |nam... |
# For this practice problem, write a one-line program that creates the
# following output 10 times, with the subsequent line indented 1 space
# to the right:
10.times {|i| puts (" " * i) + "The Flintstones Rock!"} |
class Song
attr_accessor :name, :artist, :genre
@@all = []
def initialize (name, genre = nil)
@name = name
@genre = genre
save
end
def save
@@all << self
end
def artist_name
if self.artist != nil
self.artist.name
else
nil
end
end
def self.all
@@all
end
end
|
# Encoding: utf-8
class Pdp
include PageObject
page_url("#{BASE_URL}/the-sandringham-mid-length-heritage-trench-coat-p39004551")
h1(:title_bar, :css => '.titlebar-text')
# list_item(:description, :css => '.description')
h1(:itemName, :css => 'h1.titlebar-text')
div(:carousel, :css => '.js-carouse... |
class Api::V1::SessionsController < ApplicationController
def create
user = User.find_by(email: login_params[:email])
if user && user.authenticate(login_params[:password])
jwt = Auth.issue({user: user.id})
response = {
jwt: jwt,
id: user.id,
email: user.email,
name... |
# p044inverse.rb
def inverte(x)
raise ArgumentError, 'O argumento não é numérico.' unless x.is_a? Numeric
1.0 / x
end
puts inverte(2)
puts inverte('Não é um número.')
|
ImportPage::Engine.routes.draw do
root to: 'import#show'
resource :import, controller: 'import'
end
|
module Accessible
extend ActiveSupport::Concern
protected
def get_user
current_admin ? current_admin : current_user
end
end
|
class Report < ActiveRecord::Base
belongs_to :user
has_many :subscriptions, class_name: ScheduledReport, foreign_key: :report_id
visitable # Used to track user visit associated with processed report
def client_query
@_client_query ||= ProposalFieldedSearchQuery.new(query[user.client_model_slug])
end
... |
class Day11Solver < SolverBase
class Cell
attr_reader :x, :y, :power_level
def initialize(x, y, serial)
@x, @y = x + 1, y + 1
@serial = serial
init_power_level
end
def to_s
"cell(#{x}, #{y})"
end
private
def init_power_level
@rack_id = x + 10
@power... |
module CamaleonCms
module CaptchaHelper
# build a captcha image
# len: Number or characters to include in captcha (default 5)
def cama_captcha_build(len = 5)
img = MiniMagick::Image.open(File.join($camaleon_engine_dir.present? ? $camaleon_engine_dir : Rails.root.to_s,
... |
class Repository
include Mongoid::Document
field :name
embeds_many :users
validates_presence_of :name
def set_statistic(type, users_stats, period)
users_stats.each { |user, value|
user_model = users.find_or_create_by(login: user)
user_model.set_statistic(type, value, period)
}
end
... |
class App < Sinatra::Base
enable :logging
SHARED_SECRET = ENV['SHARED_SECRET']
post '/webhooks/order' do
hmac = request.env['HTTP_X_SHOPIFY_HMAC_SHA256']
request.body.rewind
data = request.body.read
halt 403, "You're not authorized to perform this action" unless verify_webhook(hmac, data)
... |
class RenameBaseQuestionsToGameQuestions < ActiveRecord::Migration
def change
rename_table :base_questions, :game_questions
remove_column :game_questions, :type
end
end
|
class ChangeDataTypesForScoresAndDistances < ActiveRecord::Migration
def up
change_column :exercises, :score, :decimal, :precision => 12, :scale => 7
change_column :bike_records, :distance, :decimal, :precision => 12, :scale => 7
change_column :run_records, :distance, :decimal, :precision => 12, :scale =>... |
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
require 'gettext/rails'
class ApplicationController < ActionController::Base
include AuthenticatedSystem
include RoleRequirementSystem
# You can move this i... |
require 'sidekiq'
require 'sidekiq-status'
class OneMoneyPublishWorker
include Sidekiq::Worker
include Sidekiq::Status::Worker
def perform(one_money_id, target, options = {})
default_options = {
sign_url: Settings.app.website + '/authorize/weixin',
api_url: '/api/promotions/one_money',
qr... |
class AddFieldsToInstance < ActiveRecord::Migration
def change
add_column :instances, :region_id, :integer
add_column :instances, :name, :string
end
end
|
class RemoveTimeToEvents < ActiveRecord::Migration[5.0]
def change
remove_column :events, :time, :string
remove_column :events, :month, :integer
remove_column :events, :day, :integer
add_column :events, :begin_time, :datetime
add_column :events, :end_time, :datetime
end
end
|
require 'rails_helper'
require_relative '../factories/cryptocurrencies.rb'
RSpec.describe Cryptocurrency, type: :model do
subject { create(:cryptocurrency) }
let(:pairs) { ['USD'] }
describe 'validations' do
describe 'name' do
it 'must be present' do
expect(subject).to be_valid
subjec... |
class Position < ActiveRecord::Base
has_and_belongs_to_many :authors
has_and_belongs_to_many :categories
has_many :bookings
def self.search(search)
if search
where(["title LIKE ?","%#{search}%"])
else
all
end
end
def first_possible_date
if self.bookings.empty?
return DateTime.now
end
fdat... |
class User < ApplicationRecord
has_many :jokes, dependent: :destroy
has_many :gigs, dependent: :destroy
has_many :clubs, through: :gigs
validates :name, :age, :user_name, :email, :hometown, presence: true
has_secure_password
def featured_jokes
test = self.jokes.max_by {|joke| joke.li... |
class ModifyCommentStoreId < ActiveRecord::Migration
def up
rename_column :comments, :store_id, :coupon_id
end
def down
rename_column :comments, :coupon_id, :store_id
end
end
|
class Person < ActiveRecord::Base
has_many :addresses
accepts_nested_attributes_for :addresses, allow_destroy: true
def full_name
self.name + " " + self.last_name
end
end
|
=begin
Skill Master Script
by Fomar0153
Version 1.0
----------------------
Notes
----------------------
Requires my unique classes script
Allows you to learn new skills by using your existing skills.
----------------------
Instructions
----------------------
You will need to edit module Skill_Uses, further instructions... |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe PersistentApiToken do
let(:token) { create(:persistent_api_token) }
it 'does not set an expiration date on create' do
expect(token.expires_at).to be_nil
end
it 'has the correct length token' do
expect(token.new_token.bytes.length).t... |
module ApplicationHelper
require 'rtesseract'
require 'java'
java_import java.lang.System
def sysout()
version = System.getProperties["java.runtime.version"]
version
end
def getTesseract()
image = RTesseract.new("niCherries.jpg")
image.to_s
end
d... |
# displayed: with/without
Then(/^I verify the 'Close Idea' popup is displayed "([^"]*)" the "([^"]*)" radio group$/) do |displayed, radiogroup_label|
within @viewideapage.closeidea_container do
if displayed == 'with'
within(:xpath,".//div[contains(@class,'pageTypeOptions')]") do
has_text?(radiogroup... |
module Vote
module Condorcet
module Schulze
class Classifications
def initialize(schulze_basic)
@schulze_basic = schulze_basic
end
# compute all possible solutions
# since this can take days, there is an option to limit the number of calculated classifications
... |
require 'open-uri'
module TradeEvent
class DlData
include Importable
include ::VersionableResource
attr_accessor :reject_if_ends_before
ENDPOINT = 'http://www.state.gov/rss/channels/dl.xml'
XPATHS = {
event_name: './title',
description: './description',
url: './link'... |
class WordAnalysis
def initialize (text)
@text = text
end
attr_reader :text
# I guess this isn't needed but I WROTE IT AND I'M LEAVING IT HERE
def word_number
text.split.size
end
def word_count
text.scan(/\w+/).inject(Hash.new(0)) { |h, c| h[c] += 1; h }
end
def letter_count
text.sc... |
require "exact_cover"
require "byebug"
ALPHABET = %w[a b c d e f g h i j k l m n o p q r s t u v w x y z .].freeze
DICTIONARY = File.read("wordlist.txt").split("\n").map(&:strip).map(&:downcase)
WORDS = (ALPHABET + DICTIONARY).uniq
W = 6 # cols
H = 5 # rows
def build_zeroes_array(size, one_index)
(0..size - 1).map ... |
class Review < ActiveRecord::Base
belongs_to :product
belongs_to :reviewer, class_name: 'User'
end
|
Rails.application.routes.draw do
root 'movies#index'
get '/directors/(:director)/all_movies', to: 'movies#director_all_movies', as: 'director_all_movies'
resources :movies
end
|
Then(/^I type "([^"]*)" in search field$/) do |arg|
find_element(id: "search_src_text").send_keys(arg)
end
Then(/^I press on search icon$/) do
find_element(id: "action_search").click
end
And(/^I press return button on soft keyboard$/) do
Appium::TouchAction.new.tap(x:0.99 , y:0.99, count: 1).perform
end
The... |
module Pm
module ARExt
module PmModelAttr
def model_attr
[["IsWeb", true],
["base", "HtmlModel"],
["modelNamespace", namespaces.join(".")],
["controltypeNamespace", "AWatir"]].build_ordered_hash
end
def automan_class_name
name
end
end
module Pm... |
class Purchase < ActiveRecord::Base
attr_accessible :date_purchased, :price_total, :reference, :user_id, :status
has_many :purchase_items, dependent: :destroy
has_many :ipn_logs, dependent: :destroy
belongs_to :user
def download_items
purchase_items.select { |purchase_item| purchase_item.product.format ... |
## Two Classes to Interface with the Yelp API
## Yelp Base Class.
class Yelp::Base
def initialize
end
## Authenticate from YAML file stored on "/config/api.yml"
def authenticate
api_config = YAML::load(File.read(Rails.root.to_s + "/config/api.yml"))
yelp = api_config['yelp']
consumer = OAu... |
class AddCorrectAndIncorrectAnswersToBirds < ActiveRecord::Migration[5.1]
def change
change_table :birds do |t|
t.integer :correct_answers
t.integer :incorrect_answers
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.