text
stringlengths
10
2.61M
require 'stax/aws/emr' require 'yaml' module Stax module Emr def self.included(thor) thor.desc(:emr, 'Emr subcommands') thor.subcommand(:emr, Cmd::Emr) end end module Cmd class Emr < SubCommand COLORS = { RUNNING: :green, WAITING: :green, TERMINATING: :red, TERMINATED: :red, TERMINATED_WITH_ERRORS: :red, } no_commands do def stack_emr_clusters Aws::Cfn.resources_by_type(my.stack_name, 'AWS::EMR::Cluster') end end desc 'status', 'EMR cluster state' def status print_table stack_emr_clusters.map { |r| c = Aws::Emr.describe(r.physical_resource_id) [color(c.status.state, COLORS), c.status.state_change_reason.message] } end desc 'describe', 'describe EMR clusters' def describe stack_emr_clusters.each do |r| Aws::Emr.describe(r.physical_resource_id).tap do |c| puts YAML.dump(stringify_keys(c.to_hash)) end end end desc 'groups', 'EMR instance groups' def groups stack_emr_clusters.each do |r| debug("Instance groups for #{r.logical_resource_id} #{r.physical_resource_id}") print_table Aws::Emr.groups(r.physical_resource_id).map { |g| [g.id, color(g.status.state, COLORS), g.name, g.instance_type, g.running_instance_count, g.market] } end end desc 'instances', 'EMR instances' def instances stack_emr_clusters.each do |r| debug("Instances for #{r.logical_resource_id} #{r.physical_resource_id}") group_names = Aws::Emr.groups(r.physical_resource_id).each_with_object({}) { |g,h| h[g.id] = g.name } print_table Aws::Emr.instances(r.physical_resource_id).map { |i| [i.id, i.ec2_instance_id, group_names[i.instance_group_id], i.instance_type, color(i.status.state, COLORS), i.public_ip_address] } end end end end end
require 'rails_helper' require 'spec_helper' describe Pokemon do describe "creation" do it "should be valid" do pika = FactoryGirl.build(:pikachu) expect(pika).to be_valid end end end
a = [1,2,3,9,1,4,5,2,3,6,6] # Eliminar el último elemento puts 'arreglo original' p a a.delete_at(-1) puts 'elimina ultimo elemento del arreglo' p a #Eliminar el primer elemento. a.delete_at(0) puts 'elimina el primer elemento' p a #Eliminar el elemento que se encuentra en la posición media, si el arreglo tiene un número #par de elementos entonces remover el que se encuentre en la mitad izquierda. if (a.length).even? elimina=(a.length/2)/2 a.delete_at(elimina) puts 'elimina elemento que se encuentra en la posicion media, de la media en el lado izquierdo ' p a else elimina = a.length/2 a.delete_at(elimina) puts 'elimina elemento que se encuentra en la posicion media ' p a end #Borrar el último elemento mientras ese número sea distinto a 1. a.delete_at(-1) if a[-1] !=1 puts 'borra ultimo elemento siempre y cuando sea distinto de uno' p a #Utilizando un arreglo vacío auxiliar y operaciones de push and pop invertir el orden de los #elementos en un arreglo auxiliar=[] a.length.times do |i| aux = a.pop auxiliar.push(aux) end puts 'arreglo invertido ' p auxiliar
require 'helper' describe Trellohub::Form::Issue do describe '#valid_attributes' do it 'returns valid_attributes' do expect(Trellohub::Form::Issue.valid_attributes).to eq %i( title labels state assignee milestone ) end end describe '#accessible_attributes' do it 'returns accessible_attributes' do expect(Trellohub::Form::Issue).to receive(:prefix).and_call_original expect(Trellohub::Form::Issue.accessible_attributes).to eq %i( issue_title issue_labels issue_state issue_assignee issue_milestone issue_milestone_title ) end end describe '#readable_attributes' do it 'returns readable_attributes' do expect(Trellohub::Form::Issue).to receive(:prefix).and_call_original expect(Trellohub::Form::Issue.readable_attributes).to eq %i( issue_number issue_repository issue_created_at issue_updated_at issue_closed_at ) end end describe '#prefix' do it 'returns prefixed symbol array' do expect(Trellohub::Form::Issue.prefix %w(aaa bbb)).to eq %i(issue_aaa issue_bbb) end end describe '.import_issue' do it 'imports a issue' do duped_issue = double expect(duped_issue).to receive(:number) expect(duped_issue).to receive(:state) issue = double(dup: duped_issue) form = Trellohub::Form.new expect(form).to receive(:build_issue_attributes_by_issue) expect(form).to receive(:build_card_attributes_by_issue) form.import_issue('aaa/bbb', issue) end end describe '.issue_repository_name' do it 'returns repository name' do form = Trellohub::Form.new form.instance_variable_set(:@issue_repository, 'aaa/bbb') expect(form.issue_repository_name).to eq 'bbb' end end end
require 'yaml' class Configuration attr_accessor :options attr_accessor :browser def self.config_path=(path) @@config_path = path end def initialize raise ConfigurationException, "Missing configuration file" unless File.exists?(@@config_path) environment = ENV['env'] browser = ENV['browser'] configs = YAML.load_file(@@config_path) @options = configs[environment] @browser = configs[browser] end end class ConfigurationException < StandardError; end;
require 'pp' class School VERSION = 1 def initialize @grades = {} end def add(student, grade) @grades[grade] ||= [] @grades[grade].push(student).sort! end def grade(grade) @grades[grade] ||= [] @grades[grade].sort end def to_h Hash[@grades.sort] end end
Warden.test_mode! RSpec.describe "UserSessions" do after(:each) do Warden.test_reset! end it "allows a user to register" do visit new_user_registration_path fill_in(:'user_name', with: "alicia") fill_in(:'user_email', with: "alicia@example.com") fill_in(:'user_password', with: "password") fill_in(:'user_password_confirmation', with: "password") click_button('Sign up') expect(page).to have_current_path(root_path) expect(page.status_code).to be 200 end it "does not allow a user to register with invalid name" do visit new_user_registration_path user = create :user fill_in(:'user_name', with: "n") fill_in(:'user_email', with: user.email) fill_in(:'user_password', with: user.password) fill_in(:'user_password_confirmation', with: user.password) click_button('Sign up') expect(page).to have_current_path('/users') expect(page).to have_text("Nameis too short") end it "does not allow a user to register with invalid name" do visit new_user_registration_path user = create :user fill_in(:'user_name', with: "1234567890123456789012345678901") fill_in(:'user_email', with: user.email) fill_in(:'user_password', with: user.password) fill_in(:'user_password_confirmation', with: user.password) click_button('Sign up') expect(page).to have_current_path('/users') expect(page).to have_text("Nameis too long") end it "does not allow a user to register with invalid email" do visit new_user_registration_path user = create :user fill_in(:'user_name', with: user.name) fill_in(:'user_email', with: "email") fill_in(:'user_password', with: user.password) fill_in(:'user_password_confirmation', with: user.password) click_button('Sign up') expect(page).to have_current_path('/users') expect(page).to have_text("Emailis invalid") end it "sends an email to a user for confirmation" do user = attributes_for :user , confirmed_at: nil visit new_user_registration_path fill_in "Name" , with: user[:name] fill_in "Email" , with: user[:email] fill_in "user[password]" , with: user[:password] fill_in "user[password_confirmation]" , with: user[:password] expect { click_button "Sign up" }.to have_enqueued_job.on_queue('mailers') #TODO add test that it sends to user (name) and is sent from (admin@rubylaser.org) end it "allows a confirmed user to log in" do sign_in_user expect(page).to have_text("Log Out") expect(page.status_code).to be 200 end it "allows a logged in user to log out" do sign_in_user click_link("Log Out") expect(page).to have_text("Log In") expect(page.status_code).to be 200 end end
class CreateReceiveGroupLines < ActiveRecord::Migration[5.0] def change create_table :receive_group_lines do |t| t.integer :job_order_id, index: true t.integer :receive_group_id, index: true t.float :cost, precision: 7, scale: 2 t.integer :length t.integer :width t.integer :area t.string :note t.timestamps end end end
json.array!(@stickers) do |sticker| json.extract! sticker, :id, :name, :image, :quantity json.url sticker_url(sticker, format: :json) end
require 'spec_helper' require 'yt/collections/videos' require 'yt/models/channel' describe Yt::Collections::Videos do subject(:collection) { Yt::Collections::Videos.new parent: channel } let(:channel) { Yt::Channel.new id: 'any-id' } let(:page) { {items: [], token: 'any-token'} } describe '#size', :ruby2 do describe 'sends only one request and return the total results' do let(:total_results) { 123456 } before do expect_any_instance_of(Yt::Request).to receive(:run).once do double(body: {'pageInfo'=>{'totalResults'=>total_results}}) end end it { expect(collection.size).to be total_results } end end describe '#count' do let(:query) { {q: 'search string'} } context 'called once with .where(query) and once without' do after do collection.where(query).count collection.count end it 'only applies the query on the first call' do expect(collection).to receive(:fetch_page) do |options| expect(options[:params]).to include query page end expect(collection).to receive(:fetch_page) do |options| expect(options[:params]).not_to include query page end end end end end
class AddSuperDataToWfinders < ActiveRecord::Migration[6.0] def change add_column :wfinders, :super_data, :text end end
require 'constants' require 'types' # FIXME this class contains massive duplication of code from Registration::EditForm: class Admin::EditRegistrationForm < Reform::Form feature Reform::Form::Coercion property :password, virtual: true property :password_confirmation, virtual: true property :current_password, virtual: true PASSWORD_LENGTH = Registration::SignUpForm::PASSWORD_LENGTH.dup validation do validates( :password, length: { within: PASSWORD_LENGTH, allow_blank: true }, ) # http://trailblazer.to/gems/reform/validation.html#confirm-validation validate :confirm_password validate :require_current_password_to_change_password end private def confirm_password if password.present? && (password != password_confirmation) errors.add(:password_confirmation, "Doesn't match password") end end def require_current_password_to_change_password # The current password is only required if they're updating their password return unless password.present? return if model.valid_password?(current_password) errors.add(:current_password, current_password.blank? ? :blank : :invalid) end # Override the method that Reform calls internall when you call Form#save so # that their current password is required - but only if they're changing # their password. def save_model if password.present? # The attributes will already be set on `model`, but not persisted. # Annoyingly, devise doesn't provide a 'save_with_password' method, only # 'update_with_password', which requires *all* the updated attrs to be # passed as args. This is the least bad solution I could come up with to # get those attrs: attrs = schema.keys.each_with_object({}) { |k, h| h[k.to_sym] = self.send(k) } model.update_with_password(attrs) else model.save! end end end
# frozen_string_literal: true require "abstract_unit" require "active_support/core_ext/module/introspection" module ParentA module B module C; end module FrozenC; end FrozenC.freeze end module FrozenB; end FrozenB.freeze end class IntrospectionTest < ActiveSupport::TestCase def test_parent_name assert_equal "ParentA", ParentA::B.parent_name assert_equal "ParentA::B", ParentA::B::C.parent_name assert_nil ParentA.parent_name end def test_parent_name_when_frozen assert_equal "ParentA", ParentA::FrozenB.parent_name assert_equal "ParentA::B", ParentA::B::FrozenC.parent_name end def test_parent assert_equal ParentA::B, ParentA::B::C.parent assert_equal ParentA, ParentA::B.parent assert_equal Object, ParentA.parent end def test_parents assert_equal [ParentA::B, ParentA, Object], ParentA::B::C.parents assert_equal [ParentA, Object], ParentA::B.parents end end
require 'ostruct' require 'disk/modules/miq_dummy_disk' describe MiqDummyDisk do DUMMY_DISK_BLOCKS = 1000 DUMMY_DISK_BLOCKSIZE = 4096 context ".new" do it "should not raise an error with arguments" do expect do d_info = OpenStruct.new d_info.d_size = DUMMY_DISK_BLOCKS d_info.block_size = DUMMY_DISK_BLOCKSIZE MiqDummyDisk.new(d_info) end.not_to raise_error end it "should not raise an error without arguments" do expect do MiqDummyDisk.new end.not_to raise_error end it "should return an MiqDisk object without arguments" do dummy_disk = MiqDummyDisk.new expect(dummy_disk).to be_kind_of(MiqDisk) end it "should return an MiqDisk object with arguments" do d_info = OpenStruct.new d_info.d_size = DUMMY_DISK_BLOCKS d_info.block_size = DUMMY_DISK_BLOCKSIZE dummy_disk = MiqDummyDisk.new(d_info) expect(dummy_disk).to be_kind_of(MiqDisk) end end context "Instance methods" do before do d_info = OpenStruct.new d_info.d_size = DUMMY_DISK_BLOCKS d_info.block_size = DUMMY_DISK_BLOCKSIZE @dummy_disk = MiqDummyDisk.new(d_info) end describe "#d_size" do it "should return the expected dummy disk size" do expect(@dummy_disk.d_size).to eq(DUMMY_DISK_BLOCKS) end end describe "#blockSize" do it "should return the expected dummy disk block size" do expect(@dummy_disk.blockSize).to eq(DUMMY_DISK_BLOCKSIZE) end end describe "#size" do it "should return the size of the dummy disk in bytes" do expect(@dummy_disk.size).to eq(DUMMY_DISK_BLOCKS * DUMMY_DISK_BLOCKSIZE) end end describe "#lbaStart" do it "should return the expected start logical block address" do expect(@dummy_disk.lbaStart).to eq(0) end end describe "#lbaEnd" do it "should return the expected end logical block address" do expect(@dummy_disk.lbaEnd).to eq(DUMMY_DISK_BLOCKS) end end describe "#startByteAddr" do it "should return the expected start byte address" do expect(@dummy_disk.startByteAddr).to eq(0) end end describe "#d_write" do before do @dummy_string = "12345" end it "should return a dummy string" do expect(@dummy_disk.d_write(0, @dummy_string, @dummy_string.length)).to eq(@dummy_string.length) end end describe "#endByteAddr" do it "should return the expected end byte address" do expect(@dummy_disk.endByteAddr).to eq(DUMMY_DISK_BLOCKS * DUMMY_DISK_BLOCKSIZE) end it "should return a value consistent with the other values" do expect(@dummy_disk.endByteAddr).to eq(@dummy_disk.startByteAddr + @dummy_disk.lbaEnd * @dummy_disk.blockSize) end end describe "#getPartitions" do it "should return an array" do expect(@dummy_disk.getPartitions).to be_kind_of(Array) end it "should not return any partitions" do parts = @dummy_disk.getPartitions expect(parts.length).to eq(0) end end end end
class RemoveColumnsFromUsers < ActiveRecord::Migration def change change_table :users do |t| t.remove(:report_card, :skill_level) end end end
module Api module V1 class Main::MainTopicsController < ApplicationController respond_to :json resource_description do name 'Main Topics' end api :GET, '/topics', "Show All Topics" def index respond_with Topic.all end api :GET, '/topics/:id', "Show Topic" param :topic, Hash do param :id, :number, :required => true end def show respond_with Topic.find(params[:id]) end api :GET, '/topics/:id/follow', "Follow Topic" param :topic, Hash do param :id, :number, :required => true end def follow end api :GET, '/topics/:id/unfollow', "Unfollow Topic" param :topic, Hash do param :id, :number, :required => true end def unfollow end end end end
class RoleTypesController < ApplicationController respond_to :html def show @role_type = RoleType.find(params[:id]) unless @role_type.published not_found else respond_with(@role_type) end end end
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root to: 'home#index' get 'search/:role', to: 'home#search', as: 'search' post 'home', to: 'home#sign_in', as: 'sign_in' delete '/', to: 'home#sign_out', as: 'sign_out' get 'people(/:id)', to: 'people#show', as: 'people' resources :appointments resources :notes mount SqlProbe::Engine => '/sql_probe' if defined? SqlProbe end
require 'set' module Mirrors # Registers a TracePoint immediately upon load to track points at which # classes and modules are opened for definition. This is used to track # correspondence between classes/modules and files, as this information isn't # available in the ruby runtime without extra accounting. module Init @class_files = {} # we don't use +Mirrors.rebind+ for this because we don't want to load any # more code than is necessary before the +TracePoint+ is enabled. name = Module.instance_method(:inspect) # Immediately activated upon load of +mirrors/init+. Observes class/module # definition. CLASS_DEFINITION_TRACEPOINT = TracePoint.new(:class) do |tp| unless tp.self.singleton_class? key = name.bind(tp.self).call @class_files[key] ||= Set.new @class_files[key] << tp.path end end.tap(&:enable) # Returns the files in which this class or module was opened. Doesn't know # about situations where the class was opened prior to +require+ing # +mirrors/init+, or where metaprogramming was used via +eval+, etc. # # @param [String,Module] klass The class/module, or its +#name+ # @return [Set<String>,nil] set of filenames, or nil if none recorded. def class_files(klass) case klass when String @class_files[klass] else name = Mirrors.rebind(Module, klass, :inspect).call @class_files[name] end end module_function :class_files end end
class Pet < ApplicationRecord belongs_to :user belongs_to :animal has_many :pet_tag has_many :tag , :through => :pet_tag validates :name, presence: true, length: { maximum: 50 } geocoded_by :address # ActiveRecord after_validation :geocode # auto-fetch coordinates end
ActiveAdmin.register CrawlTargetUrl do menu priority: 1, label: "Urlクローラー", parent: "data" config.batch_actions = true config.per_page = 100 actions :index action_item(:index, only: :index) do link_to("クロールする", admin_urlcrawler_path, class: "table_tools_button") end index do id_column column("リンク") {|a| link_to(a.title.present? ? a.title : a.target_url, a.target_url) } column("クラス名") {|a| a.source_type } column("クロール済み?") {|a| a.crawled_at.present? } end end ActiveAdmin.register_page "UrlCrawler" do menu false content title: "Urlクローラー" do columns do column do link_to("一覧に戻る", admin_crawl_target_urls_path, class: "table_tools_button") end end columns do column do Rails.application.eager_load! models = ActiveRecord::Base.descendants.reject{|m| m.to_s.include?("Admin") || m.to_s.include?("ActiveRecord::") || m.abstract_class? } models_hash = {} models.each{|model| models_hash[model.to_s] = model.column_names.reject{|name| name == "id" || name == "created_at" || name == "updated_at" } } active_admin_form_for(:url, url: admin_urlcrawler_crawl_path) do |f| f.inputs do f.input :crawl_url, label: "クロールするサイトのURL" f.input :request_method, label: "リクエストメソッド", as: :select, collection: [:get, :post].map{|m| [m.to_s, m.to_s]}, selected: :get, include_blank: false f.input :filter, label: "該当の場所を絞りこむためのDOM要素" f.input :target_class, as: :select, collection: models.map{|m| [m.to_s, m.to_s]}, include_blank: true, label: "後でどのModelのデータに活用させるか" f.input :start_page_num, as: :number, label: "クロール開始ページ番号" f.input :end_page_num, as: :number, label: "クロール終了ページ番号" panel("以下には指定したModelのカラムに入れるデータのDOMを指定してください") do ol(id: "target_class_column_field") do end end f.submit("クロールする") end f.script do crawl_pull_down_script(models_hash) end end end end end page_action :crawl, method: :post do url = params[:url][:crawl_url] columns_dom = params[:url][:columns] || {} start_page = params[:url][:start_page_num].to_i end_page = params[:url][:end_page_num].to_i insert_count = 0 (start_page.to_i..end_page.to_i).each do |page| address_url = Addressable::URI.parse(url % page.to_s) doc = ApplicationRecord.request_and_parse_html(address_url.to_s, params[:url][:request_method]) if params[:url][:filter].present? doc = doc.css(params[:url][:filter]) end insert_count += parse_and_save_dom_data(dom: doc, target_class: params[:url][:target_class].to_s) end redirect_to(admin_urlcrawler_path, notice: "#{url}から #{start_page}〜#{end_page}ページで 合計#{insert_count}件のリンクを取得しました") end page_action :parse_and_save_html_file, method: :post do html_file = params[:url][:html_file] columns_dom = params[:url][:columns] || {} insert_count = 0 doc = doc = Nokogiri::HTML.parse(html_file.read.to_s) if params[:url][:filter].present? doc = doc.css(params[:url][:filter]) end insert_count = parse_and_save_dom_data(dom: doc, target_class: params[:url][:target_class].to_s) redirect_to(admin_urlcrawler_path, notice: "#{html_file.original_filename}から 合計#{insert_count}件のリンクを取得しました") end end private def parse_and_save_dom_data(dom:, target_class:) insert_count = 0 CrawlTargetUrl.transaction do doc.css("a").select{|anchor| anchor[:href].present? && anchor[:href] != "/" }.each do |d| link = Addressable::URI.parse(d[:href]) if link.host.blank? if link.path.blank? || link.to_s.include?("javascript:") next end link.host = address_url.host link.scheme = address_url.scheme end title = d[:title] || d.text CrawlTargetUrl.setting_target!( target_class_name: target_class, url: link.to_s, from_url: address_url.to_s, column_extension: columns_dom, title: ApplicationRecord.basic_sanitize(title.to_s) ) insert_count += 1 end end return insert_count end
module Peanut::VideoThumbnail extend ActiveSupport::Concern included do version :screenshot, {if: :video?} do process :create_screenshot # Hack to change the version's file extension def full_filename(for_file) super.sub(/\..+$/, '.jpg') end end # Create a screenshot with a max width and height of 300, preserving aspect ratio def create_screenshot Rails.logger.debug "Creating video screenshot #{current_path} #{file.inspect} ..." cache_stored_file! if !cached? ffmpeg_bin = Rails.configuration.app['carrierwave']['ffmpeg_bin'] input_path = current_path output_path = input_path.sub(/\..+$/, '.jpg') FFMPEG.ffmpeg_binary = ffmpeg_bin FFMPEG.logger = Rails.logger movie = FFMPEG::Movie.new(input_path) dimension = movie.width > movie.height ? :width : :height movie.screenshot(output_path, {resolution: '300,300'}, {preserve_aspect_ratio: dimension}) FileUtils.mv(output_path, input_path) # Need to change this from video so it gets set properly on S3 file.content_type = 'image/jpeg' model.duration = movie.duration.round end end end
namespace :db do desc "Erase database" task :erase => :environment do puts "Erasing..." [Idea, Comment, Endorsement].each(&:delete_all) end desc "Erase and fill database" task :populate => [:environment, :erase] do require 'populator' require 'faker' puts "Populating: enjoy this random pattern generator while you wait..." 50.times do Factory.create(:idea) print (['\\', '/', '_', '|'])[rand(4)] end Idea.all.each do |i| rand(11).times do Factory.create(:comment, :idea_id => i.id) print (['\\', '/', '_', '|'])[rand(4)] end rand(25).times do Factory.create(:endorsement, :idea_id => i.id) print (['\\', '/', '_', '|'])[rand(4)] end end puts "" end end
class AddNeterminalToEvaluationSessions < ActiveRecord::Migration[4.2] def change add_column :evaluation_sessions, :neterminal, :boolean end end
#!/usr/bin/env ruby # Copyright 2015, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Sample app that connects to a Greeter service. # # Usage: $ path/to/greeter_client.rb this_dir = File.expand_path(File.dirname(__FILE__)) lib_dir = File.join(this_dir, 'lib') $LOAD_PATH.unshift(lib_dir) unless $LOAD_PATH.include?(lib_dir) require 'grpc' require 'helloworld_services_pb' require 'benchmark' def connectivity_state_string(state) case state when GRPC::Core::ConnectivityStates::IDLE "IDLE" when GRPC::Core::ConnectivityStates::CONNECTING "CONNECTING" when GRPC::Core::ConnectivityStates::READY "READY" when GRPC::Core::ConnectivityStates::TRANSIENT_FAILURE "TRANSIENT_FAILURE" when GRPC::Core::ConnectivityStates::FATAL_FAILURE "FATAIL_FAILURE" end end def main stub = Helloworld::Greeter::Stub.new('badhost:50051', :this_channel_is_insecure, timeout: 2) begin start = Time.now ch = stub.instance_variable_get('@ch') puts "connectivity_state: #{connectivity_state_string(ch.connectivity_state)}" puts "request..." stub.say_hello(Helloworld::HelloRequest.new(name: "World")) rescue GRPC::DeadlineExceeded => e puts e puts "took: #{Time.now - start}" retry end end main
def suma(primero,segundo) puts primero end #suma(50,100) def say (param1) puts "saludo personalizado ", param1 end #say "seras cachondo" def suma (primero, segundo) primero + segundo #return end #puts suma (suma 1,2) , 4 def multiplica producto=25.0 * 3 cociente= 7.0/4 puts producto, cociente end #multiplica def asigna_num(param) print "Introduce valor para #{param}: " gets.to_f end =begin a=12 b=7 c=5 d=10 =end #puts "La media es: #{((asigna_num "a")+ (asigna_num "b")+( asigna_num "c")+ (asigna_num "d"))/4}" def escapando puts "Cuando escribes \\t en un string con comillas dobles se muestra así:" puts 'Lo mismo: cuando escribes \t en un string con comillas dobles se muestra así:' puts "David\tPiqué" puts "Cuando escribes \\n en un string con comillas dobles se muestra así:" puts "David\nPiqué" end #escapando def bucleando loop do print "Quieres segiçuir? (s/n)" answer=gets.chomp.downcase if answer == "n" break end end loop {print "Quieres segiçuir? (s/n) ctrl+c para abortar"} end def repeat(string,times) fail "repetir debe ser 1 o mayor de 1" if times < 1 counter = 0 loop do puts string counter+=1 if counter == times break end end end =begin puts "Pon alo a repetir: " cadena= gets puts "Pon cuantas veces: " veces= gets repeat cadena,veces.to_i =end def ej_random random_number=Random.new.rand(5) loop do puts "Adivina el numero del 1 al 5 (pulsa e para salir): " adivinando = gets if adivinando.to_i == random_number puts "Has acertado, era #{random_number}. ¡¡¡PREMIO!!! Ya no hace falta seguir" break end if adivinando.chomp == "e" puts "Te rendiste je je, era #{random_number}." break end puts "Has fallado, vuelve a intentarlo" end end #ej_random =begin answer="" while answer != "n" printf "Quieres deguir con eete desproposito? (s/n)" answer= gets.chomp.downcase end =end def print_hello(repeticiones) i=0 while i < repeticiones puts "Saludo" i+=1 end end =begin answer=0 while answer < 5 printf "Cuantas veces repetimos? (+ de 5 se acaba)" answer= gets.chomp.to_i print_hello(answer) end until answer== "no" do print "cualquier cosa" answer=gets.chomp end =end =begin array=[0,1,2,3] array.each do |valor| puts "el valor es: #{valor}" end array=[0,1,2,3] array.each do |valor| valor +=2 puts "el valor es: #{valor}" end puts array.inspect =end =begin business = {"name"=> "PixelCompany", "location"=>"Madrid"} business.each do |key,valor| puts "La clave es #{key} y su valor es #{valor}" end business.each do |fila| puts "La fila es #{fila} " end 5.times do puts "hola" end 5.times do |item| puts "hola #{item}" end for item in 1..5 do puts "el valor es #{item}" end for item in ["uno", "dos", "tres"] do puts "el valor es #{item}" end =end unavariable = "tontaina" puts unavariable.respond_to?("reverse") unavariable = 123 puts unavariable.respond_to?("reverse") unavariable = {"uno"=>"tontaina","dos"=>"idiota"} puts unavariable.respond_to?("reverse") unavariable = ["tontaina","idiota"] puts unavariable.respond_to?("reverse")
class User < ActiveRecord::Base has_many :entries, :dependent => :destroy has_many :tasks, :through => :entries def task_group_progress group entries.find_by_task_group( group ).inject(0) { |sum, e| sum += e.completion } / 4 # 4 tasks per group end def task_group_level_complete group task_group_progress( group ) == 100 end def mark_group_complete group entries.find_by_task_group( group ).each { |e| e.complete! } end end
class RemoveDistrictFromUser < ActiveRecord::Migration[5.1] def change remove_column :users, :district, :string end end
require 'carrierwave/mongoid' class Post include Mongoid::Document include Mongoid::Timestamps field :title, type: String field :content, type: String field :photo, type: String mount_uploader :photo, PhotoUploader has_many :comments, class_name: "PostComment" accepts_nested_attributes_for :comments validates_associated :comments end
lib = File.expand_path('../../../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "taobao/top/version" require 'hashie' require 'active_support/core_ext' module Taobao module TOP mattr_accessor :sandbox @@sandbox = false def self.gateways domain = self.sandbox? ? "tbsandbox" : "taobao" { :site => "http://gw.api.#{domain}.com/router/rest", :authorize_url => "https://oauth.#{domain}.com/authorize", :token_url => "https://oauth.#{domain}.com/token" } end def self.sandbox? !!self.sandbox end autoload :Options, 'taobao/top/service.rb' autoload :Params, 'taobao/top/service.rb' autoload :Service, 'taobao/top/service.rb' autoload :Response, 'taobao/top/service.rb' end end require 'taobao/rails/engine' if defined?(::Rails) && ::Rails::VERSION::MAJOR >= 3
require 'rails_helper' describe AuditField do it { should belong_to :grouping } it { should have_many :audit_field_values } it { should validate_presence_of :name } it { should validate_presence_of :value_type } it { should validate_presence_of :display_order } it 'sets its api_name based on name' do audit_field = create(:audit_field, name: 'This is my Name') expect(audit_field.api_name).to eq('this_is_my_name') end it 'does not allow changing api_name' do audit_field = create(:audit_field, name: 'This is my Name') audit_field.api_name = 'foo' expect(audit_field).to_not be_valid expect(audit_field.errors[:api_name]).to eq(["Can't change api_name"]) end it 'should validate uniqueness of display_order scoped to grouping' do create(:audit_field, value_type: 'string', grouping: create(:grouping)) should validate_uniqueness_of(:display_order).scoped_to(:grouping_id) end end
require 'rails_helper' RSpec.describe 'Profile Photos API' do let!(:user) { create(:user) } let!(:member_source_type) { create(:member_source_type)} let!(:member_type) { create(:member_type) } let!(:account_status_type) { create(:account_status_type)} let!(:member) { create(:member, member_source_type_id:member_source_type.id, member_type_id: member_type.id, account_status_type_id: account_status_type.id, user_id: user.id) } let!(:artist) { create(:artist, member_id: member.id, )} let!(:profile) { create(:profile, artist_id: artist.id, is_billing_profile: true, is_active: true)} let!(:medium_type) { create(:medium_type, code: 'PHOT')} let!(:medium) { create_list(:medium, 5, medium_type_id: medium_type.id)} let!(:artist_medium1) { create(:artist_medium, artist_id: artist.id, medium_id: medium[0].id, sequence: 1)} let!(:artist_medium2) { create(:artist_medium, artist_id: artist.id, medium_id: medium[1].id, sequence: 2)} let!(:artist_medium3) { create(:artist_medium, artist_id: artist.id, medium_id: medium[2].id, sequence: 3)} let!(:artist_medium4) { create(:artist_medium, artist_id: artist.id, medium_id: medium[3].id, sequence: 4)} let!(:artist_medium5) { create(:artist_medium, artist_id: artist.id, medium_id: medium[4].id, sequence: 5)} let!(:medium_detail1) { create(:medium_detail, medium_id:medium[0].id, title: 'test1')} let!(:medium_detail2) { create(:medium_detail, medium_id:medium[1].id, title: 'test2')} let!(:medium_detail3) { create(:medium_detail, medium_id:medium[2].id, title: 'test3')} let!(:medium_detail4) { create(:medium_detail, medium_id:medium[3].id, title: 'test4')} let!(:medium_detail5) { create(:medium_detail, medium_id:medium[4].id, title: 'test5')} let!(:profile_photo1) { create(:profile_photo, profile_id: profile.id, artist_medium_id: artist_medium1.id, sequence: 1, is_primary: true)} let!(:profile_photo2) { create(:profile_photo, profile_id: profile.id, artist_medium_id: artist_medium2.id, sequence: 3, is_primary: false)} let!(:profile_photo3) { create(:profile_photo, profile_id: profile.id, artist_medium_id: artist_medium3.id, sequence: 2, is_primary: false)} let(:profile_id) { profile.id } let(:profile_photo_id) { profile_photo2.id} let(:primary_profile_photo_id) { profile_photo1.id} describe 'GET /profiles/:profile_id/photos' do before { get "/profiles/#{profile_id}/photos"} it 'return status code 200' do expect(response).to have_http_status(200) end it 'return photos' do expect(json.size).to eq(3) expect(json[0]['id']).to eq(profile_photo1.id) expect(json[1]['id']).to eq(profile_photo3.id) expect(json[2]['id']).to eq(profile_photo2.id) end end describe 'GET /profiles/:profile_id/photos/preview' do before { get "/profiles/#{profile_id}/photos/preview"} it 'return status code 200' do expect(response).to have_http_status(200) end it 'return photos' do expect(json.size).to eq(2) expect(json[0]['id']).to eq(artist_medium4.id) end end describe 'PUT /profiles/:profile_id/photos/:id/primary' do before { put "/profiles/#{profile_id}/photos/#{profile_photo_id}/primary"} it 'return status code 204' do expect(response).to have_http_status(204) end it 'change primary correct' do get "/profiles/#{profile_id}/photos" expect(json[0]['is_primary']).to eq(false) expect(json[2]['is_primary']).to eq(true) end end describe 'DELETE /profiles/:profile_id/photos/:id' do before { delete "/profiles/#{profile_id}/photos/#{primary_profile_photo_id}"} it 'return status code 204' do expect(response).to have_http_status(204) end it 'delete profile photo correctly' do get "/profiles/#{profile_id}/photos/preview" expect(json.size).to eq(3) end it 'change primary correctly when delete primary photo' do get "/profiles/#{profile_id}/photos" expect(json.size).to eq(2) end end describe 'PUT /profiles/:profile_id/photos/apply' do let(:valid_params) {{ artist_medium_id: artist_medium4.id }} before { put "/profiles/#{profile_id}/photos/apply", params: valid_params} it 'return status code 201' do expect(response).to have_http_status(201) end it 'return profile photo' do expect(json['sequence']).to eq(4) expect(json['artist_medium_id']).to eq(artist_medium4.id) expect(json['is_primary']).to eq(false) end end describe 'PUT /profiles/:profile_id/photos/resort' do let(:valid_params) {{ from_profile_photo_id: profile_photo1.id, to_profile_photo_id: profile_photo3.id }} before { put "/profiles/#{profile_id}/photos/resort", params: valid_params} it 'return status code 204' do expect(response).to have_http_status(204) end it 'resort photo sequence' do get "/profiles/#{profile_id}/photos" expect(json[0]['id']).to eq(profile_photo3.id) end end end
require 'google/apis/youtube_v3' require 'google/api_client/client_secrets' class VideoController < ApplicationController layout false def new_service secrets = Google::APIClient::ClientSecrets.new( { "web" => { "access_token" => current_user.token, "refresh_token" => current_user.refresh_token, "client_id" => ENV["GOOGLE_CLIENT_ID"], "client_secret" => ENV["GOOGLE_CLIENT_SECRET"] } } ) service = Google::Apis::YoutubeV3::YouTubeService.new service.client_options.application_name = 'Youtube Viewer' service.authorization = secrets.to_authorization service end def index if current_user response = new_service.list_searches( 'snippet', event_type: 'live', max_results: 25, order: 'viewCount', type: 'video').to_json; response = JSON.parse(response); @top_streams = []; response['items'].each do |item| current_item = {}; current_item['videoId'] = item['id']['videoId'] current_item['title'] = item['snippet']['title'] current_item['thumbnail'] =item['snippet']['thumbnails']['medium']['url'] @top_streams << current_item end end end def show flash[:video_id] = params[:video_id] video_details = new_service.list_videos( 'snippet, liveStreamingDetails', id: params[:video_id]).to_json video_details = JSON.parse(video_details) if video_details['items'][0] Video.set(video_details['items'][0]) end redirect_to root_path end end
module WSDL module Reader class Messages < Hash def lookup_operations_by_element(type, element_name, port_types) messages = lookup_messages_by_element(element_name) messages.map do |message| port_types.lookup_operations_by_message(type, message) end.flatten end def lookup_operation_by_element! (type, element_name, port_types) messages = lookup_operations_by_element type, element_name, port_types case messages.size when 1 messages.first when 0 raise OperationNotFoundError.new type, element_name else raise ManyOperationsFoundError.new type, element_name end end def lookup_messages_by_element(element_name) values.select do |message| message.parts.values.find { |part| part[:element].split(':').last == element_name } end end end class Message attr_reader :parts attr_reader :name def initialize(element) @parts = Hash.new @name = element.attributes['name'] process_all_parts element end def element parts.map { |_, hash| hash[:element] }.first end protected def process_all_parts(element) element.select { |e| e.class == REXML::Element }.each do |part| case part.name when "part" @parts[part.attributes['name']] = Hash.new store_part_attributes(part) else warn "Ignoring element `#{part.name}' in message `#{element.attributes['name']}'" end end end def store_part_attributes(part) current_part = @parts[part.attributes['name']] part.attributes.each do |name, value| case name when 'name' current_part[:name] = value when 'element' current_part[:element] = value current_part[:mode] = :element when 'type' current_part[:type] = value current_part[:mode] = :type else warn "Ignoring attribute `#{name}' in part `#{part.attributes['name']}' for message `#{element.attributes['name']}'" end end end end end end
class Types::EventProposalType < Types::BaseObject include FormResponseAttrsFields authorize_record field :id, Integer, null: false field :title, String, null: true field :status, String, null: false field :convention, Types::ConventionType, null: false field :submitted_at, Types::DateType, null: false field :created_at, Types::DateType, null: false field :updated_at, Types::DateType, null: false field :registration_policy, Types::RegistrationPolicyType, null: true field :length_seconds, Integer, null: true field :admin_notes, String, null: true do authorize_action :read_admin_notes end field :owner, Types::UserConProfileType, null: false field :event, Types::EventType, null: true field :event_category, Types::EventCategoryType, null: false field :form_response_changes, [Types::FormResponseChangeType], null: false association_loaders EventProposal, :convention, :owner, :event, :event_category field :form, Types::FormType, null: true def form AssociationLoader.for(EventProposal, :event_category).load(object).then do |event_category| AssociationLoader.for(EventCategory, :event_proposal_form).load(event_category) end end def form_response_changes AssociationLoader.for(EventProposal, :form_response_changes).load(object).then do |changes| CompactingFormResponseChangesPresenter.new(changes).compacted_changes end end end
require File.dirname(__FILE__) + "/../spec_helper" describe ForumController do include SpecControllerHelper include FactoryScenario before :each do Site.delete_all factory_scenario :forum_with_topics controller.stub!(:current_user).and_return @user Site.stub!(:find).and_return @site @site.sections.stub!(:find).and_return @forum end it "should be a BaseController" do controller.should be_kind_of(BaseController) end describe "GET to show" do before :each do @topic = Topic.new(:section => @section, :board => nil, :author => @user) end describe "topics without boards" do act! { request_to :get, "/forums/#{@forum.id}" } it_assigns :topics it_gets_page_cached it "instantiates a new topic object" do Topic.should_receive(:new).and_return @topic act! end end describe "topics with boards" do before :each do @board = Factory :board, :section => @forum, :site => @site end act! { request_to :get, "/forums/#{@forum.id}" } it_assigns :boards it_gets_page_cached it "instantiates a new topic object" do Topic.should_receive(:new).and_return @topic act! end end describe "topics with boards, show single board" do before :each do @board = Factory :board, :section => @forum, :site => @site end act! { request_to :get, "/forums/#{@forum.id}/boards/#{@board.id}" } it_assigns :board it_assigns :topics it_gets_page_cached it "instantiates a new topic object" do Topic.should_receive(:new).and_return @topic act! end end end end
class ChangeNameOfColumn < ActiveRecord::Migration[5.2] def change rename_column :rental_lists, :descritption, :description end end
require 'spec_helper' # This spec was generated by rspec-rails when you ran the scaffold generator. # It demonstrates how one might use RSpec to specify the controller code that # was generated by Rails when you ran the scaffold generator. # # It assumes that the implementation code is generated by the rails scaffold # generator. If you are using any extension libraries to generate different # controller code, this generated spec may or may not pass. # # It only uses APIs available in rails and/or rspec-rails. There are a number # of tools you can use to make these specs even more expressive, but we're # sticking to rails and rspec-rails APIs to keep things simple and stable. # # Compared to earlier versions of this generator, there is very limited use of # stubs and message expectations in this spec. Stubs are only used when there # is no simpler way to get a handle on the object needed for the example. # Message expectations are only used when there is no simpler way to specify # that an instance is receiving a specific message. describe TeaPicturesController do before :each do @user = FactoryGirl.create :user sign_in @user @tea_picture_attrs = FactoryGirl.attributes_for(:tea_picture, :user_id => @user.id) end def self.create_picture before :each do @tea_picture = TeaPicture.create @tea_picture_attrs end end describe "GET show" do create_picture it "assigns the requested tea_picture as @tea_picture" do get :show, {:id => @tea_picture.id} assigns(:tea_picture).should eq(@tea_picture) end end describe "GET new" do it "assigns a new tea_picture as @tea_picture" do get :new, {} assigns(:tea_picture).should be_a_new(TeaPicture) end end describe "POST create" do describe "with valid params" do it "creates a new TeaPicture" do expect { post :create, {:tea_picture => @tea_picture_attrs} }.to change(TeaPicture, :count).by(1) end it "assigns a newly created tea_picture as @tea_picture" do post :create, {:tea_picture => @tea_picture_attrs} assigns(:tea_picture).should be_a(TeaPicture) assigns(:tea_picture).should be_persisted end it "redirects to the tea" do tea = Tea.find @tea_picture_attrs[:tea_id] post :create, {:tea_picture => @tea_picture_attrs} response.should redirect_to(tea) end end describe "with invalid params" do it "assigns a newly created but unsaved tea_picture as @tea_picture" do # Trigger the behavior that occurs when invalid params are submitted TeaPicture.any_instance.stub(:save).and_return(false) post :create, {:tea_picture => { }} assigns(:tea_picture).should be_a_new(TeaPicture) end it "re-renders the 'new' template" do # Trigger the behavior that occurs when invalid params are submitted TeaPicture.any_instance.stub(:save).and_return(false) post :create, {:tea_picture => { }} response.should render_template("new") end end end describe "DELETE destroy" do def self.can_destroy it "destroys the requested tea_picture" do expect { delete :destroy, {:id => @tea_picture.to_param} }.to change(TeaPicture, :count).by(-1) end it "redirects to the tea" do tea = @tea_picture.tea delete :destroy, {:id => @tea_picture.to_param} response.should redirect_to(tea) end end def self.can_not_destroy it "do not destroy tea_picture" do expect do delete :destroy, {:id => @tea_picture.to_param} end.to_not change(TeaPicture, :count) end end describe "if i am a tea owner" do before :each do @tea_picture = TeaPicture.create @tea_picture_attrs @new_user = @tea_picture.tea.user sign_out @user sign_in @new_user end can_destroy end describe "if i am a picture owner" do create_picture can_destroy end describe "if i am other user" do before :each do @tea_picture = TeaPicture.create @tea_picture_attrs @new_user = FactoryGirl.create :user sign_out @user sign_in @new_user end can_not_destroy end end end
class Offices < ActiveRecord::Migration def self.up create_table :offices do |t| t.string :office_name end end def self.down drop_table :offices 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' }]) # Character.create(name: 'Luke', movie: movies.first) # if Rails.env == "development" # 10.times do |i| # User.create!(name: "Test#{i + 1}", email: "test#{i + 1}@gmail.com", password: "123456", password_confirmation: "123456") # end # end # Category.create(name: "トップス") # Category.create(name: "アウター") # Category.create(name: "ワンピース") # Category.create(name: "スカート") # Category.create(name: "パンツ") # Category.create(name: "セットアップ") # Category.create(name: "フォーマル") # Category.create(name: "スニーカー") # Category.create(name: "シューズ") # Category.create(name: "ブーツ") # Category.create(name: "帽子") # Category.create(name: "アクセサリー") # Category.create(name: "バッグ") # # A # Brand.create(name: "A BATHING APE") # Brand.create(name: "A.P.C") # Brand.create(name: "Acne Studios") # Brand.create(name: "ADAM ET ROPE") # Brand.create(name: "ADDICTION") # Brand.create(name: "adidas") # Brand.create(name: "Aesop") # Brand.create(name: "Aeta") # Brand.create(name: "agnes b.") # Brand.create(name: "AGNONA") # Brand.create(name: "AHKAH") # Brand.create(name: "AKANE USTUNOMIYA") # Brand.create(name: "AKIKOAOKI") # Brand.create(name: "AKIRANAKA") # Brand.create(name: "ALAIA") # Brand.create(name: "alian mikli") # Brand.create(name: "ALANUI") # Brand.create(name: "ALBETRA FERRETTI") # Brand.create(name: "ALBION") # Brand.create(name: "ALDEN") # Brand.create(name: "ALETTE BLANC") # Brand.create(name: "Alexander McQueen") # Brand.create(name: "alexander wang") # Brand.create(name: "ALEXIS MABILLE") # Brand.create(name: "alice + olivia") # Brand.create(name: "alice auaa") # Brand.create(name: "ALLEGE") # Brand.create(name: "AMACA") # Brand.create(name: "AMBELL") # Brand.create(name: "AMBUSH") # Brand.create(name: "ami alexandre mattiussi") # Brand.create(name: "amiu.c") # Brand.create(name: "Amplitude") # Brand.create(name: "ANDERSEN-ANDERSEN") # Brand.create(name: "aniary") # Brand.create(name: "ANN DEMEULEMEESTER") # Brand.create(name: "ANNA SUI") # Brand.create(name: "ANREALAGE") # Brand.create(name: "ANTEPRIMA") # Brand.create(name: "ANTIPAST") # Brand.create(name: "ANTIQULOTHES") # Brand.create(name: "ANYA HINDMARCH") # Brand.create(name: "Aquascutum") # Brand.create(name: "aramis") # Brand.create(name: "ARCTERYX") # Brand.create(name: "ARMANI") # Brand.create(name: "Arobe") # Brand.create(name: "ASEEDONCLOUD") # Brand.create(name: "ASICS") # Brand.create(name: "atmos") # Brand.create(name: "ato") # Brand.create(name: "ATSUSHI NAKASHIMA") # Brand.create(name: "ATTACHMENT") # Brand.create(name: "AUBERCY") # Brand.create(name: "AUDEMARS PIGUET") # Brand.create(name: "AULA") # Brand.create(name: "AURALEE") # Brand.create(name: "AUTHENTIC SHOE & Co.") # Brand.create(name: "AVIE") # Brand.create(name: "ayame") # Brand.create(name: "ayame i wear design") # Brand.create(name: "ayumi.mitsukane") # Brand.create(name: "AYURA") # Brand.create(name: "AZUL by moussy") # # B # Brand.create(name: "B.A") # Brand.create(name: "Baccarat") # Brand.create(name: "BALENCIAGA") # Brand.create(name: "Bally") # Brand.create(name: "BALMAIN") # Brand.create(name: "BALMUNG") # Brand.create(name: "Barbour") # Brand.create(name: "BATONER") # Brand.create(name: "BAUM UND PFERDGARTEN") # Brand.create(name: "BEAMS") # Brand.create(name: "beautiful people") # Brand.create(name: "BED j.w FORD") # Brand.create(name: "bedsidedrama") # Brand.create(name: "BEDWIN & THE HEARTBREAKERS") # Brand.create(name: "Belstaff") # Brand.create(name: "BEN TAVERNITI UNRAVEL PROJECT") # Brand.create(name: "bench") # Brand.create(name: "BERING") # Brand.create(name: "Berluti") # Brand.create(name: "Bershka") # Brand.create(name: "BIRKENSTOCK") # Brand.create(name: "BlackWeirdos") # Brand.create(name: "blugiri") # Brand.create(name: "Blumarine") # Brand.create(name: "blurhms") # Brand.create(name: "BOBBI BROWN") # Brand.create(name: "bodysong.") # Brand.create(name: "Bonpoint") # Brand.create(name: "Borsalino") # Brand.create(name: "BOTANIST") # Brand.create(name: "BOTTEGA VENETA") # Brand.create(name: "BOUNTY HUNTER") # Brand.create(name: "BRACTMENT") # Brand.create(name: "Breguet") # Brand.create(name: "BREITLING") # Brand.create(name: "Brooks Brothers") # Brand.create(name: "BRUNELLO CUCINELLI") # Brand.create(name: "bubo BARCELONA") # Brand.create(name: "bukht") # Brand.create(name: "BURBERRY") # Brand.create(name: "BUTTERO") # Brand.create(name: "BVLGARI") # Brand.create(name: "BYREDO") # # C # Brand.create(name: "Calvin Klein") # Brand.create(name: "CAMPER") # Brand.create(name: "CANADA GOOSE") # Brand.create(name: "CANALI") # Brand.create(name: "Candy Stripper") # Brand.create(name: "CANMAKE") # Brand.create(name: "CAROL CHRISTIAN POELL") # Brand.create(name: "Cartier") # Brand.create(name: "CARVEN") # Brand.create(name: "Cath Kidston") # Brand.create(name: "CEDRIC CHARLIER") # Brand.create(name: "CELINE") # Brand.create(name: "Celvoke") # Brand.create(name: "Champion") # Brand.create(name: "CHAN LUU") # Brand.create(name: "CHANEL") # Brand.create(name: "CHAUMET") # Brand.create(name: "Children of the discordance") # Brand.create(name: "Chloe") # Brand.create(name: "Chopard") # Brand.create(name: "Christian Louboutin") # Brand.create(name: "CHRISTOPHE LEMAIRE") # Brand.create(name: "Christopher Kane") # Brand.create(name: "CHROME HEARTS") # Brand.create(name: "Chun Shui Tang") # Brand.create(name: "Church's") # Brand.create(name: "CINOH") # Brand.create(name: "CINQUANTA") # Brand.create(name: "CITIZEN") # Brand.create(name: "CIVILIZED") # Brand.create(name: "CLANE") # Brand.create(name: "CLARINS") # Brand.create(name: "CLAUDIA LI") # Brand.create(name: "cle de peau Beaute") # Brand.create(name: "CLINIQUE") # Brand.create(name: "CMMN SWDN") # Brand.create(name: "COACH") # Brand.create(name: "Coci la elle") # Brand.create(name: "coeur femme") # Brand.create(name: "COFFRET D'OR") # Brand.create(name: "Columbia") # Brand.create(name: "COMESANDGOES") # Brand.create(name: "COMME des GARCONS") # Brand.create(name: "COMOLI") # Brand.create(name: "CONVERSE") # Brand.create(name: "Coohem") # Brand.create(name: "COS") # Brand.create(name: "CoSTUME NATIONAL") # Brand.create(name: "COVERMARK") # Brand.create(name: "Credor") # Brand.create(name: "CROCKETT&JONES") # Brand.create(name: "Cruciani") # Brand.create(name: "CULLNI") # Brand.create(name: "CUNE") # Brand.create(name: "CYCLAS") # # D # Brand.create(name: "D'URBAN") # Brand.create(name: "DAKS") # Brand.create(name: "Daniel&Bob") # Brand.create(name: "DE LA MER") # Brand.create(name: "DECORTE") # Brand.create(name: "DEMEL") # Brand.create(name: "DENHAM") # Brand.create(name: "DEREK LAM") # Brand.create(name: "DESCENTE") # Brand.create(name: "DIANA") # Brand.create(name: "DIANE von FURSTENBERG") # Brand.create(name: "Dickies") # Brand.create(name: "DIESEL") # Brand.create(name: "DIESEL BLACK GOLD") # Brand.create(name: "DIET BUTCHER SLIM SKIN") # Brand.create(name: "DIGAWEL") # Brand.create(name: "DIOR") # Brand.create(name: "DIOR HOMME") # Brand.create(name: "diptyque") # Brand.create(name: "discord Yohji Yamamoto") # Brand.create(name: "DISCOVERD") # Brand.create(name: "DITA") # Brand.create(name: "divka") # Brand.create(name: "DOLCE&GABBANA") # Brand.create(name: "DOMENICO+SAVIO") # Brand.create(name: "Donnah Mabel") # Brand.create(name: "doublet") # Brand.create(name: "Dr.martens") # Brand.create(name: "DRESSUNDRESSED") # Brand.create(name: "DRIES VAN NOTEN") # Brand.create(name: "DSQUARED2") # Brand.create(name: "dunhill") # Brand.create(name: "DUVETICA") # # E # Brand.create(name: "e.m") # Brand.create(name: "EACH OTHER") # Brand.create(name: "EBONY") # Brand.create(name: "ED ROBERT JUDSON") # Brand.create(name: "EDWARD GREEN") # Brand.create(name: "EDWIN") # Brand.create(name: "EFFECTEN") # Brand.create(name: "EFILEVOL") # Brand.create(name: "Eggs 'in Things") # Brand.create(name: "elephant TRIBAL fabrics") # Brand.create(name: "Elizabeth and James") # Brand.create(name: "EMILIO PUCCI") # Brand.create(name: "Emily Temple cute") # Brand.create(name: "EMMETI") # Brand.create(name: "emmi") # Brand.create(name: "EMPORIO ARMANI") # Brand.create(name: "ENFOLD") # Brand.create(name: "ENGINEERED GARMENTS") # Brand.create(name: "Enharmonic TAVERN") # Brand.create(name: "EPOCA") # Brand.create(name: "EQUIPMENT") # Brand.create(name: "ERMANNO SCERVINO") # Brand.create(name: "Ermeneglido Zegna") # Brand.create(name: "ESPRIQUE") # Brand.create(name: "est") # Brand.create(name: "Estee Lauder") # Brand.create(name: "ESTNATION") # Brand.create(name: "ETHOSENS") # Brand.create(name: "ETRO") # Brand.create(name: "Ezumi") # # F # Brand.create(name: "F-LAGSTUF-F") # Brand.create(name: "FABIANA FILIPPI") # Brand.create(name: "FACETASM") # Brand.create(name: "FACTOTUM") # Brand.create(name: "FAGASSENT") # Brand.create(name: "Faliero Sarti") # Brand.create(name: "FENDI") # Brand.create(name: "FILA") # Brand.create(name: "FILL THE BALL") # Brand.create(name: "FilMelange") # Brand.create(name: "FIVEISM x THREE") # Brand.create(name: "FLICKA") # Brand.create(name: "FLUMOR") # Brand.create(name: "foot the coacher") # Brand.create(name: "FOOTSTOCK ORIGINALS") # Brand.create(name: "forte forte") # Brand.create(name: "fragment design") # Brand.create(name: "Francfranc") # Brand.create(name: "Frank & Eileen") # Brand.create(name: "FRANK LEDER") # Brand.create(name: "FRAPBOIS") # Brand.create(name: "FRAY I.D") # Brand.create(name: "FRED PERRY") # Brand.create(name: "Fulton") # Brand.create(name: "FUMIE TANAKA") # Brand.create(name: "FUMIKA_UCHIDA") # Brand.create(name: "FUMITO GANRYU") # Brand.create(name: "FURFUR") # Brand.create(name: "FURLA") # # G # Brand.create(name: "G-SHOCK") # Brand.create(name: "G-star RAW") # Brand.create(name: "G.V.G.V") # Brand.create(name: "GalaabenD") # Brand.create(name: "GAP") # Brand.create(name: "gelato pique") # Brand.create(name: "giab's ARCHIVIO") # Brand.create(name: "GIANFRANCO FERRE") # Brand.create(name: "Giorgio Armani") # Brand.create(name: "GIORGIO BRATO") # Brand.create(name: "GIUSEPPE ZANOTI") # Brand.create(name: "Givenchy") # Brand.create(name: "glamb") # Brand.create(name: "GODIVA") # Brand.create(name: "GOLDEN GOOSE DELUXE BRAND") # Brand.create(name: "gomme") # Brand.create(name: "Gosha Rubchinsky") # Brand.create(name: "Goutal") # Brand.create(name: "GRACE CONTINENTAL") # Brand.create(name: "Graphpaper") # Brand.create(name: "GREGORY") # Brand.create(name: "GU") # Brand.create(name: "GUACAMOLE") # Brand.create(name: "GUCCI") # Brand.create(name: "GUERLAIN") # Brand.create(name: "GUESS") # Brand.create(name: "GUIDI") # # H # Brand.create(name: "H&M") # Brand.create(name: "h.NAOTO") # Brand.create(name: "ha | za | ma") # Brand.create(name: "Haagen-Dazs") # Brand.create(name: "Haat") # Brand.create(name: "HACCI") # Brand.create(name: "HAIDER ACKERMANN") # Brand.create(name: "Happy Socks") # Brand.create(name: "HARE") # Brand.create(name: "Harikae") # Brand.create(name: "HARRY WINSTON") # Brand.create(name: "HATRA") # Brand.create(name: "HAVERSACK") # Brand.create(name: "HELEN KAMINSKI") # Brand.create(name: "HELENA RUBINSTEIN") # Brand.create(name: "Hender Scheme") # Brand.create(name: "Henri Charpentier") # Brand.create(name: "HENRI LE ROUX") # Brand.create(name: "HENRIK VIBSKOV") # Brand.create(name: "HERMES") # Brand.create(name: "HERNO") # Brand.create(name: "HERON PRESTON") # Brand.create(name: "HIROFU") # Brand.create(name: "HIROKO BIS") # Brand.create(name: "HIROKO KOSHINO") # Brand.create(name: "HISUI HIROKO ITO") # Brand.create(name: "HOLIDAY") # Brand.create(name: "House of Holland") # Brand.create(name: "HTC") # Brand.create(name: "HUBLOT") # Brand.create(name: "HUF") # Brand.create(name: "HUGO BOSS") # Brand.create(name: "HUTING WORLD") # Brand.create(name: "HYKE") # Brand.create(name: "HYSTERIC GLAMOUR") # # I # Brand.create(name: "Ice-Watch") # Brand.create(name: "ID DAILYWEAR") # Brand.create(name: "ikea") # Brand.create(name: "IKUMI") # Brand.create(name: "IL BISONTE") # Brand.create(name: "IN-PROCESS Tokyo") # Brand.create(name: "INCOTEX") # Brand.create(name: "INDIVIDUALIZED SHIRTS") # Brand.create(name: "INVERALLAN") # Brand.create(name: "IPSA") # Brand.create(name: "Iroquois") # Brand.create(name: "ISABEL MARANT") # Brand.create(name: "ISAMU KATAYAMA BACKLASH") # Brand.create(name: "ISSEI MIYAKE") # Brand.create(name: "IWC") # # J # Brand.create(name: "J.Crew") # Brand.create(name: "J.M WESTON") # Brand.create(name: "JACOB COHEN") # Brand.create(name: "JAM HOME MADE") # Brand.create(name: "JAMES PERSE") # Brand.create(name: "Jane Marple") # Brand.create(name: "JANE SMITH") # Brand.create(name: "JASON WU") # Brand.create(name: "JEAN PAUL GAULTIER") # Brand.create(name: "JEAN-PAUL HEVIN") # Brand.create(name: "Jeffery Campbell") # Brand.create(name: "Jenny Fax") # Brand.create(name: "Jens") # Brand.create(name: "JieDa") # Brand.create(name: "JIL SANDER") # Brand.create(name: "JILLSTUART") # Brand.create(name: "JIMMY CHOO") # Brand.create(name: "JINS") # Brand.create(name: "JO MALONE LONDON") # Brand.create(name: "Jocomomola") # Brand.create(name: "Johan Ku") # Brand.create(name: "John Galliano") # Brand.create(name: "JOHN LAWRENCE SULLIVAN") # Brand.create(name: "JOHN MASON SMITH") # Brand.create(name: "JOHN SMEDLEY") # Brand.create(name: "JOHNBULL") # Brand.create(name: "JOHNSTONS") # Brand.create(name: "JOSEPH HOMME") # Brand.create(name: "JOTARO SAITO") # Brand.create(name: "JOURNAL STANDARD") # Brand.create(name: "Julien David") # Brand.create(name: "JULIUS") # Brand.create(name: "junhashimoto") # Brand.create(name: "JUNYA WATANABE COMME des GARCONS") # Brand.create(name: "Just Cavalli") # Brand.create(name: "JUUN.J") # Brand.create(name: "JUVENILE HALL ROLLCALL") # Brand.create(name: "JW anderson") # Brand.create(name: "J&M DAVIDSON") # # K # Brand.create(name: "k3&co.") # Brand.create(name: "KAMILi") # Brand.create(name: "KAMISHIMA CHINAMI") # Brand.create(name: "KANEBO") # Brand.create(name: "Kappa") # Brand.create(name: "KAREN WALKER") # Brand.create(name: "karrimor") # Brand.create(name: "KATE") # Brand.create(name: "kate spade new york") # Brand.create(name: "Kazuki Nagayama") # Brand.create(name: "KAZUYUKI KUMAGAI") # Brand.create(name: "KEISUKEYOSHIDA") # Brand.create(name: "KEITA MARUYAMA") # Brand.create(name: "KENZO") # Brand.create(name: "KICS DOCUMENT.") # Brand.create(name: "KIDILL") # Brand.create(name: "KIEHL'S SINCE 1851") # Brand.create(name: "KIIT") # Brand.create(name: "KIJIMA TAKAYUKI") # Brand.create(name: "KINO") # Brand.create(name: "Kirov") # Brand.create(name: "KITH") # Brand.create(name: "Kiwanda") # Brand.create(name: "KOCHE") # Brand.create(name: "kolor") # Brand.create(name: "KOTONA") # Brand.create(name: "KRIZIA") # Brand.create(name: "kujaku") # Brand.create(name: "KURO") # Brand.create(name: "k三") # # L # Brand.create(name: "L'OCCITANE") # Brand.create(name: "LA MAISON DU CHOCOLAT") # Brand.create(name: "LACOSTE") # Brand.create(name: "LAD MUSICIAN") # Brand.create(name: "Laduree") # Brand.create(name: "Laline") # Brand.create(name: "Lancome") # Brand.create(name: "LANVIN") # Brand.create(name: "LANVIN COLLECTION") # Brand.create(name: "LANVIN en Bleu") # Brand.create(name: "LAPS") # Brand.create(name: "LARDINI") # Brand.create(name: "laura mercier") # Brand.create(name: "Lautashi") # Brand.create(name: "Le Creuset") # Brand.create(name: "Lee") # Brand.create(name: "Leilian") # Brand.create(name: "LEONARD") # Brand.create(name: "LeSportsac") # Brand.create(name: "leur logette") # Brand.create(name: "Levi's") # Brand.create(name: "Levi's Vintage Clothing") # Brand.create(name: "LIAM HODGES") # Brand.create(name: "LIBERUM") # Brand.create(name: "Licht Bestreben") # Brand.create(name: "LIMI feu") # Brand.create(name: "LISSAGE") # Brand.create(name: "LITTLEBIG") # Brand.create(name: "LOEWE") # Brand.create(name: "LOKITHO") # Brand.create(name: "LONGCHAMP") # Brand.create(name: "LONGINES") # Brand.create(name: "Loro Piana") # Brand.create(name: "lot holon") # Brand.create(name: "LOUIS VUITTON") # Brand.create(name: "lucien pellat-finet") # Brand.create(name: "LUIGI BORRELLI") # Brand.create(name: "LUNASOL") # Brand.create(name: "LUSH") # # M # Brand.create(name: "M A S U") # Brand.create(name: "m's braque") # Brand.create(name: "MACKINTOSH") # Brand.create(name: "MACKINTOSH PHILOSOPHY") # Brand.create(name: "MAGINE") # Brand.create(name: "Maison Boinet") # Brand.create(name: "MAISON KITSUNE") # Brand.create(name: "Maison Margiela") # Brand.create(name: "Maison MIHARA YASUHIRO") # Brand.create(name: "MAJOLICA MAJORCA") # Brand.create(name: "mame kurogouchi") # Brand.create(name: "mando") # Brand.create(name: "Manhattan Portage") # Brand.create(name: "Mannequins JAPON") # Brand.create(name: "Manolo Blahnik") # Brand.create(name: "MAQuillAGE") # Brand.create(name: "MARC JACOBS") # Brand.create(name: "MARCELO BURLON COUNTY OF MILAN") # Brand.create(name: "MARGARET HOWELL") # Brand.create(name: "marimekko") # Brand.create(name: "MARINA RINALDI") # Brand.create(name: "MARKAWARE") # Brand.create(name: "MARNI") # Brand.create(name: "master-piece") # Brand.create(name: "masterkey") # Brand.create(name: "mastermind JAPAN") # Brand.create(name: "matohu") # Brand.create(name: "MAX BRENNER") # Brand.create(name: "Max Mara") # Brand.create(name: "McQ ALexander McQueen") # Brand.create(name: "meagratia") # Brand.create(name: "meanswhile") # Brand.create(name: "MEDICOM TOY") # Brand.create(name: "MELLERIO dits MELLER") # Brand.create(name: "mercibeaucoup,") # Brand.create(name: "MESSIKA") # Brand.create(name: "Metaphor...") # Brand.create(name: "MICHAEL KORS") # Brand.create(name: "MIDDLA") # Brand.create(name: "MIDIUMISOLID") # Brand.create(name: "MIDWEST") # Brand.create(name: "MIKIMOTO") # Brand.create(name: "MIKIO SAKABE") # Brand.create(name: "Mila Schoen") # Brand.create(name: "MILK") # Brand.create(name: "MILK BOY") # Brand.create(name: "MILLY") # Brand.create(name: "MiMC") # Brand.create(name: "mina perhonen") # Brand.create(name: "MINEDENIM") # Brand.create(name: "Minimal") # Brand.create(name: "mintdesings") # Brand.create(name: "Missoni") # Brand.create(name: "MISTERGENTLEMAN") # Brand.create(name: "MIU MIU") # Brand.create(name: "MIYAO") # Brand.create(name: "MIZUNO") # Brand.create(name: "MM6 Maison Margiela") # Brand.create(name: "MONCLER") # Brand.create(name: "monkey time") # Brand.create(name: "MONTBLANC") # Brand.create(name: "MooRER") # Brand.create(name: "MOSCHINO") # Brand.create(name: "MOSCOT") # Brand.create(name: "motonari ono") # Brand.create(name: "MOUSSY") # Brand.create(name: "MSGM") # Brand.create(name: "MULBERRY") # Brand.create(name: "muller of yoshiokubo") # Brand.create(name: "MURRAL") # Brand.create(name: "MUVEIL") # Brand.create(name: "MUZE") # Brand.create(name: "MW") # Brand.create(name: "my beautiful landlet") # Brand.create(name: "my panda") # Brand.create(name: "MYKITA") # Brand.create(name: "MY__") # Brand.create(name: "M.A.C")
module Regex class Password def self.VALID_PASSWORD_REGEX /^[a-zA-Z0-9]{8,}*$/ end end end
require 'erb' module TimeHipster module Application class View < Struct.new(:template) class << self def resolve(controller, action_name) path = template_path(controller, action_name) template = File.exists?(path) ? File.read(path) : 'Ok' new(template) end def template_path(controller, action_name) File.join( File.expand_path('../views', __FILE__), controller.class.to_s.split('::').last.gsub('Controller', '').downcase, "#{action_name}.erb" ) end end def render(assigns) ERB.new(template).result(assigns) end end end end
# # Cookbook:: graphite # Recipe:: _web_packages # # Copyright:: 2014-2016, Heavy Water Software Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package Array(node['graphite']['system_packages']) python_package 'django' do user node['graphite']['user'] group node['graphite']['group'] version node['graphite']['django_version'] virtualenv node['graphite']['base_dir'] end python_package 'uwsgi' do user node['graphite']['user'] group node['graphite']['group'] options '--isolated' virtualenv node['graphite']['base_dir'] end python_package 'graphite_web' do package_name lazy { key = node['graphite']['install_type'] node['graphite']['package_names']['graphite_web'][key] } version lazy { node['graphite']['version'] if node['graphite']['install_type'] == 'package' } user node['graphite']['user'] group node['graphite']['group'] install_options '--no-binary=:all:' virtualenv node['graphite']['base_dir'] end
class RemoveLatitudeFromAssassins < ActiveRecord::Migration[6.0] def change remove_column :assassins, :latitude, :integer remove_column :assassins, :longitude, :integer end end
#[5.2]ハッシュ #ハッシュはキーと値の組み合わせでデータを管理するオブジェクトのことです。他の言語では連想配列やディクショナリ(辞書)、マップと呼ばれたりする場合があります。 #ハッシュを作成する場合は以下のような構文(ハッシュリテラル)を使います。 # EX 空のハッシュを作る {} # キーと値の組み合わせを3つ格納するハッシュ { キー1 => 値1, キー2 => 値2, キー3 => 値3} #ハッシュはHashクラスのオブジェクトになっています。 # EX 空のハッシュを作成し、そのクラス名を確認する puts {}.class # ==> Hash # EX 国ごとに通貨の単位を格納したハッシュ { 'japan' => 'yen', 'us' => 'dollar', 'india' => 'rupee'} # 改行も可能! { 'japan' => 'yen', 'us' => 'dollar', 'india' => 'rupee' } # 配列の最後にカンマがついてもエラーにはなりません { 'japan' => 'yen', 'us' => 'dollar', 'india' => 'rupee', # } #同じキーが複数使われた場合は、最後に出てきた値が有効になります。 #ですが、特別な理由がない限りこのようなハッシュを作成する意味はありません。むしろ不具合である可能性の方が高いでしょう。 { 'japan' => 'yen', 'japan' => '円'} # ==> { 'japan' => 'yen'} #ハッシュリテラルで使う{}はブロックで使う{}([4.3.5]do...endと{}の項を確認)と使っている記号が同じです。 # EX ハッシュリテラルの{} h = { 'japan' => 'yen', 'us' => 'dollar', 'india' => 'rupee'} # EX ブロックを作成する [1, 2, 3].each { |n| puts n} #慣れないうちはハッシュの{}とブロックの{}の見分けがつきにくいかもしれませんが、Rubyのコードをたくさん読み書きするうちにパッと見分けがつくようになってくるはずです。 #とはいえ、書き方を謝るとRuby自身がハッシュの{}とブロックの{}を取り違えてしまうケースもあります。(そのケースはおって学習します。) #----------------------------------------------------------------------------------------------------------------------------------------------------------------- #[5.2.1]要素の追加、変更、取得 #後から新しいキーと値を追加する場合は、次のような構文を使います。 ハッシュ[キー] = 値 # EX 新たにイタリアの通貨を追加するコード currencies = { 'japan' => 'yen', 'us' => 'dollar', 'indian' => 'rupee' } # イタリアの通貨を追加する currencies['italy'] = 'euro' puts currencies # ==> {"japan"=>"yen", "us"=>"dollar", "indian"=>"rupee", "italy"=>"euro"} # EX 既にコードが存在していた場合は、値が上書きされます。 currencies = { 'japan' => 'yen', 'us' => 'dollar', 'indian' => 'rupee' } # 既存の値を上書きする currencies['japan'] = '円' puts currencies # ==> {"japan"=>"円", "us"=>"dollar", "indian"=>"rupee"} #ハッシュから値を取り出す場合は、次のようなキーを指定します。 ハッシュ[キー] #ハッシュはその内部構造上、キーと値が大量に格納されている場合でも、指定したキーに対応する値を高速に取り出せるのが特徴です。 # EX ハッシュから値を取り出す currencies = { 'japan' => 'yen', 'us' => 'dollar', 'india' => 'rupee' } puts currencies['india'] # ==> rupee # 存在しないキーを指定するとnilが返ります。 puts currencies['brazil'] # ==> nil #------------------------------------------------------------------------------------------------------------------------------------------------------------------ #[5.2.2]ハッシュを使った繰り返し #eaxhメソッドを使うと、キーと値の組み合わせを順に取り出すことができます。 #キーと値は格納した順に取り出されます。ブロック引数がキーと値で2個になっている点に注意してください。 currencies = { 'japan' => 'yen', 'us' => 'dollar', 'india' => 'rupee' } currencies.each do |key, value| puts "#{key} : #{value}" end # ==> japan : yen # us : dollar # india : rupee #ブロック引数を1つにするとキーと値が配列に格納されます。 currencies = { 'japan' => 'yen', 'us' => 'dollar', 'india' => 'rupee' } currencies.each do |key_value| key = key_value[0] value = key_value[1] puts "#{key} : #{value}" end # ==> japan : yen # us : dollar # india : rupee #------------------------------------------------------------------------------------------------------------------------------------------------------------------ #[5.2.3]ハッシュの同値比較、要素数の取得、要素の削除 #「==」でハッシュ同士を比較すると、同じハッシュかどうかをチェックできます。この時すべてのキーと値が同じであればtrueが返ります。 # EX a = { 'x' => 1, 'y' => 2, 'z' => 3 } # すべてのキーと値が同じであればtrue b = { 'x' => 1, 'y' => 2, 'z' => 3 } puts a == b # ==> true #並び順が逆になっていてもキーと値がすべて同じならtrue c = { 'z' => 3, 'x' => 1, 'y' => 2 } puts a == c # ==> true #キー'x'の値が異なるのでfalse d = { 'x' => 10, 'y' => 2, 'z' => 3 } puts a == d # ==> false #sizeメソッド(エイリアスメソッドはlength)を使うとハッシュの要素の個数を調べることができます。 puts {}.size # ==> 0 puts { 'x' => 1, 'y' => 2, 'z' => 3 }.size # ==> 3 #deleteメソッドを使うと指定したキーに対おする要素を削除できます。戻り値はされた要素の値です。 currencies = {'japan' => 'yen', 'us' => 'dollar', 'india' => 'rupee'} currencies.delete('japan') puts currencies # ==> {"us"=>"dollar", "india"=>"rupee"} #deleteメソッドで指定したキーがなければnilが返ります。ブロックを渡すと、キーが見つからないときにブロックの戻り値をdeleteメソッドの戻り値にできます。 currencies = {'japan' => 'yen', 'us' => 'dollar', 'india' => 'rupee'} # 削除しようとしたキーが見つからない時はnilが返る puts currencies.delete('italy') # ==> nil # ブロックを渡すとキーが見つからない時の戻り値を作成できる puts currencies.delete('italy') { |key| "Not found: #{key}"} # ==> Not found: italy #--------------------------------------------------------------------------------------------------------------------------------------------------------------------
require 'spec_helper' RSpec.describe Engine do include Rack::Test::Methods context 'for the current api' do before do create :tier, :free params = { data: { name: 'Nerdcast', episodes: 352, website: 'jovemnerd.com.br' } } ultra_pod = create :api, :podcast set_auth_headers_for!(ultra_pod, 'POST', params) post '/engine/podcasts', params end it 'should create the record' do expect(last_response.status).to eql 201 last_json.tap do |json| expect(json.id).to_not be_nil expect(json.created_at).to_not be_nil expect(json.updated_at).to_not be_nil expect(json.name).to eql 'Nerdcast' expect(json.episodes).to eql '352.0' end end context 'without the required data' do before do ultra_pod = create :api, :podcast set_auth_headers_for!(ultra_pod, 'POST', {}) post '/engine/podcasts', {} end it 'should return validations errors' do expect(last_response.status).to eql 400 expect(last_json.errors).to eql \ 'name' => ["can't be blank"], 'episodes' => ["can't be blank"], 'website' => ["can't be blank"] end end context 'with duplicate data' do before do params = { data: { name: 'Nerdcast', episodes: 352, website: 'jovemnerd.com.br' } } ultra_pod = create :api, :podcast 2.times do set_auth_headers_for!(ultra_pod, 'POST', params) post '/engine/podcasts', params end end it "should not add the second record" do expect(last_response.status).to eql 400 expect(last_json.errors).to eql \ "name" => ["has already been taken"], "website" => ["has already been taken"] end end end context 'for another api' do before do create :tier, :free create :api, :podcast set_auth_headers_for!(create(:api), 'POST', {}) post '/podcasts', {} end it 'should not be found' do expect(last_response.status).to eql 404 end end end
class CommentsController < ApplicationController before_action :logged_in_user, only: [:create, :destroy] def create @entry = Entry.find(params[:entry_id]) @comment = @entry.comments.build(comment_params) @comment.user_id = current_user.id if current_user.following?(@entry.user) || current_user == @entry.user if @comment.save #@new_comment = @entry.comments.new respond_to do |format| format.html do redirect_to entry_path(@entry) end format.js # JavaScript response end else # @new_comment = @comment # respond_to do |format| # format.html { render entry_path(@entry) } # format.js flash[:warning]= "You can not comment on this post" redirect_to entry_path(@entry) end else redirect_to entry_path(@entry) end end def destroy @entry = Entry.find params[:entry_id] @comment = @entry.comments.find(params[:id]) @comment.destroy respond_to do |format| format.html do flash[:success] = 'Comment deleted.' redirect_to entry_path(@entry) end format.js # JavaScript response end end private def comment_params params.require(:comment).permit( :content) end end
require_relative "../config/environment.rb" class MovieController def initialize(url = "https://editorial.rottentomatoes.com/guide/200-essential-movies-to-watch-now/") MovieScraper.scraper(url) end def run puts "Welcome To Rotten Tomatoes Best 200 Movies Must Watch".blue view_menu input = gets.chomp.downcase until input == "exit" case input when "list movies" list_movies when "list actors" list_actors when "list directors" list_directors when "list actor movies" list_movies_by_actor when "list director movies" list_movies_by_director when "watch movie" watch_movie when "view menu" view_menu when "remove movie" remove_movie else puts "Invalid entry, try again!".red end puts view_menu input = gets.chomp.downcase system "clear" end end def view_menu puts "To list all movies, enter 'list movies'.".blue puts "To list all actors, enter 'list actors'.".blue puts "To list all directors, enter 'list directors'.".blue puts "To list all of the movies of a particular actor, enter 'list actor movies'.".blue puts "To list all of the movies of a particular director, enter 'list director movies'.".blue puts "To watch a movie, enter 'watch movie'.".blue puts "To remove a movie, enter 'remove movie'".blue puts "To quit, type 'exit'.".blue puts "What would you like to do?".blue end def list_movies movies = Movie.all movies.each_with_index do |movie, idx| puts "#{idx+1}. #{movie.name} #{movie.year} #{movie.rating}.".yellow puts "Actors: #{movie.actors.map{ |ac| ac.name }.join(", ")}.".yellow puts "Directed By: #{movie.directors.map{ |dir| dir.name }.join(", ")}.".yellow puts "Synopsis: #{movie.synopsis}.".yellow puts "Critics: #{movie.critics}.".yellow puts puts end end def list_actors actors = Actor.all.sort { |a, b| a.name <=> b.name } actors.each_with_index do |actor, idx| puts "#{idx+1}. #{actor.name}".yellow end end def list_directors directors = Director.all.sort { |a, b| a.name <=> b.name } directors.each_with_index do |director, idx| puts "#{idx+1}. #{director.name}".yellow end end def list_movies_by_actor puts "Please the actor name:".blue actor = gets.chomp.split.map{ |part| part.capitalize }.join(" ") if Actor.find_by_name(actor) movies = Actor.find_by_name(actor).movies.sort { |a, b| a.name <=> b.name } movies.each_with_index do |movie, idx| puts "#{idx+1}. #{movie.name} #{movie.year} #{movie.rating}.".yellow end else puts "Sorry, actor is not found in this database!".red end end def list_movies_by_director puts "Please enter the director name:".blue director = gets.chomp.split.map{ |part| part.capitalize }.join(" ") if Director.find_by_name(director) movies = Director.find_by_name(director).movies.sort { |a, b| a.name <=> b.name } movies.each_with_index do |movie, idx| puts "#{idx+1}. #{movie.name} #{movie.year} #{movie.rating}.".yellow end else puts "Sorry, director is not found in this database!".red end end def watch_movie movies = Movie.all.sort { |a, b| a.name <=> b.name } movies.each_with_index do |movie, idx| puts "#{idx+1}. #{movie.name} #{movie.year} #{movie.rating}." end puts "Which movie number would you like to watch?".blue number = gets.chomp.to_i if number.between?(1, movies.length) puts "Playing #{movies[number-1].name} by #{movies[number-1].directors.map{ |dir| dir.name }.join(", ")}.".green else puts "Movie number is not found!".red end end def remove_movie movies = Movie.all.sort { |a, b| a.name <=> b.name } movies.each_with_index do |movie, idx| puts "#{idx+1}. #{movie.name} #{movie.year} #{movie.rating}." end puts "Which movie number would you like to remove from this list?".blue number = gets.chomp.to_i if number.between?(1, movies.length) Movie.remove_movie(movies[number-1]) puts "Selected movies was successfully removed from your database!".green else puts "Movie number is not found!".red end end end
class Line attr_accessor :start_point, :end_point def initialize start_point, end_point @start_point = start_point @end_point = end_point end def length Math.sqrt( (@start_point[0] - @end_point[0])**2 + (@start_point[1] - @end_point[1])**2 ) end def == line ( @start_point == line.start_point and @end_point == line.end_point ) or ( @end_point == line.start_point and @start_point == line.end_point ) end end
class Field < ActiveRecord::Base belongs_to :user has_many :installations has_many :mobilizations has_many :fertilizations has_many :treatments has_many :harvests validates_presence_of :name, :culture, :date end
class CreateWords < ActiveRecord::Migration def change create_table :words do |t| t.string :entry t.string :furigana t.decimal :frequency t.boolean :is_jlpt t.integer :jlpt_level t.timestamps end end end
require 'rails_helper' RSpec.describe Stock, type: :model do let!(:stock) { described_class.create(symbol: 'MC', company_name: 'Microsoft Corp') } context 'with validations/stock should fail to save' do it 'is not valid without symbol' do stock.symbol = nil expect(stock).not_to be_valid end it 'is not valid without a company_name' do stock.company_name = nil expect(stock).not_to be_valid end end end
require "rails_helper" RSpec.describe BuildConferenceEvent do describe ".from" do it "translates a participant-join conference event into a class" do result = described_class.from(event: "participant-join", sid: "1234", conference_sid: "12345") expect(result).to be_a(ConferenceEvents::ParticipantJoin) end it "translates a participant-left conference event into a class" do result = described_class.from(event: "participant-leave", sid: "1234") expect(result).to be_a(ConferenceEvents::ParticipantLeave) end it "translates a conference-start conference event into a class" do result = described_class.from(event: "conference-start") expect(result).to be_a(ConferenceEvents::ConferenceStart) end it "translates a conference-end conference event into a class" do result = described_class.from(event: "conference-end") expect(result).to be_a(ConferenceEvents::ConferenceEnd) end it "does not return a status that we do not recognize" do result = described_class.from(event: "not-valid") expect(result).to be_a(ConferenceEvents::UnknownEvent) end end end
class Joke < ApplicationRecord has_and_belongs_to_many :categories validates :title, presence: true end
class RegistrationsController < Devise::RegistrationsController respond_to :json def create @consumer = Consumer.new(consumer_params) if(@consumer.save) render :json => { :consumer => @consumer, :status => :ok } else render :json => {:state => :failed, :messages => @consumer.errors.messages.map{|key, value| value[0]}.join('\n')} end end private def consumer_params params.require(:consumer).permit(:user_name, :phone, :email, :password, :password_confirmation) end end
class Api::V1::RescuesController < ApplicationController def create rescue1 = Rescue.new(rescue_params) rescue1.user = active_user if rescue1.save render json: {rescue: rescue1} end end def index render json: Rescue.all end def show @rescue = Rescue.find(params[:id]) render json: @rescue end private def rescue_params params.require(:rescue).permit(:organization_name, :street_address, :city, :state, :zipcode, :website, :phone) end end
class WelcomeController < ApplicationController def index p "Welcome to Rails!" end end
class Season < ApplicationRecord has_many :teams, :through => :season_teams has_many :season_teams has_many :game_dates has_many :players end
module JanusGateway class Error < StandardError # @return [Integer] attr_reader :code # @return [String] attr_reader :info # @param [Integer] error_code # @param [String] error_info def initialize(error_code, error_info) @code = error_code @info = error_info super("<Code: #{code}> <Info: #{info}>") end end end
class CreateTasks < ActiveRecord::Migration def change create_table(:tasks) do |t| t.string :title t.text :description t.date :due_time t.string :estimated_time t.integer :priority_id t.integer :state_id t.timestamps end end end
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :timeoutable, :omniauthable, :registerable devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable, :invitable, :lockable rolify include SearchCop validates :email, presence: true, uniqueness: {case_sensitive: false} validates :first_name, presence: true validates :last_name, presence: true def name "#{first_name} #{last_name}".strip end end
# == Schema Information # # Table name: comments # # id :integer not null, primary key # commentable_id :integer # commentable_type :string # text :text # response_to_id :integer # user_id :integer # created_at :datetime not null # updated_at :datetime not null # # Indexes # # index_comments_on_commentable_type_and_commentable_id (commentable_type,commentable_id) # index_comments_on_user_id (user_id) # require 'rails_helper' RSpec.describe Comment, type: :model do subject { Comment.new } context "associations" do it { should belong_to(:commentable) } it { should belong_to(:user) } it { should belong_to(:response_to).class_name('Comment').optional } end context "validations" do it { should validate_presence_of :commentable } it { should validate_presence_of :user } it { should validate_presence_of :text } end it "has a valid factory" do expect(build(:comment)).to be_valid end context "when comment is a response" do it "doesn't allow a response to another response" do comment = create(:comment) response = create(:comment, response_to: comment) response_to_response = build(:comment,response_to: response) expect(response_to_response).to_not be_valid expect(response_to_response.errors).to have_key(:response_to) end end describe ".log_activity" do it "logs activity after create" do expect { create(:comment) }.to change(ActivityLog, :count).by(1) end end end
# frozen_string_literal: true module ActiveSettings module Validation module Validate def validate! return unless self.class.schema v_res = self.class.schema.call(to_hash) return if v_res.success? raise ActiveSettings::Validation::Error, "ActiveSettings validation failed:\n\n#{ActiveSettings::Validation::Error.format(v_res)}" end end end end
class Case < ActiveRecord::Base acts_as_mappable def self.create_from_socrata!(socrata_attrs) attrs = { 'remote_id' => socrata_attrs['service_request_id'], 'service' => socrata_attrs['service_name'], 'service_subtype' => socrata_attrs['service_subtype'], 'service_details' => socrata_attrs['service_details'], 'media_url' => socrata_attrs['media_url'].try(:[], 'url'), 'source' => socrata_attrs['source'], 'lat' => Float(socrata_attrs['lat']), 'lng' => Float(socrata_attrs['long']), 'address' => socrata_attrs['address'], 'neighborhood' => socrata_attrs['neighborhoods_sffind_boundaries'], 'police_district' => socrata_attrs['police_district'], 'status' => socrata_attrs['status_description'], 'status_note' => socrata_attrs['status_notes'], 'responsible_agency' => socrata_attrs['agency_responsible'], 'supervisor_district_id' => socrata_attrs['supervisor_district'] } attrs['opened_at'] = Chronic.parse(socrata_attrs['requested_datetime'].tr('T', ' ')) if socrata_attrs['closed_date'].present? attrs['closed_at'] = Chronic.parse(socrata_attrs['closed_date'].tr('T', ' ')) end if socrata_attrs['updated_datetime'].present? attrs['remote_updated_at'] = Chronic.parse(socrata_attrs['updated_datetime'].tr('T', ' ')) end create!(attrs) end end
# == Schema Information # # Table name: niveles # # id :integer not null, primary key # nivel :string # class Nivel < ApplicationRecord ################################################### ##################Validaciones##################### #validates :nivel, presence: {message: "Campo obligatorio."}, length: {in: 5..30, message: "El nivel debe tener entre 5 y 30 caracteres."} ################################################### ####################Relaciones##################### has_many :grupos, dependent: :destroy has_many :materias, dependent: :destroy ################################################### ############Validaciones de relaciones############# validates_associated :grupos validates_associated :materias ################################################### ################################################### end
class Reservation < ApplicationRecord belongs_to :user belongs_to :menu validates :start_scheduled_at, presence: true validates :end_scheduled_at, presence: true validate :date_before_start validate :date_before_finish def date_before_start return if start_scheduled_at.blank? errors.add(:start_scheduled_at, "は現在時刻以降を選択してください") if self.start_scheduled_at < Time.now end def date_before_finish return if end_scheduled_at.blank? || start_scheduled_at.blank? errors.add(:end_scheduled_at, "は開始日以降を選択してください") if self.end_scheduled_at < self.start_scheduled_at end end
class WrapsController < ApplicationController before_action :set_wrap, only: [:show, :edit, :update, :destroy] before_action :group_menber? def index @pet = Pet.find(params[:pet_id]) @wraps = @pet.wraps.includes(:conditions).all.order(start_time: :desc) end def new @wrap = Wrap.new @wrap.conditions.build @wrap.meals.build @wrap.excretions.build @wrap.medicines.build @wrap.walks.build @wrap.pet_id = params[:pet_id] end def create @wrap = Wrap.new(wrap_params) @wrap.pet_id = params[:pet_id] if @wrap.save redirect_to pet_wraps_path(@wrap.pet_id), notice: "介護記録を登録しました!" else if @wrap[:start_time].blank? redirect_to new_pet_wrap_path(@wrap.pet_id), notice: "記録日が入力されていません!" else redirect_to new_pet_wrap_path(@wrap.pet_id), notice: "介護記録の登録に失敗しました!" end end end def show end def edit @wrap.conditions.build @wrap.meals.build @wrap.excretions.build @wrap.medicines.build @wrap.walks.build end def update if @wrap.update(update_wrap_params) redirect_to pet_wraps_path(@wrap.pet_id), notice: "介護記録を編集しました!" else render :edit end end def destroy @wrap.destroy redirect_to pet_wraps_path(@wrap.pet_id), notice:"削除しました!" end private def wrap_params params.require(:wrap).permit(:id, :precaution_title, :precaution_content, :start_time, :pet_id, conditions_attributes: [ :id, :start_time, :weight, :temperature, :memo ], meals_attributes: [ :id, :start_time, :shape, :amount, :memo ], excretions_attributes: [ :id, :start_time, :shape, :amount, :smell, :memo ], medicines_attributes: [ :id, :start_time, :shape, :memo ], walks_attributes: [ :id, :start_time, :how_many, :memo ] ) end def update_wrap_params params.require(:wrap).permit(:id, :precaution_title, :precaution_content, :start_time, :pet_id, conditions_attributes: [ :id, :start_time, :weight, :temperature, :memo, :_destroy ], meals_attributes: [ :id, :start_time, :shape, :amount, :memo, :_destroy ], excretions_attributes: [ :id, :start_time, :shape, :amount, :smell, :memo, :_destroy ], medicines_attributes: [ :id, :start_time, :shape, :memo, :_destroy ], walks_attributes: [ :id, :start_time, :how_many, :memo, :_destroy ] ) end def set_wrap params[:id] = params[:wrap_id] if params[:id].nil? @wrap = Wrap.find(params[:id]) end def group_menber? if @wrap.blank? @pet = Pet.find(params[:pet_id]) else pet = @wrap.pet[:id] @pet = Pet.find(pet) end current_user == @pet.group.members end end
class AddReportetoManten < ActiveRecord::Migration def change add_column :mantenimientos, :reporte, :string end end
module Monad class Maybe def initialize(value) @value = value end def self.lift(value) Maybe.new value end attr_reader :value def fmap(proc) if @value.nil? self else Maybe.new(proc.call(@value)) end end def apply(maybe) if @value.nil? self else maybe.fmap @value end end def bind(&block) if @value.nil? self else block.call(value) end end end end
require File.expand_path('../test_helper', __FILE__) class EncryptorTest < Test::Unit::TestCase algorithms = %x(openssl list-cipher-commands).split key = Digest::SHA256.hexdigest(([Time.now.to_s] * rand(3)).join) iv = Digest::SHA256.hexdigest(([Time.now.to_s] * rand(3)).join) salt = Time.now.to_i.to_s original_value = Digest::SHA256.hexdigest(([Time.now.to_s] * rand(3)).join) algorithms.reject { |algorithm| algorithm == 'base64' }.each do |algorithm| encrypted_value_with_iv = Encryptor.encrypt(:value => original_value, :key => key, :iv => iv, :salt => salt, :algorithm => algorithm) encrypted_value_without_iv = Encryptor.encrypt(:value => original_value, :key => key, :algorithm => algorithm) define_method "test_should_crypt_with_the_#{algorithm}_algorithm_with_iv" do assert_not_equal original_value, encrypted_value_with_iv assert_not_equal encrypted_value_without_iv, encrypted_value_with_iv assert_equal original_value, Encryptor.decrypt(:value => encrypted_value_with_iv, :key => key, :iv => iv, :salt => salt, :algorithm => algorithm) end define_method "test_should_crypt_with_the_#{algorithm}_algorithm_without_iv" do assert_not_equal original_value, encrypted_value_without_iv assert_equal original_value, Encryptor.decrypt(:value => encrypted_value_without_iv, :key => key, :algorithm => algorithm) end define_method "test_should_encrypt_with_the_#{algorithm}_algorithm_with_iv_with_the_first_arg_as_the_value" do assert_equal encrypted_value_with_iv, Encryptor.encrypt(original_value, :key => key, :iv => iv, :salt => salt, :algorithm => algorithm) end define_method "test_should_encrypt_with_the_#{algorithm}_algorithm_without_iv_with_the_first_arg_as_the_value" do assert_equal encrypted_value_without_iv, Encryptor.encrypt(original_value, :key => key, :algorithm => algorithm) end define_method "test_should_decrypt_with_the_#{algorithm}_algorithm_with_iv_with_the_first_arg_as_the_value" do assert_equal original_value, Encryptor.decrypt(encrypted_value_with_iv, :key => key, :iv => iv, :salt => salt, :algorithm => algorithm) end define_method "test_should_decrypt_with_the_#{algorithm}_algorithm_without_iv_with_the_first_arg_as_the_value" do assert_equal original_value, Encryptor.decrypt(encrypted_value_without_iv, :key => key, :algorithm => algorithm) end define_method "test_should_call_encrypt_on_a_string_with_the_#{algorithm}_algorithm_with_iv" do assert_equal encrypted_value_with_iv, original_value.encrypt(:key => key, :iv => iv, :salt => salt, :algorithm => algorithm) end define_method "test_should_call_encrypt_on_a_string_with_the_#{algorithm}_algorithm_without_iv" do assert_equal encrypted_value_without_iv, original_value.encrypt(:key => key, :algorithm => algorithm) end define_method "test_should_call_decrypt_on_a_string_with_the_#{algorithm}_algorithm_with_iv" do assert_equal original_value, encrypted_value_with_iv.decrypt(:key => key, :iv => iv, :salt => salt, :algorithm => algorithm) end define_method "test_should_call_decrypt_on_a_string_with_the_#{algorithm}_algorithm_without_iv" do assert_equal original_value, encrypted_value_without_iv.decrypt(:key => key, :algorithm => algorithm) end define_method "test_string_encrypt!_on_a_string_with_the_#{algorithm}_algorithm_with_iv" do original_value_dup = original_value.dup original_value_dup.encrypt!(:key => key, :iv => iv, :salt => salt, :algorithm => algorithm) assert_equal original_value.encrypt(:key => key, :iv => iv, :salt => salt, :algorithm => algorithm), original_value_dup end define_method "test_string_encrypt!_on_a_string_with_the_#{algorithm}_algorithm_without_iv" do original_value_dup = original_value.dup original_value_dup.encrypt!(:key => key, :algorithm => algorithm) assert_equal original_value.encrypt(:key => key, :algorithm => algorithm), original_value_dup end define_method "test_string_decrypt!_on_a_string_with_the_#{algorithm}_algorithm_with_iv" do encrypted_value_with_iv_dup = encrypted_value_with_iv.dup encrypted_value_with_iv_dup.decrypt!(:key => key, :iv => iv, :salt => salt, :algorithm => algorithm) assert_equal original_value, encrypted_value_with_iv_dup end define_method "test_string_decrypt!_on_a_string_with_the_#{algorithm}_algorithm_without_iv" do encrypted_value_without_iv_dup = encrypted_value_without_iv.dup encrypted_value_without_iv_dup.decrypt!(:key => key, :algorithm => algorithm) assert_equal original_value, encrypted_value_without_iv_dup end end define_method 'test_should_use_the_default_algorithm_if_one_is_not_specified' do assert_equal Encryptor.encrypt(:value => original_value, :key => key, :algorithm => Encryptor.default_options[:algorithm]), Encryptor.encrypt(:value => original_value, :key => key) end def test_should_have_a_default_algorithm assert !Encryptor.default_options[:algorithm].nil? assert !Encryptor.default_options[:algorithm].empty? end def test_should_raise_argument_error_if_key_is_not_specified assert_raises(ArgumentError) { Encryptor.encrypt('some value') } assert_raises(ArgumentError) { Encryptor.decrypt('some encrypted string') } assert_raises(ArgumentError) { Encryptor.encrypt('some value', :key => '') } assert_raises(ArgumentError) { Encryptor.decrypt('some encrypted string', :key => '') } end def test_should_yield_block_with_cipher_and_options called = false Encryptor.encrypt('some value', :key => 'some key') { |cipher, options| called = true } assert called end end
## -*- Ruby -*- ## XML::DOM ## 1998-2001 by yoshidam ## require 'xml/dom2/node' require 'xml/dom2/domexception' module XML module DOM =begin == Class XML::DOM::EntityReference === superclass Node =end class EntityReference<Node =begin === Class Methods --- EntityReference.new(name, *children) creates a new EntityReference. =end def initialize(name, *children) super(*children) raise "parameter error" if !name @name = name.freeze @value = nil end =begin === Methods --- EntityReference#nodeType [DOM] returns the nodeType. =end ## [DOM] def nodeType ENTITY_REFERENCE_NODE end =begin --- EntityReference#nodeName [DOM] returns the nodeName. =end ## [DOM] def nodeName @name end =begin --- EntityReference#to_s returns the string representation of the EntityReference. =end ## reference form or expanded form? def to_s "&#{@name};" end =begin --- EntityReference#dump(depth = 0) dumps the EntityReference. =end def dump(depth = 0) print ' ' * depth * 2 print "&#{@name}{\n" @children.each do |child| child.dump(depth + 1) end if @children print ' ' * depth * 2 print "}\n" end =begin --- EntityReference#cloneNode(deep = true) [DOM] returns the copy of the EntityReference. =end ## [DOM] def cloneNode(deep = true) super(deep, @name) end def _checkNode(node) unless node.nodeType == ELEMENT_NODE || node.nodeType == PROCESSING_INSTRUCTION_NODE || node.nodeType == COMMENT_NODE || node.nodeType == TEXT_NODE || node.nodeType == CDATA_SECTION_NODE || node.nodeType == ENTITY_REFERENCE_NODE raise DOMException.new(DOMException::HIERARCHY_REQUEST_ERR) end end end end end
class CatalogController < ApplicationController def get render json: Rails.application.config.catalog end end
# encoding: UTF-8 require 'rails_helper' require 'byebug' describe "User logs in", :type => :feature do before :each do #create admin user if User.find_by_email('evermentors@gmail.com').blank? ActiveRecord::Base.skip_callbacks = true havit_admin = User.create name: '에버멘토', email: 'evermentors@gmail.com', password: 'test4321', last_used_character: 1 ActiveRecord::Base.skip_callbacks = false else havit_admin = User.find_by_email('evermentors@gmail.com') end #create universe group Group.disable_search_callbacks universe = FactoryGirl.create(:group, creator: havit_admin.id) Group.enable_search_callbacks #create two users @user1 = FactoryGirl.create(:user, name: "kucho1", email: "jku856-1@gmail.com") @user2 = FactoryGirl.create(:user, name: "kucho2", email: "jku856-2@gmail.com") Group.disable_search_callbacks @group1 = FactoryGirl.create(:group, name: "Evermentors", creator: @user1.id, description: "This is evermentors group", password: "test4321", member_limit: 10) @group1.characters.create user_id: @user1.id, order: (@user1.characters.count + 1), is_admin: true Group.enable_search_callbacks end it "logs in and join group successfully", js: true do login_user(@user1) fill_in_goals_and_submit(@user1) page.find('.navbar-group-select.will-collapse > div.dropdown-toggle').click page.find('.navbar-group-select.will-collapse .group-name', :text => 'Evermentors').click fill_in_goals_and_submit(@user1) expect(page).to have_css(".metainfo") end end
class Api::V1::Batches::ClosingsController < ApplicationController def update batch = find_batch(params[:reference]) orders = batch.orders orders.update(status: 'closing') render json: { reference: batch.reference, status: 'closing' }, status: :ok rescue ActiveRecord::RecordNotFound render json: { error: "Can't find avaliable batch" }, status: :not_found end private def find_batch(reference) batch = Batch.includes(:orders).find_by(reference: reference) raise ActiveRecord::RecordNotFound if batch.nil? batch end end
class CreateOrderGroups < ActiveRecord::Migration def self.up create_table :order_groups do |t| t.date :name t.integer :department_id t.integer :type_id t.integer :now_level t.integer :no t.integer :status_id t.timestamps end end def self.down drop_table :order_groups end end
FactoryGirl.define do factory :card_product, aliases: [:product] do sequence(:name) { |n| "Example Card #{n}" } annual_fee_cents { rand(500_00) + 10_00 } bank_id { Bank.all.pluck(:id).sample } image_content_type { 'image/png' } image_file_name { 'example_card_image.png' } image_file_size { 256 } image_updated_at { Time.zone.now } network { CardProduct::Network.values.sample } personal { rand > 0.5 } type { CardProduct::Type.values.sample } # See https://github.com/thoughtbot/paperclip/issues/1333 after(:create) do |product| image_file = Rails.root.join("spec", "support", product.image_file_name) # cp test image to directories %i[original large medium small].each do |size| dest_path = product.image.path(size) `mkdir -p #{File.dirname(dest_path)}` `cp #{image_file} #{dest_path}` end end currency { Currency.all.sample || SampleDataMacros::Generator.instance.currency } trait :visa do network 'visa' end trait :mastercard do network 'mastercard' end trait :business do business true end trait :personal do business false end trait :hidden do shown_on_survey false end end end
#!/usr/bin/env jruby $:.unshift File.expand_path('../../lib', __FILE__) require 'traject/command_line' require 'benchmark' unless ARGV.size >= 2 STDERR.puts "\n Benchmark two (or more) different config files with both 0 and 3 threads against the given marc file\n" STDERR.puts "\n Usage:" STDERR.puts " jruby --server bench.rb config1.rb config2.rb [...configN.rb] filename.mrc\n\n" exit end filename = ARGV.pop config_files = ARGV puts RUBY_DESCRIPTION Benchmark.bmbm do |x| [0, 3].each do |threads| config_files.each do |cf| x.report("#{cf} (#{threads})") do cmdline = Traject::CommandLine.new(["-c", cf, '-s', 'log.file=bench.log', '-s', "processing_thread_pool=#{threads}", filename]) cmdline.execute end end end end
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :user do email {Faker::Internet.email} password {Faker::Internet.password} first_name {Faker::Name.first_name} last_name {Faker::Name.last_name} end end
class CreateSharePoints < ActiveRecord::Migration def change create_table :share_points do |t| t.integer :friendships_id t.integer :location_id t.float :points t.timestamps end end end
require "aethyr/core/actions/commands/command_action" module Aethyr module Core module Actions module Tell class TellCommand < Aethyr::Extend::CommandAction def initialize(actor, **data) super(actor, **data) end def action event = @data target = $manager.find event[:target] unless target and target.is_a? Player @player.output "That person is not available." return end if target == @player @player.output "Talking to yourself?" return end phrase = event[:message] last_char = phrase[-1..-1] unless ["!", "?", "."].include? last_char phrase << "." end phrase[0,1] = phrase[0,1].upcase phrase = phrase.strip.gsub(/\s{2,}/, ' ') @player.output "You tell #{target.name}, <tell>\"#{phrase}\"</tell>" target.output "#{@player.name} tells you, <tell>\"#{phrase}\"</tell>" target.reply_to = @player.name end #Reply to a tell. end end end end end
# Pad an Array # I worked on this challenge with Eunice Choi # I spent 3 hours on this challenge. # Complete each step below according to the challenge directions and # include it in this file. Also make sure everything that isn't code # is commented in the file. # 0. Pseudocode =begin What is the input? An array and a non-negative integer as the minimum size, and an optional third argument for what the array should be padded with What is the output? (i.e. What should the code return?) An array What are the steps needed to solve the problem? 1. create a method with 3 arguments (array, size, padding) 2. clone array for non-destructive method 3. if the array size is bigger or equal to the desired size, then just return the array 4. if the array size is smaller than the desired size, then append the padding object to the array, creating a new_array. return new_array =end # 1. Initial Solution #non-destructive def pad(array, size, string=nil) new_array = array.clone if array.length >= size return array else while new_array.length < size new_array << string end end return new_array end #destructive def pad!(array, size, string=nil) if array.length >= size return array else while array.length < size array << string end end return array end # 3. Refactored Solution #non-destructive def pad(array, size, string=nil) new_array = array.clone until new_array.count >= size new_array << string end return new_array end #destructive def pad!(array, size, string=nil) until array.count >= size array << string end return array end =begin # 4. Reflection Were you successful in breaking the problem down into small steps? - Yes it really helped with the logic for us to talk it through and figure out what the end goal was and what we needed to do to get there. It helped us to figure out what conditions needed to be met for the loops to stop at the refactoring step because we realized how much we could simplify the code. Once you had written your pseudocode, were you able to easily translate it into code? What difficulties and successes did you have? - Yes, the logic was there but we kept getting an error message which frustrated us because we knew that the logic made sense. Since we ran into a wall we decided to pick it up again later. In between that time, my partner had realized the error was due to the fact that we forgot to perserve the non-destructive method with the clone method. The frustrating part was that when we were researching I kept seeing the clone method but had skipped over it to the dup method, which did not work. It was satisfying to know that our logic was correct from the start though. Was your initial solution successful at passing the tests? If so, why do you think that is? If not, what were the errors you encountered and what did you do to resolve them? - We were so focused on the logic for the methods that we had overlooked the core differences of destructive and non-destructive methods. We discovered the error was due to that. We researched and figured out it was because we didn't clone for the non-destructive method. When you refactored, did you find any existing methods in Ruby to clean up your code? - Yes, I always overlook the until loop because it's hard for me to think of situations where it would be used over if/while methods because it seems backwards to me. I realized it worked perfectly in this challenge and was a much cleaner way. How readable is your solution? Did you and your pair choose descriptive variable names? - Yes, we feel like we gave it clear names so that it's very readable. What is the difference between destructive and non-destructive methods in your own words? - The readable difference is that destructive methods have an exclamation point, to represent permanent modification to the array or hash. This is why for the non-destructive methods, we had to create a clone of our array so that permanent changes would not be added to it, but to our new_array. =end
require 'test_helper' require 'mine' describe Result do let(:described_class) { Result } let(:mine) { Mine.new(1,2,3) } describe 'initialization' do it 'sets all properties' do inst = described_class.new(mine) inst.mine.must_equal mine inst.iterations.must_equal 0 inst.explosions.must_equal 0 end end describe '#to_s' do let(:instance) { Result.new(mine) } it 'appends current state to mine information' do mine.stub(:to_s, "MineInfo") do instance.to_s.must_equal "MineInfo Explosions: 0, Time: 0" instance.explosions = 4 instance.iterations = 2 instance.to_s.must_equal "MineInfo Explosions: 4, Time: 2" end end end describe 'comparison' do let(:result_a) { Result.new(mine) } let(:result_b) { Result.new(mine) } describe 'when number of explosions is equal' do describe 'and iterations is equal' do it 'returns 0' do (result_a <=> result_b).must_equal 0 end end describe 'and iterations is not equal' do let(:result_b) { Result.new(mine, iterations: 2) } it 'returns -1 for the one with greater iterations' do (result_a <=> result_b).must_equal 1 end it 'returns 1 for the one with lesser iterations' do (result_b <=> result_a).must_equal(-1) end end end describe 'when number of explosions is not equal' do let(:result_a) { Result.new(mine, iterations: 3, explosions: 5) } let(:result_b) { Result.new(mine, iterations: 1, explosions: 4) } it 'returns 1 for the one with greater explosions' do (result_a <=> result_b).must_equal 1 end it 'returns -1 for the one with lesser explosions' do (result_b <=> result_a).must_equal(-1) end end end end
class ToppagesController < ApplicationController def index if logged_in? redirect_to user_path(id: current_user.id) end end end
class CreateSeries < ActiveRecord::Migration[6.0] def change create_table :series do |t| t.string :name t.string :genre t.integer :no_of_seasons t.date :date_of_first_release t.string :director t.timestamps end end end
class V1::ShippingAddressSerializer < ActiveModel::Serializer attributes :id, :name, :address_line1, :address_line2, :city, :state, :country, :postal_code end
module TemplateBuilder class FromApp attr_reader :app_id, :options def initialize(app_id, options) @app_id = app_id @options = options end def create_template(persisted=true) app = App.find(app_id) Converters::AppConverter.new(app).to_template.tap do |template| template.assign_attributes(options) template.save if persisted end end end end
#!/usr/bin/env ruby require 'typhoeus' require 'bloomfilter-rb' require 'nokogiri' require 'domainatrix' require 'uri' class Spider def initialize(url, options = {}) @start_url = url @domain = parse_domain(url) @threads = options[:threads] ? options[:threads] : 200 @max_urls = options[:max_urls] ? options[:max_urls] : nil @global_visited = BloomFilter::Native.new(:size => 10000000, :hashes => 5, :seed => 1, :bucket => 8, :raise => false) @global_queue = [] @parse_queue = [] @global_queue << @start_url @mux = Mutex.new @debug = options[:debug] ? options[:debug] : false @split_url_at_hash = options[:split_url_at_hash] ? options[:split_url_at_hash] : false @exclude_urls_with_hash = options[:exclude_urls_with_hash] ? options[:exclude_urls_with_hash] : true @exclude_urls_with_extensions = options[:exclude_urls_with_extensions] ? options[:exclude_urls_with_extensions] : false end def crawl(arg_queue) hydra = nil arg_queue.each do |q| begin hydra = Typhoeus::Hydra.new(:max_concurrency => 1) request = Typhoeus::Request.new(q, :timeout => 5000) request.on_complete do |response| links = Nokogiri::HTML.parse(response.body).xpath('.//a/@href') links.each do |link| if(internal_link?(link, response.effective_url) && no_hash_in_url?(link) && ignore_extensions(link)) sanitized_link = sanitize_link(split_url_at_hash(link)) if(sanitized_link) absolute_link = make_absolute(sanitized_link, response.effective_url) @parse_queue << absolute_link if absolute_link end end end end hydra.queue request rescue => e puts "Exception caught: #{e}" if @debug end end #puts "arg_queue #{arg_queue.size} - parse_queue #{@parse_queue.size} - global_queue #{@global_queue.size} -hydra_queue#{hydra.queued_requests.size}" hydra.run if hydra end def thread(n) count = 0 q = nil while true begin if @parse_queue.size > 0 then @mux.synchronize do q = @parse_queue.shift if(q && !@global_visited.include?(q)) yield q @global_visited.insert(q) @global_queue << q end end break if (!@max_urls.nil? && @global_visited.size.to_i > @max_urls) if @global_queue.size > 0 then crawl(@global_queue.shift(1)) count = 0 end else sleep 0.1 count += 1 #puts "thread #{n} count: #{count}" if count == 200 break if count == 500 end rescue next end end end def run() crawl(@global_queue.shift(5)) thread_list = [] @threads.times do |n| puts("Checks thread #{n} start.") if @debug thread_list[n] = Thread.new{ thread(n) do |i| yield i end } end thread_list.each do |t| t.join end end def parse_domain(url) puts "Parsing URL: #{url}" if @debug begin parsed_domain = Domainatrix.parse(url) if(parsed_domain.subdomain != "") parsed_domain.subdomain + '.' + parsed_domain.domain + '.' + parsed_domain.public_suffix else parsed_domain.domain + '.' + parsed_domain.public_suffix end rescue nil end end def internal_link?(url, effective_url) absolute_url = make_absolute(url, effective_url) parsed_url = parse_domain(absolute_url) if(@domain == parsed_url) return true else return false end end def split_url_at_hash(url) return url.to_s unless @split_url_at_hash return url.to_s.split('#')[0] end def no_hash_in_url?(url) return true unless @exclude_urls_with_hash if(url.to_s.scan(/#/).size > 0 || url.to_s.end_with?('?') ) return false else return true end end def ignore_extensions(url) return true if url.to_s.length == 0 return true unless @exclude_urls_with_extensions not_found = true @exclude_urls_with_extensions.each do |e| if(url.to_s.length > e.size && url.to_s[-e.size .. -1].downcase == e.to_s.downcase) not_found = false puts "#{e} Found At URL: #{url}" if @debug end end return not_found end def sanitize_link(url) begin return url.gsub(/\s+/, "%20") rescue return false end end def make_absolute( href, root ) begin URI.parse(root).merge(URI.parse(split_url_at_hash(href.to_s.gsub(/\s+/, "%20")))).to_s rescue URI::InvalidURIError, URI::InvalidComponentError => e return false end end end if $0 == __FILE__ exit if !ARGV[0] lino = 0 exts = ['exe', 'rar', 'zip', 'tar', 'tgz', 'gz', 'jpg', 'png', 'gif'] Spider.new(ARGV[0], {:exclude_urls_with_extensions => exts}).run() do |response| lino += 1 puts "#{lino} - #{response}" end end
class Post < ApplicationRecord before_validation :create_date, on: :create before_validation :update_date, on: :update belongs_to :user, inverse_of: :posts validates_presence_of :title, :body, :user_id, :published_at private def create_date self.updated_at = self.published_at = DateTime.current end def update_date self.updated_at = DateTime.current end end
class Web::FondsController < Web::WebController layout :set_layout before_filter :authorize_admins_only, :except => [ :show, :amount_table, :popup, :contribution_names, :faq ] # ............................................................................ # def show amount_table @html_title = "Nadační fond Nezávislosti Deníku Referendum" if request.post? params[:fond][:ip_address] = request.remote_ip @fond = Fond.new(params[:fond]) if @fond.save flash.now[:notice] = "Děkujeme, na Vaši mailovou adresu právě " \ "odešel dopis s variabilním symbolem pro Váš trvalý příkaz." @fond = Fond.new else flash.now[:error] = "Při ukládání formuláře se objevila chyba." end else @fond = Fond.new end end # ............................................................................ # def popup @my_rand = rand(8) end # ............................................................................ # # jmena prispevatelu def contribution_names joins = "LEFT JOIN `fonds` ON `fonds`.id = `really_fonds`.fond_id" @fond_publish = ReallyFond.find(:all, :joins => joins, :group => :fond_id, :conditions => [ "fonds.disable = false AND fonds.publish_name = true" ], :select => "fonds.firstname, fonds.lastname, fonds.profession, fonds.city", :order => "fonds.lastname") @fond_publish_no = ReallyFond.find(:all, :joins => joins, :group => :fond_id, :conditions => [ "fonds.disable = false AND fonds.publish_name = false" ]) end # ............................................................................ # # casto kladene otazky def faq end # ............................................................................ # # Pocet aktivních trvalých příkazů def count_active_tax_returns(amount) joins = "LEFT JOIN `fonds` ON `fonds`.id = `really_fonds`.fond_id" fond = ReallyFond.find(:all, :joins => joins, :group => :fond_id, :conditions => [ "fonds.disable = false AND fonds.amount = ?", amount ] ) return fond.count end # ............................................................................ # # Celková suma všech aktivních trvalých příkazů def sum_active_tax_returns r_fonds = ReallyFond.find(:all, :group => :fond_id, :select => "fond_id" ) return Fond.sum(:amount, :conditions => [ "disable = false and id in (?)", r_fonds.map { |f| f.fond_id } ]) end # ............................................................................ # def amount_table @amount = Hash.new # Celkem nasporeno tento mesic @amount[:total] = sum_active_tax_returns @amount[:total] += params[:amount].to_i if params[:amount] [60,100,300,600,1000,3000,6000,10000,30000].each do |t| @amount["saved_#{t}".intern] = count_active_tax_returns(t) @amount["need_#{t}".intern] = ( 300000 - @amount[:total].to_i ) / t (( 300000 - @amount[:total].to_i ) % t ) == 0 ? nil : @amount["need_#{t}".intern] += 1 @amount["need_#{t}".intern] < 0 ? @amount["need_#{t}".intern] = 0 : nil end if request.xhr? @amount["saved_#{params[:amount]}".intern] += 1 render :partial => "amount_table", @object => @amount else #render :layout => nil end end # ............................................................................ # def update_fond_morals fond = Fond.find_by_id(params[:id]) fond.disable = !fond.disable fond.save render :partial => 'morals', :locals => { :fond => fond } end # ............................................................................ # # Uzivatele, kteri pouze vyplnili formular def list unless params[:search_fonds].nil? fonds = params[:search_fonds] @year = fonds[:year] @month = fonds[:month] @variable_number = fonds[:variable_number] @email = fonds[:email] conds = [] conds << "fonds.email = '#{fonds[:email]}'" unless fonds[:email].blank? conds << "fonds.variable_number = '#{fonds[:variable_number]}'" unless fonds[:variable_number].blank? conds << "YEAR(created_at) = #{fonds[:year]}" unless fonds[:year].blank? conds << "MONTH(created_at) = #{fonds[:month]}" unless fonds[:month].blank? conds = conds.join(" AND ") @fonds = Fond.paginate(:all, :order => "created_at desc", :page => params[:page], :conditions => [conds], :per_page => 1000 ) else @fonds = Fond.paginate(:all, :order => "created_at desc", :page => params[:page] ) end end # ............................................................................ # # Skutecne provedene platby def really_list joins = "INNER JOIN `fonds` ON `fonds`.id = `really_fonds`.fond_id" select = "really_fonds.*, fonds.email, fonds.variable_number" unless params[:search_fonds].nil? fonds = params[:search_fonds] @year = fonds[:year] @month = fonds[:month] @variable_number = fonds[:variable_number] @email = fonds[:email] conds = [] conds << "fonds.email = '#{fonds[:email]}'" unless fonds[:email].blank? conds << "fonds.variable_number = '#{fonds[:variable_number]}'" unless fonds[:variable_number].blank? conds << "YEAR(date) = #{fonds[:year]}" unless fonds[:year].blank? conds << "MONTH(date) = #{fonds[:month]}" unless fonds[:month].blank? conds = conds.join(" AND ") @fonds = ReallyFond.paginate(:all, :order => "really_fonds.created_at desc", :page => params[:page], :conditions => [conds], :joins => joins, :select => select, :order => "date desc", :per_page => 1000 ) else @fonds = ReallyFond.paginate(:all, :order => "really_fonds.created_at desc", :page => params[:page], :joins => joins, :select => select, :order => "date desc" ) end end # ............................................................................ # def detail @user = Fond.find_by_id(params[:id]) @my_really_fonds = ReallyFond.find_all_by_fond_id(params[:id], :order => "date DESC") if request.post? @really_fonds = ReallyFond.new(params[:really_fonds]) @date = params[:date] @really_fonds[:date] = DateTime.strptime("#{params[:date]}","%d.%m.%Y") unless params[:date].blank? if @really_fonds.save flash[:notice] = "Nová platba úspěšně uložena." @date = "" @really_fonds = ReallyFond.new redirect_to fond_detail_path(@user.id) else flash.now[:error] = "Během ukládání nové platby se vyskytla chyba." end else @really_fonds = ReallyFond.new end end # ............................................................................ # def edit_detail @fond = Fond.find_by_id(params[:id]) if request.post? if @fond.update_attributes(params[:fond]) flash.now[:notice] = "Úspěšně uloženo." redirect_to :action => :detail, :id => @fond.id else flash.now[:error] = "Při ukládání formuláře se objevila chyba." end end end # ............................................................................ # def delete_really_fond fond = ReallyFond.find(params[:id]) detail_id = fond.fond_id fond.destroy flash[:notice] = "Platba úspěšně smazána." redirect_to fond_detail_path(detail_id) end # ............................................................................ # def edit_really_fond @really_fonds = ReallyFond.find(params[:id]) @date = @really_fonds.date.to_s(:cz_date) @user = Fond.find_by_id(@really_fonds.fond_id) if request.post? @date = params[:date] params[:really_fonds][:date] = DateTime.strptime("#{params[:date]}","%d.%m.%Y") unless params[:date].blank? if @really_fonds.update_attributes(params[:really_fonds]) flash[:notice] = "Platba úspěšně editovaná." redirect_to fond_detail_path(@user.id) else flash.now[:error] = "Během ukládání platby se vyskytla chyba." end end end # ............................................................................ # protected def authorize_admins_only require_auth "ADMIN" end def set_layout if params[:action] == "show" or params[:action] == "contribution_names" or params[:action] == "faq" "web/gallery" elsif params[:action] == "popup" false else "web/admin" end end end
class Price include Virtus.model include ActiveModel::Model include ActiveModel::SerializerSupport attribute :amount, BigDecimal attribute :currency, String end
require 'statement.rb' require 'ledger.rb' require 'date.rb' describe Statement do let(:time) {Time.new} let(:ledger) {Ledger.new} let(:statement) {ledger.base_statement} context 'get statement' do it 'takes deposits and withdrawals and returns statement' do ledger.deposit(100.00) ledger.deposit(100.00) ledger.withdraw(50.00) ledger.deposit(5000.00) ledger.withdraw(450.00) statement.log_transactions expect(statement.print_statement).to eq "#{time.strftime("%d/%m/%Y")} || || -450.00 || 4700.00, #{time.strftime("%d/%m/%Y")} || || 5000.00 || 5150.00, #{time.strftime("%d/%m/%Y")} || || -50.00 || 150.00, #{time.strftime("%d/%m/%Y")} || || 100.00 || 200.00, #{time.strftime("%d/%m/%Y")} || || 100.00 || 100.00" end end end
#!/usr/bin/env ruby require 'crfsuite' # Inherit Crfsuite::Trainer to implement message() function, which receives # progress messages from a training process. class Trainer < Crfsuite::Trainer def message(s) # Simply output the progress messages to STDOUT. print s end end def instances(fi) xseq = Crfsuite::ItemSequence.new yseq = Crfsuite::StringList.new Enumerator.new do |y| fi.each do |line| line.chomp! if line.empty? # An empty line presents an end of a sequence. y << [xseq, yseq] xseq = Crfsuite::ItemSequence.new yseq = Crfsuite::StringList.new next end # Split the line with TAB characters. fields = line.split("\t") # Append attributes to the item. item = Crfsuite::Item.new fields.drop(1).each do |field| idx = field.rindex(':') if idx.nil? # Unweighted (weight=1) attribute. item << Crfsuite::Attribute.new(field) else # Weighted attribute item << Crfsuite::Attribute.new(field[0..idx-1], field[idx+1..-1].to_f) end end # Append the item to the item sequence. xseq << item # Append the label to the label sequence. yseq << fields[0] end end end if __FILE__ == $0 model_file = ARGV[0] # This demonstrates how to obtain the version string of CRFsuite. puts Crfsuite.version # Create a Trainer object. trainer = Trainer.new # Read training instances from STDIN, and set them to trainer. instances($stdin).each do |xseq, yseq| trainer.append(xseq, yseq, 0) end # Use L2-regularized SGD and 1st-order dyad features. trainer.select('l2sgd', 'crf1d') # This demonstrates how to list parameters and obtain their values. trainer.params.each do |name| print name, ' ', trainer.get(name), ' ', trainer.help(name), "\n" end # Set the coefficient for L2 regularization to 0.1 trainer.set('c2', '0.1') # Start training; the training process will invoke trainer.message() # to report the progress. trainer.train(model_file, -1) end
require 'Nokogiri' class Issue attr_accessor :project_i, :tracker, :status, :priority, :author_i, :assigned_to, :subject, :start_date, :done_ratio def initialize(attrs = {}) self.project_i = attrs.xpath("./project/@name").text self.tracker = attrs.xpath("./tracker/@name").text self.status = attrs.xpath("./status/@name").text self.priority = attrs.xpath("./priority/@name").text self.author_i = attrs.xpath("./author/@name").text self.assigned_to = attrs.xpath("./assigned_to/@name").text self.subject = attrs.xpath("./subject").text self.start_date = attrs.xpath("./start_date").text self.done_ratio = attrs.xpath("./done_ratio").text end end
require File.dirname(__FILE__) + "/../fixtures/classes" describe :delegate_instantiation, :shared => true do before(:each) do @class = @method end it "creates a delegate from bound methods" do @class.new(DelegateTester.method(:bar)).should be_kind_of @class end it "creates a delegate from lambdas" do @class.new(lambda { puts '123' }).should be_kind_of @class end it "creates a delegate from procs" do @class.new(proc { puts '123' }).should be_kind_of @class end it "creates a delegate from blocks" do (@class.new {puts '123'}).should be_kind_of @class end it "requires an argument" do lambda {@class.new}.should raise_error ArgumentError end it "requires a proc-like object" do lambda {@class.new(1)}.should raise_error TypeError end end
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :task do goal nil name "MyString" due Date.tomorrow end end
class CreateCompanies < ActiveRecord::Migration def change create_table :companies do |t| t.string :name t.string :grade t.decimal :beCutoff t.decimal :xiiCutoff t.decimal :xCutoff t.integer :backsAllowed t.string :branchesAllowed t.string :details t.decimal :package t.timestamp :deadline t.timestamps end end end
module API module V1 module Entities class Base < Grape::Entity format_with(:null) { |v| v.blank? ? "" : v } format_with(:chinese_date) { |v| v.blank? ? "" : v.strftime('%Y-%m-%d') } format_with(:chinese_datetime) { |v| v.blank? ? "" : v.strftime('%Y-%m-%d %H:%M:%S') } format_with(:money_format) { |v| v.blank? ? 0 : ('%.2f' % v).to_f } expose :id # expose :created_at, format_with: :chinese_datetime end # end Base # 用户基本信息 class UserProfile < Base expose :mobile, format_with: :null expose :nickname do |model, opts| model.nickname || model.mobile end expose :avatar do |model, opts| model.avatar.blank? ? "" : model.avatar_url(:large) end expose :sent_money, format_with: :money_format expose :receipt_money, format_with: :money_format expose :balance, format_with: :money_format end # 用户详情 class User < UserProfile expose :private_token, as: :token, format_with: :null end # 类别详情 class Category < Base expose :name, format_with: :null expose :icon do |model, opts| model.icon.blank? ? "" : model.icon.url(:icon) end end class Stream < Base expose :title, format_with: :null expose :body, format_with: :null expose :cover_image do |model, opts| model.cover_image.blank? ? "" : model.cover_image.url(:large) end expose :video_file do |model, opts| if model.class.to_s == 'LiveVideo' model.video_file_url else model.file_url end end expose :type expose :view_count, :likes_count, :favorites_count, :msg_count expose :stream_id, format_with: :null expose :created_on do |model, opts| model.created_at.blank? ? "" : model.created_at.strftime('%Y-%m-%d') end expose :liked do |model, opts| if opts[:opts].blank? false elsif opts[:opts][:liked].present? opts[:opts][:liked] else opts[:opts][:user].blank? ? false : opts[:opts][:user].liked?(model) end end expose :favorited do |model, opts| if opts[:opts].blank? false elsif opts[:opts][:favorited].present? opts[:opts][:favorited] else opts[:opts][:user].blank? ? false : opts[:opts][:user].favorited?(model) end end expose :rtmp_url, if: Proc.new { |v| v.class.to_s == 'LiveVideo' } expose :hls_url, if: Proc.new { |v| v.class.to_s == 'LiveVideo' } end class Search < Base expose :keyword, :search_count end class Video < Stream expose :category, using: API::V1::Entities::Category expose :user, using: API::V1::Entities::UserProfile, if: Proc.new { |video| video.user_id > 0 } expose :approved end class LiveSimpleVideo < Stream end class LiveVideo < Stream expose :online_users_count, as: :view_count end class ViewHistory < Base expose :play_progress do |model, opts| model.playback_progress.blank? ? 0 : model.playback_progress.to_i end expose :updated_at, as: :viewed_at expose :viewable, as: :video, using: API::V1::Entities::Stream end class PayHistory < Base expose :pay_name, format_with: :null expose :created_at, format_with: :chinese_datetime expose :pay_money do |model, opts| if model.pay_type == 0 "+ ¥ #{model.money}" elsif model.pay_type == 1 "- ¥ #{model.money}" else if model.pay_name == '打赏别人' "- ¥ #{model.money}" else "+ ¥ #{model.money}" # 收到打赏 end end end end class Favorite < Base expose :created_at, as: :favorited_at expose :favoriteable, as: :video, using: API::V1::Entities::Stream end class Like < Base expose :created_at, as: :liked_at expose :likeable, as: :video, using: API::V1::Entities::Stream end class Author < Base expose :nickname do |model, opts| model.nickname || model.mobile end expose :avatar do |model, opts| model.avatar.blank? ? "" : model.avatar_url(:large) end end class Bilibili < Base expose :content, format_with: :null expose :stream_id, format_with: :null # expose :author_name, as: :author expose :author, using: API::V1::Entities::Author, if: Proc.new { |b| b.author_id.present? } expose :location, format_with: :null expose :created_at, as: :sent_at, format_with: :chinese_datetime end # Banner class Banner < Base expose :image do |model, opts| model.image.blank? ? "" : model.image.url(:large) end expose :link, format_with: :null end # 打赏相关 class Grant < Base expose :money, format_with: :money_format expose :created_at, format_with: :chinese_datetime end class SentUserProfile < UserProfile expose :sent_money, format_with: :money_format end class ReceiptUserProfile < UserProfile expose :receipt_money, format_with: :money_format end class SentGrant < Grant expose :granted_user, as: :user, using: API::V1::Entities::UserProfile, if: Proc.new { |g| g.to.present? } end class ReceiptGrant < Grant expose :granting_user, as: :user, using: API::V1::Entities::UserProfile, if: Proc.new { |u| u.from.present? } end # 产品 class Product < Base expose :title, format_with: :null expose :price, format_with: :null expose :m_price, format_with: :null expose :category, using: API::V1::Entities::Category expose :stock, format_with: :null expose :on_sale expose :thumb_image do |model, opts| model.images.first.url(:small) end end # 产品详情 class ProductDetail < Product expose :intro, format_with: :null expose :images do |model, opts| images = [] model.images.each do |image| images << image.url(:large) end images end expose :detail_images do |model, opts| model.detail_images.map(&:url) end end end end end
require 'socket' require_relative 'logdna/client.rb' require_relative 'logdna/resources.rb' module Logdna class Ruby < ::Logger Logger::TRACE = 5 attr_accessor :level, :app, :env, :meta @level = nil @app = nil @env = nil @meta = nil def initialize(key, opts={}) @@client = Logdna::Client.new(key, opts) sleep 0.01 if @@client[:value] === Resources::LOGGER_NOT_CREATED @@client = nil puts "LogDNA logger not created" return end end def log(msg=nil, opts={}) loggerExist? optionChanged? @response = @@client.tobuffer(msg, opts) 'Saved' end def trace(msg=nil, opts={}) opts[:level] = "TRACE" loggerExist? optionChanged? @response = @@client.tobuffer(msg, opts) 'Saved' end def debug(msg=nil, opts={}) opts[:level] = "DEBUG" loggerExist? optionChanged? @response = @@client.tobuffer(msg, opts) 'Saved' end def info(msg=nil, opts={}) opts[:level] = "INFO" loggerExist? optionChanged? @response = @@client.tobuffer(msg, opts) 'Saved' end def warn(msg=nil, opts={}) opts[:level] = "WARN" loggerExist? optionChanged? @response = @@client.tobuffer(msg, opts) 'Saved' end def error(msg=nil, opts={}) opts[:level] = "ERROR" loggerExist? optionChanged? @response = @@client.tobuffer(msg, opts) 'Saved' end def fatal(msg=nil, opts={}) opts[:level] = "FATAL" loggerExist? optionChanged? @response = @@client.tobuffer(msg, opts) 'Saved' end def add(severity, msg=nil, progname=nil, &block) opts = {} opts[:level] = Resources::LOG_LEVELS[severity] loggerExist? optionChanged? if msg.nil? if block_given? msg = yield else msg = progname progname = nil end end @response = @@client.tobuffer(msg, opts) 'Saved' end def trace? loggerExist? unless @level return 'TRACE' == @@client.getLevel end logLevel('TRACE') end def debug? loggerExist? unless @level return 'DEBUG' == @@client.getLevel end logLevel('DEBUG') end def info? loggerExist? unless @level return 'INFO' == @@client.getLevel end logLevel('INFO') end def warn? loggerExist? unless @level return 'WARN' == @@client.getLevel end logLevel('WARN') end def error? loggerExist? unless @level return 'ERROR' == @@client.getLevel end logLevel('ERROR') end def fatal? loggerExist? unless @level return 'FATAL' == @@client.getLevel end logLevel('FATAL') end def clear loggerExist? @@client.clear() @level = nil @app = nil @env = nil @meta = nil return true end def loggerExist? if @@client.nil? puts "Logger Not Initialized Yet" close end end def optionChanged? if @level || @app || @env || @meta @@client.change(@level, @app, @env, @meta) @level = nil @app = nil @env = nil @meta = nil end end def logLevel(comparedTo) if @level.is_a? Numeric @level = Resources::LOG_LEVELS[@level] end return comparedTo == @level.upcase end def <<(msg=nil, opts={}) opts[:level] = "" loggerExist? optionChanged? @response = @@client.tobuffer(msg, opts) 'Saved' end def unknown(msg=nil, opts={}) opts[:level] = "UNKNOWN" loggerExist? optionChanged? @response = @@client.tobuffer(msg, opts) 'Saved' end def datetime_format(*arg) puts "datetime_format not supported in LogDNA logger" return false end def close if defined? @@client @@client.exitout() end exit! end at_exit do if defined? @@client @@client.exitout() end exit! end end end
class Union < ActiveRecord::Base has_many :tribes attr_accessible :description, :name validates :name , presence: true, length: { in: 2..30 }, uniqueness: { case_sensitive: false } end
require File.dirname(__FILE__) + '/../../../spec_helper' require 'mathn' ruby_version_is '1.9' do describe 'Kernel#Rational' do it 'returns an Integer if denominator divides numerator evenly' do Rational(42,6).should == 7 Rational(42,6).class.should == Fixnum Rational(bignum_value,1).should == bignum_value Rational(bignum_value,1).class.should == Bignum end end end