text
stringlengths
10
2.61M
module MytargetApi # An API method. It is responsible for generating it's full name and determining it's type. class Method include Resolvable # A pattern for names of methods with a boolean result. PREDICATE_NAMES = /^is.*\?$/ # Calling the API method. # It delegates the network request to `A...
require 'treetop/runtime' require_relative 'node_extensions' require_relative 'asciidoctor_grammar' module Asciidoctor # Asciidoctor Inline Parser module InlineParser @parser = ::AsciidoctorGrammarParser.new def self.parse text # HACK: Use the following rule to parse a literal line. # Is it p...
require 'controller_modules/profile_info_require_login' class EducationInfosController < ApplicationController include ControllerModules::ProfileInfoRequireLogin private :require_login, :require_login_for_delete before_action :require_login, only: [:new] before_action :require_login_for_delete, only: [:delete...
class Mail::AreasController < Mail::ApplicationController before_action :fetch_area def summary summary_period = PlaceMailer::SUMMARY_PERIOD @subject = I18n.translate('mail.place.summary.subject', place: @place.name) @start_of_period = summary_period.ago.beginning_of_week @end_of_period = @start_...
Splashbox::Application.routes.draw do root "home#show" get '/waitlist', to: 'home#index', as: :waitlist match 'auth', via: [:post], to: 'dropbox#authorize', as: :auth match 'callback', via: [:get], to: 'dropbox#authorized_callback', as: :callback end
class AddLevelToEmployees < ActiveRecord::Migration[5.2] def change add_column :employees, :level, :integer, default: 0 add_index :employees, :level end end
require "rails_helper" RSpec.feature "User deletes an artist" do scenario "user can delete unwanted artist" do artist_1 = Artist.create(name: "BOB MARLEY", image_path: "http://cps-static.rovicorp.com/3/JPG_400/MI0003/146/MI0003146038.jpg") artist_2 = Artist.create(name: "LCD SOUNDSYSTEM", image_path: "http:...
class Audio::PercentilePresenter < Audio::SegmentPresenter def ayah_cumulative_percentile filters = { audio_recitation_id: recitation_id, chapter_id: chapter_id } audio_file = Audio::ChapterAudioFile.where(filters).first if audio_file audio_file.timing_percentiles else []...
# Ruby LOOPS # while loop i = 0 while i <= 5 puts "I: #{i}" i += 1 end i = 5 while i>=0 puts "I: #{i}" i -= 1 end # iterator loop 5.times do |i| puts "#{i}: wow" end 10.downto(4) do |i| puts "down to #{i}" end 8.upto(12) do |i| puts "up to #{i}" end # range num_array = (1..10).to_a p num_array ...
module JekyllBuildEbook module Hooks def self.register overwrite_post_data end def self.overwrite_post_data Jekyll::Hooks.register :posts, :pre_render do |post, _payload| layout = post.site.config['ebook']['layout'] permalink = "#{post.cleaned_relative_path}.xhtml" ...
class Item < ApplicationRecord extend ActiveHash::Associations::ActiveRecordExtensions belongs_to :category belongs_to :status belongs_to :shipping_cost belongs_to :prefecture belongs_to :delivery_time belongs_to :user has_one_attached :image has_one :order with_options presence: true do valida...
require 'spec_helper' describe EntitiesController, :type => :controller do before(:all) do User.destroy_all Entity.destroy_all @john = User.create! :admin => false @maria = User.create! :admin => false @admin = User.create! :admin => true @private = Entity.create! :name => ...
# coding: utf-8 module Apress module Images # Public: удаляет непривязанную к какому-либо объекту картинку class DeleteImageJob extend Resque::Plugins::ExponentialBackoff @queue = :images_deleting @backoff_strategy = [1.minute, 5.minutes, 15.minutes, 30.minutes] @retry_delay_multipl...
class LibMemcache < DebianFormula homepage 'http://people.freebsd.org/~seanc/libmemcache/README' url 'http://people.freebsd.org/~seanc/libmemcache/libmemcache-1.4.0.rc2.tar.bz2' md5 '402c957cd71538c07a263542eeb513d1' name 'libmemcache' section 'libs' version '1.4.0.rc2+github1' description 'the old C API...
class MarketsController < ApplicationController # /api/v1/markets def index render json: Market.all.as_json(only: [:id, :name]), status: :ok end # /api/v1/markets/prices/BTC-LTC def prices if params[:market_name].present? if Market.exists?(name: params[:market_name]) @market = Market.f...
class AddDetailToRegistrationCourses < ActiveRecord::Migration def self.up add_column :registration_courses, :include_additional_details, :boolean add_column :registration_courses, :additional_field_ids, :string end def self.down remove_column :registration_courses, :include_additional_details re...
# == Schema Information # # Table name: diaper_drive_participants # # id :integer not null, primary key # address :string # business_name :string # comment :string # contact_name :string # email :string # latitude :float # longitude :float # pho...
class RenameDatesInEvents < ActiveRecord::Migration def change rename_column :events, :from, :start rename_column :events, :until, :stop end end
require 'formula' class Pngout < Formula url 'http://static.jonof.id.au/dl/kenutils/pngout-20110722-darwin.tar.gz' homepage 'http://www.jonof.id.au/kenutils' sha1 'f268caf5d5c72fc9a0dd42db38839b4a6b9c7094' def install prefix.install Dir['*'] File.symlink(prefix+'pngout', '/usr/local/bin/pngout') e...
# 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 RemoveVenueStyleFromEvents < ActiveRecord::Migration[5.0] def change remove_column :events, :venue_style, :integer end end
# # Cookbook Name:: bcpc-hadoop # Attributes: jolokia # # Copyright 2017, Bloomberg Finance L.P. # # 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...
FactoryGirl.define do factory :post do association :user, factory: :staff_user content { Faker::Lorem.sentence(5) } association :publisher, factory: :teacher_user categories { [create(:category)] } trait :institutional do publisher { create(:educational_institution) } end end end
class Page < ApplicationRecord belongs_to :sitemap_file def to_s url end def parser WebPageParser::PageParser.new(url) end end
require "rails_helper" RSpec.describe CalculateTotalActualCostBatchJob, type: :job do include ActiveJob::TestHelper let(:strain) { Common::Strain.create!(name: 'xyz', strain_type: 'indica') } let(:facility) do facility = create(:facility, :is_complete) facility.rooms.each do |room| room.rows.each ...
require 'fluent/plugin/input' class Fluent::Plugin::ConfigExpanderTestInput < Fluent::Plugin::Input Fluent::Plugin.register_input('config_expander_test', self) config_param :tag, :string config_section :node, param_name: :nodes, multi: true do config_param :attr1, :string, default: nil config_param :att...
ActiveAdmin.register Student do filter :course filter :username filter :last_name filter :first_name filter :fees index do column :username column :first_name column :last_name column :course column :fees column :phone_number actions end form do |f| f.inputs "student" do f.i...
class CreateEventAttrs < ActiveRecord::Migration[5.2] def change create_table :event_attrs do |t| t.string :name, null: false, limit: 190 t.timestamps end add_index :event_attrs, :name, unique: true end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Ch...
class Library attr_reader :books def initialize() @books = [] end def add_book(book) @books.push(book) end def find_by_title(title) for book in @books if book[:title] == title return book end end end def get_rental_details(title) book = find_by_title(title) ...
# lib/puppet/type/rbac_user.rb Puppet::Type.newtype(:rbac_token) do desc <<-EOT Manages RBAC user token for Puppet Enterprise EOT ensurable do defaultvalues defaultto :present end newparam(:name, :namevar => true) do desc "The user" end newparam(:password) do desc "RBAC user's pass...
class Todo < ActiveRecord::Base belongs_to :project has_one :users_todo end
case platform_family when 'debian', 'rhel', 'amazon' default['sysctl']['conf_dir'] = '/etc/sysctl.d' else default['sysctl']['conf_dir'] = nil end default['sysctl']['params'] = {} default['sysctl']['allow_sysctl_conf'] = false default['sysctl']['params']['fs']['file-max'] = 100000 # Reboot after a kernel panic d...
class AddActiveFieldToWorkspaceLayers < ActiveRecord::Migration[5.0] def change add_column :workspace_layers, :active, :boolean, default: false end end
class User < ApplicationRecord has_many :user_sports, dependent: :destroy has_many :sports, through: :user_sports has_many :user_teams, dependent: :destroy has_many :teams, through: :user_teams accepts_nested_attributes_for :user_sports, allow_destroy: true validates :name, presence: true validates :ema...
require 'spec_helper' describe TradeLead::CanadaData do let(:resource) { "#{Rails.root}/spec/fixtures/trade_leads/canada/canada_leads.csv" } let(:importer) { described_class.new(resource) } let(:expected) { YAML.load_file("#{File.dirname(__FILE__)}/canada/expected_canada_leads.yaml") } it_behaves_...
class Survey::AnsChoice < ActiveRecord::Base has_one :comment, class_name: "Survey::Comment", dependent: :destroy belongs_to :ans, class_name: "Survey::Ans" belongs_to :choice, class_name: "Survey::Choice" accepts_nested_attributes_for :comment structure do end end
class Club < ApplicationRecord belongs_to :city, :optional => true end
#!/usr/bin/env ruby require 'date' require 'rexml/document' include REXML # so that we don't have to prefix everything with REXML::... blogger_id = "111111111111" blog_title = "my blog" author_name = "my name" author_email = "noreply@blogger.com" blog_id = "222222222222222" blog_name = "myblog" file = Fi...
module Cookies class Cookie STANDARD_ATTR = ["comment","domain","expires","max-age","path","version","secure","httponly"] COOKIE_REGEXP = /[^=\s;,]+=[^;,]*[;,]?\s*((((path|version|max-age|comment|domain)=[^;,]*)|(expires=[a-zA-Z]+,[-\w\s:]+)|(secure|httponly))[;,]?\s*)*/i attr_accessor :name, :conte...
def caesar_encode(string,offset) alphabets = [*('a'..'z')] caps = [*('A'..'Z')] word = string.split("") word.map do |character| if character =~ /[[a-z]]/ encode = alphabets.index(character)+offset alphabets[encode] alphabets[encode% 26] elsif character =~ /[[A-Z]]/ caps_encode = ...
# Handling de response of all actions and set a default status module Response def json_response(object, status = :ok, serializer: nil, each_serializer: nil, method: :render, include: nil) send method, js...
class UpdateContactName < ActiveRecord::Migration def up rename_column :contacts, :Name, :name end def down rename_column :contacts, :name, :Name end end
# frozen_string_literal: true module GemTemplate VERSION = '1.0.0' end
# == Schema Information # # Table name: employees # # id :integer not null, primary key # address :string # birthdate :datetime # city :string # country :string # email :string # fax :string # first_name :string # hiredate :datetime # last_name :string # ...
class ShowsController < ApplicationController def index @show = Show.all render json: @show end def show @show = Show.find_by(id: params[:id]) render json: @show end def create @show = Show.create(show_params) render json: @show end ...
FactoryGirl.define do factory :assignment do association :user association :organization role "Member" end end
class DatePurchase < ApplicationRecord has_many :store_purchases, inverse_of: :date_purchase accepts_nested_attributes_for :store_purchases, allow_destroy: true; validates :total_cost, presence: true validates :date, presence: true, uniqueness: true scope :cost_date_by_week, -> (num, next_date){where(date:...
class DropInventoryOrdersRelation < ActiveRecord::Migration def change drop_table :inventory_orders end end
class TagsController < ApplicationController api :GET, '/tags', 'List tags with tagging_count' def index respond_with_params ActsAsTaggableOn::Tag.all end api :POST, '/products/:product_id/tags', 'Add tags to product' param :tag_list, Array, required: true, desc: 'Array of tag strings' param :product_i...
class KlassSpell < ActiveRecord::Base belongs_to :klass belongs_to :spell end
require 'rails_helper' RSpec.describe Link, type: :model do describe "validation" do it "is invalid without url" do link = Link.create() expect(link).to be_invalid end it "is valid with required attributes" do link = Link.create(url: "http://google.com") expect(link).to be_valid ...
# -*- coding: utf-8 -*- class StatusGenerator def initialize(options) @bitly = options[:bitly] end def generate(status) url = @bitly.shorten("https://twitter.com/#{status.user.screen_name}/status/#{status.id}") footer = " via #{url.short_url}" text = status.text.gsub(%r!@(\w+)!) { "#$1" } "...
class MediaGallery < ActiveRecord::Base has_many :media_medias, autosave: true, dependent: :destroy, inverse_of: :media_gallery belongs_to :playground accepts_nested_attributes_for :media_medias, :allow_destroy => true end
feature 'InvitationsController' do include ActiveJob::TestHelper let!(:user){ create(:user, :confirmed) } let!(:user_02){ create(:user, :confirmed) } context 'invitation creation' do it 'should successfully create invitation' do new_invitation = { recipient_name: "Pedrito Bodoque", recipie...
# frozen_string_literal: true module ShopifyApp module EnsureAuthenticatedLinks extend ActiveSupport::Concern included do before_action :redirect_to_splash_page, if: :missing_expected_jwt? end private def redirect_to_splash_page splash_page_path = root_path(return_to: request.fullp...
class Question < ApplicationRecord belongs_to :game has_many :answers def correct_answer answers.find_by(correct: true) end end
Pod::Spec.new do |s| s.name = "PGChinaMap" s.version = "1.0.0" s.ios.deployment_target = '6.0' s.osx.deployment_target = '10.8' s.summary = "Draw a map of China, support manual clicks, and select" s.homepage = "https://github.com/PggMan/ChinaMap" s.license = "MIT" s.author = { "P...
class Membership < ActiveRecord::Base belongs_to :project belongs_to :user validates_uniqueness_of :project_id, :message => "can be only joined once", :scope => 'user_id' end
# frozen_string_literal: true require 'spec_helper' RSpec.describe Robots::DorRepo::Assembly::Jp2Create do let(:robot) { described_class.new } let(:object_client) do instance_double(Dor::Services::Client::Object, find: cocina_model, update: true) end let(:access) { { view: 'world' } } let(:druid) { "dru...
class MembershipsController < ApplicationController def create board = Board.find(params[:board_id]) user_info = params[:user] user = user_info.split.length > 1 ? User.find_by_fname_and_lname(*user_info.split) : User.find_by_email(user_info) if user membership = board...
class ElementsController < ApplicationController #after_filter :load_piece def index @piece = Piece.find(params[:piece_id]) @elements = @piece.elements end def new @piece = Piece.find(params[:piece_id]) @element = @piece.elements.new end def create @piece = Piece.find(params[:piece_id...
# frozen_string_literal: true module Thanx # rubocop:disable Style/ClassAndModuleChildren module Style VERSION = '0.0.27' end end
require "cabin/namespace" require "cabin/mixins/logger" # Colorful logging. module Cabin::Mixins::Colors def included(klass) klass.extend(Cabin::Mixins::Logger) end COLORS = [ :black, :red, :green, :yellow, :blue, :magenta, :cyan, :white ] COLORS.each do |color| # define the color first define_me...
Dashboard::App.controllers :chart do get :index do @chart_types = Chart.new().chart_types @departments = Department.all(:order => 'id') @tags = Tag.all(:order => 'id desc', :limit => 10) render 'index' end get :new do @chart_types = Chart.new().chart_types @departments = Dep...
class SessionsController < ApplicationController def new end def create @user = User. find_by(username: params[:username]). #if we find the user we return, if not return nil try(:authentificate, params[:password]) #chain to the authentif method, and apply to nil,if we dont find the us...
class CreateProblemReports < ActiveRecord::Migration[5.1] def change create_table :problem_reports do |t| t.references :reporter_user t.references :last_update_user t.timestamps end end end
=begin On the other hand, if the coordinates are safe, maybe the best you can do is try to find a region near as many coordinates as possible. For example, suppose you want the sum of the Manhattan distance to all of the coordinates to be less than 32. For each location, add up the distances to all of the given coordi...
# frozen_string_literal: true # This concern Checks data/params sent from each VIEW associated with each # and can be used to direct STATE - before update is called on # enrollment # # TODO: Review the functionality here, it seems to be trying to do too much # rubocop:disable Metrics/ModuleLength module WasteExemptio...
require 'rails_helper' RSpec.describe AnswersController, type: :controller do let!(:user) {User.create!(name: 'VanVan',location: 'Cuba',username: 'aquinomas',password: 'aquinomas')} let!(:question) {Question.create!(title: "Test title", body: "Test body", user: user)} let!(:test_answer) {Answer.create!(body: "S...
require 'rspec' RSpec.describe 'MineBlastEvaluatorSpec' do context 'Sorting' do let(:test_mines) { ['2 -1 3', '-1 1 2', '2 2 2', '4 1 2', '1 1 1'] } let(:correct_sort_order) { ['2 -1 3', '2 2 2', '-1 1 2', '1 1 1', '4 1 2'] } before do load_test_data(test_mines) system('ruby app/mine_blast_...
#For those just starting out, one suggested way to work on your code is to have a command window open and a text editor with this #file loaded. Make changes to this file and then run 'ruby part1.rb' at the command line, this will run your program. Once you're #satisfied with your work, save your file and upload it to...
class Api::ProfileController < ApplicationController before_action :authenticate def show end def events profile = Profile.find(params[:id]) events = profile.medias.where(type_id: 5) render json: {events: events} end def images_videos profile = Profile.find(params[:id]) medias = profile.medias.wher...
#!/usr/bin/env ruby def parse_direction(ch) case ch when 'U' [0, -1] when 'D' [0, 1] when 'L' [-1, 0] when 'R' [1, 0] else raise "Unknown direction #{ch}" end end coords = [] infile = ARGV[0] || 'input.txt' File.readlines(infile).map(&:strip).each_with_index do |wire,idx| x = 0 y...
require 'test_helper' require 'securerandom' class ShortUUIDTest < Minitest::Test def test_that_it_has_a_version_number refute_nil ::ShortUUID::VERSION end def test_shorten assert_equal ShortUUID.shorten('00bb416c-5a7a-46e3-9e40-31bd76a246bb'), '1NZiG3Y1hj5wI3QRSa5UZ' end def test_expand assert...
class Hiari < ActiveRecord::Base validates :discover_ari_date, presence: true validates :longitude, presence: {message: " 住所を検索し、位置を指定してください。"} validates :latitude, presence: {message: " 住所を検索し、位置を指定してください。"} validates :title, presence: true validate :check_date #未来日付チェック mount_uploader :image, ImageUpload...
require 'spec_helper.rb' describe StreamsController do before(:each) do @user = Factory(:user) sign_in @user end describe "#new" do before do get :new end it "should be succesful" do response.should be_success end it "should create a stream object" do assigns(:str...
class EditColumnDescriptionTwoOnService < ActiveRecord::Migration def up change_column :services, :description_two, :text end def down change_column :services, :description_two, :string end end
class Addcolumntomobiles < ActiveRecord::Migration[5.0] def change add_column :mobiles, :brand_id, :integer add_column :mobiles, :manufacturing_date, :timestamp end end
class PreferencesController < ApplicationController def hide_previous_notices @current_user.preference.update_attributes :last_closed_notice_date => Time.now unless @current_user.blank? end end
require 'date' months = (1..12).each_with_object({}) do |index, memo| last_day = Date.new(2018, index, -1) month_name = last_day.strftime('%B') days_count = last_day.day memo[month_name.to_sym] = days_count end months.each { |month_name, days_count| puts month_name if days_count == 30 }
class CreateCompanies < ActiveRecord::Migration def change create_table :companies do |t| t.string :name t.string :country t.string :region t.references :stage t.text :description t.text :team t.float :revenue t.timestamps end add_index :companies, :stage_i...
module CDI module V1 class SimpleGamePollSerializer < ActiveModel::Serializer root false attributes :id, :status, :status_changed_at, :user_id, :image_url, :created_at, :updated_at end end end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. #before_action :all_tasks, only: [:index, :create] protect_from_forgery with: :exception respond_to :html, :js after_filter :set_csrf_cookie_for_ng ...
class Billpart < ActiveRecord::Base attr_accessible :bill_id, :part_amt, :particular_id belongs_to :bill belongs_to :particular end
class Term < ApplicationRecord belongs_to :user belongs_to :section belongs_to :agreement has_many :notes acts_as_commentable include Workflow workflow do state :draft do event :set_draft, :transitions_to => :draft event :set_approved, :transitions_to => :approved end state :approv...
class Settings::UserSessionsController < ApplicationController def destroy @session = current_user.sessions.find(params[:id]) authorize [:settings, @session] @session.destroy respond_to do |format| format.html { redirect_to security_settings_url, notice: 'Successfully killed session!' } f...
class MiscUtil def self.uri_get(uri, logger = nil) response = nil uri = URI(uri) logger.info "Calling [#{uri.to_s}]" if logger Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http| request = Net::HTTP::Get.new uri.request_uri response = http.request req...
namespace :order do desc 'create a new order' task :create, [:quantity] => :environment do |task, args| begin args[:quantity].to_i.times do Order::CreateInteractor.new.execute! end rescue ActiveRecord::RecordInvalid => error puts "Exception rescue: #{error.message}" end end ...
class MediaScanner attr_accessor :roots def self.singleton @singleton ||= MediaScanner.new @singleton.reload_roots @singleton end def initialize(roots = nil) self.roots = roots || MediaRoot.active end def reload_roots self.roots = MediaRoot.active end def raze_and_build Phil...
class EventsController < ApplicationController ################################################################ # The events controller is also the home page of our webpage, # and contains the calendar in its view, with all visible events # displayed. It also contains the calls that determine what # events ...
#class for Model2 goes here #Feel free to change the name of the class class Doctor < ApplicationRecord has_many :appointments has_many :patients, through: :appointments end
class FontRoboto < Formula head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "apache/roboto" desc "Roboto" desc "Font with a mechanical skeleton and the forms are largely geometric" homepage "https://fonts.google.com/specimen/Roboto" def install (s...
json.array!(@groupes) do |groupe| json.extract! groupe, :id, :nom, :salle, :tache json.url groupe_url(groupe, format: :json) end
class FontPhotonicoCode < Formula version "1.4" sha256 "a6919ca4e80089843027c0e17bee2ab1f7a8f022ad651425cabe8c07ef8e53a2" url "https://github.com/Photonico/Photonico_Code/releases/download/#{version}/Photonico.#{version}.Regular.ttf" desc "Photonico Code" desc "Free, monospace, slab-serif style font for codin...
# # Author:: Matheus Francisco Barra Mina (<mfbmina@gmail.com>) # © Copyright IBM Corporation 2015. # # LICENSE: MIT (http://opensource.org/licenses/MIT) # module Fog module Softlayer class Compute class Mock # Gets all Virtual Guest active tickets # @param [Integer] id # @return [Ex...
class AddBlobFieldsToClaim < ActiveRecord::Migration[5.1] def change add_column :claims, :damage_room_overview_1, :binary add_column :claims, :details_of_damage_1, :binary add_column :claims, :damage_room_overview_2, :binary add_column :claims, :details_of_damage_2, :binary end end
class VisitorMailer < ApplicationMailer # method that the worker will execute def contact_email(name, email, message) @name = name @email = email @message = message mail(from: @email, to: 'javier@badaboom.com', subject: 'New Visitor\'s Email') end end
class SeparateNames < ActiveRecord::Migration def self.up if ::Subscription.table_exists? rename_column ::Subscription.table_name, :name, :given_name add_column ::Subscription.table_name, :family_name, :string end end def self.down if ::Subscription.table_exists? rename_column...
# encoding: UTF-8 module FreeImage ## # FreeImage supports the following color types: # # :minis_black:: Monochrome bitmap (1-bit) -> first palette entry is black. # Palletised bitmap (4 or 8-bit) and single channel non standard bitmap -> the bitmap has a greyscale palette # :minis_...