text
stringlengths
10
2.61M
require "hemp/extensions/object" require "hemp/extensions/hash" require "hemp/routing/base" require "hemp/request_processor" require "rack" module Hemp class Application attr_reader :route_pot, :request, :params def initialize @route_pot = Hemp::Routing::Base.new end def call(env) @requ...
require("./block.rb") class BlockChain attr_accessor :blocks def initialize(array) self.blocks = [] previous_hash = "" array.each_with_index do |content, i| if i === 0 # genesis block block = Block.new(content, nil) previous_hash = block.do_work else block =...
class CardTemplateItem < ActiveRecord::Base belongs_to :card_apply_template belongs_to :item validates :card_apply_template, presence: true validates :item, presence: true, uniqueness: { scope: :card_apply_template_id } end
class Rating < ActiveRecord::Base belongs_to :rating_definition serialize :value def self.set!(rundef, item_id, value) if item_id.nil? r = Rating.find(:first, :conditions => ['rating_definition_id = ? AND item_id IS NULL', rundef.id]) else r = Rating.find(:first, :conditions => ['rating_...
module Nsn class TScore SIZE = 100 def initialize @data = data end def call result = nil @result = result || Result.latest t_score end def data Result.night.where(is_sunny: true).limit(SIZE).map {|v| v.darkness } .compact end def max data.max ...
class CreateThemes < ActiveRecord::Migration def change create_table :themes do |t| t.string :name t.text :about t.datetime :created_at t.timestamps end create_table :items_themes, id: false do |t| t.belongs_to :item t.belongs_to :theme end end end
class CreateActivities < ActiveRecord::Migration def change create_table :activities do |t| t.string :description t.boolean :active , null: false, default: true t.timestamps end add_index :activities, :description, :unique => true end end
class ShameInit < ActiveRecord::Migration def change create_table "case_signs", force: true do |t| t.integer "case_id" t.integer "sign_id" end create_table "cases", force: true do |t| t.string "title" t.integer "user_id" t.datetime "created_at" t.datetime "updated_...
class InvoicesController < ApplicationController def index invoices = Invoice.all.order(created_at: :desc) render json: invoices end def create invoice = Invoice.create!(invoice_params) if invoice render json: invoice else render json: invoice.errors.full_messages end @fu...
class AddConfirmStateToLadyDoctors < ActiveRecord::Migration def change add_column :lady_doctors, :confirm_state, :boolean, default: false, null: false end end
class CapturedImagesController < ApplicationController def destroy captured_images_sub = CapturedImage.find_by(id: params[:id], user_id: params[:user_id]) if captured_images_sub.destroy redirect_to "/users/#{params[:user_id]}/edit" else redirect_to "/users/#{params[:user_id]}/edit", alert: ...
module Admin class CommitteesController < BaseController load_and_authorize_resource def index @committees = Committee.all @committee = Committee.new end def show @congressman = Congressman.new end def create if @committee.save redirect_to [:admin, @committee...
class RemoveTagListFromProducts < ActiveRecord::Migration def change remove_column :products, :tag_list, :text end end
# frozen_string_literal: true module RollbarApi class Resource attr_reader :response_json def initialize(response) response = response.body if response.is_a?(Faraday::Response) @response_json = if response.is_a?(String) JSON.parse(response) else ...
module Boxes class Box < Apotomo::Widget helper Boxes::ViewHelpers attr_accessor :meta, :widget def initialize(controller, name) super(controller, name, :display) # prevent propagation of some event on :configure do |event| event.stop!; end on :save do |event| event.stop!; end ...
FactoryBot.define do factory :loan do value { Faker::Number.decimal(l_digits: 2) } rate { Faker::Number.between(from: 0.1, to: 1.0) } pmt { Faker::Number.decimal(l_digits: 2) } months { Faker::Number.decimal(l_digits: 2) } end end
require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') describe "/admin/tags/index" do include Admin::TagsHelper before(:each) do blog = mock_model(Blog, :title => 'Blog Title') tag_98 = mock_model(Tag) tag_99 = mock_model(Tag) tag_98.should_receive(:name).and_retu...
def merge_sort(array, sorted_left, sorted_right) array_size = array.length left_size = sorted_left.length right_size = sorted_right.length array_pointer = 0 left_pointer = 0 right_pointer = 0 while left_pointer < left_size && right_pointer < right_size if sorted_left[left_pointer...
class ReviewsController < ApplicationController def new end def create @review = Review.new(review_params) @idea = Idea.find params[:idea_id] @review.idea = @idea @review.user = current_user if cannot? :create, @review flash[:alert] = "cannot create a review." redirect_to @idea ...
class FontTrebuchetMs < Formula head "https://downloads.sourceforge.net/corefonts/trebuc32.exe" desc "Trebuchet MS" homepage "https://sourceforge.net/projects/corefonts/files/the%20fonts/final/" def install (share/"fonts").install "trebuc.ttf" (share/"fonts").install "Trebucbd.ttf" (share/"fonts").i...
class AddFieldsToUsers < ActiveRecord::Migration[5.0] def change add_column :users, :name, :string add_column :users, :birthdate, :datetime add_column :users, :about, :text add_column :users, :twitter_url, :string add_column :users, :facebook_url, :string add_column :users, :youtube_url, :stri...
class RemindsController < ApplicationController def index @reminds = Remind.all.page(params[:page]) end def new @remind = Remind.new end def show @remind = Remind.find(params[:id]) respond_to do |format| format.html format.json { render :json => { id: @remind.id, alarm: @remind.a...
require_relative '../views/orders_view' class OrdersController def initialize(orders_repository) @orders_repository = orders_repository @meals_repository = orders_repository.meals_repository @customers_repository = orders_repository.customers_repository @employees_repository = orders_repository.emplo...
module Strategies class Log def initialize path @path = path @file = File.open path, "w" end def call msg ts = msg.timestamp.strftime '%Y/%m/%d %H:%M:%S' @file.puts "[#{ts}] #{msg.user} - #{msg.text}" @file.flush end def history File.read(@path).split("\n") ...
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'graphql/query_resolver/version' Gem::Specification.new do |spec| spec.name = "graphql-query-resolver" spec.version = GraphQL::QueryResolver::VERSION spec.authors = ["ne...
RSpec.shared_context "dummy provider" do before(:each) do if defined? ::DiscourseChat::Provider::DummyProvider ::DiscourseChat::Provider.send(:remove_const, :DummyProvider) end module ::DiscourseChat::Provider::DummyProvider PROVIDER_NAME = "dummy".freeze PROVIDER_ENABLED_SETTING =...
class CommentsController < ApplicationController before_action :set_pattern def index @comments = @pattern.comments respond_to do |format| format.html format.json {render json: @comments} end end def create @comment = @pattern.comments.build(comments_params) if @comment.save ...
require 'rails_helper' RSpec.describe User, type: :model do describe '正常系の機能' do context 'ユーザー登録する' do it '正しく登録できること 名前:田中太郎、ユーザーネーム:たなたろ、 email: taro.tanaka@example.com' do user = FactoryBot.build(:user_tanaka) expect(user).to be_valid user.save regista...
class CreateUnusedRestaurants < ActiveRecord::Migration def change create_table :unused_restaurants do |t| t.string :name t.string :address1 t.string :address2 t.string :town t.string :towns t.string :postcode t.string :norm_postcode t.string :phone t.string :...
class Admin::BaseController < ApplicationController before_filter :authenticate_user! before_filter :admin_required! def admin_required! if current_user.admin? true else render :file => "#{Rails.root}/public/401.html" end end end
# frozen_string_literal: true class OutputService class << self include InitialData def fine_print(results) prepare_results(results).each do |k, v| total_length = v.first[:from].to_s.length + ' to '.length + v.first[:from].to_s.length puts '=' * total_length puts k puts...
class AddSchoolIdToUser < ActiveRecord::Migration def change add_column :users, :school_id, :integer add_column :classrooms, :school_id, :integer add_column :classrooms, :teacher_id, :integer end end
json.array!(@profiles) do |profile| json.extract! profile, :id, :client_id, :staff_id, :name, :dob, :contact_no, :work_no json.url profile_url(profile, format: :json) end
require Core::ROOT + "utils/TechniqueUsine.rb" # => Author:: Valentin, DanAurea # => Version:: 0.1 # => Copyright:: © 2016 # => License:: Distributes under the same terms as Ruby # ## ## Classe permettant de créer un contrôleur pour la vue FenetreJeuLibre ## class JeuLibreControleur < Controller...
require 'spec_helper' describe StudentGrades::Student do subject(:student) { StudentGrades::Student.new } describe '#add' do it 'adds a grade to a student' do student.add '85' student.add '76' expect(student.grades).to eq([85,76]) end end describe '#grade_average' do it 'avera...
class ApplicationController < ActionController::Base # :nodoc: protect_from_forgery with: :exception layout 'application' #before_action :authorize_user! helper_method :logger!, :current_user private def logger!(*args) @log = ActiveCodhab::LoggerService.new(args[:target_model], args[:user_id], args[...
module Protip module Resource # Mixin for a resource that has an active `:destroy` action. Should be treated as private, # and will be included automatically when appropriate. module Destroyable def destroy raise RuntimeError.new("Can't destroy a non-persisted object") if !persisted? ...
# (c) Copyright 2016-2017 Hewlett Packard Enterprise Development LP # # 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 applicabl...
# Create a person class with at least 2 attributes and 2 behaviors. # Call all person methods below the class and print results # to the terminal that show the methods in action. # YOUR CODE HERE class Person attr_accessor :name, :age, :hometown def initialize(name, age, hometown) @name = name @age = age ...
class User < ActiveRecord::Base before_save { self.email = email.downcase } validates :username, presence: true, length: {minimum:3 , maximum:25}, uniqueness: {case_sensitive: false } VALID_EMAIL_REGEX= /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, presence: true,length: {maximum:105}, uniqueness: {case_se...
require_relative "../question" describe Question do describe "#rating_question?" do context "type is ratingquestion" do before do @question = Question.new("ratingquestion") @question.text="What is your favorite number?" end it { expect(@question.rating_question?).to be tr...
class Admin::GuitarAttachmentsController < ApplicationController before_action :set_guitar_attachment def create @guitar_attachment = GuitarAttachment.new(guitar_attachment_params) respond_to do |format| if @guitar_attachment.save format.html { redirect_to @guitar_attachment,...
class CreateFormularios < ActiveRecord::Migration def self.up create_table :formularios do |t| t.string :nm_titulo t.string :nm_subtitulo t.string :desc_msg_sucesso t.integer :usuario_id t.boolean :varias_respostas, :default => true t.timestamps end end def self.down...
module Noodle module Factories class Node def self.create(service_name, node_class_name, properties) node_class = Noodle::NodeClass.where(["service = ? and name = ?", service_name, node_class_name]).first node = Noodle::Node.new(node_class: node_class) node.from_json(propert...
class SessionsController < ApplicationController skip_before_filter :require_login def create session[:github_user_id] = env['omniauth.auth'].extra.raw_info.id session[:github_login] = env['omniauth.auth'].extra.raw_info.login session[:github_token] = env['omniauth.auth'].credentials.token if...
class AddVideoHtmlToUpdate < ActiveRecord::Migration def change add_column :updates, :video_html, :string end end
class AddPetType < ActiveRecord::Migration def up add_column :pets, :pet_type, :string end end
module SheepWall class Display def initialize @history = [] @timestamps = [] end def show entity return if @history.include? entity if ENV["DEBUG"] print "[debug] Accepted: " p entity end @history << entity @timestamps << [ entity, Time.now ] ...
class CreateLinksTable < ActiveRecord::Migration[5.0] def change create_table :links do |t| t.string :url t.integer :trend_id t.timestamps(null:false) end end end
class CreateMessages < ActiveRecord::Migration def change create_table :messages do |t| t.string :department t.string :email t.string :name t.string :subject t.text :body t.boolean :read, default: false t.timestamps end add_index :messages, :email add_index :m...
require 'rails_helper' RSpec.describe "entries/edit", :type => :request do it "show form to edit an entry with values (body and title)" do entry = Entry.create(title: "First entry", body: "Bla bla bla", author: "me XD") get edit_entry_path(entry) assert_select "form" do assert_select "input" do ...
class AddRatingToTrails < ActiveRecord::Migration[5.0] def change add_column :trails, :rating, :integer end end
require_relative '../phase2/controller_base' require 'active_support/core_ext' require 'erb' require 'active_support/inflector' module Phase3 class ControllerBase < Phase2::ControllerBase # use ERB and binding to evaluate templates # pass the rendered html to render_content def render(template_name) ...
require 'spec_helper' describe Api::V2::CountsController do before(:each) do post api_sessions_path, {:user => {:email => 'gxbsst@gmail.com', :password => 'wxh51448888'}}, {'Accept' => 'application/vnd.iwine.com; version=2'} @user = User.find_by_email('gxbsst@gmail.com') @response = re...
json.array!(@empregadors) do |empregador| json.extract! empregador, :id, :nome, :endereco, :numero json.url empregador_url(empregador, format: :json) end
class User < ActiveRecord::Base has_many :reservations has_many :listings include Clearance::User end
# The Luhn formula is a simple checksum formula used to validate a variety of identification numbers, such as credit card # numbers and Canadian Social Insurance Numbers. # # The formula verifies a number against its included check digit, which is usually appended to a partial number to generate # the full number. Thi...
# This is a test file used for the test driven development process. Each test ensures the URL of each page can be accessed, # and the title of each page is correct. require 'test_helper' class StaticPagesControllerTest < ActionDispatch::IntegrationTest def setup @base_title1 = "CS2012 Assignment 2: Earthquak...
control "M-1.2" do title "Ensure the container host has been Hardened (Not Scored)" desc " Description: Containers run on a Linux host. A container host can run one or more containers. It is of utmost importance to harden the host to mitigate host security misconfiguration. Rationale: You should fo...
class ProductArtist < ApplicationRecord belongs_to :product belongs_to :artist end
# This class is a rails controller for calendar objects # Author:: Mark Grebe # Copyright:: Copyright (c) 2013 Mark Grebe # License:: Distributes under the same terms as Ruby # Developed for Master of Engineering Project # University of Colorado - Boulder - Spring 2013 class CalendarsController < ApplicationCont...
#!/usr/bin/env ruby # https://en.wikipedia.org/wiki/Monty_Hall_problem class MontyHallSimulator attr_reader :switcher_total_wins attr_reader :stayer_total_wins attr_reader :chaosmonkey_total_wins attr_reader :random def initialize(num_games) @num_games = num_games.to_i put_greeting @printer = P...
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :tenant do title "MyString" firstname "MyString" surname "MyString" dateofbirth "2013-07-13" telno 1 contact_type "MyString" email "MyString" end end
class AddSpotsToPictures < ActiveRecord::Migration def change add_column :pictures, :spot_id, :integer, index: true end end
require "rails_helper" RSpec.describe "Order", type: :system, js:true do let!(:product) { create(:product) } before do visit "/" click_button "Add to Cart" within("#aside-cart") do expect(page).to have_content product.title expect(page).to have_content "1 times;" end end conte...
require 'rails_helper' RSpec.describe Item, type: :model do before do @item = FactoryBot.build(:item) end describe '新規商品出品' do context '新規出品できるとき' do it '全項目存在すれば出品できる' do expect(@item).to be_valid end it 'priceが300以上9999999以下であれば出品できる' do @item.price = 300 expe...
class TeamRandomizer attr_reader :error_message attr_reader :teams def initialize @heads = [] @teams = [] @head_count = 0 @team_count = 0 @loose_head_count = 0 @team_head_count = 0 @error_message = '' @testnames = "Alfa,Bravo,Coca,Delta,Echo,Foxtrot,Golf,Hotel,India,Juliett,Kilo,...
# frozen_string_literal: true RSpec.describe 'Reset password' do resource 'Reset password request' do route '/api/v1/reset_password', 'Reset password' do post 'Reset password' do with_options scope: %i[data attributes] do parameter :email, required: true end let(:email) {...
require 'spec_helper' describe Issue do before :each do @project = Factory(:project) @attr = { :title => "Major Bug", :content => "Something important doesn't seem to work", :status => "new", :priority => 1 } end it "should create a new instance given valid attributes" do @projec...
class Ositem < ApplicationRecord has_many :dataositems has_many :t3ds, through: :dataositems end
puts "\n Newline (0x0a) \r Carriage return (0x0d) \f Formfeed (0x0c) \b Backspace (0x08) \a Bell (0x07) \e Escape (0x1b) \s Space (0x20) \nnn Octal notation (n being 0-7) \xnn Hexadecimal notation (n being 0-9, a-f, or A-F) \cx, \C-x Control-x \M-x Meta-x (c | 0x80) \M-\C-x Meta-Control-x \x Character x "
require_relative "../Modules" require_relative "../Piece" class Queen < Piece attr_reader :symbol, :color include Slidable def initialize(name, start_pos, color, board) super(name, start_pos, color, board) @symbol = :Q @color = color end def move_dirs return [[-1,0], [0,1], [1,0], [0,-1]...
module V1::ImgurApiWrapperHelper def handleRequest(response, errorMsg) if(response.status == 200) render :json => response.body else puts response render json: { :error => errorMsg }.to_json, :status => response.status end rescue JSON::ParserError ...
class StaticPagesController < ApplicationController before_action :logged_in_user, except: [:signup] def home @photos = Photo.all.reverse end def help end def about end def tutorial render "static_pages/tutorial_page_#{params[:id]}", layout: "home_layout" end def signup render layou...
describe Exporter::FieldContactNames do include_context "exporter" describe "minimal field_contact_name" do let!(:field_contact_name) { create(:field_contact_name) } it "exports" do export expect(record["fc_num"]).to eql("FC123") expect(record["field_contact_fc_num"]).to eql("FC123") ...
module AresClient # model pro praci se zakladnim vypisem ARES class Records attr_accessor :ic, :basic_output, :response, :http_response include HTTParty base_uri 'http://wwwinfo.mfcr.cz/cgi-bin/ares/darv_bas.cgi' def initialize(ic=nil) @ic = ic if ic end def fetch self.http_...
require 'rails_helper' describe CurrentCharacter do describe "#id" do it "returns the id of the character" do character = Character.create current_character = CurrentCharacter.new(character) expect(current_character.id).to eq character.id end end describe "#player_name" do it "retu...
require "spec_helper" describe Item do describe "Item.rate(item_id, incoming_rating)" do it "changes an items rating" do item = Item.new item.times_rated = 0 item.save! Item.rate(item.id, 5) item = Item.find(item.id) expect(item.times_rated).to eq 1 expect(item.rating).t...
# encoding: UTF-8 module API module V1 module Games class RelatedItems < API::V1::Base helpers API::Helpers::V1::GamesHelpers before do authenticate_user end namespace :games do namespace :related_items do desc "Create a new game GameRelate...
class AddRestaurantIDtoDeals < ActiveRecord::Migration def change add_column :deals, :restaurant_id, :integer end end
# frozen_string_literal: true class Rubocop < Aid::Script def self.description 'Runs rubocop against the codebase' end def self.help <<~HELP Usage: #{colorize(:green, '$ aid rubocop')} - runs all the cops #{colorize(:green, '$ aid rubocop fix')} - auto-fixes any issues HELP ...
class Message < ApplicationRecord include Rails.application.routes.url_helpers belongs_to :reporting_relationship, class_name: 'ReportingRelationship', foreign_key: 'reporting_relationship_id' belongs_to :original_reporting_relationship, class_name: 'ReportingRelationship', foreign_key: 'original_reporting_relat...
MagickTitle::Options.class_eval do # Alias the defaults for use later alias :standard_defaults :defaults # Overwrite defaults to include the attribute option def defaults standard_defaults.merge(:attribute => :title) end end
Pod::Spec.new do |s| s.name = 'PhilipsHueiOS' s.version = '1.1.3' s.license = 'Copyright (c) 2012- 2013, Philips Electronics N.V. All rights reserved.' s.summary = 'The Software Development Kit for Philips Hue on iOS' s.homepage = 'https://github.com/PhilipsHue/PhilipsHueSDK-iOS-OSX' s.requires_arc =...
class Candidate < ApplicationRecord belongs_to :job belongs_to :user, -> { where.not role: 'company_admin' } end
class SessionsController < ApplicationController layout "login" def new # render the login form end def create @user = User.find_by("LOWER(email) = ?", user_params[:email].downcase) if @user.present? && @user.authenticate(user_params[:password]) cookies.permanent.signed[:user_id] = @user.id...
require 'flip_the_switch/generator/base' require 'plist' module FlipTheSwitch module Generator class Plist < Base def generate ::Plist::Emit.save_plist(feature_states, output_file) end private def output_file File.join(output, 'Features.plist') end end end en...
# encoding: utf-8 class Zone attr_accessor :objects def initialize(&block) @objects = Array.new instance_eval(&block) end def objects(&block) if block_given? instance_eval(&block) else @objects end end def add(object) @objects << object end end
# frozen_string_literal: true require "spec_helper" RSpec.describe Milestoner::Errors::Base do subject(:error) { described_class.new } describe "#message" do it "answers default message" do expect(error.message).to eq("Invalid Milestoner action.") end end end
# encoding: utf-8 # # © Copyright 2013 Hewlett-Packard Development Company, L.P. # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights #...
class ChangeFiguresCorrectTableName < ActiveRecord::Migration[5.1] def change rename_table :name, :figures end end
class Rating < ApplicationRecord validates :value, :inclusion => 1..5 belongs_to :user belongs_to :post end
module TicTacToeGame class Play def initialize(board) @board = board end def possible_moves @board.map.with_index { |piece, idx| piece == "-" ? idx : nil }.compact end end end
require './board' class KnownBoard < Board UNKNOWN = -3 FLAGGED = -2 EXPLODED = -1 def initialize(width, height) super(width, height, UNKNOWN) end def known?(x, y) get(x, y) != UNKNOWN end def unknown?(x, y) get(x, y) == UNKNOWN end def flag!(x, y) set(x, y, FLAGGED) end ...
unit_tests do test "can try pr merge" do default_vcr_state do status = PRW.try_merge assert status.key?(:result) assert status.key?(:message) assert_equal :ok, status[:result] assert_equal status, PRW.build_status[:main][:steps][:merge] end end test "can try run build step...
class User < ActiveRecord::Base has_many :scores belongs_to :user_type def new_token s = SecureRandom.base64(24) s[0, if s.size > 32 then 32 else s.size end] self.token = s end end
class AppDelegate attr_accessor :should_kill_workers, :window def application(application, didFinishLaunchingWithOptions:launchOptions) application.setStatusBarHidden(true, withAnimation:UIStatusBarAnimationFade) @window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds) @window.rootViewControll...
# frozen_string_literal: true module WasteExemptionsShared class SummaryData include WasteExemptionsShared::PrepareDataForReview end class EnrollmentMailer < WasteExemptionsShared::ApplicationMailer # Note that because we were getting issues connecting to PG from here, possible because # we were run...
# -*- mode: ruby -*- # vi: set ft=ruby : # ARRAY APP VM vmsrvs=[ { :hostname => "dbapp", :ip => "192.168.1.16", :cpu => "2", :ram => 1024, :file => "" }, { :hostname => "webapp", :ip => "192.168.1.15", :cpu => "2", :ram => 1024, :file => "cfg_files.tgz" } ] # MAIN CONFI...
class IctVpnsController < ApplicationController before_filter :authenticate_user! def index if current_user && current_user.is_super_admin? @ict_vpn = IctVpn.page(params[:page]).per(2) elsif current_user && current_user.is_department_admin? @ict_vpn = IctVpn.page(params[:page]).per(2) else ...