text
stringlengths
10
2.61M
class ListWord < ApplicationRecord validates :list_id, :word_id, presence: true validates :word_id, uniqueness: { scope: :list_id } belongs_to :word belongs_to :list end
FactoryGirl.define do factory :measurement do measured_at { rand(1..100).days.ago } weight { rand(100..400) } fat { rand(10..50) } user end end
class RemoveEmailFromAuthentication < ActiveRecord::Migration def change remove_column :authentications, :email, :string end end
class CreateGcodes < ActiveRecord::Migration[5.1] def change create_table :gcodes do |t| t.references :model, foreign_key: true t.string :filename t.decimal :filament_length t.decimal :print_time t.timestamps end end end
require 'json' require 'csv' class SurveyGenerator def self.daters CSV.read("survey.csv")[2..-1].map { |fields| gender = case fields[17] when "1" "Man" when "2" "Woman" else "Otherwise" #Shouldn't ha...
require 'open-uri' require 'nokogiri' require 'csv' require 'kconv' def read_html_file(path) File.open(path, "r") do |file| text = file.read doc = Nokogiri::HTML.parse(text, nil, 'utf-8') return doc end end def fetch_page(url) sleep(2) charset = nil html = open(url) do |f| raise "Got 404 err...
class PagesController < ApplicationController def show if @page = Page.for_path("/#{params[:path]}") render @page.template else render_404 end end end
class ClassMaterialsController < ApplicationController before_action :set_class_material, only: [:show, :edit, :update, :destroy] # GET /class_materials def index @class_materials = ClassMaterial.all end # GET /class_materials/1 def show end # GET /class_materials/new def new @class_materia...
class CreateCategoryGroups < ActiveRecord::Migration[5.0] def change create_table :category_groups do |t| t.string :name t.boolean :is_hidden,default: false t.string :logo t.text :description t.string :image t.timestamps end end end
require 'rails_helper' RSpec.describe Services::NewAnswerNotification do ActiveJob::Base.queue_adapter = :test let!(:question) { create(:question) } let(:answer) { create(:answer, question: question) } let(:not_subscribed_user) { create(:user) } it 'sends notification to author of the question' do expe...
require 'rails_helper' RSpec.describe Project, type: :model do # pending "add some examples to (or delete) #{__FILE__}" # ユーザー単位では重複したプロジェクト名を許可しないこと it "does not allow duplicate project names per user" do user = User.create( first_name: "Joe", last_name: "Tester", email: "joetester@e...
# == Schema Information # # Table name: users # # id :integer not null, primary key # email :string(255) default(""), not null # encrypted_password :string(255) default(""), not null # reset_password_token :string(255) # reset_password_sent_at :datetime...
class WargamesController < ApplicationController skip_before_filter :set_session Wargames::settings.each do |name, status, port, admin| define_method(name) do params.merge!({wargame: name, status: status, port: port, admin: admin}) session[:channel] = "##{name}" render template: "wargames/#...
require 'spec_helper' include ApplicationHelper describe ItemsDesignsController do before(:all){ create_init_data } after(:all){ delete_init_data } before do @item = FactoryGirl.create(:item) @items_design = FactoryGirl.create(:items_design,item_id:@item.id) @admin = FactoryGirl.create(:admin) ...
class Blog < ApplicationRecord validates :name, presence: true validates :email, presence: true validates :content, presence: true, length: {in: 1..140} end
require 'test_helper' class NavigationTest < ActionDispatch::IntegrationTest test 'can render home page' do visit root_path assert page.has_text? 'Joe Doe' end end
module Alf module Text # # Implements Alf::Renderer for outputting beautiful text tables. # class Renderer < ::Alf::Renderer module Utils def looks_a_relation?(value) value.is_a?(Alf::Iterator) or (value.is_a?(Array) && !value.empty? && value.all?{|v| v.is_a?...
FactoryGirl.define do factory :service do service_name "Go-Ride" price_per_km 1500 end factory :invalid_service, parent: :service do service_name "Grab Car" price_per_km nil end end
module PostDecorator include ActionView::Helpers::TagHelper def as_html content_tag 'article' do html_title = content_tag 'h2' do title end html_body = simple_format body [html_title, html_body].join.html_safe end end end
class ColorSelectView < UIScrollView attr_accessor :delegate def initWithFrame(theFrame, andColors:colors) if super self.initColorViews(colors) self.contentSize = [colors.length * 60 + 20, frame.size.height] end self end def initColorViews(colors) colors.each_with_index do |(co...
#!/usr/bin/env ruby # frozen_string_literal: true # # Copyright (C) 2016 Harald Sitter <sitter@kde.org> # 2016 Scarlett Clark <sgclark@kde.org> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free ...
class InvalidExtension < RuntimeError end class FileNotAccessible < RuntimeError end class ItemKeyNotPresent < RuntimeError end class WrongFormatError < RuntimeError end class IniFileSectionUndefined < WrongFormatError end
class BooksController < ApplicationController before_action :authenticate_user!, only: [:create, :index, :show, :edit, :update, :destroy] before_action :correct_user, only: [:edit, :update, :destroy] def index @books = Book.all @book = Book.new #@books = Book.all #@book = Book.new end def crea...
# Write a game where the player has to guess a random price between 1 and 100 chosen by the program. The program should keep asking until the player guesses the right price. When the guess is right, the program displays how many guesses it took the player to win. # we need a random price # counter to display how man...
# encoding: UTF-8 require 'spec_helper' describe XmlFileDownload do before :each do @shop = Shop.create({:name => "alza.sk", :url => "http://www.alza.sk"}) end def valid_attributes { :shop => @shop, :url => "http://c.sme.sk/imgs/pager/logo.gif" } end it "should ...
# frozen_string_literal: true require "cases/helper" require "models/author" require "models/post" require "models/comment" require "models/developer" require "models/computer" require "models/project" require "models/reader" require "models/person" require "models/ship" class ReadOnlyTest < ActiveRecord::TestCase ...
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :authenticate_user!, except: [:home] rescue_from Exception, with: :render_exception # NOTE https://stackoverflow.com/a/48744792/446267 rescue_from ActionController::UnknownFormat, with: ->{ render no...
class CadastroFazenda_PessoaJuridica < SitePrism::Page #element :selecionarLogo, element :campo_nome, '#Nome' element :campo_proprietario, '#proprietario' #element :usu_resposavel, '#usuarioResponsavel' #element :usu_resposavel_select, 'div[tabindex*="-1"]' element :area_Total, '#Area' @combo...
include RSpec require_relative 'binary_heap' RSpec.describe BinaryHeap, type: Class do let (:root) { Node.new("The Matrix", 87) } let (:heap) { BinaryHeap.new(root) } let (:pacific_rim) { Node.new("Pacific Rim", 72) } let (:braveheart) { Node.new("Braveheart", 78) } let (:jedi) { Node.new("Star Wars: Retur...
# rubocop:disable Layout/LineLength class TranslationsDatatable < BaseDatatable CLASSES = [Activity, Club, Discipline, Happening, DisciplineHappening, Venue, Tag, Requirement].freeze CLASSES_THAT_HAS_SHOW_PAGE = [Activity, Club].freeze def columns { 'translations.translateable_id': {}, 'translatio...
require 'test_helper' class Api::V2::AnimeControllerTest < ActionController::TestCase setup do @controller.class.skip_before_filter :require_client_id # Mind the fixture data generated on anime.yml until we get rid of it create(:anime, title: 'Anime name1', show_type: 'OVA', age_rating: 'PG', ...
require 'spec_helper' require 'require_js/configuration' require 'require_js/builder' describe RequireJs do describe '#include_tag' do let(:configuration) { class_double('RequireJs::Configuration').as_stubbed_const } let(:builder) { class_double('RequireJs::Builder').as_stubbed_const } let(:options) { {...
json.favorites @favorites do |favorite| json.id favorite.article_id.to_s json.title favorite.article_title json.createdAt favorite.article_created_at.xmlschema json.favoritesCount favorite.article_favorites_count json.commentsCount favorite.article_comments_count json.__typename 'Article' json.user favor...
#============================================================================== # ** DataManager #------------------------------------------------------------------------------ # This module manages the database and game objects. Almost all of the # global variables used by the game are initialized by this module. #=...
class Project include Mongoid::Document embeds_many :tasks, inverse_of: :project field :name, type: String include Mongoid::Timestamps validates :name, presence: true end
# Component class for GameObject components, such # as sound, or graphics # # Registers itself with component list upon init class Component def initialize(game_object = nil) self.object = game_object end def update # override end def draw(viewport) # override end ...
class Category < ActiveRecord::Base has_ltree_hierarchy has_many :transaction_categories has_many :plaid_transactions, through: :transaction_categories def self.inheritance_column "category_type" end def self.add_plaid_category(category) length = category.hierarchy.length if length == 1 ...
# 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 rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel...
class RoleRouteConstraint def initialize @block = block || ->(_user) { true } end def matches?(request) request.subdomain.present? && !FORBIDDEN_SUBDOMAINS.include?(request.subdomain) && request.subdomain == 'me' user.present? && @block.call(user) end def current_user(request) User.find_by_i...
module Admin::DashboardHelper def num_total_users User.all.count end def num_active_users User.where('last_active_at > ?', Date.current - 7).count end def num_challenges_solved Solution.completed.count end def progress_data_past_months data = 6.downto(0).map do |i| range = i.month...
class LayerProperties < JsonCore attr_accessor :color #{}, attr_accessor :visible #true, attr_accessor :pointsize #0, attr_accessor :linewidth #0, attr_accessor :shininess #0, attr_accessor :smooth #true, attr_accessor :showEdges #true, attr_accessor :wireframe #true def initialize(hex) super ...
class RemoveLevelFromExperts < ActiveRecord::Migration[6.1] def change remove_column :experts, :level, :text end end
# Setting the path for home directory and granting privileges. puts "==== Setting the path for home directory and granting privileges! ====" directory "/home/#{node['user']['name']}/" do owner "#{node['user']['name']}" group "#{node['group']}" mode "#{node['expertiza_clone']['mode']}" action :create end ...
# encoding: utf-8 control "V-52447" do title "The DBMS must have its auditing configured to reduce the likelihood of storage capacity being exceeded." desc "Applications need to be cognizant of potential audit log storage capacity issues. During the installation and/or configuration process, applications should dete...
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :omniauthable, omniauth_providers: %i[facebo...
class Artist < ActiveRecord::Base belongs_to :user before_create :set_photo, :set_similar validates :name, presence: true #, uniqueness: { case_sensitive: false } validates :user_id, presence: true def set_photo self.photo ||= "http://i.imgur.com/Ha087R9.jpg?3" end def set_similar self.s...
class Moip::BillingInfo < Moip::Model attr_accessor :holder_name, :number, :expiration_month, :expiration_year validates :holder_name, :number, :expiration_month, :expiration_year, :presence => true validate :validates_format_of_number, :valida_numero_cartao, :validates_format_of_expiration_month, :valida...
# typed: true # frozen_string_literal: true module Packwerk class ReferenceOffense < Offense extend T::Sig extend T::Helpers attr_reader :reference, :violation_type sig do params( reference: Packwerk::Reference, violation_type: Packwerk::ViolationType, location: T.nila...
class WidgetNotification # Attempt to send 15 mins after registration, then several times after that DELAYS = [15, 5, 5, 5, 8, 16, 32, 64] def self.schedule(user) info = user.widget_notification_info.all return if user.nil? || info['received'] || info['attempts_exhausted'] attempts = info['attempts...
require './lib/trail' describe Trail do describe '#initialize' do it 'exists' do details = { name: 'Grand Wash', length: '2.2 miles', level: :easy } trail = Trail.new(details) expect(trail).is_a? Trail end it 'has attributes' do details = { ...
class Duration %w(month days hours minutes seconds).each do |name| attr_accessor name end end time = Duration.new # singlton method time.month = 3 time.days = 31 time.hours = 21 time.minutes = 56 time.seconds = 22 puts "time is #{ time.month }/#{ time.days }, #{ time.hours }h : #{ time.minutes }m : #{ time.s...
class Captain < ActiveRecord::Base has_many :boats class << self def catamaran_operators # Boat.joins(:classifications).where("classifications.name = 'Catamaran'").map { |boat| boat.captain.name } includes(boats: :classifications).where(classifications: {name: "Catamaran"}).uniq end def s...
namespace :elasticsearch do desc "Configure index templates" task :setup => :environment do client = Elasticsearch::Client.new(Settings.elasticsearch) body = JSON.parse(<<-EOS) { "template" : "logstash-*", "order" : 0, "mappings" : { "fluentd" : { "@target" : { "type": "strin...
Redmine::Plugin.register :redmine_issue_tabs do name 'Redmine Issue Tabs plugin' author 'Pitin Vladimir, Alexey Glukhov' description 'Plugin enhances issue interface by adding several useful tabs: timelog, time spent, code commits, history' version '1.1.1' url 'https://github.com/pineapple-thief/redmine_issue...
class User < ActiveRecord::Base include DeviseTokenAuth::Concerns::User devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_and_belongs_to_many :projects has_many :projects has_many :categories def search(term) term = term.present? ? ter...
RSpec.describe AnimalInfo do it "has a version number" do expect(AnimalInfo::VERSION).not_to be nil end end
module Tokenizer class Lexer module TokenLexers def comp_1_emp?(chunk) %w[空 から].include? chunk end def tokenize_comp_1_emp(_chunk) Token.new Token::COMP_1_EMP end end end end
require 'spec_helper' describe StepsController do before do user = create(:user, role: "admin", name: "evan") sign_in user end describe "update" do it "should update the step and redirect to the kit" do step = create(:step) post :update, id: step.id, step: {description: "foo"} res...
# == Schema Information # # Table name: material_categories # # id :integer not null, primary key # lesson_category_id :integer # name :string # created_at :datetime not null # updated_at :datetime not null # require 'rails_helper' RSpec.desc...
class ApplicationController < ActionController::Base protect_from_forgery :with => :exception USER = Rails.env["RALLY_USERNAME"] PASSWORD = Rails.env["RALLY_PASSWORD"] before_filter :authenticate def authenticate return true if %w(test development staging).include? Rails.env authenticate_or_reques...
require 'test_helper' class ProductsControllerTest < ActionController::TestCase setup do @product = products(:one) @update = { title: 'Lorem Ipsum' , description: 'Wibbles are fun!' , image_url: 'lorem.jpg' , price: 19.95 } end test "should get index" do get :index assert_response :success as...
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "rails_markitup/version" require "rails_markitup/engine" Gem::Specification.new do |s| s.name = "rails_markitup" s.version = RailsMarkitup::VERSION s.authors = ["AlexZhang"] s.email = ["blackanger.z@gmail.com"] ...
require 'spec_helper' module BeerList describe List do let(:est_name){ 'MuddyWaters' } let(:list){ List.new [], est_name} it 'knows its establishent' do list.establishment.should == est_name end describe '#to_hash' do it 'hashes its establishment name with its content' do ex...
module PasswordHolder extend ActiveSupport::Concern def password=(raw_password) if raw_password.kind_of?(String) self.hashed_password=BCrypt::Password.create(raw_password) elsif raw_password.nil? self.hashed_password=nil end end end
class CiudadtsController < ApplicationController before_action :set_ciudadt, only: [:show, :edit, :update, :destroy] # GET /ciudadts # GET /ciudadts.json def index @ciudadts = Ciudadt.all #params.permit(:tipo_cliente, :cliente_id) @cliente_id = params['cliente_id'] # params.permit(:tipo_cliente)...
require 'yaml' require File.expand_path('proc', File.dirname(__FILE__)) class CTFBootstrap def self.run!(config) @@config = YAML.load_file(config) $DEBUG = 1 if @@config['debug'] == true validate_config() print_info "setting up #{n} levels" setup_users() setup_levels() end # deletes all...
class RecordtnyntsController < ApplicationController before_action :set_recordtnynt, only: [:show, :edit, :update, :destroy] # GET /recordtnynts # GET /recordtnynts.json def index @recordtnynts = Recordtnynt.all end # GET /recordtnynts/1 # GET /recordtnynts/1.json def show end # GET /recordtn...
require 'rails_helper' RSpec.describe CommentsController, :type => :controller do before do @user = User.create(name: "Frank", email_address: "frank@example.com", password: "123456", password_confirmation: "123456") @memorial = Memorial.create(moderator: @user, deceased_name: "Nanners") @post = Post.crea...
class League class Match class CommPresenter < BasePresenter presents :comm def user_roster @user_roster ||= if comm.match.home_team.on_roster?(comm.created_by) comm.match.home_team elsif comm.match.away_team.on_roster?(comm.created_by) comm.match.a...
require 'test_helper' class AutomoveisControllerTest < ActionDispatch::IntegrationTest setup do @automovel = automoveis(:one) end test "should get index" do get automoveis_url assert_response :success end test "should get new" do get new_automovel_url assert_response :success end t...
require 'blue_hawaii/rental_unit' require 'pp' require 'json' class BlueHawaii def initialize(options) @input_path = options[:input] @rental_path = options[:rentals] end def solve raw_date_range = File.read(@input_path) date_range = raw_date_range.split("-").collect &:strip rental_data =...
class TradesController < ApplicationController # POST /trade_resources def trade_resources trade = Trade.new(trade_params) if trade.process render json: { message: trade.message }, status: :ok else render json: { error: trade.message }, status: :conflict end end private def...
class AddStarToMobileUser < ActiveRecord::Migration def change add_column :mobile_users, :star, :integer, default: 0 end end
class ChangeTypeOnDivisionTime < ActiveRecord::Migration[5.2] def change change_column :divisions, :time, :string end end
class Post < ActiveRecord::Base has_many :comments has_many :admin_comments, :class_name => "Comment", :conditions => { :author => "Admin" } has_many :people end
################################ # 给grape打补丁(修改源码自用)# ################################ # 修改Logger类,在production模式禁止debug输出 class Logger alias_method :old_debug, :debug def debug(*args, &block) return if Goliath.env? "production" old_debug(*args, &block) end end
class RenameBudgetActivityIdToParentActivityId < ActiveRecord::Migration[6.0] def up add_column :budgets, :parent_activity_id, :uuid add_index :budgets, :parent_activity_id add_foreign_key :budgets, :activities, column: :parent_activity_id, on_delete: :cascade ActiveRecord::Base.transaction do ...
class CreateServices < ActiveRecord::Migration def change create_table :services do |t| t.string :name t.text :description t.text :from t.text :ports t.text :expose t.text :environment t.text :command t.text :volumes t.string :type t.references :app, ind...
class AddUserToFlagVotes < ActiveRecord::Migration def change add_column :flag_votes, :user_id, :integer, :null=>:false end end
class Category < ApplicationRecord validates :name, length: { in: 2..90} has_many :laser_gems end
class AddPrimaryKeys < ActiveRecord::Migration def change change_column :limit_serv_channels, :id, :primary_key end end
class ImagestocksController < ApplicationController before_action :set_imagestock, only: [:show, :update, :destroy] # GET /imagestocks def index @imagestocks = Imagestock.all render json: @imagestocks end # GET /imagestocks/1 def show render json: @imagestock end # POST /imagestocks de...
class AddNameToTopics < ActiveRecord::Migration def change add_column :topics, :name, :string, null: false, default: :blank end end
class NotesController < ApplicationController def create Note.create(note_params) end private def note_params params.require(:note).permit(:content, :song_id) end end
require 'net/http' require 'rexml/document' require 'open-uri' require 'json' require "redis" class Forecast class Http def initialize(options = {}) @options = {cache: nil}.merge options if @options[:cache] cache_options = @options[:cache].merge({ host: "127.0.0.1", ...
require 'spec_helper' describe Profile do it { should belong_to(:user) } it { should validate_presence_of(:user_id) } it { should validate_uniqueness_of(:user_id) } it { should allow_mass_assignment_of(:childcaring) } it { should allow_mass_assignment_of(:designing) } it { should allow_mass_assignment_of(...
# frozen_string_literal: true module Dynflow module Dispatcher class ClientDispatcher < Abstract TrackedRequest = Algebrick.type do fields! id: String, request: Request, accepted: Concurrent::Promises::ResolvableFuture, finished: Concurrent::Promises::ResolvableFuture end ...
### # # This file is part of nTodo # # Copyright (c) 2009 Wael Nasreddine <wael.nasreddine@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at...
class LeaveManagement < ApplicationRecord validates :holiday_name, :date, presence: true end
class Opendata::Agents::Nodes::App::SearchAppController < ApplicationController include Cms::NodeFilter::View helper Opendata::UrlHelper private def pages @model = Opendata::App focus = params.permit(s: [@model.search_params])[:s].presence || {} focus = focus.merge(site: @cur_site) ...
require 'rails_helper' RSpec.describe "critters/edit", type: :view do before(:each) do @critter = assign(:critter, Critter.create!( :name => "MyString", :age => 1, :crit_type => 1 )) end it "renders the edit critter form" do render assert_select "form[action=?][method=?]", cri...
require 'redcloth' module Indoctrinatr module Tools class ContentForTexFiles # a class that DefaultValues, TemplateDocumentationContent, and field_names_as_variables should inherit from # or to be precise: When we want use variables in an indoctrinatr tex.erb file, we should use this class def ...
class Dog @@all= [] attr_accessor :name def initialize(name) @name=name @@all << self end def self.all @@all.each do |all_dogs| puts all_dogs.name end end def self.clear_all @@all.clear end end
class AddingDamperFaileAndDamperrepairedFields < ActiveRecord::Migration def change add_column :project_completions, :m_total_no_of_dampers_failed, :string add_column :project_completions, :m_total_no_of_dampersrepaired, :string end end
class Isi1 attr_reader :x, :y attr_accessor :x, :tomeruh, :tomerum, :noru, :noruy, :oisinoru, :noru def initialize(window,sound,hero,x,y,isn) @isi = Array.new() 2.times {|i| @isi[i] = SDL::Surface.load("isi#{i}.gif")} @window = window @sound = sound @hero = hero @x = @syokix = x @y = @syokiy = y...
require 'rails_helper' RSpec.describe LoyaltyAccount do describe '.build' do let(:person) { Person.new(id: 2, first_name: 'Erik') } let(:updated_at) { Time.new(2016, 12, 31, 12, 55, 32) } context 'for a Balance' do let(:balance) do Balance.new( id: 1, person: person, ...
require 'module_extensions' # == Synopsis # Various extensions to the File class # Note, uses the Module.my_extension method to only add the method if # it doesn't already exist. class File class << self my_extension("mkdirs") do # == Synopsis # make directories including any missing in the path ...
# Require this file to build a testing environment. $:.push(File.expand_path(__FILE__+'/../..')) require 'extend/module' require 'extend/fileutils' require 'extend/pathname' require 'extend/ARGV' require 'extend/string' require 'extend/symbol' require 'extend/enumerable' require 'exceptions' require 'utils' require '...
class RenameColumnToDvd < ActiveRecord::Migration def change rename_column :movies, :DVD, :dvd end end
class AddKerberosIndexToStudents < ActiveRecord::Migration def change add_index :students, :kerberos end end