text
stringlengths
10
2.61M
# frozen_string_literal: true module Decidim module Opinions module Admin # A command with all the business logic when an admin answers a opinion. class AnswerOpinion < Rectify::Command # Public: Initializes the command. # # form - A form object with the params. # opin...
FactoryGirl.define do factory :crammer_class, class: 'Crammer::Class' do name { Faker::Lorem.word.capitalize } user end end
Fabricator(:client) do bride_name { Faker::Lorem.name } bride_phone { Faker::PhoneNumber.phone_number } bride_email { Faker::Internet.safe_email } groom_name { Faker::Lorem.name } groom_phone { Faker::PhoneNumber.phone_number } groom_email { Faker::Internet.safe_email } end
# Install MySQL Client & Server unless node["chef-devstax"]["mysql"]["version"] Chef::Application.fatal! "chef-devstax.mysql.version attribute cannot be nil. Please populate that attribute." end db_root_passwd = node["chef-devstax"]["mysql"]["rootpasswd"] db_verison = node["chef-devstax"]["mysql"]["version"] # i...
class ChangePossibleAnswersType < ActiveRecord::Migration def up change_column :questions, :possible_answers, :string, null: false end def down change_column :questions, :possible_answers, :text end end
# -*- encoding : utf-8 -*- class Count include Mongoid::Document embedded_in :vote_event field :option, type: String field :value, type: Integer end
class Build < ApplicationRecord include Sluggable validates :title, presence: true, length: { maximum: 250 } end
class FantasyLeague < ActiveRecord::Base DEFAULT_LEAGUE_ID = 1 has_many :fantasy_teams validates :year, presence: true validates :division, presence: true def self.right_joins_fantasy_players(league_id) fantasy_team_subquery_by_league(league_id). merge(FantasyTeam.all_fantasy_players_with_details...
class CreatedPostEvent include ActiveEvent::EventType attributes :id, :title, :text, :user_id, :created_at, :topic_id def values attributes_except :id end end
def valid_number?(number_string) number_string.to_i.to_s == number_string && number_string.to_i != 0 end loop do input_1 = nil input_2 = nil result = nil my_boolean = true while my_boolean == true while input_1 == nil puts "Please enter a positive or negative integer:" input_1 = gets.chom...
class Word def initialize(string) @dic = Dictionary.new @user_word = string @killer_dic = Killer_Dic.new @candidate = make_candidate end def in_dic? return @dic.include?(user_word) end def make_candidate @dic.each do |word| if word[0] == @user_word.reverse[0] candid...
lib = File.expand_path('../lib/', __FILE__) $:.unshift lib unless $:.include?(lib) require 'boris/version' Gem::Specification.new do |s| s.name = 'boris' s.version = Boris::VERSION s.summary = 'Boris: A networked-device scanning library.' s.description = s.summary + ' Bo...
module HTTPalooza module Players class PatronPlayer < Base introducing! :patron, %w[ patron ] def response session = Patron::Session.new session.base_url = request.url response = session.get('') Response.new(response.status, response.body) end end end end
# == Schema Information # # Table name: requests # # id :integer not null, primary key # type :integer # status :integer # created_at :datetime not null # updated_at :datetime not null # user_id :integer # project_id :integer # class Request < ActiveRecord::Base e...
module Fog module Compute class Brkt class Real def list_workload_template_server_templates(workload_template_id) request( :expects => [200], :path => "v1/api/config/workloadtemplate/#{workload_template_id}/instancetemplates" ) end end ...
class ChangeDefaultRanking < ActiveRecord::Migration def change change_column :players, :rating, :integer, :default => 0 end end
# encoding: utf-8 require 'fileutils' require 'design_storyboard' require 'thor' require 'design_storyboard/version' module DesignStoryboard class Cli < Thor option :open, :type => :boolean desc 'build [INPUT_FILE_PATH] --open', 'Build storyboard (html) from file.' def build(path) Setting[:input_...
class Profile < ActiveRecord::Base belongs_to :user mount_uploader :avatar, AvatarUploader validates_uniqueness_of :user_id end
require 'rails_helper' feature 'user registers an account' do scenario 'successfully' do visit '/user/sign_up' fill_in 'Username', :with => 'username' fill_in 'Email', :with => 'personal@example.com' fill_in 'Password', :with => 'password' fill_in 'Password Confirm', :with => 'password' click_button 'Sig...
class Menu < ActiveRecord::Base has_one :rating mount_uploader :image, ImageUploader def getCurrentRate rating return Rating.new().currentRate(rating) end end
class MyPerformance < ApplicationRecord belongs_to :user belongs_to :exercice end
class JobsController < ApplicationController before_action :set_job, only: [:update, :destroy, :edit, :show] respond_to :json def index @jobs = Job.all @slots = Slot.all @friendJobs = FriendJob.all @hospitals = Hospital.all if current_prof @user = current_prof else @user = cur...
class User < ApplicationRecord validates :email, :passsword, presence: true, on: :step1 validates :first_name, :last_name, presence: true, on: :step2 end
class ExaminationsController < ApplicationController before_action :authenticate_user! def index load_examinations end def new build_examination end def edit load_examination build_examination end def create build_examination save_examination or render(:new) end def upda...
class AddColumnsToCceReports < ActiveRecord::Migration def self.up add_column :cce_reports, :max_mark, :float add_column :cce_reports, :obtained_mark, :float add_column :cce_reports, :converted_mark, :float end def self.down remove_column :cce_reports, :converted_mark remove_column :cce_repor...
module V1 module Entities class User < Grape::Entity include V1::Entities::Defaults expose :id, documentation: { type: String, desc: "用户编号" } expose :name, documentation: { type: String, desc: "姓名" } expose :mobile, documentation: { type: String, desc: "手机号码" } with_options(forma...
class AddPriceToLineItem < ActiveRecord::Migration def change add_column :line_items, :price, :decimal, precision: 8, scale: 2 end def up LineItem.all.each do |line_item| line_item.price = Product.find_by(id: line_item.product_id).price end end end
class Customer attr_reader :id, :datasource def initialize(id, datasource) @id = id @datasource = datasource end end
module Concerns::Help::Validation extend ActiveSupport::Concern included do validates :name, presence: true validates :help_category_id, presence: true end end
require "outputs/executor" module SpecRunner RSpec.describe(Executor) do let(:executor) { instance_spy("StdoutWriter") } subject { described_class.new(executor) } it "clears the screen and executes multiple commands as a single command" do subject.execute("echo hello", "echo world") expect...
atom_feed do |feed| feed.title "Colorado Financial Services News" feed.updated @news_articles.maximum(:updated_at) @news_articles.each do |news_article| feed.entry news_article, published: news_article.created_at do |entry| entry.title news_article.title entry.content news_article.content ...
require "base_stitch" class SlipStitch < BaseStitch def make self.class.abbrev end def self.abbrev "sl st" end def count 1 end end
namespace :report do THIS_WEEK = (Time.now.midnight - 7.days)..Time.now.midnight THIS_MONTH = (Time.now.midnight - 1.month)..Time.now.midnight THE_PAST_THREE_MONTHS = (Time.now.midnight - 3.months)..Time.now.midnight def generate_report(data) output_file = File.new('report.json', 'w') report = JSON.pr...
module Jekyll class CSTopicPage < Page def underscore(word) word.gsub('_', ' ') end def titleize(word) underscore(word).gsub(/\b('?[a-z])/) { $1.capitalize } end def semesterize(string) season = string[0..1] case season when "fa" season = "Fall" when ...
class Comment < ApplicationRecord validates_length_of :body, minimum: 5 belongs_to :article # связывание сущностей coment и arcticle end
require File.dirname(__FILE__) + '/../test_helper' class LocationTest < Test::Unit::TestCase fixtures :locations, :people def test_association assert_kind_of(Location, locations(:location1)) assert_equal(1, locations(:location1).people.size) assert_kind_of(Person, locations(:location1).people[0]) e...
# encoding: utf-8 class FeedbackMailer < ActionMailer::Base default from: APP_DATA["email"]["from"]["normal"], to: APP_DATA["email"]["to"]["feedback"] def feedback(feedback) @feedback = feedback mail(:subject => "反馈:#{@feedback.subject}" ) end def error_feedback(feedback) @feedback = feedback mail(:subjec...
class Rssreader < ActiveRecord::Base has_and_belongs_to_many :users # TO-DO: Re-visit validations validates :rssaddress, presence: true validates :friendly_name, presence: true scope :asc, -> { order('friendly_name ASC') } end
class AddPhotoCarouselToPhotos < ActiveRecord::Migration[5.2] def change add_column :photos, :photo_carousel, :boolean, default: true end end
require "active_record" require "active_record_repo/version" require "active_record_repo/models/user" module ActiveRecordRepo class << self def env @env ||= (ENV["TEPHUE_ENV"] || ENV["RAILS_ENV"] || "development").to_sym end def env=(new_env) @env = new_env.to_sym end def project...
class HiddenWord attr_reader :word, :displayed_word, :guess, :response def initialize(word) @word = word @displayed_word = "*" * word.length() # @displayed_word.gsub( / @word / , "*") @guess = "" @reponse = "" end # def receive_guess(guess) # @guess = guess # word_copy = @word ...
# frozen_string_literal: true class Rogare::Commands::Pick extend Rogare::Command command 'pick' usage '`!% <start> <end>` - Picks a number/letter between start and end' handle_help match_command /(\d+|[a-z])\s+(\d+|[a-z])/ match_empty :help_message def execute(m, start, ending) start, ending = [s...
=begin Karen West - April 7th, 2013 HW 1-2: Rock-Paper-Scissors In a game of rock-paper-scissors (RPS), each player chooses to play Rock (R), Paper (P), or Scissors (S). The rules are: R beats S; S beats P; and P beats R. We will encode a rock-paper-scissors game as a list, where the elements are themselves 2-elemen...
class Mileage < ActiveRecord::Base belongs_to :vehicle validates_presence_of :vehicle_id # validates :vehicle_id, length: { minimum: 1 } validates :vehicle_id, :numericality => { :only_integer => true, :greater_than => 0} validates_presence_of :filled_tank_on validates :filled_tank_on,...
class AudienceNameAndDocNameAreStringsNotIntegersDuh < ActiveRecord::Migration def self.up change_column :titles, :doc_name, :string change_column :titles, :audience_name, :string end def self.down change_column :titles, :doc_name, :integer change_column :titles, :audience_name, :integer end en...
# frozen_string_literal: true class ScheduleGenerator include MemoizedCourseScopes def initialize(agenda) @agenda = agenda end def combine combinations.each do |course_set| iterate(course_set, []) end end private def combinations if mandatory_courses.empty? courses.combina...
# frozen_string_literal: true ## --- BEGIN LICENSE BLOCK --- # Original work Copyright (c) 2015-present the fastlane authors # Modified work Copyright 2016-present WeWantToKnow AS # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the...
class AddDeletedColumnToWorks < ActiveRecord::Migration[5.2] def change add_column :works, :deleted, :boolean, default: false end end
class MembershipsController < ApplicationController before_action :authenticate_user! # POST /labs def create @membership = Membership.new(membership_params) if @membership.save redirect_to @membership.belongable, notice: 'Membership was successfully created.' else redirect_to root_...
require 'bundler' Bundler.require :test if ENV['COVERAGE'] require 'simplecov' SimpleCov.start do add_filter '/test/' end end if ENV['COVERALLS'] require 'coveralls' Coveralls.wear! end $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'soffes/blog' require 'soffes/blog/importer' # re...
class Holiday require 'holiday_japan' def self.holiday(day) weekend(day) || public_holiday(day) || substitute_holiday(day) end def self.weekend(day) !day.workday? end def self.public_holiday(day) !!HolidayJapan.check(day) end # 振替休日 def self.substitute_holiday(day) day.wday == 1 &&...
require_relative 'cronter/version' module Cronter class << self def convert_to_cron(frequency, time: nil, range: nil) cron_expression = parse_time(time) if frequency.is_a?(Symbol) cron_expression = parse_keyword(frequency, cron_expression) elsif frequency.is_a?(String) cron_exp...
require 'test/unit' require_relative './driver' include Test::Unit::Assertions include ::Driver step 'Go to the store website' do driver.navigate.to ENV['APP_URL'] assert_equal 'The Active Admin Store', driver.title end
class Group < ActiveRecord::Base attr_accessible :district, :lgid, :perfemale, :phase, :totalpart, :upazilla has_many :farmers has_many :gpfs, :through => :farmers def self.average_fat(date) gpfs.where("date(created_at) = ?", date).average(:fat) end end
num = ARGV[0] num = num.to_i str = "public class HUTupleInt#{num} " str +="implements Comparable<HUTupleInt#{num}>" str +=", Serializable" str +="{" # field for i in 0..num-1 str += "private int el#{i};" end str += "private int hashCode = 0;" # constructors str += "public HUTupleInt#{num}(){}" str += "public HUT...
require 'rails_helper' RSpec.describe Project, type: :model do it { should belong_to(:user) } it { should have_many(:tasks).dependent(:destroy) } it { should validate_presence_of(:title) } it { should validate_uniqueness_of(:title).scoped_to(:user_id) } end
class InfrastructurePolicy < ApplicationPolicy def show? return true if is_barito_superadmin? end def retry_provision? show? end def provisioning_check? show? end def retry_bootstrap? show? end def toggle_status? return true if is_barito_superadmin? false end def delet...
class ChangeCompanyUrlInStripes < ActiveRecord::Migration def change change_column :stripes, :company_url, :string, default: "" change_column :stripes, :company, :string, default: "" end end
class Vigil class Report attr_reader :status attr_reader :log def initialize(status, log) @status = status @log = log end def serialize { status: @status, log: @log.serialize, } end end end
FactoryGirl.define do sequence(:number) { |n| n.to_s } factory :user do given_name { Random.firstname } middle_name { Random.firstname } family_name { Random.lastname } email { "#{given_name.first}#{family_name}#{generate(:number)}@sample.com" } password { Random.alphanumeric(8) } passwor...
class Show attr_writer :name, :date, :genre @@all = [] def self.all @@all << self end def initialize(name, date, genre) @name = name @date = date @genre = genre end def on_the_big_screen Movie.all.select {|movie| movie.name == self.name} end def add_character(char) MovieOr...
# 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...
#! /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby $:.unshift(File.dirname(__FILE__) + '/../lib/') require 'optparse' require 'redcloth' if %w(--version -v).include? ARGV.first puts "#{RedCloth::NAME} #{RedCloth::VERSION}" exit(0) end output_as = "html" opts = OptionParser.new do |opts| op...
require "spec_helper" describe "Create external event of talk", :type => :request do let!(:user) { create(:user, :paul) } let!(:talk) { create(:talk, :users => [ user ], :owner => user.id) } context "when valid data" do before do login_as user click_link "Palestras" click_link "Compartilhe...
# events # name string, not null # description text # user_id integer, not null # date datetime, not null # active boolean class Event < ActiveRecord::Base belongs_to :user has_many :user_events has_many :users, through: :user_events end
json.array!(@auto_brands) do |auto_brand| json.extract! auto_brand, :id, :name, :auto_brand_photo json.url auto_brand_url(auto_brand, format: :json) end
require 'test_helper' class OriginalMenusControllerTest < ActionController::TestCase setup do @original_menu = original_menus(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:original_menus) end test "should get new" do get :new assert...
require 'ostruct' class MailLogRecipientList < ActiveRecord::Base belongs_to :mail_log serialize :recipients, Array def increment_recipient_count self.recipients_count ||= 0 self.recipients_count += 1 end def add_recipient (args) if args[:recipient_record] args[:recipient_record_id]...
class MoveAttemptCountFromRecordsToPuzzles < ActiveRecord::Migration def self.up add_column :puzzles, :attempt_count, :integer, :null => false, :default => 1 end def self.down remove_column :puzzles, :attempt_count end end
# NOTE: When using in an Extension, replace module name on following line with # that of your own Extension. module YourExtensionNamespace module FaceShading # Determine the (unshaded) color of the viewed side of a face. # If face is textured the average color of the texture will be used. # A custom pla...
class ApikeyController < ApplicationController before_action :logged_in_user, only: [:getkey, :changekey, :addkey] def getkey @user = current_user @keyapi = Apikey.find_by(user_id: @user.id) render json: [[@keyapi]] end def changekey @user = current_user if has_apikey? @keyapi = Ap...
require "rb-skypemac" require_relative "base_client" include SkypeMac class SkypeClient < BaseClient def send_message(message, title="") send_command "CHATMESSAGE #{@config.skype.chat_id} #{message}" if @config.skype.enable end def chat_ids send_command("SEARCH RECENTCHATS").sub("CHATS ","").split(/,/)...
class CreateTrainerComponents < ActiveRecord::Migration def change create_table :trainer_components do |t| t.integer :trainer_id, null: false, index: true t.integer :component_id, null: false t.string :component_type, null: false t.timestamps null: false end end end
DEBUG_LVL=2 require 'network' require 'helper_classes' include Network::Monitor include HelperClasses::DPuts def main #test_user #test_user_measure #test_json test_new_month end def assert(cond, str = nil) return if cond log_msg :assert, "Failed on #{str}" end def assert_equal(a, b, str = nil) return i...
require 'benchmark' test_string = "apples, pears # and bananas\ngrapes\nbananas !apples" args = ["#", "!"] # first try => def r_remove_comments(str, markers) formatted_string = "" str.each_line do |line| markers.each do |marker| line.slice!(/#{marker}.*$/) end formatted_string += line end re...
class CreateTweetStats < ActiveRecord::Migration def change create_table :tweet_stats do |t| t.datetime :date t.integer :num_tweets t.integer :num_rt t.timestamps null: false end end end
class WorldwidePolicy < DatabasePolicy def manage? user.present? && user.administrator? end def show? false end def update? false end def destroy? false end def index_association? association association = association.to_sym return false if %i[managed_records registrations...
# -*- coding: UTF-8 -*- # # Author:: lnznt # Copyright:: (C) 2011 lnznt. # License:: Ruby's # require 'openssl' require 'gmrw/extension/extension' require 'gmrw/extension/integer' module GMRW::Extension mixin String do def indent(n, s=' ') (s * n) + self end alias >> indent def div(n=1) ...
class Project < ActiveRecord::Base has_many :stories validates :name, :presence => true end
class AddEndsAtDateToEvents < ActiveRecord::Migration def change add_column :events, :ends_at_date, :date end end
class LinksController < ApplicationController def show @link = Link.find(params[:id]) end def new @link = Link.new end def create @link = Link.new(link_params) @link.user = current_user @link.save redirect_to @link end def link_params params.require(:link).permit(:url, :title) ...
class Holiday < ActiveRecord::Base validates :name, :presence => true validates :date, :presence => true, :uniqueness => true attr_protected :id end
class TumblrDatum < ActiveRecord::Base include Datum belongs_to :social_network set_type :tumblr_data def new_followers previous_datum.present? ? total_followers - previous_datum.total_followers : 0 end def total_investment (investment_agency + investment_ads + investment_actions) end end
require 'addressable/uri' module Poms module Api module Uris # URI for the /schedule API module Schedule API_PATH = '/v1/api/schedule'.freeze module_function def now(base_uri, channel) uri_for_path( base_uri, "/channel/#{channel}", ...
# :nodoc: # Attributes of a project in the test corpus of Java projects. # Test corpus has classes in classes/ or classes.zip. Same for test-classes. # Author:: Peter Kofler # Copyright:: Copyright (c) 2009, Peter Kofler. # License:: {BSD License}[link:/files/license_txt.html] # c...
require 'rails_helper' RSpec.describe Shop, type: :model do context'validation tests'do it 'ensures shop name presence' do shop = build(:shop, name:nil) expect(shop).to_not be_valid end it 'should save successfully' do shop = Shop.new(name:'test').save expect(shop).to eq(true) ...
class SpecializationWeightsController < ApplicationController before_action :set_specialization_weight, only: [:show, :edit, :update, :destroy] # GET /specialization_weights # GET /specialization_weights.json def index @specialization_weights = SpecializationWeight.all end # GET /specialization_weight...
require 'test_helper' class DealTest < ActiveSupport::TestCase test "should not save deal without title" do deal = Deal.new deal.category = categories(:valid_category) deal.merchant = merchants(:valid_merchant) assert_not deal.save, "Saved the deal without a title" end test "should not save dea...
class AuthenticationsController < ApplicationController #only call into before_action :authenticate_user, only: [:destroy] def new # are they already logged in? if current_user #they are! can't create them again redirect_to user else @user = User.new render :new # i dont know if this function act...
class Item include HTTParty # default_options.update(verify: false) # Turn off SSL verification base_uri "http://localhost:8082" format :json def Item.getItemById(id) response = get "/items?id=#{id}", headers: { "ACCEPT" => "application/json" } status = response.code ...
require File.join(File.dirname(__FILE__), '../iis/iis_object') require 'pathname' Puppet::Type.type(:iis_config).provide(:iis_config, :parent => Puppet::Provider::IISObject) do desc "IIS Config" confine :operatingsystem => :windows defaultfor :operatingsystem => :windows commands :appcmd => File.join(EN...
class Good < ApplicationRecord belongs_to :gooder, class_name: "User" belongs_to :gooded, class_name: "User" belongs_to :post, polymorphic: true, optional: true belongs_to :comment, class_name: 'Comment', foreign_key: 'post_id', ...
class GcmsController < ApplicationController protect_from_forgery except: [:create] def create gcm = Gcm.new(gcm_params) if gcm.save render status: 200, json: { 'message': 'OK' } else render status: 422, json: { 'message': 'failure' } end end private def gcm_params params.r...
module Admin class SeminarsController < BaseController before_action :set_seminar, only: %i[show edit update destroy attendees pras versions toggle_category publish unpublish finish_editing finish_layout] def index authorize Seminar respond_to do |format| ...
class CreateSchedules < ActiveRecord::Migration def change create_table :schedules do |t| t.string :status t.string :crn t.string :course t.string :sect t.string :part_term t.string :title t.string :cr_hrs t.string :beg_date t.string :end_date t.string ...
class Roll < ApplicationRecord validates :player_id, :die_one, :die_two, presence: true validates :die_one, :die_two, numericality: { greater_than: 0, less_than: 7 } belongs_to :player def total die_one + die_two end end
require 'colorize' module Command # height - get block height class Base def height send_chain send_final_message(height_prefix) msgs = receive_message parse_height(msgs[1]) if msgs.length == 2 end def parse_height(resp) resp.unpack('H*').first.to_i(height_length).to_s.lj...
require 'rails_helper' RSpec.describe User, type: :model do # pending "add some examples to (or delete) #{__FILE__} before { @user = FactoryBot.build(:user) } subject { @user } it { should validate_presence_of(:email) } it { should validate_uniqueness_of(:password) } it { sho...
class MutantsController < ApplicationController before_action :set_mutant, only: [:show, :update, :destroy] # GET /mutants def index @mutants = Mutant.all render json: @mutants end # GET /mutants/1 def show render json: @mutant end # POST /mutants def create @mutant = Mutant.new(mu...
# Source: https://launchschool.com/exercises/5c3e3cf3 # Write a program that reads the content of a text file and then prints the # longest sentence in the file based on number of words. Sentences may end with # periods (.), exclamation points (!), or question marks (?). Any sequence of # characters that are not space...