text stringlengths 10 2.61M |
|---|
#!/usr/bin/env ruby
# Load the Rails environment in case:
# * config files contain references that require rails loading
# * initializers configure Cassie options or override behavior
# * other initialization is required for Cassie to connect correctly
rails_root = Dir.pwd
environment = File.expand_path("config/en... |
require_relative('./sql_runner.rb')
class Crud
# # relies on
# # - all object insance value name keys being strings (or symbols) matching column names
# # - all tables / objects having 'id' as primary key / instance variable, which is returned from database on saving
# # Possible Future enhancement
# put tabl... |
#Add remote data source and pull in stories from Reddit, Mashable and Digg.
# http://mashable.com/stories.json
# http://digg.com/api/news/popular.json
# These stories will also be upvoted based on our rules. No more user input!
# Pull the json, parse it and then make a new story hash out of each story(Title, Categ... |
class AdminsController < ApplicationController
before_filter :ensure_admin
def ensure_admin
unless current_user && current_user.admin?
flash[:danger] = 'Access Denied'
redirect_to root_path
end
end
end
|
class Product
include Mongoid::Document
field :name, type: String
field :type, type: String
field :length, type: Integer
field :width, type: Integer
field :height, type: Integer
field :weight, type: Integer
validates :name, :type, :length, :width, :height, :weight, presence: true
... |
class ProductSerializer < ActiveModel::Serializer
attributes :id, :name, :total_purchased, :lowest_price, :most_recently_puchased, :highest_price
# def user
# @user ||= instance_options.first
# end
def total_purchased
user = instance_options[:option_name]
object.total_purchased_by_user(user)
end
... |
class FeatureFlag < ApplicationRecord
validates :flag, presence: true, uniqueness: true
validates :enabled, inclusion: { in: [true, false] }
def self.enabled?(flag)
feature = self.find_by(flag: flag)
if feature
feature.enabled
else
false
end
end
end
|
class NotImplentedError < StandardError
def initialize(msg="Must be implemented in subclass")
super
end
end
module HerokuJobGovernator
module Interfaces
class Interface
def self.enqueued_jobs(_queue)
raise NotImplentedError
end
end
end
end
|
# Generalized queue. Design a generalized queue data type that supports all of
# the following operations in logarithmic time (or better) in the worst case.
# Create an empty data structure.
# Append an item to the end of the queue.
# Remove an item from the front of the queue.
# Return the ith item in the queue.
# Re... |
class Ability
include CanCan::Ability
def initialize(user)
cannot [:read, :create, :update, :destroy], [Continent, Country, User, Temple]
admin(user)
end
def admin(user)
return unless user.admin
can [:read, :create, :update, :destroy], [Continent, Country, User, Temple]
end
end
|
class Review < ActiveRecord::Base
belongs_to :title
belongs_to :user
attr_accessor :d_user_id, :d_title_id
before_validation( :set_title_and_user , :on => :create )
validates :title_id, :presence => true, :uniqueness => {:scope => :user_id}
validates :user_id, :presence => true
validate :heading, :length ... |
# Design the data structures for a generic deck of cards. Explain how you would
# subclass the data structures to implement blackjack.
SUITS = [:clubs, :diamonds, :hearts, :spades]
VALUES = ["A",2,3,4,5,6,7,8,9,10,"J","Q","K"]
class Card
attr_reader :value, :suit
def initialize(value, suit)
raise "Invalid Suit... |
#!/usr/bin/ruby
class TextEditor
attr_reader :text
def initialize(array)
@text = array
end
def crypt_text
@text.map! {|string| change_str(string)}
end
def decrypt_text
@text.map! {|string| change_str_back(string)}
end
def remove_word(str)
@text.select... |
require 'fileutils'
class ProjectsController < ApplicationController
before_filter :authorize
def index
@projects = Project.active
end
def show
@project = Project.find(params[:id])
@locale = @project.locale(params[:locale_id])
if stale? :etag => @project.etag
@localizations = @project.l... |
class SockSerializer < ActiveModel::Serializer
attributes :id, :title, :body, :latitude, :longitude
def latitude
object.latitude.to_f
end
def longitude
object.longitude.to_f
end
end
|
require 'spec_helper'
describe Album do
it "should have basic information" do
album =Album.create()
album.should respond_to :title
album.should respond_to :description
album.should respond_to :year
album.should respond_to :total_tracks
album.should respond_to :art
end
it 'has many songs t... |
class TrainingSeeder
attr_accessor :training
def seed
@created_session_ids = []
training_spreadsheet.worksheets.each do |worksheet|
seed_training_from_worksheet worksheet
end
special_progressions
cleanup_stale
check
end
private
def cleanup_stale
Session.where('id NOT IN ... |
class CountValidator < ::ActiveModel::EachValidator
def validate_each(record, attribute, value)
if (!value.nil? && options.include?(:allow_blank))
if options.include? :limit
if value.length > options[:limit]
message = options[:message] || "can have maximum of #{ options[:limit] }"
... |
class Genre < ActiveRecord::Base
has_many :songs
has_many :artists, through: :songs
def song_count
all_songs = Song.select { |s|
s.genre == self
}.length
# self.songs.count
# return the number of songs in a genre
end
def all_artists
all_songs = Song.select { |s|
s.genre == s... |
require 'spec_helper'
describe Seedify::ParamValue do
let(:options) { { } }
subject { Seedify::ParamValue.get(:seedify_param, options) }
it { is_expected.to eq nil }
context 'with default' do
let(:options) { { default: 'x' } }
it { is_expected.to eq 'x' }
end
context 'with type :integer' do
... |
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :car do
color "red"
year 2010
mileage 3000
description "Awesome BMW ride"
manufacturer
end
end
|
class Namechangeagain < ActiveRecord::Migration
def change
change_column :isolates, :varianthash, :string
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :configure_permitted_parameters, if: :devise_controller?
# before_action :check_for_printer -- if current user is a printer, redirect to custom_printer form
# byebug
# before_action :check_... |
class ApplicationController < ActionController::API
before_filter :cors_preflight_check
after_filter :cors_set_access_control_headers
def cors_set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*' #TODO: Specify permitted domains
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPT... |
class ApplicationController < ActionController::Base
include SessionsHelper
layout "layouts/user_layouts/application"
before_action :set_locale
def after_sign_in_path_for _resource
current_user.customer? ? root_url : rails_admin.dashboard_path
end
private
rescue_from CanCan::AccessDenied do
ren... |
# encoding: utf-8
class Document
include DataMapper::Resource
storage_names[:default] = 'documents'
property :id, Serial
property :name, String, :required => true
property :tags, String
property :description, String
property :rights, Boolean, :default => true
property :user_id, Integer
belongs_to ... |
class Character < ApplicationRecord
RACES = ["Human", "Elf", "Dwarf", "Gnome", "Ent", "Custom"]
CULTURES = ["Cryogen", "Venthos", "Sengra", "Illumen/Lumiend", "Shaiden/Om'Oihanna", "Illugar/Unan Gens", "Shaigar/Alkon'Gol", "Hella", "Thundermark", "Minor", "Custom"]
# (1..50).each { |i| EXP_CHART << EXP_CHART[i-1]... |
#!/usr/bin/ruby
require 'stringio'
require 'set'
class Token
attr_reader :type, :line, :col
def initialize(type,lineNum,colNum)
@type = type
@line = lineNum
@col = colNum
end
end
class LexicalToken < Token
attr_reader :lex
def initialize(type,lex,lineNum,colNum)
super(type,lineNum,colN... |
require File.dirname(__FILE__) + "/../../spec_helper"
describe Admins::GroupsController do
let(:group) { mock_model(Group) }
before{ login_as(:admin) }
context "GET index" do
it "" do
# Group.should_receive(:paginate).and_return([group])
get :index
response.should render_template(:index)... |
class Data
attr_reader :x
def initialize(i)
@x = i
end
end
|
Vagrant.configure("2") do |config|
config.vm.box = "generic/debian10"
config.vm.network "forwarded_port", guest: 3000, host: 3000, auto_correct: true
config.vm.network "forwarded_port", guest: 5672, host: 5672, auto_correct: true
config.vm.network "forwarded_port", guest: 5984, host: 5984, auto_correct: true
... |
#!/usr/bin/env ruby
#
# Generate some test data
#
require 'Date'
SIZE = 100000
USERS = %w( Jannette Kiana Cary Tyree Harriet Hugo Randal Osvaldo Joeann Katina Minna Tammie Tajuana Bobbye Tami Carina Penni Shanon Maritza Deloras Magda Ai Ashly Francina Janyce Hassie Maya Dorethea Danyelle Chante Tobie Curt Genny Dodie ... |
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "jquery-cookie-rails"
s.version = "1.3.1.1"
s.required_rubygems_version = Gem::Requirement.new(">= 1.3.6") if s.respond_to? :required_rubygems_version=
s.authors = ["Ryan Scott Lewis"]
s.date = "2013-09-24"
s.description = "This gem provides... |
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe SrpmsController do
describe "routing" do
it "should route /Sisyphus/srpms/glibc to srpms#show" do
{ :get => "/Sisyphus/srpms/glibc" }.should route_to(:controller => 'srpms',
... |
require 'hashie/mash'
module OmniAuth
class AuthHash < Hashie::Mash
# Tells you if this is considered to be a valid
# OmniAuth AuthHash. The requirements for that
# are that it has a provider name, a uid, and a
# valid user_info hash. See UserInfo#valid? for
# more details there.
def val... |
# represent a job posted by employer member
class EmployerInitiatedServiceEvent < WorkspaceStatusEvent
CNAME = 'employer_initiated_service_event'
belongs_to :member
def display
I18n.t("workspaces.events.#{CNAME}", :employer => self.workspace.employer.username, :freelancer => self.workspace.freelancer.usern... |
require_relative '../config/environment.rb'
prompt = TTY::Prompt.new
def trainer_creation
prompt = TTY::Prompt.new
print TTY::Box.frame "Please enter your account information:", padding: 1, align: :center
name = prompt.ask('What is your name?', required: true)
age = prompt.ask('How old are you?', requ... |
module CDI
module V1
module PageStructure
class ModelSerializer::CyclePlanningSerializer < ActiveModel::Serializer
attributes :learning_cycle_id
end
end
end
end |
#Animated Battlers v1.0
#----------#
#Features: Allows you to mostly uneasily incorporate animated battlers into
# your game for that cooler and more polished look! You'll be able
# to decide individual sprite animations and more complicated skill
# animations.
#
#Usage: Plug and play, ... |
# 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... |
#!/usr/bin/env ruby
##
## spreadsheet.rb
##
## This demos shows how you can simulate a 3D table
## and has other basic features to begin a basic spreadsheet
##
## ( based on 'spreadsheet.tcl' included source archive of tktable extension )
##
require 'tk'
require 'tkextlib/tktable'
rows = 10
cols = 10
cur_var = TkVari... |
# frozen_string_literal: true
Rails.application.routes.draw do
get 'password_resets/new'
post 'password_resets/edit',as:"edit_password_reset_url"
get '/login_form' => 'sessions#new'
post '/login' => 'sessions#create'
delete '/logout' => 'sessions#destroy'
resources :account_activations, only: [:e... |
module FileControl::Test
extend self
def setup
RSpec.configure do |c|
c.before(:each){
FileControl::Test.setup_dirs
FileControl.root_path = FileControl::Test.root_path
}
c.after(:each){ FileControl::Test.clean! }
end # /rspec
end
def root_path
File.join(Maria::... |
# encoding: UTF-8
# Copyright 2012 Twitter, Inc
# http://www.apache.org/licenses/LICENSE-2.0
require 'spec_helper'
describe TwitterCldr::Parsers::UnicodeRegexParser::Literal do
describe "#to_set" do
it "should return literal characters as codepoints" do
literal = described_class.new("a")
expect(lit... |
require 'test_helper'
class JournalFavoritesControllerTest < ActionController::TestCase
setup do
setup_json_api
setup_default_profiles
@profile = @dragon
@user = @profile.user
@journal = journals(:dragon_journal_1)
end
test "fave journal" do
login_user
set_profile
assert_differe... |
# kinda a buffer, everything flows through discussions
class Discussion < ApplicationRecord
# discussion belongs_to a channel and a user in db/schema.rb
belongs_to :channel
belongs_to :user
has_many :replies, dependent: :destroy
# validates hooks into the title and content parameter of a discussion
# wont a... |
require "pg"
class TodoDbStorage
BASE_CONN_INFO = {
host: "localhost",
port: 5432,
user: "postgres",
password: "kohei",
}
TABLE_NAME = "todos"
@@conn = nil
def initialize(db_name)
create_db_if_not_exist(db_name)
@@conn = PG.connect(BASE_CONN_INFO.merge(dbname: db_name))
end
def... |
require 'spec_helper'
require 'liger_engine/search_strategies/search_strategy'
describe LigerEngine::SearchStrategies::PubmedSearchStrategy do
it_should_behave_like 'A Search Strategy'
before(:each) do
@strategy = LigerEngine::SearchStrategies::PubmedSearchStrategy.new
@query = 'biodiversity_informatics... |
require 'spec helper'
describe "Authentication" do
subject { page }
describe "signin" do
before { visit signin_path }
describe "with invalid information" do
let(:user) { FactoryGirl.create(:user) }
before { sign in user }
it { should have selector('title', text: user.name) }
it { should have link('Profi... |
require 'spec_helper'
module Naf
describe Affinity do
let!(:normal) { FactoryGirl.create(:normal_affinity) }
let(:canary) { FactoryGirl.create(:canary_affinity) }
let(:perennial) { FactoryGirl.create(:perennial_affinity) }
let!(:machine) { FactoryGirl.create(:machine) }
let!(:machine_classificati... |
require 'test_helper'
class RelationshipsTest < Minitest::Spec
class Order < TestModel
attr_accessor :customer
attr_writer :products
def products
@products ||= []
end
end
class Customer < TestModel
attr_accessor :name
end
class Product < TestModel
attr_accessor :name
end
... |
require 'rails_helper'
def stub_omniauth
OmniAuth.config.test_mode = true
OmniAuth.config.mock_auth[:google] = OmniAuth::AuthHash.new({
provider: "google",
uid: "12345678910",
info: {
email: "mimi@mountainmantechnologies.com",
},
credentials: {
token: "abcdefg12345",
... |
class MoviesController < ApplicationController
before_action :find_movie, :only => [:show, :edit, :update, :destroy]
# before_action :find_movie, :except => [:index, :create, :new]
def find_movie
@movie = Movie.find_by(id: params["id"])
end
def index
if params["keyword"].present?
@movies = Mo... |
#!/usr/bin/env ruby
##
## buttons.rb
##
## demonstrates the simulation of a button array
##
## ( based on 'buttons.tcl' included source archive of tktable extension )
##
require 'tk'
require 'tkextlib/tktable'
# create the table
tab = TkVariable.new_hash
rows = 20
cols = 20
table = Tk::TkTable.new(:rows=>rows + 1, :... |
# frozen_string_literal: true
# Authorizations for transactions
class TransactionPolicy < ApplicationPolicy
def update?
record_belongs_to_user?
end
def destroy?
record_belongs_to_user?
end
end
|
class CreatePersonalInformations < ActiveRecord::Migration[5.0]
def change
create_table :personal_informations do |t|
t.string :last_name, null: false
t.string :first_name, null: false
t.string :last_name_k, null: false
t.string :first_name_k, null: false
t.integer :prefecture
... |
class Post < ApplicationRecord
searchkick suggest: [:text]
self.per_page = 10
belongs_to :user
has_many :comments, as: :commentable, dependent: :destroy
has_many :likes, as: :likeable, dependent: :destroy
has_many :reports, as: :reportable, dependent: :destroy
accepts_nested_attributes_for :comments, allo... |
class RemoveIntentFromAnswer < ActiveRecord::Migration[5.0]
def change
remove_reference :answers, :intent, foreign_key: true
end
end
|
# frozen_string_literal: true
# !/usr/bin/env ruby
require_relative '../lib/gamelogic'
require_relative '../lib/players'
class UserInterface
def initialize
@again = nil
@player = Players.new
@game = GameLogic.new
end
def display_instructions
puts '*' * 50
puts 'Welcome To Our Tic-Tac-Toe Gam... |
require 'danger/danger_core/environment_manager'
describe Danger::Dangerfile::DSL do
describe '#import' do
before do
file = make_temp_file('')
env = Danger::EnvironmentManager.new({ 'HAS_JOSH_K_SEAL_OF_APPROVAL' => 'true', 'TRAVIS_REPO_SLUG' => 'KrauseFx/fastlane', 'TRAVIS_PULL_REQUEST' => '12' })
... |
require 'test_helper'
class Robut::PluginTest < Test::Unit::TestCase
class HandrolledStubPlugin
include Robut::Plugin
match /^message sent to robut with anchor (\w+)/, :sent_to_me => true do |word|
reply word
end
match /^another message sent to robut with anchor (\w+)/, :sent_to_me => true d... |
module GameEngine
public
FILE_NAME = "score.txt".freeze
def open_file
puts File.open(FILE_NAME, "r", &:read)
end
def create_or_append_file(data)
File.open(FILE_NAME, "a+") do |file|
file.puts(data)
end
end
end
class String
def colorize(color_code)
"\e[#{color_code}m#{self}\e[0m"
... |
def prime?(prime_number)
start = 2
if prime_number > 1
range = (start..prime_number-1).to_a
range.none? do |num_to_test|
prime_number % num_to_test == 0
end
else
false
end
end |
class CreateBusinesses < ActiveRecord::Migration
def change
create_table :businesses do |t|
t.string :name
t.text :address
t.string :city
t.integer :user_id
end
add_column :businesses, :created_at, :timestamptz
add_column :businesses, :updated_at, :timestamptz
ad... |
# 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... |
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
require 'authorization.rb'
class ApplicationController < ActionController::Base
include Authorization::ControllerMixin
helper :all # include all helpers, all the... |
module Ai
class Gene
attr_reader :tile, :score, :blank
attr_accessor :value
def initialize data = Hash.new
@tile = data[:tile]
@score = data[:score]
@blank = data[:blank]
@value = data[:value]
end
def flatten
ret = Array.new
@tile.each do |row|
ret.concat row
end
ret.push @score... |
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'qless/threaded_worker/version'
Gem::Specification.new do |gem|
gem.name = "qless-threaded_worker"
gem.version = Qless::ThreadedWorker::VERSION
gem.authors = [... |
class CadresController < ApplicationController
allow_access :authenticated
before_filter :find_cadre, only: [:show, :edit, :update]
def index
@cadres = Cadre.all
end
def new
@cadre = Cadre.new
end
def create
@cadre = Cadre.new cadre_params
if @cadre.save
redirect_to cadre_url(@cad... |
# -*- encoding : utf-8 -*-
class ApplicationController < ActionController::Base
protect_from_forgery
rescue_from CanCan::AccessDenied do |exception|
render :layout=>nil,:file => "#{Rails.root}/public/403.html", :status => 403
end
protected
def current_ability
@current_ability ||= Ability.new(current... |
module QML
# The JSObject represents JavaScript objects.
class JSObject
alias_method :each, :each_pair
# @return [Array<String>]
def keys
each.map { |k, v| k }
end
# @return [Array]
def values
each.map { |k, v| v }
end
# @return [Hash]
def to_hash
{}.tap do ... |
class CreateFamiliesStreets < ActiveRecord::Migration[6.0]
def change
create_table :families_streets do |t|
t.references :families
t.references :streets
t.timestamps
end
end
end
|
class AddInvitableToEventInvitees < ActiveRecord::Migration
def up
add_column :event_invitees, :invitable_type, :string
add_column :event_invitees, :inviter_id, :integer
rename_column :event_invitees, :event_id, :invitable_id
rename_column :event_invitees, :user_id, :invitee_id
end
def down
... |
module Archiver
class TweetCreator
def initialize(twitter_tweet, parser: TweetParser)
@twitter_tweet = twitter_tweet
@parser = parser
end
def create
tweet = Tweet.new(@parser.parse(@twitter_tweet))
TweetUserCreator.new(tweet).create
tweet.save
FeedItemCreator.new(tweet... |
module ASCIIToons
class Art
attr_accessor :message_sentinel, :message_callout_symbol, :message_callout_sentinel, :alignment
def initialize(template)
@alignment = :center
parse File.read(template)
end
def print(message = nil)
if message
# Create a clean slate for the body bu... |
#!/usr/bin/env ruby
USAGE = <<~USAGE
bin/mirror --all
Mirror all NPM packages, gracefully resuming via tmp/sequence
bin/mirror PACKAGE...
Mirror specific package name(s), like `jquery`
bin/mirror --deps PACKAGE...
mirror the specified packages names plus all dependencies, recursively
USAGE
req... |
class User < ActiveRecord::Base
has_many :user_iteration_review_ships, dependent: :destroy
has_many :iteration_reviews, through: :user_iteration_review_ships
has_many :user_message_ships, dependent: :destroy
has_many :messages, :through => :user_message_ships
end
|
class Genre
attr_reader :name
@@all = []
def initialize(name)
@name = name
@@all << self
end
def self.all
@@all
end
def songs
Song.all.select do |sag|
sag.genre == self
end
end
def artists
self.songs.map do |genre... |
# frozen_string_literal: true
module NewDawn
Container.boot(:vehicles) do
init do
require 'new_dawn/vehicles/events'
use :event_bus
Vehicles::Events.register_events(event_bus)
end
start do
Vehicles::Events.subscribe_to_events(event_bus)
end
end
end
|
class MessagesController < ApplicationController
def create
@message = Message.new(message_params)
@message.user_id = current_user.id
@message.event_id = params[:id]
@message.save!
redirect_to messages_path(params[:id])
end
private
def message_params
params.require(:message... |
# encoding: utf-8
class Version < ActiveRecord::Base
# Attributes
attr_accessible :content, :published
# Associations
belongs_to :localization
# Validations
validates_presence_of :localization_id
# Callbacks
before_validation :set_number, :on => :create
after_create :update_localization
after_cre... |
require_relative "comment"
class PullRequest
def initialize(data)
@data = data
end
def data
@data
end
def url
data["html_url"]
end
def base_repo_html_url
data["base"]["repo"]["html_url"]
end
def title
data['title']
end
def created_at
Time.parse(data['created_at'])
e... |
FactoryGirl.define do
factory :country do
name_en 'Germany'
country_code 'DE'
end
factory :germany, parent: :country
factory :ghana, parent: :country do
name_en 'Ghana'
country_code 'GH'
end
end
|
#!/usr/bin/env ruby
# (c) Copyright 2016 Thoughtgang <http://www.thoughtgang.org>
# Utility for adding a Note to a repository
require 'plan-r/application/cli'
require 'plan-r/repo'
require 'plan-r/document/note'
class App < PlanR::CliApplication
def handle_options(args)
@options.repo = nil
@options.dest =... |
class ChangePrice < ActiveRecord::Migration[5.2]
def change
remove_column :courses, :price
add_column :courses, :price, :text
end
end
|
Spree::Core::Engine.add_routes do
# Add your extension routes here
Spree::Core::Engine.routes.draw do
namespace :admin do
resources :banners
end
namespace :api, defaults: { format: 'json' } do
namespace :v1 do
resources :index, only: [:index]
resources :banners, only: [:inde... |
name 'python'
maintainer 'Roland Moriz'
maintainer_email 'info+github@moriz.de'
license 'Apache 2.0'
description 'Installs Python, pip and virtualenv. Includes LWRPs for managing Python packages with `pip` and `virtualenv` isolated Python environments.'
version '2.0.0'
depends 'build-essential'
depends 'yum-epel'
rec... |
require 'tinny'
require 'distance_utils'
module Tinny
class CoordDistanceCalculator
attr_reader :distance, :measurement
def initialize(distance, measurement)
@distance = distance
@measurement = measurement
end
def completed_distance?(starting_lat_long, current_lat_long)
current_di... |
#!/usr/bin/env ruby
require 'base64'
require 'optparse'
require 'pp'
require 'socket'
require 'helper_methods'
@options = {}
DEFAULT_PORT = 8080
include Helpers
# Parse arguments
OptionParser.new do |opts|
opts.banner = "Usage: wos.rb [options]"
opts.on("-v", "--verbose", "Be verbose") do |v|
@options[:verb... |
#Given a stream of objects, find first unique object
#If stream is A B C A B C A D => First unique char is D. If stream is A B C => first unique char is A
#Approach => Store each char in hash map, create a node in doubly linked list and store its value in hash
#If repeated, we can remove it from the list and update no... |
# Copyright 2007-2014 Greg Hurrell. All rights reserved.
# Licensed under the terms of the BSD 2-clause license.
require 'walrat'
module Walrat
class LeftRecursionException < Exception
attr_accessor :continuation
def initialize continuation = nil
super self.class.to_s
@continuation = continuati... |
class CreatePitchEvents < ActiveRecord::Migration[5.0]
def change
create_table :pitch_events do |t|
t.integer :game_id
t.integer :season_id
t.string :game_date
t.integer :year
t.string :sv_pitch_id
t.integer :at_bat_number
t.integer :pitch_number
t.integer :inning... |
module Goaler
class Main
attr_reader :user
def initialize(user, options)
@user = user
@options = options
@options[:base_date] = if options[:base_date]
DateTime.parse options[:base_date]
else
DateTime... |
class AutoP
def self.process(path = "_posts")
end
attr_accessor :contents
def initialize(contents)
@contents = contents
end
def process
syntax_block = false
contents.split("\n").each do |line|
# Skip lines with tags
next if line =~ /^<.*?>/
# Mark syntax blocks as such
... |
# frozen_string_literal: true
class CreateWorkLogs < ActiveRecord::Migration[6.0]
def change
create_table :work_logs do |t|
t.datetime :start
t.datetime :end
t.string :status
t.integer :user_id
t.jsonb :pending_edits
t.timestamps
end
add_index :work_logs, %i[user_id ... |
class RemoveStateFromHabits < ActiveRecord::Migration[5.2]
def change
remove_column :habits, :state
end
end
|
# frozen_string_literal: true
module Lib
class InProcessStore
def initialize
@index = {}
@lock = Concurrent::ReadWriteLock.new
@queries = {}
@referenced_by = []
@triggers = {}
end
def read
@lock.with_read_lock do
yield @index
end
end
def get i... |
class AddFieldsToInternets < ActiveRecord::Migration
def change
add_reference :internets, :cliente, index: true, foreign_key: true
end
end
|
class User < ActiveRecord::Base
has_many :photos, as: :imageable
has_many :favorited_relationships
has_many :favorite_restaurants, through: :favorited_relationships, source: :restaurant
validates :name, presence: true
validates :email, presence: true
validates :password, presence: true
validates_uniqueness_o... |
class AnalysesController < ApplicationController
before_action :set_analysis, only: [:show, :edit, :update, :destroy]
# GET /analyses
# GET /analyses.json
def index
@analyses = Analysis.all
end
# GET /analyses/1
# GET /analyses/1.json
def show
end
# GET /analyses/new
def new
@analysis =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.