text stringlengths 10 2.61M |
|---|
class Age < ActiveRecord::Migration
def self.up
change_table :users do |t|
t.integer "age", :default => 0
end
end
def self.down
remove_column :users, :age
end
end
|
class TrainersController < ApplicationController
def index
@trainers = Trainer.all
jawn = @trainers.map do |trainer|
poke = {id: trainer.id, name: trainer.name, pokemons: trainer.pokemons}
end
render json: jawn , except:[:updated_at, :created_at]
end
def show
@trainer = Trainer.find(... |
class BackupGenerator < Rails::Generators::Base
source_root File.expand_path('../templates', __FILE__)
def copy_files
copy_file 'backup.rake', 'lib/tasks/backup.rake'
copy_file 'backup.rb', 'config/backup.rb'
unless Dir["#{Rails.root}/db/migrate/*create_backup_tables.... |
describe 'RcAlertsViewController' do
tests RcAlertsViewController
def controller
rotate_device to: :portrait, button: :bottom
@alerts_view_controller = RcAlertsViewController.alloc.initWithStyle(UITableViewStyleGrouped)
end
after do
@alerts_view_controller = nil
end
it 'sets the title' do
... |
class UsersController < ApplicationController
def destroy
if user_signed_in?
current_user.destroy
Rails.logger.warn "Destroyed user #{current_user}"
end
redirect_to root_path
end
end |
class Game < ActiveRecord::Base
belongs_to :leaderboard
belongs_to :player
end |
include_recipe "joomla"
include_recipe "chef::depends"
include_recipe "hosts"
hosts "127.0.0.1" do
action "add"
host "#{node['web_app']['ui']['domain']}"
end
case node[:web_app][:system][:backend]
when "apache"
include_recipe "joomla::apache_app"
when "php"
include_recipe "joomla::fpm_app"
end
ruby_... |
require "faraday"
class Credibility
def initialize(applicant)
@applicant = applicant
@response = fetch_info(@applicant.email)
@score = 0
end
def get_score
if @response["status"] == 200
@score += 1 if presence_of("socialProfiles", "type", "linkedin")
@score += 1 if presence_of("social... |
class CommentReplySerializer < ActiveModel::Serializer
attributes :id,
:body,
:user_full_name,
:created_at,
:like_count,
:replies
has_many :replies, serializer: CommentSerializer
def user_full_name
"#{object.user.first_name} #{object.user.... |
require 'rails_helper'
RSpec.describe User, type: :model do # rubocop:disable Metrics/BlockLength
describe 'validations' do
it { should validate_presence_of(:email) }
it { should validate_presence_of(:first_name) }
it { should validate_presence_of(:password) }
it { should validate_uniqueness_of(:uid)... |
class RestaurantsController < ActionController::Base
def index
@restaurant = Restaurant.all
end
def new
@restaurant = Restaurant.new
end
def create
@restaurant = Restaurant.new(user_params)
if @restaurant.save
redirect_to restaurant_path(@restaurant.id)
else
flash[:alert] = "Som... |
# frozen_string_literal: true
module Api::V1::Admin::Videos
class DestroyAction < ::Api::V1::BaseAction
step :authorize
try :find, catch: Sequel::NoMatchingRow
map :destroy
private
def find(input)
::Video.with_pk!(input.fetch(:id))
end
def destroy(video)
::SoftDestroyEntity... |
require 'csv'
require 'date'
require 'digest/md5'
module HttpdLogParser
class Common < Base
def set_string(str)
str.gsub!(/\[(\d+\/[a-zA-Z]{3}\/\d+.+?)\]/, "\"\\1\"")
if str.include?(' ')
begin
line = CSV::parse_line(str, {col_sep: ' ', skip_blanks: true})
self.remote_host... |
class BackgroundImageSerializer
include FastJsonapi::ObjectSerializer
attributes :search_term, :image_url
end
|
Pod::Spec.new do |s|
s.platform = :ios
s.ios.deployment_target = '10.0'
s.name = "Tiledesk"
s.summary = "Tiledesk adds a Live Chat to your iOS App."
s.description = <<-DESC
Tiledesk SDK adds Live Chat messaging to your App. Swift and Objc supported.
DESC
s.requires_arc = true
s.version = "0.1.4"... |
require 'rails_helper'
RSpec.feature "User views all playlists" do
scenario "each playlist links to the individual playlist page" do
playlist_one = Playlist.create(name: "Jones Juicy Jams")
playlit_two = Playlist.create(name: "The Cut")
visit playlists_path
expect(page).to have_content "Jones Jui... |
module Specmon
module Adapter
class Base
def initialize(project)
@project = project
end
def recent_builds
raise 'Needs to be implemented'
end
end
end
end
|
#Building Class
class Building
attr_accessor :name, :address, :apartments
#hint apartments should be an array i.e @apartments = []
def initialize(name, address)
@name = name
#why does line 16 use name instead of building_name if I assigned it that here?
@address = address
@apartments =[]
end
def... |
# Cookbook Name:: ant
# Recipe:: install_source
include_recipe 'ark'
ant_path = ::File.join(node['ant']['home'], 'bin', 'ant')
ark 'ant' do
not_if do
::File.exist?(ant_path) &&
"#{ant_path} -version | grep '#{node['ant']['version']}'"
end
url "#{node['ant']['url']}/apache-ant-#{node['ant']['version']... |
Given(/^I fill in "(.*?)" with "(.*?)"$/) do |field, value|
fill_in(field, :with => value)
end
When(/^I fill the "(.*?)" field with "(.*?)"$/) do |field_name, value|
fill_in field_name, :with => value
end
When(/^I write on the "(.*?)" text area "(.*?)"$/) do |text_area_name, text|
fill_in text_area_name, :with... |
module RSpec
module Rest
module Util
def load_yaml(file_path)
unless File.readable?(file_path)
raise RSpec::Rest::FileNotReadable.new(file_path)
end
YAML.load(File.read(file_path))
end
module_function :load_yaml
def logger
RSpec.configuration.log... |
require 'rails_helper'
describe "Authors to items relationship" do
before(:all) do
@smashup = FactoryGirl.create(:item, :title => 'Smash Up')
@wonders = FactoryGirl.create(:item, :title => '7 Wonders')
@bcathala = FactoryGirl.create(:author, :firstname => 'Bruno', :lastname => 'Cathala')
@abauza = F... |
$: << "lib"
require "optparse"
require "activity"
# Get output file of activities from command line.
options = {}
optparse = OptionParser.new do |opts|
opts.banner = "Usage: script/update.rb [options] [FileName]"
opts.on('-o File', '--output File', 'The output file of activities') do |file|
options[:output... |
class AddXToIdeas < ActiveRecord::Migration
def change
add_column :ideas, :x, :float
add_column :ideas, :y, :float
end
end
|
class PhotosController < ApplicationController
def index
@photos_count = 26
@photo_index = params[:photo_index].to_i
end
end
|
module LonoCfn
class CLI < Command
class Help
class << self
def create
<<-EOL
Examples:
Provided that you are in a lono project and have a `my-stack` lono template definition. To create a stack you can simply run:
$ lono-cfn create my-stack
The above command will generate and use the template in... |
class UpdateResetPasswordForm
include ActiveModel::Model
attr_accessor :email, :password, :password_confirmation, :token_value
validates :password, :password_confirmation, presence: true
validates :password, confirmation: { case_sensitive: true }
def save
return false unless valid? && tok... |
class CruiseType < ActiveRecord::Base
has_many :scheduled_cruises
validates :name, length: { minimum: 5 }
validate :validate_capacity
# default_scope { where status: 'active' }
private
def validate_capacity
if not (capacity and capacity > 0)
errors.add(:capacity, "should be at least 1"... |
class EmployeesController < ApplicationController
before_action :set_object, only: [:show]
def index
@employees = Employee.active.not_admin
end
def show
end
# def new
# @employee = Employee.new
# end
# def edit
# if @employee == current_user
# redirect_to edit_user_registration_pa... |
module CDI
module V1
class GameGroupAnswerSerializer < ActiveModel::Serializer
root false
attributes :id, :user_id, :items, :group_id, :correct?,
:correct_items, :wrong_items, :created_at, :updated_at
def group_id
object.game_id
end
def items
obj... |
require 'rubygems' if RUBY_VERSION < '1.9'
require 'spec'
require 'git'
SPEC_PATH = File.expand_path( File.dirname( __FILE__ ) )
ROOT_PATH = File.dirname( SPEC_PATH )
require File.join( ROOT_PATH, 'lib', 'git', 'confident' )
Joiner = lambda do |base|
lambda do |*others|
File.join(base, *others)
end
end
descr... |
class DestroyCustomer
include Interactor
before do
context.fail! if context.response.blank? || (@customer = Customer.find_by_id(context.customer[:id])).blank?|| context.current_user.blank?
@customer.destroyer = context.current_user
end
def call
@customer.destroy! rescue context.fail!
end
end |
#!/usr/bin/env ruby
#
require 'narp.rb'
require 'json'
def parse_options
options = OpenStruct.new
opt_parser = OptionParser.new do |opts|
opts.banner = "Usage: narp.rb [options] narp_program_definition"
mess = "\nIf the program definition is provided on the command line: \n"
mess += "1) it must be enclo... |
class HashSet
attr_reader :count
attr_accessor :store
def initialize(num_buckets = 8)
@store = Array.new(num_buckets) { Array.new }
@count = 0
end
def insert(key)
@count += 1 unless include?(key)
@store[(key.hash % num_buckets)] << key unless include?(key)
if @count == num_buckets
... |
FactoryBot.define do
factory :relationship do
sequence(:id) { |n| }
created_at { Time.now }
updated_at { Time.now }
end
end
|
class Task
def initialize(task_name)
@description = task_name
end
def description
@description
end
end
|
class MatchResultsController < ApplicationController
def update
@round = Round.find(params[:round])
@round_next = Round.find_by(id: params[:round].to_i + 1)
@match_results = MatchResult.find(params[:end_round][:match_result].keys)
if @match_results.each do |mr|
mr.update(params[:end_round][:matc... |
require 'rails_helper'
RSpec.describe Round, type: :model do
describe 'after creating a model' do
before(:all) { Match.delete_all ;Round.delete_all }
after(:all) { Round.delete_all }
context 'associations' do
it 'should have many matches' do
association = Round.reflect_on_association(:matc... |
class AddRandomColumnGenerator < Rails::Generator::NamedBase
def manifest
column_name = args.shift || "random"
record do |m|
options = {}
options[:assigns] = {:migration_name => "Add#{column_name.camelize}To#{class_name}", :column_name => column_name}
options[:migration_file_name] = "add_#{... |
class MiniUrl
include Mongoid::Document
field :url_code, type: String
field :url, type: String
field :redirect_count, type: Integer, default: 0
field :expiry, type: Date
belongs_to :user, optional: true
validates :url_code, presence: true, uniqueness: true
validates :url, presence: true
index({url... |
require 'digest'
module GlacierBackup
RETRIES = 3
DEFAULT_ALGORITHM = :sha1
READ_SIZE = 2**16
extend self
# Simple wrapper around AWS network transfers to make them slightly more
# resilient to transient failures.
def retry
attempts = 0
while true
begin
yield
rescue Aws::Co... |
class RemoveColumnsFromMaterials < ActiveRecord::Migration
def change
remove_column :materials, :point, :string
remove_column :materials, :strategy, :string
remove_column :materials, :cers, :string
remove_column :materials, :promotion, :string
end
end
|
class ChangeColumnDefaultToOrderedProduct < ActiveRecord::Migration[5.0]
def change
change_column :orders, :payment_method, :integer, :default => 0
change_column :orders, :order_status, :integer, :default => 0
end
end
|
class Event < ActiveRecord::Base
belongs_to :user
belongs_to :restaurant
has_many :events_users
has_many :users, through: :events_users
end
|
RSpec.describe 'Invoice Dashboard Page' do
before(:each) do
@invoice_1 = Invoice.create(merchant_id: 12346, status: "pending")
@invoice_2 = Invoice.create(merchant_id: 12347, status: "pending")
@invoice_3 = Invoice.create(merchant_id: 12348, status: "shipped")
@invoice_4 = Invoice.create(merchant_id: ... |
module API
module Base
extend ActiveSupport::Concern
included do
content_type :json, 'application/json'
format :json
default_format :json
end
end
end
|
class Group < ActiveRecord::Base
has_many :user_groups
has_many :user_items
# 新規グループのレコードを作成する際にデフォルト値を設定
after_initialize :set_default, if: :new_record?
# paperclip用
has_attached_file :avatar, styles: { medium: "300x300#", thumb: "100x100#" }
validates_attachment_content_type :avatar, content_type: ["... |
require 'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
@rowling = users(:jk_rowling)
@tolkien = users(:tolkien)
@nobody = users(:no_name)
end
test "name must be present" do
assert_equal 'Jk Rowling', @rowling.name, 'The expected user is not found'
end
test "event should be linked to ... |
require File.join(File.dirname(__FILE__), '..', '..', 'spec', 'spec_helper')
require File.join(File.dirname(__FILE__), 'auditor_proxy_mock')
require File.join(File.dirname(__FILE__), 'instantiation_mock')
require 'instance_lib'
require 'instance_scheduler'
describe InstanceScheduler do
include RightScale::SpecHelpe... |
module Veeqo
class Warehouse < Base
include Veeqo::Actions::Base
def create(name:)
create_resource(name: name)
end
def update(warehouse_id, attributes)
update_resource(warehouse_id, attributes)
end
private
def end_point
"warehouses"
end
end
end
|
class CustomersBase
attr_accessor :data_object
def initialize(group)
@group = group
end
def next
@data_object.next_record
end
def prior
@data_object.prior_record
end
def add(customer)
@data_object.add_record(customer)
end
def delete(customer)
@data_object.delete_record(custo... |
class Employee
attr_reader :name, :email
def initialize(name, email)
@name = name
@email = email
end
def calculate_weekly_salary
@hours_worked * @hourly_rate
end
def calculate_annual_salary
(@annual_salary.to_f/365) * 7
end
def show_salary
print "#{@name}'s weekly ... |
def palindrome?(str)
str = str.gsub(/\W/i, '').downcase
str == str.reverse
end
def count_words(str)
str_hash = Hash.new
str.gsub(/(\w+\b)/i) do |m|
str_hash[m.downcase] = str_hash[m.downcase].nil? ? 1 : str_hash[m.downcase] + 1
end
str_hash
end
|
class AddExtraFieldsToDeliveries < ActiveRecord::Migration
def change
add_column :deliveries, :extra1, :string
add_column :deliveries, :extra2, :string
add_column :deliveries, :extra3, :string
end
end
|
# frozen_string_literal: true
require "date"
module Redox
class Query < Models::Message
def perform(source, destination_id)
data_model, event_type = self.class.name.split("::").drop(1)
self.meta = {
data_model: data_model,
event_type: event_type,
event_date_time: DateTime.now... |
class Talentist < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
acts_as_token_authenticatable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :relati... |
class Usermailer < ApplicationMailer
default from: "jalexy12@example.com"
def entry_created(project)
@project = project
mail(to: "jalexy12@gmail.com", subject: "New entry created in project #{project.name}")
end
end
|
#--
# Copyright (c) 2010-2017 David Kellum
#
# Licensed under the Apache License, Version 2.0 (the "License"); you
# may not use this file except in compliance with the License. You
# may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
cask :v1 => 'inssider' do
version :latest
sha256 :no_check
url 'http://files.metageek.net/downloads/inSSIDer4-installer.dmg'
name 'inSSIDer'
homepage 'http://www.inssider.com/'
license :commercial
app 'inSSIDer.app'
end
|
## Задача №2:
#
# Ганс Грубер в это время пытается намайнить биткоины - чтобы сделать это ему нужно найти MD5 хэши,
# которые начинаются как минимум с 5 нулей.
# Значение, хэш которого нужно посчитать - это инпут (пользовательский ввод), за которым следует положительное число (1, 2, 3 итд).
#
# Например, для инпута ... |
class ApplicationController < ActionController::Base
before_action :set_cache_buster
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
include RoundsHelper
include SeasonsHelper
include TeamsHelper
def set_cache_... |
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
get '/math', :to => 'mathematics#plus'
post '/math', :to => 'mathematics#minus'
put '/math', :to => 'mathematics#multiply'
delete '/math', :to => 'mathematics#divide'
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
config.vm.provision "shell" do |s|
ssh_pub_key = File.readlines("#{Dir.home}/.ssh/id_rsa.pub").first.strip
s.inline = <<-SHELL
echo #{ssh_pub_key} >> /home/vagrant/.ssh/authorized_keys
mkdir -p /root/.ssh
echo #{ssh... |
module Munich
class Router
attr_accessor :agency
def initialize(agency)
@agency = agency
end
# origin, destination: Geokit::LatLng representing the start and end points.
# Returns a list of routes.
#
def route(origin, destination)
end
end
end
|
FactoryBot.define do
factory :user do
password {"00000000"}
password_confirmation {"00000000"}
sequence(:name) { Faker::Internet.username(specifier: 3..8)}
sequence(:email) {Faker::Internet.email}
end
end
|
class EARMMS::SystemDataController < EARMMS::SystemController
get '/' do
next halt 404 unless logged_in?
next halt 404 unless has_role? 'system:data_correction'
@title = "Data correction"
@branches = EARMMS::Branch.all.map do |b|
[b.id, b.decrypt(:name).force_encoding("UTF-8")]
end.to_h
... |
require 'toml-rb'
class TaskConfig
# 問題設定ファイルを読み込む
def initialize
@config_file = TomlRB.load_file('./config.toml')
end
# 変更結果を新たに書き込む
def save_config
config = TomlRB.dump(@config_file)
file = File.open('./config.toml', 'w')
file.puts config
file.close
end
# 問題一覧を取得する
def get_task... |
class AddColsToSeats < ActiveRecord::Migration
def change
change_table :seats do |t|
t.boolean :booked, :default => false
end
end
end
|
require 'spec_helper'
describe TradeLead::Fbopen, type: :model do
describe '#self.importer_class' do
it 'returns correct importer_class' do
expect(described_class.importer_class).to match(TradeLead::FbopenImporter::FullData)
end
end
end
|
# frozen_string_literal: true
class BoxberryController < ApplicationController
def index
@cost = shipping_cost
end
def shipping_cost # (code, weight, type, insurance, sum)
# Входящие параметры:
# weight - вес посылки в граммах,
# type - тип доставки (1 - выдача в ПВЗ, 2 - Курьерская доставка (КД... |
namespace :plugins do
namespace :git do
desc "Set up your git plugins after gems:install"
task :install do
puts `git submodule init`
puts `git submodule update`
end
end
end
|
# encoding: UTF-8
module CDI
module V1
module Photos
class CreateService < BaseCreateService
include V1::ServiceConcerns::PhotoParams
record_type ::Photo
private
def build_record
current_photo_params = create_photo_params.dup
album_id = current_photo_p... |
class AddMovieIdToClip < ActiveRecord::Migration
def self.up
add_column :clips, :movie_id, :integer, :limit => 6
add_index :clips, :movie_id
add_index :quotes, :movie_id
add_index :likes, :movie_id
end
def self.down
remove_column :clips, :movie_id
add_column :clips, :movie_id, :integer, :... |
class Writer
attr_accessor :csv_writer
def initialize(file_path)
self.csv_writer = CSV.open(file_path, "w")
end
def push_data(data)
csv_writer << data
end
def headers(data)
push_data(data)
end
def close
csv_writer.close
end
end |
# = DeferProxy
#
# Create a proxy for lazy-loading objects.
#
# == Example for Ruby
#
# In the example below, we create an @array variable that behaves just like an
# Array instance, but is actually a proxy that will return array content. The
# proxy materialies this content the first time that an instance method is
# ... |
# temporary code to support flagged enums (AnchorStyles.Bottom | AnchorStyles.Top)
# this code will be removed when | is implemented on enums in IronRuby
module EnumSupport
def enum_to_int(enval)
entype = enval.GetType()
undertype = Enum.GetUnderlyingType(entype)
Convert.ChangeType(enval, undertype)
end... |
describe Job do
it "requires name" do
expect{
described_class.new
}.to raise_error(ArgumentError)
end
it "sets the correct job name" do
expect(described_class.new("a").name).to eq("a")
end
context "job name is equals job dependency" do
it "raises an error" do
expect{
desc... |
class Fyle < ActiveRecord::Base
acts_as_taggable
def self.get_mime_type(file)
r = self.find_by_file_name(file);
r.mime_type
end
end
|
module HelpWizard
# school_ids, school_date, start_date, end_date, for a config_name
@@configurations = {}
# use it to render a wizard from any page. by default will render a partial 'help_wizard/_controllername_action_name'
# or pass those as options :controller_name, :action_name.
# or pass a partial, 'p... |
require_relative 'prompt'
require_relative 'score'
class Player
attr_reader :name
attr_reader :hand
attr_reader :scores
def initialize(name)
@name = name
initialize_hand
end
def initialize_hand
@hand = []
@scores = []
end
def take_card(card)
@hand << card
end
def print_hand
puts
puts @... |
class Event
attr_accessor :name, :event_type, :short_descrip, :location, :location_link, :details_link, :date, :long_descrip, :start_time, :address, :speakers
@@all = []
def initialize(event_hash)
event_hash.each do |k, v|
self.send("#{k}=", v)
end
save
end
def self.make_events(scraped_... |
require_relative 'spec_helper'
describe "Room Class" do
before do
room_num = 1
@room = Hotel::Room.new(room_num)
end
describe "Initializer" do
it "is an instance of Room" do
expect(@room).must_be_kind_of Hotel::Room
expect(@room.room_reservations).must_be :empty?
end
it "must kee... |
require "rails_helper"
RSpec.describe RotaSlot, "validations" do
it { should validate_presence_of(:starting_time) }
it { should validate_presence_of(:shift) }
it { should validate_presence_of(:organisation_uid) }
end
RSpec.describe RotaSlot, "relationships" do
it { should belong_to(:shift) }
it { should bel... |
class AdminController < ApplicationController
before_filter :chequear_login
layout 'admin'
private
def chequear_login
unless logueado? or Rails.env.development?
redirect_to new_session_path
end
end
end
|
module WpImportDsl
module Wxr
# Image
class Image < Base
attr_accessor :width, :height, :aperture, :credit, :camera, :caption,
:created_timestamp, :copyright, :focal_length, :iso,
:shutter_speed, :title, :image
def read!
self.image = nil... |
FactoryGirl.define do
factory :pullrequest, class: Hash do
id { Faker::Number.between(1, 10000) }
title { Faker::Lorem.sentence }
description { Faker::Lorem.paragraph(2) }
state { "OPEN|MERGED|DECLINED".split('|').sample }
author { FactoryGirl.attributes_for(:user) }
source {{
branch: { ... |
#!/usr/bin/env ruby
require 'bundler/setup'
require 'zebra/checker'
require 'zebra/configuration'
require 'zebra/git_parser'
require 'zebra/exceptions'
require 'zebra/version'
module Zebra
def self.configure(&block)
yield configuration
end
def self.configuration
@config ||= Configuration.new
end
... |
class Api::CardsController < ApplicationController
def index
@category = Category.find(params[:category_id])
@cards = @category.cards
render json: @cards
end
end
|
$: << File.join(File.dirname(__FILE__), 'lib')
require 'environment'
class Snippets < Sinatra::Base
include Caching
use Rack::Flash, :sweep => true, :accessorize => [:notice]
use Rack::Static, :urls => ['/css', '/images', '/js'], :root => 'public'
enable :sessions, :logging, :dump_errors, :static
s... |
class Link < ApplicationRecord
validates :url, presence: true, uniqueness: true, length: { within: 10..255 }
validates :slug, presence: true, uniqueness: true, length: { within: 3..255 }
before_validation :generate_slug
def self.init user_params
user_params[:url] = "http://#{user_params[:u... |
class Libedit < BuildDependency
desc "BSD-style licensed readline alternative"
homepage "http://thrysoee.dk/editline/"
url "http://thrysoee.dk/editline/libedit-${version}.tar.gz"
# todo: version 20160618-3.1 fails to build on darwin
release version: '20150325-3.1', crystax_version: 3
def build_for_platfo... |
# encoding: UTF-8
module CDI
module V1
module LearningDynamics
class DeleteService < BaseDeleteService
record_type ::LearningDynamic
def after_success
# Is better delete all associations here, dependent: :destroy will perform
# several UPDATE and DELETE queries in datab... |
module Jekyll
require 'slim'
class SlimConverter < Converter
safe true
priority :low
def matches(ext)
ext =~ /slim/i
end
def output_ext(ext)
".html"
end
def convert(content)
begin
Slim::Template.new { content }.render
rescue StandardError => e
p... |
require 'scraperwiki'
require 'rubygems'
require 'mechanize'
def scrape_table(agent, scrape_url)
puts "Scraping " + scrape_url
doc = agent.get(scrape_url)
texts = doc.search('.text').map { |e| e.inner_text.strip }
bldtexts = doc.search('.bldtxt').map { |e| e.inner_text.strip }
reference = texts[0]
on_noti... |
class RemoveRatingUrlColumnFromRestaurants < ActiveRecord::Migration
def change
remove_column :restaurants, :rating_url
end
end
|
class Garden < ApplicationRecord
belongs_to :user
has_many :plant
end
|
# Write a function:
# int solution(int A[], int B[], int N);
# that, given two non-empty arrays A and B consisting of N integers, returns the number of fish that will stay alive.
# Note: Again, keeping the stack operations strictly .push and .pop only.
def solution(a, b)
n = a.size
total_upstream = 0
down... |
module EpisodesHelper
def media_wrapped_url(media_url)
"http://dts.podtrac.com/redirect.mp3/#{media_url}"
end
def episode_path(episode, options={})
url_for(options.merge(
:controller => 'episodes',
:action => 'show',
:podcast_path => episode.podcast.path,
:episode_number => episod... |
# -*- encoding : utf-8 -*-
class AddTempPeriodColumnToZayavkas < ActiveRecord::Migration
def change
add_column :zayavkas, :temp_period, :string
end
end
|
# encoding: utf-8
class Direction < ActiveRecord::Base
has_many :regions
def page_title
"Направления"
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.